diff --git a/eng/Versions.props b/eng/Versions.props index b83e2dd249c0c5..7cc1a72696ed13 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -30,6 +30,8 @@ release, increase this number by one. --> 0 + + 3.9.0-2.20516.4 "); s.Append(innerException.ToString()); } string? stackTrace = StackTrace; - if (stackTrace != null) + if (stackTrace is not null) { s.AppendLine(); s.Append(stackTrace); diff --git a/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs b/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs index ea3b3f88eb7481..e51284eeca112d 100644 --- a/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs +++ b/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs @@ -10,7 +10,7 @@ public static class RegistryAclExtensions { public static RegistrySecurity GetAccessControl(this RegistryKey key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); return key.GetAccessControl(); @@ -18,7 +18,7 @@ public static RegistrySecurity GetAccessControl(this RegistryKey key) public static RegistrySecurity GetAccessControl(this RegistryKey key, AccessControlSections includeSections) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); return key.GetAccessControl(includeSections); @@ -26,7 +26,7 @@ public static RegistrySecurity GetAccessControl(this RegistryKey key, AccessCont public static void SetAccessControl(this RegistryKey key, RegistrySecurity registrySecurity) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); key.SetAccessControl(registrySecurity); diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs index 56cbc26afe977c..778706b3361e62 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs @@ -35,7 +35,7 @@ public static class Registry /// private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) { - if (keyName == null) + if (keyName is null) { throw new ArgumentNullException(nameof(keyName)); } @@ -55,7 +55,7 @@ private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subK } // If a potential base key was found, see if keyName actually starts with the potential base key's name. - if (baseKey != null && keyName.StartsWith(baseKey.Name, StringComparison.OrdinalIgnoreCase)) + if (baseKey is not null && keyName.StartsWith(baseKey.Name, StringComparison.OrdinalIgnoreCase)) { subKeyName = (i == -1 || i == keyName.Length) ? string.Empty : @@ -88,7 +88,7 @@ public static void SetValue(string keyName, string? valueName, object value, Reg using (RegistryKey? key = basekey.CreateSubKey(subKeyName)) { - Debug.Assert(key != null, "An exception should be thrown if failed!"); + Debug.Assert(key is not null, "An exception should be thrown if failed!"); key.SetValue(valueName, value, valueKind); } } diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs index 16b3d1aecfbf1b..b9d41f8cc53ef2 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs @@ -75,7 +75,7 @@ private void ClosePerfDataKey() private void FlushCore() { - if (_hkey != null && IsDirty()) + if (_hkey is not null && IsDirty()) { Interop.Advapi32.RegFlushKey(_hkey); } @@ -513,7 +513,7 @@ private unsafe string[] GetValueNamesCore(int values) } finally { - if (name != null) + if (name is not null) ArrayPool.Shared.Return(name); } @@ -750,7 +750,7 @@ private unsafe string[] GetValueNamesCore(int values) } cur = nextNull + 1; - if (toAdd != null) + if (toAdd is not null) { if (strings.Length == stringsCount) { @@ -822,7 +822,7 @@ private unsafe void SetValueCore(string? name, object value, RegistryValueKind v int sizeInChars = 1; // no matter what, we have the final null terminator. for (int i = 0; i < dataStrings.Length; i++) { - if (dataStrings[i] == null) + if (dataStrings[i] is null) { throw new ArgumentException(SR.Arg_RegSetStrArrNull); } @@ -918,7 +918,7 @@ private void Win32Error(int errorCode, string? str) switch (errorCode) { case Interop.Errors.ERROR_ACCESS_DENIED: - throw str != null ? + throw str is not null ? new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) : new UnauthorizedAccessException(); @@ -951,7 +951,7 @@ private void Win32Error(int errorCode, string? str) private static void Win32ErrorStatic(int errorCode, string? str) => throw errorCode switch { - Interop.Errors.ERROR_ACCESS_DENIED => str != null ? + Interop.Errors.ERROR_ACCESS_DENIED => str is not null ? new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) : new UnauthorizedAccessException(), diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs index 54054d809c2847..35ed81ab4b611d 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -98,7 +98,7 @@ public void Close() public void Dispose() { - if (_hkey != null) + if (_hkey is not null) { if (!IsSystemKey()) { @@ -167,7 +167,7 @@ public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permis if (!_remoteKey) { RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree)); - if (key != null) + if (key is not null) { // Key already exits key._checkMode = permissionCheck; @@ -199,7 +199,7 @@ public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) // explicitly call close to avoid keeping an extra HKEY open. // RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, false); - if (key != null) + if (key is not null) { using (key) { @@ -243,7 +243,7 @@ public void DeleteSubKeyTree(string subkey, bool throwOnMissingSubKey) subkey = FixupName(subkey); // Fixup multiple slashes to a single slash RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, true); - if (key != null) + if (key is not null) { using (key) { @@ -273,7 +273,7 @@ public void DeleteSubKeyTree(string subkey, bool throwOnMissingSubKey) private void DeleteSubKeyTreeInternal(string subkey) { RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, true); - if (key != null) + if (key is not null) { using (key) { @@ -325,7 +325,7 @@ public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineNam public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName, RegistryView view) { - if (machineName == null) + if (machineName is null) { throw new ArgumentNullException(nameof(machineName)); } @@ -405,7 +405,7 @@ public RegistrySecurity GetAccessControl(AccessControlSections includeSections) public void SetAccessControl(RegistrySecurity registrySecurity) { EnsureWriteable(); - if (registrySecurity == null) + if (registrySecurity is null) { throw new ArgumentNullException(nameof(registrySecurity)); } @@ -449,7 +449,7 @@ public static RegistryKey FromHandle(SafeRegistryHandle handle) public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { - if (handle == null) throw new ArgumentNullException(nameof(handle)); + if (handle is null) throw new ArgumentNullException(nameof(handle)); ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); @@ -559,12 +559,12 @@ public void SetValue(string? name, object value) public void SetValue(string? name, object value, RegistryValueKind valueKind) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } - if (name != null && name.Length > MaxValueLength) + if (name is not null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); } @@ -626,7 +626,7 @@ public override string ToString() private static string FixupName(string name) { - Debug.Assert(name != null, "[FixupName]name!=null"); + Debug.Assert(name is not null, "[FixupName]name!=null"); // string.Contains(char) is .NetCore2.1+ specific if (name.IndexOf('\\') == -1) @@ -647,7 +647,7 @@ private static string FixupName(string name) private static void FixupPath(StringBuilder path) { - Debug.Assert(path != null); + Debug.Assert(path is not null); int length = path.Length; bool fixup = false; @@ -690,7 +690,7 @@ private static void FixupPath(StringBuilder path) private void EnsureNotDisposed() { - if (_hkey == null) + if (_hkey is null) { throw new ObjectDisposedException(_keyName, SR.ObjectDisposed_RegKeyClosed); } @@ -724,7 +724,7 @@ private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) private static void ValidateKeyName(string name) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } diff --git a/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs b/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs index ef4047801ab678..0830e09ea24a12 100644 --- a/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs +++ b/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs @@ -331,7 +331,7 @@ private static void AddEventHandler(object key, Delegate? value) lock (s_eventLockObject) { - if (s_handlers == null) + if (s_handlers is null) { s_handlers = new Dictionary>(); EnsureSystemEvents(requireHandle: false); @@ -451,7 +451,7 @@ private void Dispose() } } - if (_consoleHandler != null) + if (_consoleHandler is not null) { Interop.Kernel32.SetConsoleCtrlHandler(_consoleHandler, false); _consoleHandler = null; @@ -463,11 +463,11 @@ private void Dispose() /// private static void EnsureSystemEvents(bool requireHandle) { - if (s_systemEvents == null) + if (s_systemEvents is null) { lock (s_procLockObject) { - if (s_systemEvents == null) + if (s_systemEvents is null) { // If we are creating system events on a thread declared as STA, then // just share the thread. @@ -715,7 +715,7 @@ private unsafe void Initialize() /// private void InvokeMarshaledCallbacks() { - Debug.Assert(s_threadCallbackList != null, "Invoking marshaled callbacks before there are any"); + Debug.Assert(s_threadCallbackList is not null, "Invoking marshaled callbacks before there are any"); Delegate? current = null; lock (s_threadCallbackList!) @@ -727,7 +727,7 @@ private void InvokeMarshaledCallbacks() } // Now invoke on all the queued items. - while (current != null) + while (current is not null) { try { @@ -767,14 +767,14 @@ public static void InvokeOnEventsThread(Delegate method) #if DEBUG int pid; int thread = Interop.User32.GetWindowThreadProcessId(new HandleRef(s_systemEvents, s_systemEvents!._windowHandle), out pid); - Debug.Assert(s_windowThread == null || thread != Interop.Kernel32.GetCurrentThreadId(), "Don't call MarshaledInvoke on the system events thread"); + Debug.Assert(s_windowThread is null || thread != Interop.Kernel32.GetCurrentThreadId(), "Don't call MarshaledInvoke on the system events thread"); #endif - if (s_threadCallbackList == null) + if (s_threadCallbackList is null) { lock (s_eventLockObject) { - if (s_threadCallbackList == null) + if (s_threadCallbackList is null) { s_threadCallbackMessage = Interop.User32.RegisterWindowMessageW("SystemEventsThreadCallbackMessage"); s_threadCallbackList = new Queue(); @@ -996,7 +996,7 @@ private static void RaiseEvent(object key, params object[] args) private static void RaiseEvent(bool checkFinalization, object key, params object[] args) { - Debug.Assert(args != null && args.Length == 2); + Debug.Assert(args is not null && args.Length == 2); // If the AppDomain's unloading, we shouldn't fire SystemEvents other than Shutdown. if (checkFinalization && AppDomain.CurrentDomain.IsFinalizingForUnload()) @@ -1008,20 +1008,20 @@ private static void RaiseEvent(bool checkFinalization, object key, params object lock (s_eventLockObject) { - if (s_handlers != null && s_handlers.ContainsKey(key)) + if (s_handlers is not null && s_handlers.ContainsKey(key)) { List invokeItems = s_handlers[key]; // clone the list so we don't have this type locked and cause // a deadlock if someone tries to modify handlers during an invoke. - if (invokeItems != null) + if (invokeItems is not null) { invokeItemArray = invokeItems.ToArray(); } } } - if (invokeItemArray != null) + if (invokeItemArray is not null) { for (int i = 0; i < invokeItemArray.Length; i++) { @@ -1045,9 +1045,9 @@ private static void RaiseEvent(bool checkFinalization, object key, params object for (int i = 0; i < invokeItemArray.Length; i++) { SystemEventInvokeInfo? info = invokeItemArray[i]; - if (info != null) + if (info is not null) { - if (invokeItems == null) + if (invokeItems is null) { if (!s_handlers!.TryGetValue(key, out invokeItems)) { @@ -1072,7 +1072,7 @@ private static void RemoveEventHandler(object key, Delegate? value) lock (s_eventLockObject) { - if (s_handlers != null && s_handlers.ContainsKey(key)) + if (s_handlers is not null && s_handlers.ContainsKey(key)) { List invokeItems = s_handlers[key]; @@ -1083,14 +1083,14 @@ private static void RemoveEventHandler(object key, Delegate? value) private static void Shutdown() { - if (s_systemEvents != null && s_systemEvents._windowHandle != IntPtr.Zero) + if (s_systemEvents is not null && s_systemEvents._windowHandle != IntPtr.Zero) { lock (s_procLockObject) { - if (s_systemEvents != null) + if (s_systemEvents is not null) { // If we are using system events from another thread, request that it terminate - if (s_windowThread != null) + if (s_windowThread is not null) { s_eventThreadTerminated = new ManualResetEvent(false); @@ -1135,7 +1135,7 @@ private IntPtr WindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam) if (lParam != IntPtr.Zero) { newString = Marshal.PtrToStringUni(lParam); - if (newString != null) + if (newString is not null) { newStringPtr = Marshal.StringToHGlobalUni(newString); } @@ -1305,7 +1305,7 @@ private void WindowThreadProc() } Dispose(); - if (s_eventThreadTerminated != null) + if (s_eventThreadTerminated is not null) { s_eventThreadTerminated.Set(); } @@ -1328,7 +1328,7 @@ public void Invoke(bool checkFinalization, params object[] args) try { // If we didn't get call back invoke directly. - if (_syncContext == null) + if (_syncContext is null) { InvokeCallback(args); } diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index 322da79bf88adc..09d8207e83b34c 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -66,7 +66,7 @@ private int Run(string[] args) else if (ArgumentMatch(arg, "out") || ShortNameArgumentMatch(arg, "o")) { i++; - if (i >= args.Length || codePath != null) + if (i >= args.Length || codePath is not null) { errs.Add(SR.Format(SR.ErrInvalidArgument, arg)); } @@ -94,7 +94,7 @@ private int Run(string[] args) else if (ArgumentMatch(arg, "assembly") || ShortNameArgumentMatch(arg, "a")) { i++; - if (i >= args.Length || assembly != null) + if (i >= args.Length || assembly is not null) { errs.Add(SR.Format(SR.ErrInvalidArgument, arg)); } @@ -140,7 +140,7 @@ private int Run(string[] args) { if (arg.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase) || arg.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase)) { - if (assembly != null) + if (assembly is not null) { errs.Add(SR.Format(SR.ErrInvalidArgument, arg)); } @@ -167,9 +167,9 @@ private int Run(string[] args) } } - if (args.Length == 0 || assembly == null) + if (args.Length == 0 || assembly is null) { - if (assembly == null) + if (assembly is null) { Console.Error.WriteLine(FormatMessage(parsableErrors, false, SR.Format(SR.ErrMissingRequiredArgument, SR.Format(SR.ErrAssembly, "assembly")))); } @@ -211,7 +211,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox Assembly assembly = LoadAssembly(assemblyName, true); Type[] types; - if (typeNames == null || typeNames.Count == 0) + if (typeNames is null || typeNames.Count == 0) { try { @@ -222,7 +222,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox List loadedTypes = new List(); foreach (Type type in typeException.Types) { - if (type != null) + if (type is not null) { loadedTypes.Add(type); } @@ -238,7 +238,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox foreach (string typeName in typeNames) { Type type = assembly.GetType(typeName); - if (type == null) + if (type is null) { Console.Error.WriteLine(FormatMessage(parsableerrors, false, SR.Format(SR.ErrorDetails, SR.Format(SR.ErrLoadType, typeName, assemblyName)))); } @@ -257,7 +257,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox try { - if (type != null) + if (type is not null) { bool isObsolete = false; object[] obsoleteAttributes = type.GetCustomAttributes(typeof(ObsoleteAttribute), false); @@ -300,7 +300,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox var allMappings = (XmlMapping[])mappings.ToArray(typeof(XmlMapping)); bool gac = assembly.GlobalAssemblyCache; - outputDirectory = outputDirectory == null ? (gac ? Environment.CurrentDirectory : Path.GetDirectoryName(assembly.Location)) : outputDirectory; + outputDirectory = outputDirectory is null ? (gac ? Environment.CurrentDirectory : Path.GetDirectoryName(assembly.Location)) : outputDirectory; if (!Directory.Exists(outputDirectory)) { @@ -341,7 +341,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox using (FileStream fs = File.Create(codePath)) { MethodInfo method = typeof(System.Xml.Serialization.XmlSerializer).GetMethod("GenerateSerializer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - if (method == null) + if (method is null) { Console.Error.WriteLine(FormatMessage(parsableerrors: false, warning: false, message: SR.GenerateSerializerNotFound)); } @@ -429,7 +429,7 @@ private void ImportType(Type type, ArrayList mappings, ArrayList importedTypes, return; } - if (xmlTypeMapping != null) + if (xmlTypeMapping is not null) { xmlTypeMapping = importer.ImportTypeMapping(type); mappings.Add(xmlTypeMapping); @@ -442,7 +442,7 @@ private static Assembly LoadAssembly(string assemblyName, bool throwOnFail) Assembly assembly = null; string path = Path.IsPathRooted(assemblyName) ? assemblyName : Path.GetFullPath(assemblyName); assembly = Assembly.LoadFile(path); - if (assembly == null) + if (assembly is null) { throw new InvalidOperationException(SR.Format(SR.ErrLoadAssembly, assemblyName)); } @@ -489,7 +489,7 @@ private static string FormatMessage(bool parsableerrors, bool warning, string co private static void WriteError(Exception e, bool parsableerrors) { Console.Error.WriteLine(FormatMessage(parsableerrors, false, e.Message)); - if (e.InnerException != null) + if (e.InnerException is not null) { WriteError(e.InnerException, parsableerrors); } @@ -498,7 +498,7 @@ private static void WriteError(Exception e, bool parsableerrors) private static void WriteWarning(Exception e, bool parsableerrors) { Console.Out.WriteLine(FormatMessage(parsableerrors, true, e.Message)); - if (e.InnerException != null) + if (e.InnerException is not null) { WriteWarning(e.InnerException, parsableerrors); } @@ -511,7 +511,7 @@ private static string GetXmlSerializerAssemblyName(Type type) private static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -520,7 +520,7 @@ private static string GetXmlSerializerAssemblyName(Type type, string defaultName private static string GetTempAssemblyName(AssemblyName parent, string ns) { - return parent.Name + ".XmlSerializers" + (ns == null || ns.Length == 0 ? "" : "." + ns.GetHashCode()); + return parent.Name + ".XmlSerializers" + (ns is null || ns.Length == 0 ? "" : "." + ns.GetHashCode()); } private static void ParseReferences() @@ -586,7 +586,7 @@ private static Assembly SgenAssemblyResolver(object source, ResolveEventArgs e) } catch { } - if (match != null && match.Success) + if (match is not null && match.Success) { int index = match.Index + 1; StringBuilder sb = new StringBuilder(reference); diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index 0d7bc48f361b8f..c86c8b1650fdbe 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -66,7 +66,7 @@ internal CSharpCodeGenerator(IDictionary providerOptions) private string CompilerName => "csc.exe"; - private string CurrentTypeName => _currentClass != null ? _currentClass.Name : "<% unknown %>"; + private string CurrentTypeName => _currentClass is not null ? _currentClass.Name : "<% unknown %>"; private int Indent { @@ -74,15 +74,15 @@ private int Indent set => _output.Indent = value; } - private bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; + private bool IsCurrentInterface => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; - private bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; + private bool IsCurrentClass => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; - private bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; + private bool IsCurrentStruct => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; - private bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; + private bool IsCurrentEnum => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; - private bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; + private bool IsCurrentDelegate => _currentClass is not null && _currentClass is CodeTypeDelegate; private string NullToken => "null"; @@ -220,7 +220,7 @@ private void GenerateArrayCreateExpression(CodeArrayCreateExpression e) Output.Write(GetBaseTypeOutput(e.CreateType)); Output.Write('['); - if (e.SizeExpression != null) + if (e.SizeExpression is not null) { GenerateExpression(e.SizeExpression); } @@ -286,7 +286,7 @@ private void GenerateCastExpression(CodeCastExpression e) public void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { - if (_output != null) + if (_output is not null) { throw new InvalidOperationException(SR.CodeGenReentrance); } @@ -343,9 +343,9 @@ private void GenerateEvents(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberEvent imp = (CodeMemberEvent)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateEvent(imp, e); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -372,9 +372,9 @@ private void GenerateFields(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberField imp = (CodeMemberField)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateField(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -385,7 +385,7 @@ private void GenerateFields(CodeTypeDeclaration e) private void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -443,9 +443,9 @@ private void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { GenerateDirectives(e.StartDirectives); - if (e.LinePragma != null) GenerateLinePragmaStart(e.LinePragma); + if (e.LinePragma is not null) GenerateLinePragmaStart(e.LinePragma); Output.WriteLine(e.Value); - if (e.LinePragma != null) GenerateLinePragmaEnd(e.LinePragma); + if (e.LinePragma is not null) GenerateLinePragmaEnd(e.LinePragma); if (e.EndDirectives.Count > 0) { @@ -468,7 +468,7 @@ private void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e) private void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { if (e.TargetObject is CodeBinaryOperatorExpression) { @@ -493,7 +493,7 @@ private void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) private bool GetUserData(CodeObject e, string property, bool defaultValue) { object o = e.UserData[property]; - if (o != null && o is bool) + if (o is not null && o is bool) { return (bool)o; } @@ -518,7 +518,7 @@ private void GenerateNamespace(CodeNamespace e) private void GenerateStatement(CodeStatement e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -528,7 +528,7 @@ private void GenerateStatement(CodeStatement e) GenerateDirectives(e.StartDirectives); } - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaStart(e.LinePragma); } @@ -603,7 +603,7 @@ private void GenerateStatement(CodeStatement e) throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaEnd(e.LinePragma); } @@ -625,15 +625,15 @@ private void GenerateNamespaceImports(CodeNamespace e) { foreach (CodeNamespaceImport imp in e.Imports) { - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateNamespaceImport(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); } } private void GenerateEventReferenceExpression(CodeEventReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -643,7 +643,7 @@ private void GenerateEventReferenceExpression(CodeEventReferenceExpression e) private void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); } @@ -688,7 +688,7 @@ private void GeneratePrimitiveExpression(CodePrimitiveExpression e) Output.Write(((ulong)e.Value).ToString(CultureInfo.InvariantCulture)); Output.Write("ul"); } - else if (e.Value == null) + else if (e.Value is null) { Output.Write(NullToken); } @@ -790,7 +790,7 @@ private void GeneratePrimitiveChar(char c) private void AppendEscapedChar(StringBuilder b, char value) { - if (b == null) + if (b is null) { Output.Write("\\u"); Output.Write(((int)value).ToString("X4", CultureInfo.InvariantCulture)); @@ -838,7 +838,7 @@ private void GenerateIterationStatement(CodeIterationStatement e) private void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e) { Output.Write("throw"); - if (e.ToThrow != null) + if (e.ToThrow is not null) { Output.Write(' '); GenerateExpression(e.ToThrow); @@ -886,7 +886,7 @@ private void GenerateComment(CodeComment e) private void GenerateCommentStatement(CodeCommentStatement e) { - if (e.Comment == null) + if (e.Comment is null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); } @@ -904,7 +904,7 @@ private void GenerateCommentStatements(CodeCommentStatementCollection e) private void GenerateMethodReturnStatement(CodeMethodReturnStatement e) { Output.Write("return"); - if (e.Expression != null) + if (e.Expression is not null) { Output.Write(' '); GenerateExpression(e.Expression); @@ -1042,7 +1042,7 @@ private void GenerateLabeledStatement(CodeLabeledStatement e) Output.Write(e.Label); Output.WriteLine(':'); Indent++; - if (e.Statement != null) + if (e.Statement is not null) { GenerateStatement(e.Statement); } @@ -1051,7 +1051,7 @@ private void GenerateLabeledStatement(CodeLabeledStatement e) private void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e) { OutputTypeNamePair(e.Type, e.Name); - if (e.InitExpression != null) + if (e.InitExpression is not null) { Output.Write(" = "); GenerateExpression(e.InitExpression); @@ -1089,13 +1089,13 @@ private void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) GenerateAttributes(e.CustomAttributes); } - if (e.PrivateImplementationType == null) + if (e.PrivateImplementationType is null) { OutputMemberAccessModifier(e.Attributes); } Output.Write("event "); string name = e.Name; - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { name = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false) + "." + name; } @@ -1207,7 +1207,7 @@ private void GenerateExpression(CodeExpression e) } else { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1229,7 +1229,7 @@ private void GenerateField(CodeMemberField e) GenerateAttributes(e.CustomAttributes); } OutputIdentifier(e.Name); - if (e.InitExpression != null) + if (e.InitExpression is not null) { Output.Write(" = "); GenerateExpression(e.InitExpression); @@ -1247,7 +1247,7 @@ private void GenerateField(CodeMemberField e) OutputVTableModifier(e.Attributes); OutputFieldScopeModifier(e.Attributes); OutputTypeNamePair(e.Type, e.Name); - if (e.InitExpression != null) + if (e.InitExpression is not null) { Output.Write(" = "); GenerateExpression(e.InitExpression); @@ -1307,7 +1307,7 @@ private void GenerateMethods(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberMethod imp = (CodeMemberMethod)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); if (current is CodeEntryPointMethod) { GenerateEntryPointMethod((CodeEntryPointMethod)current, e); @@ -1316,7 +1316,7 @@ private void GenerateMethods(CodeTypeDeclaration e) { GenerateMethod(imp, e); } - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -1340,7 +1340,7 @@ private void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c) if (!IsCurrentInterface) { - if (e.PrivateImplementationType == null) + if (e.PrivateImplementationType is null) { OutputMemberAccessModifier(e.Attributes); OutputVTableModifier(e.Attributes); @@ -1354,7 +1354,7 @@ private void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c) } OutputType(e.ReturnType); Output.Write(' '); - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { Output.Write(GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false)); Output.Write('.'); @@ -1404,9 +1404,9 @@ private void GenerateProperties(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberProperty imp = (CodeMemberProperty)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateProperty(imp, e); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -1426,7 +1426,7 @@ private void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c) if (!IsCurrentInterface) { - if (e.PrivateImplementationType == null) + if (e.PrivateImplementationType is null) { OutputMemberAccessModifier(e.Attributes); OutputVTableModifier(e.Attributes); @@ -1440,7 +1440,7 @@ private void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c) OutputType(e.Type); Output.Write(' '); - if (e.PrivateImplementationType != null && !IsCurrentInterface) + if (e.PrivateImplementationType is not null && !IsCurrentInterface) { Output.Write(GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false)); Output.Write('.'); @@ -1690,7 +1690,7 @@ private void OutputFieldScopeModifier(MemberAttributes attributes) private void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -1716,9 +1716,9 @@ private void GenerateConstructors(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeConstructor imp = (CodeConstructor)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateConstructor(imp, e); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -1815,7 +1815,7 @@ private void GenerateType(CodeTypeDeclaration e) GenerateCommentStatements(e.Comments); - if (e.LinePragma != null) GenerateLinePragmaStart(e.LinePragma); + if (e.LinePragma is not null) GenerateLinePragmaStart(e.LinePragma); GenerateTypeStart(e); @@ -1848,7 +1848,7 @@ private void GenerateType(CodeTypeDeclaration e) _currentClass = e; GenerateTypeEnd(e); - if (e.LinePragma != null) GenerateLinePragmaEnd(e.LinePragma); + if (e.LinePragma is not null) GenerateLinePragmaEnd(e.LinePragma); if (e.EndDirectives.Count > 0) { @@ -1950,7 +1950,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla GenerateCommentStatements(member.Comments); - if (member.LinePragma != null) + if (member.LinePragma is not null) { GenerateLinePragmaStart(member.LinePragma); } @@ -2005,7 +2005,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla Output.WriteLine(); } - if (member.LinePragma != null) + if (member.LinePragma is not null) { GenerateLinePragmaEnd(member.LinePragma); } @@ -2034,9 +2034,9 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeTypeConstructor imp = (CodeTypeConstructor)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -2065,7 +2065,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeSnippetTypeMember imp = (CodeSnippetTypeMember)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging @@ -2078,7 +2078,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) // Restore the indent Indent = savedIndent; - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -2497,7 +2497,7 @@ private void GenerateChecksumPragma(CodeChecksumPragma checksumPragma) Output.Write("\" \""); Output.Write(checksumPragma.ChecksumAlgorithmId.ToString("B", CultureInfo.InvariantCulture)); Output.Write("\" \""); - if (checksumPragma.ChecksumData != null) + if (checksumPragma.ChecksumData is not null) { foreach (byte b in checksumPragma.ChecksumData) { @@ -2569,12 +2569,12 @@ private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, s } GenerateAttributeDeclarationsStart(attributes); - if (prefix != null) + if (prefix is not null) { Output.Write(prefix); } - if (current.AttributeType != null) + if (current.AttributeType is not null) { Output.Write(GetTypeOutput(current.AttributeType)); } @@ -2609,7 +2609,7 @@ private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, s if (paramArray) { - if (prefix != null) + if (prefix is not null) { Output.Write(prefix); } @@ -2669,7 +2669,7 @@ public void ValidateIdentifier(string value) public string CreateValidIdentifier(string name) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -2689,7 +2689,7 @@ public string CreateValidIdentifier(string name) public string CreateEscapedIdentifier(string name) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -2839,13 +2839,13 @@ public string GetTypeOutput(CodeTypeReference typeRef) string s = string.Empty; CodeTypeReference baseTypeRef = typeRef; - while (baseTypeRef.ArrayElementType != null) + while (baseTypeRef.ArrayElementType is not null) { baseTypeRef = baseTypeRef.ArrayElementType; } s += GetBaseTypeOutput(baseTypeRef); - while (typeRef != null && typeRef.ArrayRank > 0) + while (typeRef is not null && typeRef.ArrayRank > 0) { char[] results = new char[typeRef.ArrayRank + 1]; results[0] = '['; @@ -2876,7 +2876,7 @@ private void OutputStartingBrace() CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -2893,7 +2893,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -2910,7 +2910,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -2927,7 +2927,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -2944,11 +2944,11 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (fileNames == null) + if (fileNames is null) { throw new ArgumentNullException(nameof(fileNames)); } @@ -2972,7 +2972,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -2989,7 +2989,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt private CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -3000,11 +3000,11 @@ private CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) private CompilerResults FromFile(CompilerParameters options, string fileName) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (fileName == null) + if (fileName is null) { throw new ArgumentNullException(nameof(fileName)); } @@ -3018,7 +3018,7 @@ private CompilerResults FromFile(CompilerParameters options, string fileName) private CompilerResults FromSource(CompilerParameters options, string source) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -3028,11 +3028,11 @@ private CompilerResults FromSource(CompilerParameters options, string source) private CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (ea == null) + if (ea is null) { throw new ArgumentNullException(nameof(ea)); } @@ -3041,7 +3041,7 @@ private CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit for (int i = 0; i < ea.Length; i++) { - if (ea[i] == null) + if (ea[i] is null) { continue; // the other two batch methods just work if one element is null, so we'll match that. } @@ -3075,11 +3075,11 @@ private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompile private CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (sources == null) + if (sources is null) { throw new ArgumentNullException(nameof(sources)); } @@ -3103,7 +3103,7 @@ private CompilerResults FromSourceBatch(CompilerParameters options, string[] sou private static string JoinStringArray(string[] sa, string separator) { - if (sa == null || sa.Length == 0) + if (sa is null || sa.Length == 0) { return string.Empty; } @@ -3131,11 +3131,11 @@ private static string JoinStringArray(string[] sa, string separator) void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -3159,11 +3159,11 @@ void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, Co void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -3187,11 +3187,11 @@ void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, C void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -3222,11 +3222,11 @@ void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -3250,11 +3250,11 @@ void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, Cod void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs index 796a01ea8df91b..8ac1514927125d 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs @@ -22,7 +22,7 @@ public CSharpCodeProvider() public CSharpCodeProvider(IDictionary providerOptions) { - if (providerOptions == null) + if (providerOptions is null) { throw new ArgumentNullException(nameof(providerOptions)); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs index 23371016fa05b6..e075787cdfe78d 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs @@ -19,7 +19,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string name = value as string; - if (name != null) + if (name is not null) { string[] names = Names; for (int i = 0; i < names.Length; i++) @@ -36,7 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs index 028476723aedbe..e6b13418c01b2e 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs @@ -432,7 +432,7 @@ private void OutputAttributes(CodeAttributeDeclarationCollection attributes, boo Output.Write(prefix); } - if (current.AttributeType != null) + if (current.AttributeType is not null) { Output.Write(GetTypeOutput(current.AttributeType)); } @@ -648,12 +648,12 @@ protected override void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpre } // "o <> nothing" should be "not o is nothing" - if (e.Right is CodePrimitiveExpression && ((CodePrimitiveExpression)e.Right).Value == null) + if (e.Right is CodePrimitiveExpression && ((CodePrimitiveExpression)e.Right).Value is null) { GenerateNotIsNullExpression(e.Left); return; } - if (e.Left is CodePrimitiveExpression && ((CodePrimitiveExpression)e.Left).Value == null) + if (e.Left is CodePrimitiveExpression && ((CodePrimitiveExpression)e.Left).Value is null) { GenerateNotIsNullExpression(e.Right); return; @@ -768,7 +768,7 @@ protected override void OutputTypeNamePair(CodeTypeReference typeRef, string nam private string GetArrayPostfix(CodeTypeReference typeRef) { string s = ""; - if (typeRef.ArrayElementType != null) + if (typeRef.ArrayElementType is not null) { // Recurse up s = GetArrayPostfix(typeRef.ArrayElementType); @@ -846,7 +846,7 @@ protected override void GeneratePrimitiveExpression(CodePrimitiveExpression e) protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e) { Output.Write("Throw"); - if (e.ToThrow != null) + if (e.ToThrow is not null) { Output.Write(' '); GenerateExpression(e.ToThrow); @@ -892,7 +892,7 @@ protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression } // The tricky thing is we need to declare the size - 1 - if (e.SizeExpression != null) + if (e.SizeExpression is not null) { Output.Write('('); GenerateExpression(e.SizeExpression); @@ -941,7 +941,7 @@ protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpre protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -1075,7 +1075,7 @@ protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpressio protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -1094,7 +1094,7 @@ protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExp protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { bool localReference = (e.TargetObject is CodeThisReferenceExpression); GenerateExpression(e.TargetObject); @@ -1116,7 +1116,7 @@ protected override void GenerateEventReferenceExpression(CodeEventReferenceExpre private void GenerateFormalEventReferenceExpression(CodeEventReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { // Visual Basic Compiler does not like the me reference like this. if (!(e.TargetObject is CodeThisReferenceExpression)) @@ -1130,7 +1130,7 @@ private void GenerateFormalEventReferenceExpression(CodeEventReferenceExpression protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { if (e.TargetObject is CodeEventReferenceExpression) { @@ -1190,7 +1190,7 @@ protected override void GenerateExpressionStatement(CodeExpressionStatement e) private bool IsDocComment(CodeCommentStatement comment) { - return ((comment != null) && (comment.Comment != null) && comment.Comment.DocComment); + return ((comment is not null) && (comment.Comment is not null) && comment.Comment.DocComment); } protected override void GenerateCommentStatements(CodeCommentStatementCollection e) @@ -1250,7 +1250,7 @@ protected override void GenerateComment(CodeComment e) protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e) { - if (e.Expression != null) + if (e.Expression is not null) { Output.Write("Return "); GenerateExpression(e.Expression); @@ -1354,7 +1354,7 @@ protected override void GenerateLabeledStatement(CodeLabeledStatement e) Output.Write(e.Label); Output.WriteLine(':'); Indent++; - if (e.Statement != null) + if (e.Statement is not null) { GenerateStatement(e.Statement); } @@ -1367,16 +1367,16 @@ protected override void GenerateVariableDeclarationStatement(CodeVariableDeclara Output.Write("Dim "); CodeTypeReference typeRef = e.Type; - if (typeRef.ArrayRank == 1 && e.InitExpression != null) + if (typeRef.ArrayRank == 1 && e.InitExpression is not null) { CodeArrayCreateExpression eAsArrayCreate = e.InitExpression as CodeArrayCreateExpression; - if (eAsArrayCreate != null && eAsArrayCreate.Initializers.Count == 0) + if (eAsArrayCreate is not null && eAsArrayCreate.Initializers.Count == 0) { doInit = false; OutputIdentifier(e.Name); Output.Write('('); - if (eAsArrayCreate.SizeExpression != null) + if (eAsArrayCreate.SizeExpression is not null) { Output.Write('('); GenerateExpression(eAsArrayCreate.SizeExpression); @@ -1389,7 +1389,7 @@ protected override void GenerateVariableDeclarationStatement(CodeVariableDeclara Output.Write(')'); - if (typeRef.ArrayElementType != null) + if (typeRef.ArrayElementType is not null) OutputArrayPostfix(typeRef.ArrayElementType); Output.Write(" As "); @@ -1401,7 +1401,7 @@ protected override void GenerateVariableDeclarationStatement(CodeVariableDeclara else OutputTypeNamePair(e.Type, e.Name); - if (doInit && e.InitExpression != null) + if (doInit && e.InitExpression is not null) { Output.Write(" = "); GenerateExpression(e.InitExpression); @@ -1435,7 +1435,7 @@ protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) } string eventName = e.Name; - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { string impl = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false); impl = impl.Replace('.', '_'); @@ -1465,7 +1465,7 @@ protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) OutputIdentifier(eventName); } } - else if (e.PrivateImplementationType != null) + else if (e.PrivateImplementationType is not null) { Output.Write(" Implements "); OutputType(e.PrivateImplementationType); @@ -1488,7 +1488,7 @@ protected override void GenerateField(CodeMemberField e) } OutputIdentifier(e.Name); - if (e.InitExpression != null) + if (e.InitExpression is not null) { Output.Write(" = "); GenerateExpression(e.InitExpression); @@ -1512,7 +1512,7 @@ protected override void GenerateField(CodeMemberField e) } OutputTypeNamePair(e.Type, e.Name); - if (e.InitExpression != null) + if (e.InitExpression is not null) { Output.Write(" = "); GenerateExpression(e.InitExpression); @@ -1536,7 +1536,7 @@ private bool MethodIsOverloaded(CodeMemberMethod e, CodeTypeDeclaration c) if (!(current is CodeTypeConstructor) && !(current is CodeConstructor) && meth != e && meth.Name.Equals(e.Name, StringComparison.OrdinalIgnoreCase) - && meth.PrivateImplementationType == null) + && meth.PrivateImplementationType is null) { return true; } @@ -1562,7 +1562,7 @@ protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c // need to change the implements name before doing overloads resolution // string methodName = e.Name; - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { string impl = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false); impl = impl.Replace('.', '_'); @@ -1571,7 +1571,7 @@ protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c if (!IsCurrentInterface) { - if (e.PrivateImplementationType == null) + if (e.PrivateImplementationType is null) { OutputMemberAccessModifier(e.Attributes); if (MethodIsOverloaded(e, c)) @@ -1638,7 +1638,7 @@ protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c OutputIdentifier(methodName); } } - else if (e.PrivateImplementationType != null) + else if (e.PrivateImplementationType is not null) { Output.Write(" Implements "); OutputType(e.PrivateImplementationType); @@ -1696,7 +1696,7 @@ private bool PropertyIsOverloaded(CodeMemberProperty e, CodeTypeDeclaration c) CodeMemberProperty prop = (CodeMemberProperty)current; if (prop != e && prop.Name.Equals(e.Name, StringComparison.OrdinalIgnoreCase) - && prop.PrivateImplementationType == null) + && prop.PrivateImplementationType is null) { return true; } @@ -1715,7 +1715,7 @@ protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclarati } string propName = e.Name; - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { string impl = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false); impl = impl.Replace('.', '_'); @@ -1723,7 +1723,7 @@ protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclarati } if (!IsCurrentInterface) { - if (e.PrivateImplementationType == null) + if (e.PrivateImplementationType is null) { OutputMemberAccessModifier(e.Attributes); if (PropertyIsOverloaded(e, c)) @@ -1785,7 +1785,7 @@ protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclarati OutputIdentifier(propName); } } - else if (e.PrivateImplementationType != null) + else if (e.PrivateImplementationType is not null) { Output.Write(" Implements "); OutputType(e.PrivateImplementationType); @@ -1833,7 +1833,7 @@ protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclarati protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -2144,7 +2144,7 @@ protected override void GenerateNamespace(CodeNamespace e) private bool AllowLateBound(CodeCompileUnit e) { object o = e.UserData["AllowLateBound"]; - if (o != null && o is bool) + if (o is not null && o is bool) { return (bool)o; } @@ -2156,7 +2156,7 @@ private bool AllowLateBound(CodeCompileUnit e) private bool RequireVariableDeclaration(CodeCompileUnit e) { object o = e.UserData["RequireVariableDeclaration"]; - if (o != null && o is bool) + if (o is not null && o is bool) { return (bool)o; } @@ -2166,7 +2166,7 @@ private bool RequireVariableDeclaration(CodeCompileUnit e) private bool GetUserData(CodeObject e, string property, bool defaultValue) { object o = e.UserData[property]; - if (o != null && o is bool) + if (o is not null && o is bool) { return (bool)o; } @@ -2265,7 +2265,7 @@ private void GenerateChecksumPragma(CodeChecksumPragma checksumPragma) Output.Write("\",\""); Output.Write(checksumPragma.ChecksumAlgorithmId.ToString("B", CultureInfo.InvariantCulture)); Output.Write("\",\""); - if (checksumPragma.ChecksumData != null) + if (checksumPragma.ChecksumData is not null) { foreach (byte b in checksumPragma.ChecksumData) { @@ -2507,7 +2507,7 @@ private string GetTypeOutputWithoutArrayPostFix(CodeTypeReference typeRef) { StringBuilder sb = new StringBuilder(); - while (typeRef.ArrayElementType != null) + while (typeRef.ArrayElementType is not null) { typeRef = typeRef.ArrayElementType; } diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs index 4fba75ee9e7d0c..d8ee9e24361873 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs @@ -22,7 +22,7 @@ public VBCodeProvider() public VBCodeProvider(IDictionary providerOptions) { - if (providerOptions == null) + if (providerOptions is null) { throw new ArgumentNullException(nameof(providerOptions)); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs index affa1d3c66c391..056fe7b99f445f 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs @@ -19,7 +19,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string name = value as string; - if (name != null) + if (name is not null) { string[] names = Names; for (int i = 0; i < names.Length; i++) @@ -36,7 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs index 5db624817188ac..e284e13c5ee872 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs @@ -29,7 +29,7 @@ public CodeAttributeArgument this[int index] public void AddRange(CodeAttributeArgument[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeAttributeArgument[] value) public void AddRange(CodeAttributeArgumentCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclaration.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclaration.cs index b04f5398693a4c..feffc26f6ed963 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclaration.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclaration.cs @@ -27,12 +27,12 @@ public CodeAttributeDeclaration(CodeTypeReference attributeType) : this(attribut public CodeAttributeDeclaration(CodeTypeReference attributeType, params CodeAttributeArgument[] arguments) { _attributeType = attributeType; - if (attributeType != null) + if (attributeType is not null) { _name = attributeType.BaseType; } - if (arguments != null) + if (arguments is not null) { Arguments.AddRange(arguments); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs index 942d26368d254e..581867095be7d9 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs @@ -31,7 +31,7 @@ public CodeAttributeDeclaration this[int index] public void AddRange(CodeAttributeDeclaration[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -44,7 +44,7 @@ public void AddRange(CodeAttributeDeclaration[] value) public void AddRange(CodeAttributeDeclarationCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs index a825620e8ec8e9..f84c2c6daa19be 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs @@ -29,7 +29,7 @@ public CodeCatchClause this[int index] public void AddRange(CodeCatchClause[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeCatchClause[] value) public void AddRange(CodeCatchClauseCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs index 8a8dc513818405..82fa21f9d60f81 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs @@ -29,7 +29,7 @@ public CodeCommentStatement this[int index] public void AddRange(CodeCommentStatement[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeCommentStatement[] value) public void AddRange(CodeCommentStatementCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs index 797d978473e9ce..a83e61bd1da1f4 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs @@ -29,7 +29,7 @@ public CodeDirective this[int index] public void AddRange(CodeDirective[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeDirective[] value) public void AddRange(CodeDirectiveCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs index 7b9c731cf69240..81378ae61857ad 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs @@ -29,7 +29,7 @@ public CodeExpression this[int index] public void AddRange(CodeExpression[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeExpression[] value) public void AddRange(CodeExpressionCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs index 10229bd6d53dfc..c749cc2683c529 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs @@ -61,7 +61,7 @@ public CodeTypeReferenceCollection ImplementationTypes { get { - if (_implementationTypes == null) + if (_implementationTypes is null) { _implementationTypes = new CodeTypeReferenceCollection(); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs index ccd0bffe19d2d5..10b54980c9fea2 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs @@ -29,7 +29,7 @@ public CodeNamespace this[int index] public void AddRange(CodeNamespace[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeNamespace[] value) public void AddRange(CodeNamespaceCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs index bb63f182dd5df0..ce6e6e50153912 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs @@ -38,7 +38,7 @@ public void Add(CodeNamespaceImport value) public void AddRange(CodeNamespaceImport[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs index d9ff397330c3cc..1991e01236964b 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs @@ -29,7 +29,7 @@ public CodeParameterDeclarationExpression this[int index] public void AddRange(CodeParameterDeclarationExpression[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeParameterDeclarationExpression[] value) public void AddRange(CodeParameterDeclarationExpressionCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs index 5999b37c7ee5ee..51ceda89b44edc 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs @@ -31,7 +31,7 @@ public CodeStatement this[int index] public void AddRange(CodeStatement[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -44,7 +44,7 @@ public void AddRange(CodeStatement[] value) public void AddRange(CodeStatementCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs index 242506fb267a3b..ceafd0c51eb83a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs @@ -29,7 +29,7 @@ public CodeTypeDeclaration this[int index] public void AddRange(CodeTypeDeclaration[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeTypeDeclaration[] value) public void AddRange(CodeTypeDeclarationCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs index caa36a5130bf2f..2d63d3a87300b6 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs @@ -29,7 +29,7 @@ public CodeTypeMember this[int index] public void AddRange(CodeTypeMember[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CodeTypeMember[] value) public void AddRange(CodeTypeMemberCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs index 8b00ec1c267f5e..1f403870043e9a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs @@ -31,7 +31,7 @@ public CodeTypeParameter this[int index] public void AddRange(CodeTypeParameter[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -44,7 +44,7 @@ public void AddRange(CodeTypeParameter[] value) public void AddRange(CodeTypeParameterCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs index cbd5b6e30c1072..47ae3c315f96dc 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs @@ -10,7 +10,7 @@ public abstract class CodeCompiler : CodeGenerator, ICodeCompiler { CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -27,7 +27,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -44,7 +44,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -61,7 +61,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -78,11 +78,11 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (fileNames == null) + if (fileNames is null) { throw new ArgumentNullException(nameof(fileNames)); } @@ -105,7 +105,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -126,7 +126,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt protected virtual CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -136,11 +136,11 @@ protected virtual CompilerResults FromDom(CompilerParameters options, CodeCompil protected virtual CompilerResults FromFile(CompilerParameters options, string fileName) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (fileName == null) + if (fileName is null) { throw new ArgumentNullException(nameof(fileName)); } @@ -153,7 +153,7 @@ protected virtual CompilerResults FromFile(CompilerParameters options, string fi protected virtual CompilerResults FromSource(CompilerParameters options, string source) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -163,11 +163,11 @@ protected virtual CompilerResults FromSource(CompilerParameters options, string protected virtual CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (ea == null) + if (ea is null) { throw new ArgumentNullException(nameof(ea)); } @@ -176,7 +176,7 @@ protected virtual CompilerResults FromDomBatch(CompilerParameters options, CodeC for (int i = 0; i < ea.Length; i++) { - if (ea[i] == null) + if (ea[i] is null) { continue; // the other two batch methods just work if one element is null, so we'll match that. } @@ -210,11 +210,11 @@ private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompile protected virtual CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (fileNames == null) + if (fileNames is null) { throw new ArgumentNullException(nameof(fileNames)); } @@ -242,11 +242,11 @@ protected virtual string GetResponseFileCmdArgs(CompilerParameters options, stri protected virtual CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } - if (sources == null) + if (sources is null) { throw new ArgumentNullException(nameof(sources)); } @@ -270,7 +270,7 @@ protected virtual CompilerResults FromSourceBatch(CompilerParameters options, st protected static string JoinStringArray(string[] sa, string separator) { - if (sa == null || sa.Length == 0) + if (sa is null || sa.Length == 0) { return string.Empty; } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs index 5274f8160a58eb..c2aae06dec9e14 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs @@ -65,21 +65,21 @@ public static CodeDomProvider CreateProvider(string language) public static string GetLanguageFromExtension(string extension) { CompilerInfo compilerInfo = GetCompilerInfoForExtensionNoThrow(extension); - if (compilerInfo == null) + if (compilerInfo is null) { throw new ConfigurationErrorsException(SR.CodeDomProvider_NotDefined); } return compilerInfo._compilerLanguages[0]; } - public static bool IsDefinedLanguage(string language) => GetCompilerInfoForLanguageNoThrow(language) != null; + public static bool IsDefinedLanguage(string language) => GetCompilerInfoForLanguageNoThrow(language) is not null; - public static bool IsDefinedExtension(string extension) => GetCompilerInfoForExtensionNoThrow(extension) != null; + public static bool IsDefinedExtension(string extension) => GetCompilerInfoForExtensionNoThrow(extension) is not null; public static CompilerInfo GetCompilerInfo(string language) { CompilerInfo compilerInfo = GetCompilerInfoForLanguageNoThrow(language); - if (compilerInfo == null) + if (compilerInfo is null) { throw new ConfigurationErrorsException(SR.CodeDomProvider_NotDefined); } @@ -88,7 +88,7 @@ public static CompilerInfo GetCompilerInfo(string language) private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) { - if (language == null) + if (language is null) { throw new ArgumentNullException(nameof(language)); } @@ -100,7 +100,7 @@ private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) private static CompilerInfo GetCompilerInfoForExtensionNoThrow(string extension) { - if (extension == null) + if (extension is null) { throw new ArgumentNullException(nameof(extension)); } @@ -184,7 +184,7 @@ public virtual CodeCompileUnit Parse(TextReader codeStream) => private ICodeCompiler CreateCompilerHelper() { ICodeCompiler compiler = CreateCompiler(); - if (compiler == null) + if (compiler is null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } @@ -194,7 +194,7 @@ private ICodeCompiler CreateCompilerHelper() private ICodeGenerator CreateGeneratorHelper() { ICodeGenerator generator = CreateGenerator(); - if (generator == null) + if (generator is null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } @@ -204,7 +204,7 @@ private ICodeGenerator CreateGeneratorHelper() private ICodeParser CreateParserHelper() { ICodeParser parser = CreateParser(); - if (parser == null) + if (parser is null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs index 60c0117280cd15..e6aebbc3d8d71b 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs @@ -20,21 +20,21 @@ public abstract class CodeGenerator : ICodeGenerator protected CodeTypeDeclaration CurrentClass => _currentClass; - protected string CurrentTypeName => _currentClass != null ? _currentClass.Name : "<% unknown %>"; + protected string CurrentTypeName => _currentClass is not null ? _currentClass.Name : "<% unknown %>"; protected CodeTypeMember CurrentMember => _currentMember; - protected string CurrentMemberName => _currentMember != null ? _currentMember.Name : "<% unknown %>"; + protected string CurrentMemberName => _currentMember is not null ? _currentMember.Name : "<% unknown %>"; - protected bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; + protected bool IsCurrentInterface => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; - protected bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; + protected bool IsCurrentClass => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; - protected bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; + protected bool IsCurrentStruct => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; - protected bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; + protected bool IsCurrentEnum => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; - protected bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; + protected bool IsCurrentDelegate => _currentClass is not null && _currentClass is CodeTypeDelegate; protected int Indent { @@ -59,7 +59,7 @@ private void GenerateType(CodeTypeDeclaration e) GenerateCommentStatements(e.Comments); - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaStart(e.LinePragma); } @@ -89,7 +89,7 @@ private void GenerateType(CodeTypeDeclaration e) _currentClass = e; GenerateTypeEnd(e); - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaEnd(e.LinePragma); } @@ -129,7 +129,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla GenerateCommentStatements(member.Comments); - if (member.LinePragma != null) + if (member.LinePragma is not null) { GenerateLinePragmaStart(member.LinePragma); } @@ -184,7 +184,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla Output.WriteLine(); } - if (member.LinePragma != null) + if (member.LinePragma is not null) { GenerateLinePragmaEnd(member.LinePragma); } @@ -213,9 +213,9 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeTypeConstructor imp = (CodeTypeConstructor)current; - if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma is not null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -234,7 +234,7 @@ protected void GenerateNamespaces(CodeCompileUnit e) protected void GenerateTypes(CodeNamespace e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -254,11 +254,11 @@ protected void GenerateTypes(CodeNamespace e) void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -282,11 +282,11 @@ void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, Co void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -310,11 +310,11 @@ void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, C void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -345,11 +345,11 @@ void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -373,11 +373,11 @@ void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, Cod void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; - if (_output != null && w != _output.InnerWriter) + if (_output is not null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } - if (_output == null) + if (_output is null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); @@ -400,11 +400,11 @@ void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, Cod public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } - if (_output != null) + if (_output is not null) { throw new InvalidOperationException(SR.CodeGenReentrance); } @@ -453,12 +453,12 @@ private void GenerateConstructors(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeConstructor imp = (CodeConstructor)current; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateConstructor(imp, e); - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -488,12 +488,12 @@ private void GenerateEvents(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberEvent imp = (CodeMemberEvent)current; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateEvent(imp, e); - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -609,7 +609,7 @@ protected void GenerateExpression(CodeExpression e) } else { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -638,12 +638,12 @@ private void GenerateFields(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberField imp = (CodeMemberField)current; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateField(imp); - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -675,7 +675,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeSnippetTypeMember imp = (CodeSnippetTypeMember)current; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } @@ -691,7 +691,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) // Restore the indent Indent = savedIndent; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -712,19 +712,19 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } GenerateDirectives(e.StartDirectives); - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaStart(e.LinePragma); } Output.WriteLine(e.Value); - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaEnd(e.LinePragma); } @@ -753,7 +753,7 @@ private void GenerateMethods(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberMethod imp = (CodeMemberMethod)current; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } @@ -765,7 +765,7 @@ private void GenerateMethods(CodeTypeDeclaration e) { GenerateMethod(imp, e); } - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -802,7 +802,7 @@ protected virtual void GenerateCompileUnit(CodeCompileUnit e) protected virtual void GenerateNamespace(CodeNamespace e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -819,20 +819,20 @@ protected virtual void GenerateNamespace(CodeNamespace e) protected void GenerateNamespaceImports(CodeNamespace e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } foreach (CodeNamespaceImport imp in e.Imports) { - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateNamespaceImport(imp); - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -857,12 +857,12 @@ private void GenerateProperties(CodeTypeDeclaration e) } GenerateCommentStatements(_currentMember.Comments); CodeMemberProperty imp = (CodeMemberProperty)current; - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateProperty(imp, e); - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { GenerateLinePragmaEnd(imp.LinePragma); } @@ -876,7 +876,7 @@ private void GenerateProperties(CodeTypeDeclaration e) protected void GenerateStatement(CodeStatement e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -886,7 +886,7 @@ protected void GenerateStatement(CodeStatement e) GenerateDirectives(e.StartDirectives); } - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaStart(e.LinePragma); } @@ -961,7 +961,7 @@ protected void GenerateStatement(CodeStatement e) throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } - if (e.LinePragma != null) + if (e.LinePragma is not null) { GenerateLinePragmaEnd(e.LinePragma); } @@ -973,7 +973,7 @@ protected void GenerateStatement(CodeStatement e) protected void GenerateStatements(CodeStatementCollection stmts) { - if (stmts == null) + if (stmts is null) { throw new ArgumentNullException(nameof(stmts)); } @@ -986,7 +986,7 @@ protected void GenerateStatements(CodeStatementCollection stmts) protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes) { - if (attributes == null) + if (attributes is null) { throw new ArgumentNullException(nameof(attributes)); } @@ -1033,7 +1033,7 @@ protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationColle protected virtual void OutputAttributeArgument(CodeAttributeArgument arg) { - if (arg == null) + if (arg is null) { throw new ArgumentNullException(nameof(arg)); } @@ -1289,7 +1289,7 @@ protected virtual void OutputOperator(CodeBinaryOperatorType op) protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters) { - if (parameters == null) + if (parameters is null) { throw new ArgumentNullException(nameof(parameters)); } @@ -1327,7 +1327,7 @@ protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollec protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1383,7 +1383,7 @@ protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpres protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1400,7 +1400,7 @@ protected virtual void GenerateParameterDeclarationExpression(CodeParameterDecla protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1411,12 +1411,12 @@ protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } - if (e.Value == null) + if (e.Value is null) { Output.Write(NullToken); } @@ -1491,7 +1491,7 @@ protected virtual void GenerateDefaultValueExpression(CodeDefaultValueExpression protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1501,7 +1501,7 @@ protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpressi protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1516,11 +1516,11 @@ protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) protected abstract void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e); protected virtual void GenerateCommentStatement(CodeCommentStatement e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } - if (e.Comment == null) + if (e.Comment is null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); } @@ -1529,7 +1529,7 @@ protected virtual void GenerateCommentStatement(CodeCommentStatement e) protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1552,7 +1552,7 @@ protected virtual void GenerateCommentStatements(CodeCommentStatementCollection protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1576,7 +1576,7 @@ protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -1589,7 +1589,7 @@ protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGeneratorOptions.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGeneratorOptions.cs index 86384a277f45f7..d792ffa8a58e1b 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGeneratorOptions.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGeneratorOptions.cs @@ -23,7 +23,7 @@ public string IndentString get { object o = _options[nameof(IndentString)]; - return o != null ? (string)o : " "; + return o is not null ? (string)o : " "; } set => _options[nameof(IndentString)] = value; } @@ -33,7 +33,7 @@ public string BracingStyle get { object o = _options[nameof(BracingStyle)]; - return o != null ? (string)o : "Block"; + return o is not null ? (string)o : "Block"; } set => _options[nameof(BracingStyle)] = value; } @@ -43,7 +43,7 @@ public bool ElseOnClosing get { object o = _options[nameof(ElseOnClosing)]; - return o != null ? (bool)o : false; + return o is not null ? (bool)o : false; } set => _options[nameof(ElseOnClosing)] = value; } @@ -53,7 +53,7 @@ public bool BlankLinesBetweenMembers get { object o = _options[nameof(BlankLinesBetweenMembers)]; - return o != null ? (bool)o : true; + return o is not null ? (bool)o : true; } set => _options[nameof(BlankLinesBetweenMembers)] = value; } @@ -63,7 +63,7 @@ public bool VerbatimOrder get { object o = _options[nameof(VerbatimOrder)]; - return o != null ? (bool)o : false; + return o is not null ? (bool)o : false; } set => _options[nameof(VerbatimOrder)] = value; } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs index cd806bc7f5ceea..d93bc452d9f012 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -53,7 +53,7 @@ internal void ValidateIdentifiers(CodeObject e) { ValidateCodeDirective((CodeDirective)e); } - else if (e == null) + else if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -68,7 +68,7 @@ private void ValidateTypeMember(CodeTypeMember e) ValidateCommentStatements(e.Comments); ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); - if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); + if (e.LinePragma is not null) ValidateLinePragmaStart(e.LinePragma); if (e is CodeMemberEvent) { @@ -118,7 +118,7 @@ private void ValidateCodeCompileUnit(CodeCompileUnit e) private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) { - if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); + if (e.LinePragma is not null) ValidateLinePragmaStart(e.LinePragma); } private void ValidateCompileUnitStart(CodeCompileUnit e) @@ -162,7 +162,7 @@ private void ValidateNamespaceImports(CodeNamespace e) { foreach (CodeNamespaceImport imp in e.Imports) { - if (imp.LinePragma != null) + if (imp.LinePragma is not null) { ValidateLinePragmaStart(imp.LinePragma); } @@ -259,7 +259,7 @@ private void ValidateField(CodeMemberField e) ValidateTypeReference(e.Type); } - if (e.InitExpression != null) + if (e.InitExpression is not null) { ValidateExpression(e.InitExpression); } @@ -300,7 +300,7 @@ private void ValidateProperty(CodeMemberProperty e) ValidateTypeReference(e.Type); ValidateTypeReferences(e.ImplementationTypes); - if (e.PrivateImplementationType != null && !IsCurrentInterface) + if (e.PrivateImplementationType is not null && !IsCurrentInterface) { ValidateTypeReference(e.PrivateImplementationType); } @@ -334,7 +334,7 @@ private void ValidateProperty(CodeMemberProperty e) private void ValidateMemberMethod(CodeMemberMethod e) { ValidateCommentStatements(e.Comments); - if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); + if (e.LinePragma is not null) ValidateLinePragmaStart(e.LinePragma); ValidateTypeParameters(e.TypeParameters); ValidateTypeReferences(e.ImplementationTypes); @@ -374,7 +374,7 @@ private void ValidateMethod(CodeMemberMethod e) } ValidateTypeReference(e.ReturnType); - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { ValidateTypeReference(e.PrivateImplementationType); } @@ -435,7 +435,7 @@ private void ValidateComment(CodeComment e) private void ValidateStatement(CodeStatement e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -528,7 +528,7 @@ private void ValidateIterationStatement(CodeIterationStatement e) private void ValidateThrowExceptionStatement(CodeThrowExceptionStatement e) { - if (e.ToThrow != null) + if (e.ToThrow is not null) { ValidateExpression(e.ToThrow); } @@ -536,7 +536,7 @@ private void ValidateThrowExceptionStatement(CodeThrowExceptionStatement e) private void ValidateMethodReturnStatement(CodeMethodReturnStatement e) { - if (e.Expression != null) + if (e.Expression is not null) { ValidateExpression(e.Expression); } @@ -601,7 +601,7 @@ private static void ValidateGotoStatement(CodeGotoStatement e) private void ValidateLabeledStatement(CodeLabeledStatement e) { ValidateIdentifier(e, nameof(e.Label), e.Label); - if (e.Statement != null) + if (e.Statement is not null) { ValidateStatement(e.Statement); } @@ -611,7 +611,7 @@ private void ValidateVariableDeclarationStatement(CodeVariableDeclarationStateme { ValidateTypeReference(e.Type); ValidateIdentifier(e, nameof(e.Name), e.Name); - if (e.InitExpression != null) + if (e.InitExpression is not null) { ValidateExpression(e.InitExpression); } @@ -627,7 +627,7 @@ private void ValidateEvent(CodeMemberEvent e) { ValidateAttributes(e.CustomAttributes); } - if (e.PrivateImplementationType != null) + if (e.PrivateImplementationType is not null) { ValidateTypeReference(e.Type); ValidateIdentifier(e, nameof(e.Name), e.Name); @@ -821,7 +821,7 @@ private void ValidateExpression(CodeExpression e) } else { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -842,7 +842,7 @@ private void ValidateArrayCreateExpression(CodeArrayCreateExpression e) } else { - if (e.SizeExpression != null) + if (e.SizeExpression is not null) { ValidateExpression(e.SizeExpression); } @@ -879,7 +879,7 @@ private void ValidateDelegateCreateExpression(CodeDelegateCreateExpression e) private void ValidateFieldReferenceExpression(CodeFieldReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { ValidateExpression(e.TargetObject); } @@ -926,7 +926,7 @@ private void ValidateMethodInvokeExpression(CodeMethodInvokeExpression e) private void ValidateMethodReferenceExpression(CodeMethodReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { ValidateExpression(e.TargetObject); } @@ -936,7 +936,7 @@ private void ValidateMethodReferenceExpression(CodeMethodReferenceExpression e) private void ValidateEventReferenceExpression(CodeEventReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { ValidateExpression(e.TargetObject); } @@ -945,7 +945,7 @@ private void ValidateEventReferenceExpression(CodeEventReferenceExpression e) private void ValidateDelegateInvokeExpression(CodeDelegateInvokeExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { ValidateExpression(e.TargetObject); } @@ -980,7 +980,7 @@ private void ValidatePrimitiveExpression(CodePrimitiveExpression e) private void ValidatePropertyReferenceExpression(CodePropertyReferenceExpression e) { - if (e.TargetObject != null) + if (e.TargetObject is not null) { ValidateExpression(e.TargetObject); } @@ -1034,8 +1034,8 @@ private static void ValidateRegionDirective(CodeRegionDirective e) throw new ArgumentException(SR.Format(SR.InvalidRegion, e.RegionText), nameof(e)); } - private bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; + private bool IsCurrentInterface => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; - private bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; + private bool IsCurrentEnum => _currentClass is not null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs index 5ececb97f7ade1..91351cb6290873 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs @@ -29,7 +29,7 @@ public CompilerError this[int index] public void AddRange(CompilerError[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -42,7 +42,7 @@ public void AddRange(CompilerError[] value) public void AddRange(CompilerErrorCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs index 84c19410797fde..5aae1c72153772 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs @@ -26,11 +26,11 @@ public Type CodeDomProviderType { get { - if (_type == null) + if (_type is null) { lock (this) { - if (_type == null) + if (_type is null) { _type = Type.GetType(_codeDomProviderTypeName); } @@ -41,7 +41,7 @@ public Type CodeDomProviderType } } - public bool IsCodeDomProviderTypeValid => Type.GetType(_codeDomProviderTypeName) != null; + public bool IsCodeDomProviderTypeValid => Type.GetType(_codeDomProviderTypeName) is not null; public CodeDomProvider CreateProvider() { @@ -49,12 +49,12 @@ public CodeDomProvider CreateProvider() // provider options have been provided then call that and give it the // provider options dictionary. Otherwise call the normal one. - Debug.Assert(_providerOptions != null, "Created CompilerInfo w/ null _providerOptions"); + Debug.Assert(_providerOptions is not null, "Created CompilerInfo w/ null _providerOptions"); if (_providerOptions.Count > 0) { ConstructorInfo ci = CodeDomProviderType.GetConstructor(new Type[] { typeof(IDictionary) }); - if (ci != null) + if (ci is not null) { return (CodeDomProvider)ci.Invoke(new object[] { _providerOptions }); } @@ -65,13 +65,13 @@ public CodeDomProvider CreateProvider() public CodeDomProvider CreateProvider(IDictionary providerOptions) { - if (providerOptions == null) + if (providerOptions is null) { throw new ArgumentNullException(nameof(providerOptions)); } ConstructorInfo constructor = CodeDomProviderType.GetConstructor(new Type[] { typeof(IDictionary) }); - if (constructor != null) + if (constructor is not null) { return (CodeDomProvider)constructor.Invoke(new object[] { providerOptions }); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs index 596d9b5be515f9..6e7d7f3e681d72 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs @@ -25,7 +25,7 @@ public CompilerParameters(string[] assemblyNames, string outputName) : public CompilerParameters(string[] assemblyNames, string outputName, bool includeDebugInformation) { - if (assemblyNames != null) + if (assemblyNames is not null) { ReferencedAssemblies.AddRange(assemblyNames); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerResults.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerResults.cs index c22fb20f3990d7..9015bb8d370aa4 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerResults.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerResults.cs @@ -21,7 +21,7 @@ public Assembly CompiledAssembly { get { - if (_compiledAssembly == null && PathToAssembly != null) + if (_compiledAssembly is null && PathToAssembly is not null) { _compiledAssembly = Assembly.LoadFile(PathToAssembly); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/Executor.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/Executor.cs index 4b2513a6d27520..eaa39886afed02 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/Executor.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/Executor.cs @@ -68,14 +68,14 @@ public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string curre { p.OutputDataReceived += (s, e) => { - if (e.Data != null) + if (e.Data is not null) { outputWriter.WriteLine(e.Data); } }; p.ErrorDataReceived += (s, e) => { - if (e.Data != null) + if (e.Data is not null) { errorWriter.WriteLine(e.Data); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/ExposedTabStringIndentedTextWriter.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/ExposedTabStringIndentedTextWriter.cs index a6b310ce43a875..926eb6c4f78a25 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/ExposedTabStringIndentedTextWriter.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/ExposedTabStringIndentedTextWriter.cs @@ -10,7 +10,7 @@ internal sealed class ExposedTabStringIndentedTextWriter : IndentedTextWriter { public ExposedTabStringIndentedTextWriter(TextWriter writer, string tabString) : base(writer, tabString) { - Debug.Assert(tabString != null, "CodeGeneratorOptions can never have a null TabString"); + Debug.Assert(tabString is not null, "CodeGeneratorOptions can never have a null TabString"); TabString = tabString; } @@ -42,7 +42,7 @@ internal string IndentationString { get { - if (_s == null) + if (_s is null) { string tabString = _writer.TabString; diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs index 2b3d6c08fff8b4..09435a84a3a9dc 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs @@ -20,7 +20,7 @@ public CodeMethodReferenceExpression(CodeExpression targetObject, string methodN { TargetObject = targetObject; MethodName = methodName; - if (typeParameters != null && typeParameters.Length > 0) + if (typeParameters is not null && typeParameters.Length > 0) { TypeArguments.AddRange(typeParameters); } diff --git a/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs b/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs index 2899e28bdb2b77..3f00c3a28af4dd 100644 --- a/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs +++ b/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs @@ -23,7 +23,7 @@ internal static bool Contains(string[][] lookupTable, string value, bool ignoreC } string[] subArray = lookupTable[length - 1]; - if (subArray == null) + if (subArray is null) { return false; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs index e44135512ed8e5..33b5cc1c157c75 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs @@ -25,7 +25,7 @@ public static void TryAdd(T item) public static bool TryTake([MaybeNullWhen(false)] out T item) { Stack> localStack = ThreadLocalStack; - if (localStack != null && localStack.Count > 0) + if (localStack is not null && localStack.Count > 0) { item = localStack.Pop().Value; return true; @@ -41,7 +41,7 @@ private static Stack> ThreadLocalStack { // Ensure the [ThreadStatic] is initialized to a dictionary Dictionary? typesToStacks = AllocFreeConcurrentStack.t_stacks; - if (typesToStacks == null) + if (typesToStacks is null) { AllocFreeConcurrentStack.t_stacks = typesToStacks = new Dictionary(); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/DisposableEnumeratorAdapter_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/DisposableEnumeratorAdapter_2.cs index 1e8d4f5638b565..873486cb2dedfd 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/DisposableEnumeratorAdapter_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/DisposableEnumeratorAdapter_2.cs @@ -55,7 +55,7 @@ internal DisposableEnumeratorAdapter(IEnumerator enumerator) /// public T Current { - get { return _enumeratorObject != null ? _enumeratorObject.Current : _enumeratorStruct.Current; } + get { return _enumeratorObject is not null ? _enumeratorObject.Current : _enumeratorStruct.Current; } } /// @@ -63,7 +63,7 @@ public T Current /// public bool MoveNext() { - return _enumeratorObject != null ? _enumeratorObject.MoveNext() : _enumeratorStruct.MoveNext(); + return _enumeratorObject is not null ? _enumeratorObject.MoveNext() : _enumeratorStruct.MoveNext(); } /// @@ -71,7 +71,7 @@ public bool MoveNext() /// public void Dispose() { - if (_enumeratorObject != null) + if (_enumeratorObject is not null) { _enumeratorObject.Dispose(); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs index 5558be5bfdbdee..5012b9b6a234a9 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs @@ -96,10 +96,10 @@ public static ImmutableArray CreateRange(IEnumerable items) // Note that this allows for automatic upcasting and downcasting of arrays // where the CLR allows it. var immutableArray = items as IImmutableArray; - if (immutableArray != null) + if (immutableArray is not null) { Array? array = immutableArray.Array; - if (array == null) + if (array is null) { throw new InvalidOperationException(SR.InvalidOperationOnDefaultArray); } @@ -136,7 +136,7 @@ public static ImmutableArray CreateRange(IEnumerable items) /// An immutable array. public static ImmutableArray Create(params T[]? items) { - if (items == null || items.Length == 0) + if (items is null || items.Length == 0) { return ImmutableArray.Empty; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs index 87f6e75131c2a3..1cd7f028466998 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs @@ -341,7 +341,7 @@ public void AddRange(ImmutableArray items, int length) { Requires.Range(length >= 0, nameof(length)); - if (items.array != null) + if (items.array is not null) { this.AddRange(items.array, length); } @@ -353,7 +353,7 @@ public void AddRange(ImmutableArray items, int length) /// The items. public void AddRange(ImmutableArray items) where TDerived : T { - if (items.array != null) + if (items.array is not null) { this.AddRange(items.array); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Minimal.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Minimal.cs index f1f14b1c2684a3..04a9fe92b2d002 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Minimal.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Minimal.cs @@ -123,7 +123,7 @@ public T this[int index] [NonVersionable] get { - // We intentionally do not check this.array != null, and throw NullReferenceException + // We intentionally do not check this.array is not null, and throw NullReferenceException // if this is called while uninitialized. // The reason for this is perf. // Length and the indexer must be absolutely trivially implemented for the JIT optimization @@ -140,7 +140,7 @@ public T this[int index] /// A read-only reference to the element at the specified index in the read-only list. public ref readonly T ItemRef(int index) { - // We intentionally do not check this.array != null, and throw NullReferenceException + // We intentionally do not check this.array is not null, and throw NullReferenceException // if this is called while uninitialized. // The reason for this is perf. // Length and the indexer must be absolutely trivially implemented for the JIT optimization @@ -168,7 +168,7 @@ public int Length [NonVersionable] get { - // We intentionally do not check this.array != null, and throw NullReferenceException + // We intentionally do not check this.array is not null, and throw NullReferenceException // if this is called while uninitialized. // The reason for this is perf. // Length and the indexer must be absolutely trivially implemented for the JIT optimization @@ -183,7 +183,7 @@ public int Length [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefault { - get { return this.array == null; } + get { return this.array is null; } } /// @@ -195,7 +195,7 @@ public bool IsDefaultOrEmpty get { var self = this; - return self.array == null || self.array.Length == 0; + return self.array is null || self.array.Length == 0; } } @@ -296,7 +296,7 @@ public Enumerator GetEnumerator() public override int GetHashCode() { var self = this; - return self.array == null ? 0 : self.array.GetHashCode(); + return self.array is null ? 0 : self.array.GetHashCode(); } /// diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs index 60e35e387ec88c..0814e145a82091 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs @@ -672,7 +672,7 @@ public ImmutableArray RemoveAll(Predicate match) { if (match(self.array[i])) { - if (removeIndices == null) + if (removeIndices is null) { removeIndices = new List(); } @@ -681,7 +681,7 @@ public ImmutableArray RemoveAll(Predicate match) } } - return removeIndices != null ? + return removeIndices is not null ? self.RemoveAtRange(removeIndices) : self; } @@ -746,7 +746,7 @@ public ImmutableArray Sort(int index, int count, IComparer? comparer) // 0 and 1 element arrays don't need to be sorted. if (count > 1) { - if (comparer == null) + if (comparer is null) { comparer = Comparer.Default; } @@ -784,7 +784,7 @@ public ImmutableArray Sort(int index, int count, IComparer? comparer) public IEnumerable OfType() { var self = this; - if (self.array == null || self.array.Length == 0) + if (self.array is null || self.array.Length == 0) { return Enumerable.Empty(); } @@ -1124,17 +1124,17 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { var self = this; Array? otherArray = other as Array; - if (otherArray == null) + if (otherArray is null) { if (other is IImmutableArray theirs) { otherArray = theirs.Array; - if (self.array == null && otherArray == null) + if (self.array is null && otherArray is null) { return true; } - else if (self.array == null) + else if (self.array is null) { return false; } @@ -1154,7 +1154,7 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { var self = this; IStructuralEquatable? ours = self.array; - return ours != null ? ours.GetHashCode(comparer) : self.GetHashCode(); + return ours is not null ? ours.GetHashCode(comparer) : self.GetHashCode(); } /// @@ -1174,27 +1174,27 @@ int IStructuralComparable.CompareTo(object? other, IComparer comparer) { var self = this; Array? otherArray = other as Array; - if (otherArray == null) + if (otherArray is null) { if (other is IImmutableArray theirs) { otherArray = theirs.Array; - if (self.array == null && otherArray == null) + if (self.array is null && otherArray is null) { return 0; } - else if (self.array == null ^ otherArray == null) + else if (self.array is null ^ otherArray is null) { throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other)); } } } - if (otherArray != null) + if (otherArray is not null) { IStructuralComparable? ours = self.array; - if (ours == null) + if (ours is null) { throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other)); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary.cs index 53e6a030761e43..198dde65a9d488 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary.cs @@ -233,7 +233,7 @@ public static ImmutableDictionary ToImmutableDictionary; - if (existingDictionary != null) + if (existingDictionary is not null) { return existingDictionary.WithComparers(keyComparer, valueComparer); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs index eb94a5bfd27c07..fc30d0883ae2a4 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs @@ -255,7 +255,7 @@ object ICollection.SyncRoot { get { - if (_syncRoot == null) + if (_syncRoot is null) { Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } @@ -505,7 +505,7 @@ public ImmutableDictionary ToImmutable() // Creating an instance of ImmutableSortedMap with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) + if (_immutable is null) { _immutable = ImmutableDictionary.Wrap(_root, _comparers, _count); } @@ -748,7 +748,7 @@ public KeyValuePair[] Contents { get { - if (_contents == null) + if (_contents is null) { _contents = _map.ToArray(_map.Count); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Enumerator.cs index 88754c32ae8ca2..38eda6eb727705 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Enumerator.cs @@ -45,7 +45,7 @@ internal Enumerator(SortedInt32KeyNode root, Builder? builder = null _builder = builder; _mapEnumerator = new SortedInt32KeyNode.Enumerator(root); _bucketEnumerator = default(HashBucket.Enumerator); - _enumeratingBuilderVersion = builder != null ? builder.Version : -1; + _enumeratingBuilderVersion = builder is not null ? builder.Version : -1; } /// @@ -99,7 +99,7 @@ public bool MoveNext() /// The collection was modified after the enumerator was created. public void Reset() { - _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; + _enumeratingBuilderVersion = _builder is not null ? _builder.Version : -1; _mapEnumerator.Reset(); // Resetting the bucket enumerator is pointless because we'll start on a new bucket later anyway. @@ -122,7 +122,7 @@ public void Dispose() /// Thrown if the collection has changed. private void ThrowIfChanged() { - if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + if (_builder is not null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs index 77e65ecf25dd5a..3c947f1e72d5b4 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs @@ -50,7 +50,7 @@ private HashBucket(KeyValuePair firstElement, ImmutableList internal bool IsEmpty { - get { return _additionalElements == null; } + get { return _additionalElements is null; } } /// @@ -337,7 +337,7 @@ internal bool TryGetKey(TKey equalKey, Comparers comparers, out TKey actualKey) /// internal void Freeze() { - if (_additionalElements != null) + if (_additionalElements is not null) { _additionalElements.Freeze(); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs index 346fdc1d1160e3..6aa32499ae0889 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs @@ -424,12 +424,12 @@ public bool TryGetKey(TKey equalKey, out TKey actualKey) /// public ImmutableDictionary WithComparers(IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) { - if (keyComparer == null) + if (keyComparer is null) { keyComparer = EqualityComparer.Default; } - if (valueComparer == null) + if (valueComparer is null) { valueComparer = EqualityComparer.Default; } @@ -851,7 +851,7 @@ private static ImmutableDictionary EmptyWithComparers(Comparers co private static bool TryCastToImmutableMap(IEnumerable> sequence, [NotNullWhen(true)] out ImmutableDictionary? other) { other = sequence as ImmutableDictionary; - if (other != null) + if (other is not null) { return true; } @@ -1038,7 +1038,7 @@ private static ImmutableDictionary Wrap(SortedInt32KeyNodeThe immutable collection. private ImmutableDictionary Wrap(SortedInt32KeyNode? root, int adjustedCountIfDifferentRoot) { - if (root == null) + if (root is null) { return this.Clear(); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs index 93efe0f90f1727..43963cecc14dcb 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs @@ -98,8 +98,8 @@ internal static int GetCount(ref IEnumerable sequence) /// internal static bool TryCopyTo(this IEnumerable sequence, T[] array, int arrayIndex) { - Debug.Assert(sequence != null); - Debug.Assert(array != null); + Debug.Assert(sequence is not null); + Debug.Assert(array is not null); Debug.Assert(arrayIndex >= 0 && arrayIndex <= array.Length); // IList is the GCD of what the following types implement. diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs index 34b40e4a83eee6..e2fa4088c9ba65 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs @@ -19,7 +19,7 @@ internal static bool IsValueType() #if NETCOREAPP return typeof(T).IsValueType; #else - if (default(T) != null) + if (default(T) is not null) { return true; } @@ -46,13 +46,13 @@ internal static IOrderedCollection AsOrderedCollection(this IEnumerable Requires.NotNull(sequence, nameof(sequence)); var orderedCollection = sequence as IOrderedCollection; - if (orderedCollection != null) + if (orderedCollection is not null) { return orderedCollection; } var listOfT = sequence as IList; - if (listOfT != null) + if (listOfT is not null) { return new ListOfTWrapper(listOfT); } @@ -92,7 +92,7 @@ internal static DisposableEnumeratorAdapter GetEnumerableDisposa Requires.NotNull(enumerable, nameof(enumerable)); var strongEnumerable = enumerable as IStrongEnumerable; - if (strongEnumerable != null) + if (strongEnumerable is not null) { return new DisposableEnumeratorAdapter(strongEnumerable.GetEnumerator()); } @@ -197,7 +197,7 @@ public int Count { get { - if (_collection == null) + if (_collection is null) { int count; if (_sequence.TryGetCount(out count)) @@ -219,7 +219,7 @@ public T this[int index] { get { - if (_collection == null) + if (_collection is null) { _collection = _sequence.ToArray(); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs index 2a83032cba7458..d3df1d65f00a93 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs @@ -194,7 +194,7 @@ public ImmutableHashSet ToImmutable() // Creating an instance of ImmutableSortedMap with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) + if (_immutable is null) { _immutable = ImmutableHashSet.Wrap(_root, _equalityComparer, _count); } @@ -210,7 +210,7 @@ public ImmutableHashSet ToImmutable() /// A value indicating whether the search was successful. public bool TryGetValue(T equalValue, out T actualValue) { - int hashCode = equalValue != null ? _equalityComparer.GetHashCode(equalValue) : 0; + int hashCode = equalValue is not null ? _equalityComparer.GetHashCode(equalValue) : 0; if (_root.TryGetValue(hashCode, out HashBucket bucket)) { return bucket.TryExchange(equalValue, _equalityComparer, out actualValue); diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Enumerator.cs index 37a43e40367f1d..b4bbb0700ccd67 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Enumerator.cs @@ -45,7 +45,7 @@ internal Enumerator(SortedInt32KeyNode root, Builder? builder = null _builder = builder; _mapEnumerator = new SortedInt32KeyNode.Enumerator(root); _bucketEnumerator = default(HashBucket.Enumerator); - _enumeratingBuilderVersion = builder != null ? builder.Version : -1; + _enumeratingBuilderVersion = builder is not null ? builder.Version : -1; } /// @@ -99,7 +99,7 @@ public bool MoveNext() /// The collection was modified after the enumerator was created. public void Reset() { - _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; + _enumeratingBuilderVersion = _builder is not null ? _builder.Version : -1; _mapEnumerator.Reset(); // Resetting the bucket enumerator is pointless because we'll start on a new bucket later anyway. @@ -122,7 +122,7 @@ public void Dispose() /// Thrown if the collection has changed. private void ThrowIfChanged() { - if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + if (_builder is not null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs index ca83720330930c..c47c72b389bed5 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs @@ -65,7 +65,7 @@ private HashBucket(T firstElement, ImmutableList.Node? additionalElements = n /// internal bool IsEmpty { - get { return _additionalElements == null; } + get { return _additionalElements is null; } } /// @@ -244,7 +244,7 @@ internal HashBucket Remove(T value, IEqualityComparer equalityComparer, out O /// internal void Freeze() { - if (_additionalElements != null) + if (_additionalElements is not null) { _additionalElements.Freeze(); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs index 411c38a4ea3dfe..068383e192afeb 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs @@ -218,7 +218,7 @@ public ImmutableHashSet Remove(T item) /// public bool TryGetValue(T equalValue, out T actualValue) { - int hashCode = equalValue != null ? _equalityComparer.GetHashCode(equalValue) : 0; + int hashCode = equalValue is not null ? _equalityComparer.GetHashCode(equalValue) : 0; HashBucket bucket; if (_root.TryGetValue(hashCode, out bucket)) { @@ -418,7 +418,7 @@ public bool Contains(T item) /// public ImmutableHashSet WithComparer(IEqualityComparer? equalityComparer) { - if (equalityComparer == null) + if (equalityComparer is null) { equalityComparer = EqualityComparer.Default; } @@ -431,7 +431,7 @@ public ImmutableHashSet WithComparer(IEqualityComparer? equalityComparer) { var result = new ImmutableHashSet(equalityComparer); result = result.Union(this, avoidWithComparer: true); - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } } @@ -620,7 +620,7 @@ private static bool IsSupersetOf(IEnumerable other, MutationInput origin) private static MutationResult Add(T item, MutationInput origin) { OperationResult result; - int hashCode = item != null ? origin.EqualityComparer.GetHashCode(item) : 0; + int hashCode = item is not null ? origin.EqualityComparer.GetHashCode(item) : 0; HashBucket bucket = origin.Root.GetValueOrDefault(hashCode); var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) @@ -639,7 +639,7 @@ private static MutationResult Add(T item, MutationInput origin) private static MutationResult Remove(T item, MutationInput origin) { var result = OperationResult.NoChangeRequired; - int hashCode = item != null ? origin.EqualityComparer.GetHashCode(item) : 0; + int hashCode = item is not null ? origin.EqualityComparer.GetHashCode(item) : 0; HashBucket bucket; var newRoot = origin.Root; if (origin.Root.TryGetValue(hashCode, out bucket)) @@ -661,7 +661,7 @@ private static MutationResult Remove(T item, MutationInput origin) /// private static bool Contains(T item, MutationInput origin) { - int hashCode = item != null ? origin.EqualityComparer.GetHashCode(item) : 0; + int hashCode = item is not null ? origin.EqualityComparer.GetHashCode(item) : 0; HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { @@ -682,7 +682,7 @@ private static MutationResult Union(IEnumerable other, MutationInput origin) var newRoot = origin.Root; foreach (var item in other.GetEnumerableDisposable()) { - int hashCode = item != null ? origin.EqualityComparer.GetHashCode(item) : 0; + int hashCode = item is not null ? origin.EqualityComparer.GetHashCode(item) : 0; HashBucket bucket = newRoot.GetValueOrDefault(hashCode); OperationResult result; var newBucket = bucket.Add(item, origin.EqualityComparer, out result); @@ -793,7 +793,7 @@ private static MutationResult Except(IEnumerable other, IEqualityComparer var newRoot = root; foreach (var item in other.GetEnumerableDisposable()) { - int hashCode = item != null ? equalityComparer.GetHashCode(item) : 0; + int hashCode = item is not null ? equalityComparer.GetHashCode(item) : 0; HashBucket bucket; if (newRoot.TryGetValue(hashCode, out bucket)) { @@ -1014,7 +1014,7 @@ private ImmutableHashSet Union(IEnumerable items, bool avoidWithComparer) // If the items being added actually come from an ImmutableHashSet, // reuse that instance if possible. var other = items as ImmutableHashSet; - if (other != null) + if (other is not null) { return other.WithComparer(this.KeyComparer); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList.cs index 88fc144b23bbb6..33b2802b7dad95 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList.cs @@ -57,7 +57,7 @@ public static class ImmutableList public static ImmutableList ToImmutableList(this IEnumerable source) { var existingList = source as ImmutableList; - if (existingList != null) + if (existingList is not null) { return existingList; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs index ee6b888241d255..15db8984f072ac 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs @@ -930,7 +930,7 @@ public ImmutableList ToImmutable() // Creating an instance of ImmutableList with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) + if (_immutable is null) { _immutable = ImmutableList.WrapNode(this.Root); } @@ -1085,7 +1085,7 @@ object ICollection.SyncRoot { get { - if (_syncRoot == null) + if (_syncRoot is null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } @@ -1130,7 +1130,7 @@ public T[] Contents { get { - if (_cachedContents == null) + if (_cachedContents is null) { _cachedContents = _list.ToArray(_list.Count); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs index a4f0c6516f7195..590ad7eeff58fa 100755 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs @@ -108,7 +108,7 @@ internal Enumerator(Node root, Builder? builder = null, int startIndex = -1, int _count = count == -1 ? root.Count : count; _remainingCount = _count; _reversed = reversed; - _enumeratingBuilderVersion = builder != null ? builder.Version : -1; + _enumeratingBuilderVersion = builder is not null ? builder.Version : -1; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (_count > 0) @@ -133,7 +133,7 @@ public T Current get { this.ThrowIfDisposed(); - if (_current != null) + if (_current is not null) { return _current.Value; } @@ -154,7 +154,7 @@ public void Dispose() { _root = null!; _current = null; - if (_stack != null && _stack.TryUse(ref this, out Stack>? stack)) + if (_stack is not null && _stack.TryUse(ref this, out Stack>? stack)) { stack.ClearFastWhenEmpty(); s_EnumeratingStacks.TryAdd(this, _stack!); @@ -172,7 +172,7 @@ public bool MoveNext() this.ThrowIfDisposed(); this.ThrowIfChanged(); - if (_stack != null) + if (_stack is not null) { var stack = _stack.Use(ref this); if (_remainingCount > 0 && stack.Count > 0) @@ -196,9 +196,9 @@ public void Reset() { this.ThrowIfDisposed(); - _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; + _enumeratingBuilderVersion = _builder is not null ? _builder.Version : -1; _remainingCount = _count; - if (_stack != null) + if (_stack is not null) { this.ResetStack(); } @@ -207,7 +207,7 @@ public void Reset() /// Resets the stack used for enumeration. private void ResetStack() { - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); @@ -254,7 +254,7 @@ private void ThrowIfDisposed() // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. - if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + if (_root is null || (_stack is not null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } @@ -266,7 +266,7 @@ private void ThrowIfDisposed() /// Thrown if the collection has changed. private void ThrowIfChanged() { - if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + if (_builder is not null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } @@ -281,7 +281,7 @@ private void PushNext(Node node) Requires.NotNull(node, nameof(node)); if (!node.IsEmpty) { - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); var stack = _stack.Use(ref this); while (!node.IsEmpty) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs index ef0381384f29ac..48e35934475c78 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs @@ -105,8 +105,8 @@ public bool IsEmpty { get { - Debug.Assert(!(_left == null ^ _right == null)); - return _left == null; + Debug.Assert(!(_left is null ^ _right is null)); + return _left is null; } } @@ -170,7 +170,7 @@ internal T this[int index] get { Requires.Range(index >= 0 && index < this.Count, nameof(index)); - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); if (index < _left._count) { @@ -196,7 +196,7 @@ internal ref readonly T ItemRef(int index) { Requires.Range(index >= 0 && index < this.Count, nameof(index)); - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); if (index < _left._count) { return ref _left.ItemRef(index); @@ -379,7 +379,7 @@ internal Node InsertRange(int index, IEnumerable keys) internal Node RemoveAt(int index) { Requires.Range(index >= 0 && index < this.Count, nameof(index)); - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); Node result = this; if (index == _left._count) @@ -466,7 +466,7 @@ internal Node RemoveAll(Predicate match) enumerator.Dispose(); } - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } @@ -1040,7 +1040,7 @@ internal ImmutableList FindAll(Predicate match) { if (match(item)) { - if (list == null) + if (list is null) { list = new List(); } @@ -1049,7 +1049,7 @@ internal ImmutableList FindAll(Predicate match) } } - return list != null ? + return list is not null ? ImmutableList.CreateRange(list) : ImmutableList.Empty; } @@ -1399,19 +1399,19 @@ private Node BalanceRight() private Node BalanceMany() { Node tree = this; - Debug.Assert(tree._left != null && tree._right != null); + Debug.Assert(tree._left is not null && tree._right is not null); while (!tree.IsBalanced) { if (tree.IsRightHeavy) { tree = tree.BalanceRight(); - Debug.Assert(tree._left != null); + Debug.Assert(tree._left is not null); tree.MutateLeft(tree._left.BalanceMany()); } else { tree = tree.BalanceLeft(); - Debug.Assert(tree._right != null); + Debug.Assert(tree._right is not null); tree.MutateRight(tree._right.BalanceMany()); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.cs index 9597b0a98b6ae3..65bb0be66c1017 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.cs @@ -1103,13 +1103,13 @@ private static ImmutableList WrapNode(Node root) private static bool TryCastToImmutableList(IEnumerable sequence, [NotNullWhen(true)] out ImmutableList? other) { other = sequence as ImmutableList; - if (other != null) + if (other is not null) { return true; } var builder = sequence as Builder; - if (builder != null) + if (builder is not null) { other = builder.ToImmutable(); return true; @@ -1130,7 +1130,7 @@ private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); + return ((value is T) || (value is null && default(T) is null)); } /// diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue.cs index 0a6f76f9456fd5..19f499b1523bd6 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue.cs @@ -41,7 +41,7 @@ public static ImmutableQueue CreateRange(IEnumerable items) Requires.NotNull(items, nameof(items)); var array = items as T[]; - if (array != null) + if (array is not null) { return Create(items: array); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.Enumerator.cs index 844a414a2e8b7d..505fd3bb2f362d 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.Enumerator.cs @@ -50,7 +50,7 @@ public T Current { get { - if (_remainingForwardsStack == null) + if (_remainingForwardsStack is null) { // The initial call to MoveNext has not yet been made. throw new InvalidOperationException(); @@ -78,7 +78,7 @@ public T Current /// A value indicating whether there is another element in the enumeration. public bool MoveNext() { - if (_remainingForwardsStack == null) + if (_remainingForwardsStack is null) { // This is the initial step. // Empty queues have no forwards or backwards @@ -141,7 +141,7 @@ public T Current get { this.ThrowIfDisposed(); - if (_remainingForwardsStack == null) + if (_remainingForwardsStack is null) { // The initial call to MoveNext has not yet been made. throw new InvalidOperationException(); @@ -178,7 +178,7 @@ object IEnumerator.Current public bool MoveNext() { this.ThrowIfDisposed(); - if (_remainingForwardsStack == null) + if (_remainingForwardsStack is null) { // This is the initial step. // Empty queues have no forwards or backwards diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs index 7d6f6b97391d04..060b9de65cdd4b 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs @@ -47,8 +47,8 @@ public sealed partial class ImmutableQueue : IImmutableQueue /// The backwards stack. internal ImmutableQueue(ImmutableStack forwards, ImmutableStack backwards) { - Debug.Assert(forwards != null); - Debug.Assert(backwards != null); + Debug.Assert(forwards is not null); + Debug.Assert(backwards is not null); _forwards = forwards; _backwards = backwards; @@ -109,12 +109,12 @@ private ImmutableStack BackwardsReversed // Although this is a lazy-init pattern, no lock is required because // this instance is immutable otherwise, and a double-assignment from multiple // threads is harmless. - if (_backwardsReversed == null) + if (_backwardsReversed is null) { _backwardsReversed = _backwards.Reverse(); } - Debug.Assert(_backwardsReversed != null); + Debug.Assert(_backwardsReversed is not null); return _backwardsReversed; } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary.cs index 6514d034bc3ce2..8c3c5da193491a 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary.cs @@ -202,7 +202,7 @@ public static ImmutableSortedDictionary ToImmutableSortedDictionar Requires.NotNull(source, nameof(source)); var existingDictionary = source as ImmutableSortedDictionary; - if (existingDictionary != null) + if (existingDictionary is not null) { return existingDictionary.WithComparers(keyComparer, valueComparer); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs index 2f8fafe67b298e..e44c49f2834e48 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs @@ -268,7 +268,7 @@ object ICollection.SyncRoot { get { - if (_syncRoot == null) + if (_syncRoot is null) { Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } @@ -642,7 +642,7 @@ public ImmutableSortedDictionary ToImmutable() // Creating an instance of ImmutableSortedMap with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) + if (_immutable is null) { _immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer); } @@ -685,7 +685,7 @@ public KeyValuePair[] Contents { get { - if (_contents == null) + if (_contents is null) { _contents = _map.ToArray(_map.Count); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs index 9d68df2f94585d..bf39d5ac214a5a 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs @@ -77,7 +77,7 @@ internal Enumerator(Node root, Builder? builder = null) _root = root; _builder = builder; _current = null; - _enumeratingBuilderVersion = builder != null ? builder.Version : -1; + _enumeratingBuilderVersion = builder is not null ? builder.Version : -1; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (!_root.IsEmpty) @@ -99,7 +99,7 @@ public KeyValuePair Current get { this.ThrowIfDisposed(); - if (_current != null) + if (_current is not null) { return _current.Value; } @@ -129,7 +129,7 @@ public void Dispose() { _root = null!; _current = null; - if (_stack != null && _stack.TryUse(ref this, out Stack>? stack)) + if (_stack is not null && _stack.TryUse(ref this, out Stack>? stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack!); @@ -147,7 +147,7 @@ public bool MoveNext() this.ThrowIfDisposed(); this.ThrowIfChanged(); - if (_stack != null) + if (_stack is not null) { var stack = _stack.Use(ref this); if (stack.Count > 0) @@ -170,9 +170,9 @@ public void Reset() { this.ThrowIfDisposed(); - _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; + _enumeratingBuilderVersion = _builder is not null ? _builder.Version : -1; _current = null; - if (_stack != null) + if (_stack is not null) { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); @@ -191,7 +191,7 @@ internal void ThrowIfDisposed() // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. - if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + if (_root is null || (_stack is not null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } @@ -203,7 +203,7 @@ internal void ThrowIfDisposed() /// Thrown if the collection has changed. private void ThrowIfChanged() { - if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + if (_builder is not null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } @@ -216,7 +216,7 @@ private void ThrowIfChanged() private void PushLeft(Node node) { Requires.NotNull(node, nameof(node)); - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); var stack = _stack.Use(ref this); while (!node.IsEmpty) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs index 99173a5b2715cd..7c3e73aebadb8b 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs @@ -101,7 +101,7 @@ public bool IsEmpty { get { - return _left == null; + return _left is null; } } @@ -730,7 +730,7 @@ private Node RemoveRecursive(TKey key, IComparer keyComparer, out bool mut } else { - Debug.Assert(_right != null && _left != null); + Debug.Assert(_right is not null && _left is not null); Node result = this; int compare = keyComparer.Compare(key, _key); if (compare == 0) @@ -798,19 +798,19 @@ private Node RemoveRecursive(TKey key, IComparer keyComparer, out bool mut /// The mutated (or created) node. private Node Mutate(Node? left = null, Node? right = null) { - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); if (_frozen) { return new Node(_key, _value, left ?? _left, right ?? _right); } else { - if (left != null) + if (left is not null) { _left = left; } - if (right != null) + if (right is not null) { _right = right; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs index e734dbba8be0dc..512ac3284449e5 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs @@ -332,12 +332,12 @@ public ImmutableSortedDictionary RemoveRange(IEnumerable key /// public ImmutableSortedDictionary WithComparers(IComparer? keyComparer, IEqualityComparer? valueComparer) { - if (keyComparer == null) + if (keyComparer is null) { keyComparer = Comparer.Default; } - if (valueComparer == null) + if (valueComparer is null) { valueComparer = EqualityComparer.Default; } @@ -772,7 +772,7 @@ private static ImmutableSortedDictionary Wrap(Node root, int count private static bool TryCastToImmutableMap(IEnumerable> sequence, [NotNullWhen(true)] out ImmutableSortedDictionary? other) { other = sequence as ImmutableSortedDictionary; - if (other != null) + if (other is not null) { return true; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs index 2a1c606d12aace..9528a7b2dd7161 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs @@ -445,7 +445,7 @@ public ImmutableSortedSet ToImmutable() // Creating an instance of ImmutableSortedSet with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) + if (_immutable is null) { _immutable = ImmutableSortedSet.Wrap(this.Root, _comparer); } @@ -503,7 +503,7 @@ object ICollection.SyncRoot { get { - if (_syncRoot == null) + if (_syncRoot is null) { Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs index 029815936870c3..105124189c01ad 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs @@ -91,7 +91,7 @@ internal Enumerator(Node root, Builder? builder = null, bool reverse = false) _builder = builder; _current = null; _reverse = reverse; - _enumeratingBuilderVersion = builder != null ? builder.Version : -1; + _enumeratingBuilderVersion = builder is not null ? builder.Version : -1; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (!s_enumeratingStacks.TryTake(this, out _stack)) @@ -116,7 +116,7 @@ public T Current get { this.ThrowIfDisposed(); - if (_current != null) + if (_current is not null) { return _current.Value; } @@ -140,7 +140,7 @@ public void Dispose() { _root = null!; _current = null; - if (_stack != null && _stack.TryUse(ref this, out Stack>? stack)) + if (_stack is not null && _stack.TryUse(ref this, out Stack>? stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack!); @@ -179,7 +179,7 @@ public void Reset() { this.ThrowIfDisposed(); - _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; + _enumeratingBuilderVersion = _builder is not null ? _builder.Version : -1; _current = null; var stack = _stack!.Use(ref this); stack.ClearFastWhenEmpty(); @@ -197,7 +197,7 @@ private void ThrowIfDisposed() // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. - if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + if (_root is null || (_stack is not null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } @@ -209,7 +209,7 @@ private void ThrowIfDisposed() /// Thrown if the collection has changed. private void ThrowIfChanged() { - if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + if (_builder is not null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs index 89b044c0ce9793..03121443930ade 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs @@ -100,7 +100,7 @@ private Node(T key, Node left, Node right, bool frozen = false) /// public bool IsEmpty { - get { return _left == null; } + get { return _left is null; } } /// @@ -236,7 +236,7 @@ internal T this[int index] get { Requires.Range(index >= 0 && index < this.Count, nameof(index)); - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); if (index < _left._count) { @@ -261,7 +261,7 @@ internal T this[int index] internal ref readonly T ItemRef(int index) { Requires.Range(index >= 0 && index < this.Count, nameof(index)); - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); if (index < _left._count) { @@ -421,7 +421,7 @@ internal Node Remove(T key, IComparer comparer, out bool mutated) } else { - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); Node result = this; int compare = comparer.Compare(key, _key); if (compare == 0) @@ -502,7 +502,7 @@ internal void Freeze() // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); _left.Freeze(); _right.Freeze(); _frozen = true; @@ -557,7 +557,7 @@ internal int IndexOf(T key, IComparer comparer) } else { - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); int compare = comparer.Compare(key, _key); if (compare == 0) { @@ -774,19 +774,19 @@ internal static Node NodeTreeFromList(IOrderedCollection items, int start, in /// The mutated (or created) node. private Node Mutate(Node? left = null, Node? right = null) { - Debug.Assert(_left != null && _right != null); + Debug.Assert(_left is not null && _right is not null); if (_frozen) { return new Node(_key, left ?? _left, right ?? _right); } else { - if (left != null) + if (left is not null) { _left = left; } - if (right != null) + if (right is not null) { _right = right; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs index b74674d8e2718f..db58b9a2d6fe53 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs @@ -251,7 +251,7 @@ public ImmutableSortedSet Intersect(IEnumerable other) } } - Debug.Assert(newSet != null); + Debug.Assert(newSet is not null); return newSet; } @@ -348,7 +348,7 @@ public ImmutableSortedSet Union(IEnumerable other) /// public ImmutableSortedSet WithComparer(IComparer? comparer) { - if (comparer == null) + if (comparer is null) { comparer = Comparer.Default; } @@ -361,7 +361,7 @@ public ImmutableSortedSet WithComparer(IComparer? comparer) { var result = new ImmutableSortedSet(Node.EmptyNode, comparer); result = result.Union(this); - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } } @@ -992,13 +992,13 @@ public Enumerator GetEnumerator() private static bool TryCastToImmutableSortedSet(IEnumerable sequence, [NotNullWhen(true)] out ImmutableSortedSet? other) { other = sequence as ImmutableSortedSet; - if (other != null) + if (other is not null) { return true; } var builder = sequence as Builder; - if (builder != null) + if (builder is not null) { other = builder.ToImmutable(); return true; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.Enumerator.cs index daabed2227f14f..566d2d844c204a 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.Enumerator.cs @@ -42,7 +42,7 @@ public T Current { get { - if (_remainingStack == null || _remainingStack.IsEmpty) + if (_remainingStack is null || _remainingStack.IsEmpty) { throw new InvalidOperationException(); } @@ -59,7 +59,7 @@ public T Current /// A value indicating whether there are any more elements. public bool MoveNext() { - if (_remainingStack == null) + if (_remainingStack is null) { // initial move _remainingStack = _originalStack; @@ -111,7 +111,7 @@ public T Current get { this.ThrowIfDisposed(); - if (_remainingStack == null || _remainingStack.IsEmpty) + if (_remainingStack is null || _remainingStack.IsEmpty) { throw new InvalidOperationException(); } @@ -138,7 +138,7 @@ public bool MoveNext() { this.ThrowIfDisposed(); - if (_remainingStack == null) + if (_remainingStack is null) { // initial move _remainingStack = _originalStack; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.cs index f8b70a0a230d89..d7ea8184551add 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack_1.cs @@ -49,7 +49,7 @@ private ImmutableStack() /// The rest of the elements on the stack. private ImmutableStack(T head, ImmutableStack tail) { - Debug.Assert(tail != null); + Debug.Assert(tail is not null); _head = head; _tail = tail; @@ -92,7 +92,7 @@ IImmutableStack IImmutableStack.Clear() /// public bool IsEmpty { - get { return _tail == null; } + get { return _tail is null; } } /// @@ -163,7 +163,7 @@ public ImmutableStack Pop() throw new InvalidOperationException(SR.InvalidEmptyOperation); } - Debug.Assert(_tail != null); + Debug.Assert(_tail is not null); return _tail; } @@ -237,7 +237,7 @@ internal ImmutableStack Reverse() r = r.Push(f.Peek()); } - Debug.Assert(r != null); + Debug.Assert(r is not null); Debug.Assert(r.IsEmpty == IsEmpty); return r; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/KeysOrValuesCollectionAccessor.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/KeysOrValuesCollectionAccessor.cs index 869faa412de5a7..2a6fc15e8c5a99 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/KeysOrValuesCollectionAccessor.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/KeysOrValuesCollectionAccessor.cs @@ -202,13 +202,13 @@ internal ValuesCollectionAccessor(IImmutableDictionary dictionary) public override bool Contains(TValue item) { var sortedDictionary = this.Dictionary as ImmutableSortedDictionary; - if (sortedDictionary != null) + if (sortedDictionary is not null) { return sortedDictionary.ContainsValue(item); } var dictionary = this.Dictionary as IImmutableDictionaryInternal; - if (dictionary != null) + if (dictionary is not null) { return dictionary.ContainsValue(item); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs index bbbc680b8aa85b..e325d390bd2b06 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs @@ -85,7 +85,7 @@ public KeyValuePair Current get { this.ThrowIfDisposed(); - if (_current != null) + if (_current is not null) { return _current.Value; } @@ -115,7 +115,7 @@ public void Dispose() { _root = null!; _current = null; - if (_stack != null && _stack.TryUse(ref this, out Stack>>? stack)) + if (_stack is not null && _stack.TryUse(ref this, out Stack>>? stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack!); @@ -132,7 +132,7 @@ public bool MoveNext() { this.ThrowIfDisposed(); - if (_stack != null) + if (_stack is not null) { var stack = _stack.Use(ref this); if (stack.Count > 0) @@ -156,7 +156,7 @@ public void Reset() this.ThrowIfDisposed(); _current = null; - if (_stack != null) + if (_stack is not null) { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); @@ -175,7 +175,7 @@ internal void ThrowIfDisposed() // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. - if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + if (_root is null || (_stack is not null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs index 25cc0638f62f6a..a9301c0872431d 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs @@ -97,7 +97,7 @@ private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode lef /// /// true if this instance is empty; otherwise, false. /// - public bool IsEmpty { get { return _left == null; } } + public bool IsEmpty { get { return _left is null; } } /// /// Gets the height of the tree beneath this node. @@ -486,7 +486,7 @@ private SortedInt32KeyNode RemoveRecursive(int key, out bool mutated) } else { - Debug.Assert(_right != null && _left != null); + Debug.Assert(_right is not null && _left is not null); SortedInt32KeyNode result = this; if (key == _key) { @@ -554,19 +554,19 @@ private SortedInt32KeyNode RemoveRecursive(int key, out bool mutated) /// The mutated (or created) node. private SortedInt32KeyNode Mutate(SortedInt32KeyNode? left = null, SortedInt32KeyNode? right = null) { - Debug.Assert(_right != null && _left != null); + Debug.Assert(_right is not null && _left is not null); if (_frozen) { return new SortedInt32KeyNode(_key, _value!, left ?? _left, right ?? _right); } else { - if (left != null) + if (left is not null) { _left = left; } - if (right != null) + if (right is not null) { _right = right; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs b/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs index 2850cc5c1c368d..25ab90f547213a 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs @@ -54,7 +54,7 @@ public static IEnumerable SelectMany( Func resultSelector) { immutableArray.ThrowNullRefIfNotInitialized(); - if (collectionSelector == null || resultSelector == null) + if (collectionSelector is null || resultSelector is null) { // throw the same exception as would LINQ return Enumerable.SelectMany(immutableArray, collectionSelector!, resultSelector!); @@ -167,7 +167,7 @@ public static bool SequenceEqual(this ImmutableArray imm return false; } - if (comparer == null) + if (comparer is null) { comparer = EqualityComparer.Default; } @@ -192,7 +192,7 @@ public static bool SequenceEqual(this ImmutableArray imm { Requires.NotNull(items, nameof(items)); - if (comparer == null) + if (comparer is null) { comparer = EqualityComparer.Default; } diff --git a/src/libraries/System.Collections.Immutable/src/Validation/Requires.cs b/src/libraries/System.Collections.Immutable/src/Validation/Requires.cs index f1a9228e445f52..58404c21449fbb 100644 --- a/src/libraries/System.Collections.Immutable/src/Validation/Requires.cs +++ b/src/libraries/System.Collections.Immutable/src/Validation/Requires.cs @@ -24,7 +24,7 @@ internal static class Requires public static void NotNull([ValidatedNotNull]T value, string? parameterName) where T : class // ensures value-types aren't passed to a null checking method { - if (value == null) + if (value is null) { FailArgumentNullException(parameterName); } @@ -60,7 +60,7 @@ public static T NotNullPassthrough([ValidatedNotNull]T value, string? paramet [DebuggerStepThrough] public static void NotNullAllowStructs([ValidatedNotNull]T value, string? parameterName) { - if (null == value) + if (value is null) { FailArgumentNullException(parameterName); } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs index a104d6518122ec..29d0f666d91988 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs @@ -26,7 +26,7 @@ public CaseInsensitiveComparer() public CaseInsensitiveComparer(CultureInfo culture) { - if (culture == null) + if (culture is null) { throw new ArgumentNullException(nameof(culture)); } @@ -45,7 +45,7 @@ public static CaseInsensitiveComparer DefaultInvariant { get { - if (s_InvariantCaseInsensitiveComparer == null) + if (s_InvariantCaseInsensitiveComparer is null) { s_InvariantCaseInsensitiveComparer = new CaseInsensitiveComparer(CultureInfo.InvariantCulture); } @@ -64,7 +64,7 @@ public int Compare(object? a, object? b) { string? sa = a as string; string? sb = b as string; - if (sa != null && sb != null) + if (sa is not null && sb is not null) return _compareInfo.Compare(sa, sb, CompareOptions.IgnoreCase); else return Comparer.Default.Compare(a, b); diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs index 5c9d8b8099f168..f8bf4afa949ff1 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs @@ -22,7 +22,7 @@ public CaseInsensitiveHashCodeProvider() public CaseInsensitiveHashCodeProvider(CultureInfo culture) { - if (culture == null) + if (culture is null) { throw new ArgumentNullException(nameof(culture)); } @@ -36,13 +36,13 @@ public CaseInsensitiveHashCodeProvider(CultureInfo culture) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } string? s = obj as string; - return s != null ? + return s is not null ? _compareInfo.GetHashCode(s, CompareOptions.IgnoreCase) : obj.GetHashCode(); } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs index 086be37456c27e..3325b7ea27526d 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs @@ -227,7 +227,7 @@ protected virtual void OnRemove(int index, object? value) protected virtual void OnValidate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); } protected virtual void OnSetComplete(int index, object? oldValue, object? newValue) diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs index 151b361274e58e..04236cd127002c 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs @@ -22,7 +22,7 @@ protected Hashtable InnerHashtable { get { - if (_hashtable == null) + if (_hashtable is null) _hashtable = new Hashtable(); return _hashtable; } @@ -36,7 +36,7 @@ protected IDictionary Dictionary public int Count { // to avoid newing inner list if no items are ever added - get { return _hashtable == null ? 0 : _hashtable.Count; } + get { return _hashtable is null ? 0 : _hashtable.Count; } } bool IDictionary.IsReadOnly @@ -87,7 +87,7 @@ public void CopyTo(Array array, int index) OnValidate(key, value); bool keyExists = true; object? temp = InnerHashtable[key]; - if (temp == null) + if (temp is null) { keyExists = InnerHashtable.Contains(key); } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs index 99c0e15761f2cc..867c4c530b5d53 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs @@ -66,9 +66,9 @@ public Queue(int capacity, float growFactor) // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // - public Queue(ICollection col) : this((col == null ? 32 : col.Count)) + public Queue(ICollection col) : this((col is null ? 32 : col.Count)) { - if (col == null) + if (col is null) throw new ArgumentNullException(nameof(col)); IEnumerator en = col.GetEnumerator(); @@ -131,7 +131,7 @@ public virtual void Clear() // public virtual void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -212,7 +212,7 @@ public virtual IEnumerator GetEnumerator() // public static Queue Synchronized(Queue queue) { - if (queue == null) + if (queue is null) throw new ArgumentNullException(nameof(queue)); return new SynchronizedQueue(queue); @@ -228,12 +228,12 @@ public virtual bool Contains(object? obj) while (count-- > 0) { - if (obj == null) + if (obj is null) { - if (_array[index] == null) + if (_array[index] is null) return true; } - else if (_array[index] != null && _array[index]!.Equals(obj)) + else if (_array[index] is not null && _array[index]!.Equals(obj)) { return true; } @@ -492,7 +492,7 @@ internal class QueueDebugView public QueueDebugView(Queue queue) { - if (queue == null) + if (queue is null) throw new ArgumentNullException(nameof(queue)); _queue = queue; diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs index 9947faf360966c..c74a885d20a9d6 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs @@ -22,7 +22,7 @@ protected ArrayList InnerList { get { - if (_list == null) + if (_list is null) _list = new ArrayList(); return _list; } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs index f50a1d5603152b..96d460e3d1b8e9 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs @@ -117,7 +117,7 @@ public SortedList(int initialCapacity) public SortedList(IComparer? comparer) : this() { - if (comparer != null) this.comparer = comparer; + if (comparer is not null) this.comparer = comparer; } // Constructs a new sorted list with a given IComparer @@ -155,9 +155,9 @@ public SortedList(IDictionary d) // subsequently added to the sorted list. // public SortedList(IDictionary d, IComparer? comparer) - : this(comparer, (d != null ? d.Count : 0)) + : this(comparer, (d is not null ? d.Count : 0)) { - if (d == null) + if (d is null) throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); d.Keys.CopyTo(keys, 0); @@ -178,7 +178,7 @@ public SortedList(IDictionary d, IComparer? comparer) // public virtual void Add(object key, object? value) { - if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + if (key is null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) @@ -339,7 +339,7 @@ public virtual bool ContainsValue(object? value) // Copies the values in this SortedList to an array. public virtual void CopyTo(Array array, int arrayIndex) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -434,7 +434,7 @@ public virtual object GetKey(int index) // public virtual IList GetKeyList() { - if (keyList == null) keyList = new KeyList(this); + if (keyList is null) keyList = new KeyList(this); return keyList; } @@ -451,7 +451,7 @@ public virtual IList GetKeyList() // public virtual IList GetValueList() { - if (valueList == null) valueList = new ValueList(this); + if (valueList is null) valueList = new ValueList(this); return valueList; } @@ -468,7 +468,7 @@ public virtual object? this[object key] } set { - if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + if (key is null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) { @@ -489,7 +489,7 @@ public virtual object? this[object key] // public virtual int IndexOfKey(object key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; @@ -563,7 +563,7 @@ public virtual void SetByIndex(int index, object? value) // public static SortedList Synchronized(SortedList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new SyncSortedList(list); } @@ -742,7 +742,7 @@ public override IList GetValueList() public override int IndexOfKey(object key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); lock (_root) @@ -953,7 +953,7 @@ public virtual bool Contains(object? key) public virtual void CopyTo(Array array, int arrayIndex) { - if (array != null && array.Rank != 1) + if (array is not null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // defer error checking to Array.Copy @@ -984,7 +984,7 @@ public virtual IEnumerator GetEnumerator() public virtual int IndexOf(object? key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int i = Array.BinarySearch(sortedList.keys, 0, @@ -1057,7 +1057,7 @@ public virtual bool Contains(object? value) public virtual void CopyTo(Array array, int arrayIndex) { - if (array != null && array.Rank != 1) + if (array is not null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // defer error checking to Array.Copy @@ -1109,7 +1109,7 @@ internal class SortedListDebugView public SortedListDebugView(SortedList sortedList) { - if (sortedList == null) + if (sortedList is null) { throw new ArgumentNullException(nameof(sortedList)); } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs index fa9e96d8898564..a1d21b6e9d0e20 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs @@ -53,9 +53,9 @@ public Stack(int initialCapacity) // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // - public Stack(ICollection col) : this((col == null ? 32 : col.Count)) + public Stack(ICollection col) : this((col is null ? 32 : col.Count)) { - if (col == null) + if (col is null) throw new ArgumentNullException(nameof(col)); IEnumerator en = col.GetEnumerator(); @@ -101,12 +101,12 @@ public virtual bool Contains(object? obj) while (count-- > 0) { - if (obj == null) + if (obj is null) { - if (_array[count] == null) + if (_array[count] is null) return true; } - else if (_array[count] != null && _array[count]!.Equals(obj)) + else if (_array[count] is not null && _array[count]!.Equals(obj)) { return true; } @@ -117,7 +117,7 @@ public virtual bool Contains(object? obj) // Copies the stack into an array. public virtual void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -128,7 +128,7 @@ public virtual void CopyTo(Array array, int index) int i = 0; object?[]? objArray = array as object[]; - if (objArray != null) + if (objArray is not null) { while (i < _size) { @@ -193,7 +193,7 @@ public virtual void Push(object? obj) // public static Stack Synchronized(Stack stack) { - if (stack == null) + if (stack is null) throw new ArgumentNullException(nameof(stack)); return new SyncStack(stack); @@ -390,7 +390,7 @@ internal class StackDebugView public StackDebugView(Stack stack) { - if (stack == null) + if (stack is null) throw new ArgumentNullException(nameof(stack)); _stack = stack; diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs index eaf4375b4abc4d..926bfee98d0389 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs @@ -68,11 +68,11 @@ public object? this[object key] // it is still nice to do the same thing here since we have recommended // HybridDictionary as replacement for Hashtable. ListDictionary? cachedList = list; - if (hashtable != null) + if (hashtable is not null) { return hashtable[key]; } - else if (cachedList != null) + else if (cachedList is not null) { return cachedList[key]; } @@ -81,7 +81,7 @@ public object? this[object key] // (2) There is writer which is doing ChangeOver. However in that case // we should see the change to hashtable as well. // So it should work just fine. - else if (key == null) + else if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -89,16 +89,16 @@ public object? this[object key] } set { - if (hashtable != null) + if (hashtable is not null) { hashtable[key] = value; } - else if (list != null) + else if (list is not null) { if (list.Count >= CutoverPoint - 1) { ChangeOver(); - Debug.Assert(hashtable != null); + Debug.Assert(hashtable is not null); hashtable[key] = value; } else @@ -118,7 +118,7 @@ private ListDictionary List { get { - if (list == null) + if (list is null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); } @@ -128,7 +128,7 @@ private ListDictionary List private void ChangeOver() { - Debug.Assert(list != null); + Debug.Assert(list is not null); IDictionaryEnumerator en = list.GetEnumerator(); Hashtable newTable; if (caseInsensitive) @@ -156,11 +156,11 @@ public int Count get { ListDictionary? cachedList = list; - if (hashtable != null) + if (hashtable is not null) { return hashtable.Count; } - else if (cachedList != null) + else if (cachedList is not null) { return cachedList.Count; } @@ -175,7 +175,7 @@ public ICollection Keys { get { - if (hashtable != null) + if (hashtable is not null) { return hashtable.Keys; } @@ -222,7 +222,7 @@ public ICollection Values { get { - if (hashtable != null) + if (hashtable is not null) { return hashtable.Values; } @@ -235,13 +235,13 @@ public ICollection Values public void Add(object key, object? value) { - if (hashtable != null) + if (hashtable is not null) { hashtable.Add(key, value); } else { - if (list == null) + if (list is null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); list.Add(key, value); @@ -249,7 +249,7 @@ public void Add(object key, object? value) else if (list.Count + 1 >= CutoverPoint) { ChangeOver(); - Debug.Assert(hashtable != null); + Debug.Assert(hashtable is not null); hashtable.Add(key, value); } else @@ -261,14 +261,14 @@ public void Add(object key, object? value) public void Clear() { - if (hashtable != null) + if (hashtable is not null) { Hashtable cachedHashtable = hashtable; hashtable = null; cachedHashtable.Clear(); } - if (list != null) + if (list is not null) { ListDictionary cachedList = list; list = null; @@ -279,15 +279,15 @@ public void Clear() public bool Contains(object key) { ListDictionary? cachedList = list; - if (hashtable != null) + if (hashtable is not null) { return hashtable.Contains(key); } - else if (cachedList != null) + else if (cachedList is not null) { return cachedList.Contains(key); } - else if (key == null) + else if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -296,7 +296,7 @@ public bool Contains(object key) public void CopyTo(Array array, int index) { - if (hashtable != null) + if (hashtable is not null) { hashtable.CopyTo(array, index); } @@ -308,11 +308,11 @@ public void CopyTo(Array array, int index) public IDictionaryEnumerator GetEnumerator() { - if (hashtable != null) + if (hashtable is not null) { return hashtable.GetEnumerator(); } - if (list == null) + if (list is null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); } @@ -321,11 +321,11 @@ public IDictionaryEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - if (hashtable != null) + if (hashtable is not null) { return hashtable.GetEnumerator(); } - if (list == null) + if (list is null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); } @@ -334,15 +334,15 @@ IEnumerator IEnumerable.GetEnumerator() public void Remove(object key) { - if (hashtable != null) + if (hashtable is not null) { hashtable.Remove(key); } - else if (list != null) + else if (list is not null) { list.Remove(key); } - else if (key == null) + else if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs index bf5184b8699690..d5bc38e58663b1 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs @@ -34,14 +34,14 @@ public object? this[object key] { get { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } DictionaryNode? node = head; - if (comparer == null) + if (comparer is null) { - while (node != null) + while (node is not null) { object oldKey = node.key; if (oldKey.Equals(key)) @@ -53,7 +53,7 @@ public object? this[object key] } else { - while (node != null) + while (node is not null) { object oldKey = node.key; if (comparer.Compare(oldKey, key) == 0) @@ -67,23 +67,23 @@ public object? this[object key] } set { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } version++; DictionaryNode? last = null; DictionaryNode? node; - for (node = head; node != null; node = node.next) + for (node = head; node is not null; node = node.next) { object oldKey = node.key; - if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) + if ((comparer is null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { break; } last = node; } - if (node != null) + if (node is not null) { // Found it node.value = value; @@ -93,7 +93,7 @@ public object? this[object key] DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; - if (last != null) + if (last is not null) { last.next = newNode; } @@ -157,17 +157,17 @@ public ICollection Values public void Add(object key, object? value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } version++; DictionaryNode? last = null; - for (DictionaryNode? node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node is not null; node = node.next) { object oldKey = node.key; - if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) + if ((comparer is null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key)); } @@ -177,7 +177,7 @@ public void Add(object key, object? value) DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; - if (last != null) + if (last is not null) { last.next = newNode; } @@ -197,14 +197,14 @@ public void Clear() public bool Contains(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - for (DictionaryNode? node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node is not null; node = node.next) { object oldKey = node.key; - if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) + if ((comparer is null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { return true; } @@ -214,7 +214,7 @@ public bool Contains(object key) public void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); @@ -222,7 +222,7 @@ public void CopyTo(Array array, int index) if (array.Length - index < count) throw new ArgumentException(SR.Arg_InsufficientSpace); - for (DictionaryNode? node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node is not null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; @@ -241,23 +241,23 @@ IEnumerator IEnumerable.GetEnumerator() public void Remove(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } version++; DictionaryNode? last = null; DictionaryNode? node; - for (node = head; node != null; node = node.next) + for (node = head; node is not null; node = node.next) { object oldKey = node.key; - if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) + if ((comparer is null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { break; } last = node; } - if (node == null) + if (node is null) { return; } @@ -267,7 +267,7 @@ public void Remove(object key) } else { - Debug.Assert(last != null); + Debug.Assert(last is not null); last.next = node.next; } count--; @@ -301,7 +301,7 @@ public DictionaryEntry Entry { get { - if (_current == null) + if (_current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -313,7 +313,7 @@ public object Key { get { - if (_current == null) + if (_current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -325,7 +325,7 @@ public object? Value { get { - if (_current == null) + if (_current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -344,11 +344,11 @@ public bool MoveNext() _current = _list.head; _start = false; } - else if (_current != null) + else if (_current is not null) { _current = _current.next; } - return (_current != null); + return (_current is not null); } public void Reset() @@ -375,12 +375,12 @@ public NodeKeyValueCollection(ListDictionary list, bool isKeys) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); - for (DictionaryNode? node = _list.head; node != null; node = node.next) + for (DictionaryNode? node = _list.head; node is not null; node = node.next) { array.SetValue(_isKeys ? node.key : node.value, index); index++; @@ -392,7 +392,7 @@ int ICollection.Count get { int count = 0; - for (DictionaryNode? node = _list.head; node != null; node = node.next) + for (DictionaryNode? node = _list.head; node is not null; node = node.next) { count++; } @@ -443,7 +443,7 @@ public object? Current { get { - if (_current == null) + if (_current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -462,11 +462,11 @@ public bool MoveNext() _current = _list.head; _start = false; } - else if (_current != null) + else if (_current is not null) { _current = _current.next; } - return (_current != null); + return (_current is not null); } public void Reset() diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs index afa8b7a1cfbde4..9233cac564b5e7 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs @@ -43,7 +43,7 @@ protected NameObjectCollectionBase() : this(s_defaultComparer) protected NameObjectCollectionBase(IEqualityComparer? equalityComparer) { - _keyComparer = (equalityComparer == null) ? s_defaultComparer : equalityComparer; + _keyComparer = (equalityComparer is null) ? s_defaultComparer : equalityComparer; Reset(); } @@ -118,7 +118,7 @@ private void Reset(int capacity) private NameObjectEntry? FindEntry(string? key) { - if (key != null) + if (key is not null) return (NameObjectEntry?)_entriesTable[key]; else return _nullKeyEntry; @@ -171,14 +171,14 @@ protected void BaseAdd(string? name, object? value) NameObjectEntry entry = new NameObjectEntry(name, value); // insert entry into hashtable - if (name != null) + if (name is not null) { - if (_entriesTable[name] == null) + if (_entriesTable[name] is null) _entriesTable.Add(name, entry); } else { // null key -- special case -- hashtable doesn't like null keys - if (_nullKeyEntry == null) + if (_nullKeyEntry is null) _nullKeyEntry = entry; } @@ -197,7 +197,7 @@ protected void BaseRemove(string? name) if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); - if (name != null) + if (name is not null) { // remove from hashtable _entriesTable.Remove(name); @@ -217,7 +217,7 @@ protected void BaseRemove(string? name) // remove from array for (int i = _entriesArray.Count - 1; i >= 0; i--) { - if (BaseGetKey(i) == null) + if (BaseGetKey(i) is null) _entriesArray.RemoveAt(i); } } @@ -236,7 +236,7 @@ protected void BaseRemoveAt(int index) string? key = BaseGetKey(index); - if (key != null) + if (key is not null) { // remove from hashtable _entriesTable.Remove(key); @@ -275,7 +275,7 @@ protected void BaseClear() protected object? BaseGet(string? name) { NameObjectEntry? e = FindEntry(name); - return (e != null) ? e.Value : null; + return (e is not null) ? e.Value : null; } /// @@ -290,7 +290,7 @@ protected void BaseSet(string? name, object? value) throw new NotSupportedException(SR.CollectionReadOnly); NameObjectEntry? entry = FindEntry(name); - if (entry != null) + if (entry is not null) { entry.Value = value; _version++; @@ -365,7 +365,7 @@ public virtual int Count void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -437,7 +437,7 @@ bool ICollection.IsSynchronized protected object?[] BaseGetAllValues(Type type) { int n = _entriesArray.Count; - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -463,7 +463,7 @@ public virtual KeysCollection Keys { get { - if (_keys == null) + if (_keys is null) _keys = new KeysCollection(this); return _keys; } @@ -603,7 +603,7 @@ public int Count void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs index 2db1ae9a49807f..e23be4828dcfc6 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs @@ -41,7 +41,7 @@ public NameValueCollection() : base() /// provider and the default case-insensitive comparer. /// public NameValueCollection(NameValueCollection col) - : base(col != null ? col.Comparer : null) + : base(col is not null ? col.Comparer : null) { Add(col!); } @@ -77,9 +77,9 @@ public NameValueCollection(int capacity, IEqualityComparer? equalityComparer) /// case-insensitive comparer. /// public NameValueCollection(int capacity, NameValueCollection col) - : base(capacity, (col != null ? col.Comparer : null)) + : base(capacity, (col is not null ? col.Comparer : null)) { - if (col == null) + if (col is null) { throw new ArgumentNullException(nameof(col)); } @@ -113,16 +113,16 @@ protected void InvalidateCachedArrays() private static string? GetAsOneString(ArrayList? list) { - int n = (list != null) ? list.Count : 0; + int n = (list is not null) ? list.Count : 0; if (n == 1) { - Debug.Assert(list != null); + Debug.Assert(list is not null); return (string?)list[0]; } else if (n > 1) { - Debug.Assert(list != null); + Debug.Assert(list is not null); StringBuilder s = new StringBuilder((string?)list[0]); for (int i = 1; i < n; i++) @@ -141,7 +141,7 @@ protected void InvalidateCachedArrays() private static string[]? GetAsStringArray(ArrayList? list) { - int n = (list != null) ? list.Count : 0; + int n = (list is not null) ? list.Count : 0; if (n == 0) return null; @@ -159,7 +159,7 @@ protected void InvalidateCachedArrays() /// public void Add(NameValueCollection c) { - if (c == null) + if (c is null) { throw new ArgumentNullException(nameof(c)); } @@ -173,7 +173,7 @@ public void Add(NameValueCollection c) string? key = c.GetKey(i); string[]? values = c.GetValues(i); - if (values != null) + if (values is not null) { for (int j = 0; j < values.Length; j++) Add(key, values[j]); @@ -200,7 +200,7 @@ public virtual void Clear() public void CopyTo(Array dest, int index) { - if (dest == null) + if (dest is null) { throw new ArgumentNullException(nameof(dest)); } @@ -221,7 +221,7 @@ public void CopyTo(Array dest, int index) } int n = Count; - if (_all == null) + if (_all is null) { string?[] all = new string[n]; for (int i = 0; i < n; i++) @@ -273,18 +273,18 @@ public virtual void Add(string? name, string? value) ArrayList? values = (ArrayList?)BaseGet(name); - if (values == null) + if (values is null) { // new key - add new key with single value values = new ArrayList(1); - if (value != null) + if (value is not null) values.Add(value); BaseAdd(name, values); } else { // old key -- append value to the list of values - if (value != null) + if (value is not null) values.Add(value); } } @@ -402,7 +402,7 @@ public virtual string?[] AllKeys { get { - if (_allKeys == null) + if (_allKeys is null) _allKeys = BaseGetAllKeys(); return _allKeys; } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs index db4a023525a793..38a4b190357076 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs @@ -55,7 +55,7 @@ public OrderedDictionary(int capacity, IEqualityComparer? comparer) private OrderedDictionary(OrderedDictionary dictionary) { - Debug.Assert(dictionary != null); + Debug.Assert(dictionary is not null); _readOnly = true; _objectsArray = dictionary._objectsArray; @@ -79,7 +79,7 @@ public int Count { get { - if (_objectsArray == null) + if (_objectsArray is null) { return 0; } @@ -157,7 +157,7 @@ public object? this[int index] { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (_objectsArray == null || index < 0 || index >= _objectsArray.Count) + if (_objectsArray is null || index < 0 || index >= _objectsArray.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } @@ -176,7 +176,7 @@ public object? this[object key] { get { - if (_objectsTable == null) + if (_objectsTable is null) { return null; } @@ -238,11 +238,11 @@ public void Clear() { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (_objectsTable != null) + if (_objectsTable is not null) { _objectsTable.Clear(); } - if (_objectsArray != null) + if (_objectsArray is not null) { _objectsArray.Clear(); } @@ -261,11 +261,11 @@ public OrderedDictionary AsReadOnly() /// public bool Contains(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (_objectsTable == null) + if (_objectsTable is null) { return false; } @@ -283,14 +283,14 @@ public void CopyTo(Array array, int index) private int IndexOfKey(object key) { - if (_objectsArray == null) + if (_objectsArray is null) { return -1; } for (int i = 0; i < _objectsArray.Count; i++) { object o = ((DictionaryEntry)_objectsArray[i]!).Key; - if (_comparer != null) + if (_comparer is not null) { if (_comparer.Equals(o, key)) { @@ -356,7 +356,7 @@ public void Remove(object key) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -392,7 +392,7 @@ IEnumerator IEnumerable.GetEnumerator() #region ISerializable implementation public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -416,7 +416,7 @@ void IDeserializationCallback.OnDeserialization(object? sender) protected virtual void OnDeserialization(object? sender) { - if (_siInfo == null) + if (_siInfo is null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } @@ -426,7 +426,7 @@ protected virtual void OnDeserialization(object? sender) object[]? serArray = (object[]?)_siInfo.GetValue(ArrayListName, typeof(object[])); - if (serArray != null) + if (serArray is not null) { Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); @@ -474,7 +474,7 @@ public object? Current { get { - Debug.Assert(_arrayEnumerator.Current != null); + Debug.Assert(_arrayEnumerator.Current is not null); if (_objectReturnType == Keys) { return ((DictionaryEntry)_arrayEnumerator.Current).Key; @@ -494,7 +494,7 @@ public DictionaryEntry Entry { get { - Debug.Assert(_arrayEnumerator.Current != null); + Debug.Assert(_arrayEnumerator.Current is not null); return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value); } } @@ -506,7 +506,7 @@ public object Key { get { - Debug.Assert(_arrayEnumerator.Current != null); + Debug.Assert(_arrayEnumerator.Current is not null); return ((DictionaryEntry)_arrayEnumerator.Current).Key; } } @@ -518,7 +518,7 @@ public object? Value { get { - Debug.Assert(_arrayEnumerator.Current != null); + Debug.Assert(_arrayEnumerator.Current is not null); return ((DictionaryEntry)_arrayEnumerator.Current).Value; } } @@ -558,13 +558,13 @@ public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); foreach (object? o in _objects) { - Debug.Assert(o != null); + Debug.Assert(o is not null); array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index); index++; } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs index 0ffc7ac0822ce7..23ae56564d31e2 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs @@ -71,7 +71,7 @@ public int Add(string? value) /// public void AddRange(string[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs index 436514bf1773eb..5f2a22bfd5f834 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs @@ -66,7 +66,7 @@ public virtual string? this[string key] { get { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -75,7 +75,7 @@ public virtual string? this[string key] } set { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -123,7 +123,7 @@ public virtual ICollection Values /// public virtual void Add(string key, string? value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -144,7 +144,7 @@ public virtual void Clear() /// public virtual bool ContainsKey(string key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -182,7 +182,7 @@ public virtual IEnumerator GetEnumerator() /// public virtual void Remove(string key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/libraries/System.Collections/src/System/Collections/BitArray.cs b/src/libraries/System.Collections/src/System/Collections/BitArray.cs index 9eed0c8150c43b..dd146996e0e6dd 100644 --- a/src/libraries/System.Collections/src/System/Collections/BitArray.cs +++ b/src/libraries/System.Collections/src/System/Collections/BitArray.cs @@ -63,11 +63,11 @@ public BitArray(int length, bool defaultValue) ** represents the lowest index value; bytes[0] & 1 represents bit 0, ** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc. ** - ** Exceptions: ArgumentException if bytes == null. + ** Exceptions: ArgumentException if bytes is null. =========================================================================*/ public BitArray(byte[] bytes) { - if (bytes == null) + if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } @@ -123,7 +123,7 @@ public BitArray(byte[] bytes) private const uint Vector256IntCount = 8; public unsafe BitArray(bool[] values) { - if (values == null) + if (values is null) { throw new ArgumentNullException(nameof(values)); } @@ -235,11 +235,11 @@ public unsafe BitArray(bool[] values) ** integer represents the lowest index value; values[0] & 1 represents bit ** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc. ** - ** Exceptions: ArgumentException if values == null. + ** Exceptions: ArgumentException if values is null. =========================================================================*/ public BitArray(int[] values) { - if (values == null) + if (values is null) { throw new ArgumentNullException(nameof(values)); } @@ -260,11 +260,11 @@ public BitArray(int[] values) /*========================================================================= ** Allocates a new BitArray with the same length and bit values as bits. ** - ** Exceptions: ArgumentException if bits == null. + ** Exceptions: ArgumentException if bits is null. =========================================================================*/ public BitArray(BitArray bits) { - if (bits == null) + if (bits is null) { throw new ArgumentNullException(nameof(bits)); } @@ -347,12 +347,12 @@ public void SetAll(bool value) /*========================================================================= ** Returns a reference to the current instance ANDed with value. ** - ** Exceptions: ArgumentException if value == null or + ** Exceptions: ArgumentException if value is null or ** value.Length != this.Length. =========================================================================*/ public unsafe BitArray And(BitArray value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with @@ -433,12 +433,12 @@ public unsafe BitArray And(BitArray value) /*========================================================================= ** Returns a reference to the current instance ORed with value. ** - ** Exceptions: ArgumentException if value == null or + ** Exceptions: ArgumentException if value is null or ** value.Length != this.Length. =========================================================================*/ public unsafe BitArray Or(BitArray value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with @@ -519,12 +519,12 @@ public unsafe BitArray Or(BitArray value) /*========================================================================= ** Returns a reference to the current instance XORed with value. ** - ** Exceptions: ArgumentException if value == null or + ** Exceptions: ArgumentException if value is null or ** value.Length != this.Length. =========================================================================*/ public unsafe BitArray Xor(BitArray value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with @@ -847,7 +847,7 @@ public int Length public unsafe void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0) diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs b/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs index 39158f2e18cde2..34bf3e93679b43 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs @@ -14,7 +14,7 @@ public static class CollectionExtensions public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue) { - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } @@ -25,7 +25,7 @@ public static TValue GetValueOrDefault(this IReadOnlyDictionary(this IDictionary dictionary, TKey key, TValue value) { - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } @@ -41,7 +41,7 @@ public static bool TryAdd(this IDictionary dictionar public static bool Remove(this IDictionary dictionary, TKey key, [MaybeNullWhen(false)] out TValue value) { - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs index cd2718696213ac..6f55a4abbe46d1 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs @@ -30,7 +30,7 @@ public LinkedList() public LinkedList(IEnumerable collection) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -58,7 +58,7 @@ public LinkedListNode? First public LinkedListNode? Last { - get { return head == null ? null : head.prev; } + get { return head is null ? null : head.prev; } } bool ICollection.IsReadOnly @@ -114,7 +114,7 @@ public void AddBefore(LinkedListNode node, LinkedListNode newNode) public LinkedListNode AddFirst(T value) { LinkedListNode result = new LinkedListNode(this, value); - if (head == null) + if (head is null) { InternalInsertNodeToEmptyList(result); } @@ -130,7 +130,7 @@ public void AddFirst(LinkedListNode node) { ValidateNewNode(node); - if (head == null) + if (head is null) { InternalInsertNodeToEmptyList(node); } @@ -145,7 +145,7 @@ public void AddFirst(LinkedListNode node) public LinkedListNode AddLast(T value) { LinkedListNode result = new LinkedListNode(this, value); - if (head == null) + if (head is null) { InternalInsertNodeToEmptyList(result); } @@ -160,7 +160,7 @@ public void AddLast(LinkedListNode node) { ValidateNewNode(node); - if (head == null) + if (head is null) { InternalInsertNodeToEmptyList(node); } @@ -174,7 +174,7 @@ public void AddLast(LinkedListNode node) public void Clear() { LinkedListNode? current = head; - while (current != null) + while (current is not null) { LinkedListNode temp = current; current = current.Next; // use Next the instead of "next", otherwise it will loop forever @@ -188,12 +188,12 @@ public void Clear() public bool Contains(T value) { - return Find(value) != null; + return Find(value) is not null; } public void CopyTo(T[] array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -214,7 +214,7 @@ public void CopyTo(T[] array, int index) } LinkedListNode? node = head; - if (node != null) + if (node is not null) { do { @@ -228,9 +228,9 @@ public void CopyTo(T[] array, int index) { LinkedListNode? node = head; EqualityComparer c = EqualityComparer.Default; - if (node != null) + if (node is not null) { - if (value != null) + if (value is not null) { do { @@ -245,7 +245,7 @@ public void CopyTo(T[] array, int index) { do { - if (node!.item == null) + if (node!.item is null) { return node; } @@ -258,14 +258,14 @@ public void CopyTo(T[] array, int index) public LinkedListNode? FindLast(T value) { - if (head == null) return null; + if (head is null) return null; LinkedListNode? last = head.prev; LinkedListNode? node = last; EqualityComparer c = EqualityComparer.Default; - if (node != null) + if (node is not null) { - if (value != null) + if (value is not null) { do { @@ -281,7 +281,7 @@ public void CopyTo(T[] array, int index) { do { - if (node!.item == null) + if (node!.item is null) { return node; } @@ -305,7 +305,7 @@ IEnumerator IEnumerable.GetEnumerator() public bool Remove(T value) { LinkedListNode? node = Find(value); - if (node != null) + if (node is not null) { InternalRemoveNode(node); return true; @@ -321,13 +321,13 @@ public void Remove(LinkedListNode node) public void RemoveFirst() { - if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); } + if (head is null) { throw new InvalidOperationException(SR.LinkedListEmpty); } InternalRemoveNode(head); } public void RemoveLast() { - if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); } + if (head is null) { throw new InvalidOperationException(SR.LinkedListEmpty); } InternalRemoveNode(head.prev!); } @@ -336,7 +336,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte // Customized serialization for LinkedList. // We need to do this because it will be too expensive to Serialize each node. // This will give us the flexiblility to change internal implementation freely in future. - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -354,7 +354,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte public virtual void OnDeserialization(object? sender) { - if (_siInfo == null) + if (_siInfo is null) { return; //Somebody had a dependency on this LinkedList and fixed us up before the ObjectManager got to it. } @@ -366,7 +366,7 @@ public virtual void OnDeserialization(object? sender) { T[]? array = (T[]?)_siInfo.GetValue(ValuesName, typeof(T[])); - if (array == null) + if (array is null) { throw new SerializationException(SR.Serialization_MissingValues); } @@ -396,7 +396,7 @@ private void InternalInsertNodeBefore(LinkedListNode node, LinkedListNode private void InternalInsertNodeToEmptyList(LinkedListNode newNode) { - Debug.Assert(head == null && count == 0, "LinkedList must be empty when this method is called!"); + Debug.Assert(head is null && count == 0, "LinkedList must be empty when this method is called!"); newNode.next = newNode; newNode.prev = newNode; head = newNode; @@ -407,7 +407,7 @@ private void InternalInsertNodeToEmptyList(LinkedListNode newNode) internal void InternalRemoveNode(LinkedListNode node) { Debug.Assert(node.list == this, "Deleting the node from another list!"); - Debug.Assert(head != null, "This method shouldn't be called on empty list!"); + Debug.Assert(head is not null, "This method shouldn't be called on empty list!"); if (node.next == node) { Debug.Assert(count == 1 && head == node, "this should only be true for a list with only one node"); @@ -429,12 +429,12 @@ internal void InternalRemoveNode(LinkedListNode node) internal void ValidateNewNode(LinkedListNode node) { - if (node == null) + if (node is null) { throw new ArgumentNullException(nameof(node)); } - if (node.list != null) + if (node.list is not null) { throw new InvalidOperationException(SR.LinkedListNodeIsAttached); } @@ -442,7 +442,7 @@ internal void ValidateNewNode(LinkedListNode node) internal void ValidateNode(LinkedListNode node) { - if (node == null) + if (node is null) { throw new ArgumentNullException(nameof(node)); } @@ -462,7 +462,7 @@ bool ICollection.IsSynchronized void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -488,7 +488,7 @@ void ICollection.CopyTo(Array array, int index) } T[]? tArray = array as T[]; - if (tArray != null) + if (tArray is not null) { CopyTo(tArray, index); } @@ -497,14 +497,14 @@ void ICollection.CopyTo(Array array, int index) // No need to use reflection to verify that the types are compatible because it isn't 100% correct and we can rely // on the runtime validation during the cast that happens below (i.e. we will get an ArrayTypeMismatchException). object?[]? objects = array as object[]; - if (objects == null) + if (objects is null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } LinkedListNode? node = head; try { - if (node != null) + if (node is not null) { do { @@ -564,7 +564,7 @@ public bool MoveNext() throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } - if (_node == null) + if (_node is null) { _index = _list.Count + 1; return false; @@ -634,12 +634,12 @@ public LinkedList? List public LinkedListNode? Next { - get { return next == null || next == list!.head ? null : next; } + get { return next is null || next == list!.head ? null : next; } } public LinkedListNode? Previous { - get { return prev == null || this == list!.head ? null : prev; } + get { return prev is null || this == list!.head ? null : prev; } } public T Value diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/Queue.cs b/src/libraries/System.Collections/src/System/Collections/Generic/Queue.cs index c468d1663c45c4..ef1dcfdf06d89d 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/Queue.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/Queue.cs @@ -54,7 +54,7 @@ public Queue(int capacity) // to get each of the elements. public Queue(IEnumerable collection) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); @@ -103,7 +103,7 @@ public void Clear() // index into the array. public void CopyTo(T[] array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -133,7 +133,7 @@ public void CopyTo(T[] array, int arrayIndex) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/QueueDebugView.cs b/src/libraries/System.Collections/src/System/Collections/Generic/QueueDebugView.cs index 31ac94a0f48334..8501a68778d681 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/QueueDebugView.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/QueueDebugView.cs @@ -11,7 +11,7 @@ internal sealed class QueueDebugView public QueueDebugView(Queue queue) { - if (queue == null) + if (queue is null) { throw new ArgumentNullException(nameof(queue)); } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs index fd649d52ca3476..804a2ca0b565d3 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs @@ -30,7 +30,7 @@ public SortedDictionary(IDictionary dictionary) : this(dictionary, public SortedDictionary(IDictionary dictionary, IComparer? comparer) { - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } @@ -56,14 +56,14 @@ void ICollection>.Add(KeyValuePair keyV bool ICollection>.Contains(KeyValuePair keyValuePair) { TreeSet>.Node? node = _set.FindNode(keyValuePair); - if (node == null) + if (node is null) { return false; } - if (keyValuePair.Value == null) + if (keyValuePair.Value is null) { - return node.Item.Value == null; + return node.Item.Value is null; } else { @@ -74,7 +74,7 @@ bool ICollection>.Contains(KeyValuePair bool ICollection>.Remove(KeyValuePair keyValuePair) { TreeSet>.Node? node = _set.FindNode(keyValuePair); - if (node == null) + if (node is null) { return false; } @@ -99,13 +99,13 @@ public TValue this[TKey key] { get { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } TreeSet>.Node? node = _set.FindNode(new KeyValuePair(key, default(TValue)!)); - if (node == null) + if (node is null) { throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } @@ -114,13 +114,13 @@ public TValue this[TKey key] } set { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } TreeSet>.Node? node = _set.FindNode(new KeyValuePair(key, default(TValue)!)); - if (node == null) + if (node is null) { _set.Add(new KeyValuePair(key, value)); } @@ -152,7 +152,7 @@ public KeyCollection Keys { get { - if (_keys == null) _keys = new KeyCollection(this); + if (_keys is null) _keys = new KeyCollection(this); return _keys; } } @@ -177,7 +177,7 @@ public ValueCollection Values { get { - if (_values == null) _values = new ValueCollection(this); + if (_values is null) _values = new ValueCollection(this); return _values; } } @@ -200,7 +200,7 @@ IEnumerable IReadOnlyDictionary.Values public void Add(TKey key, TValue value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -214,7 +214,7 @@ public void Clear() public bool ContainsKey(TKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -225,11 +225,11 @@ public bool ContainsKey(TKey key) public bool ContainsValue(TValue value) { bool found = false; - if (value == null) + if (value is null) { _set.InOrderTreeWalk(delegate (TreeSet>.Node node) { - if (node.Item.Value == null) + if (node.Item.Value is null) { found = true; return false; // stop the walk @@ -270,7 +270,7 @@ IEnumerator> IEnumerable>. public bool Remove(TKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -280,13 +280,13 @@ public bool Remove(TKey key) public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } TreeSet>.Node? node = _set.FindNode(new KeyValuePair(key, default(TValue)!)); - if (node == null) + if (node is null) { value = default; return false; @@ -337,12 +337,12 @@ ICollection IDictionary.Values } set { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (value == null && !(default(TValue) == null)) + if (value is null && !(default(TValue) is null)) throw new ArgumentNullException(nameof(value)); try @@ -366,12 +366,12 @@ ICollection IDictionary.Values void IDictionary.Add(object key, object? value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (value == null && !(default(TValue) == null)) + if (value is null && !(default(TValue) is null)) throw new ArgumentNullException(nameof(value)); try @@ -404,7 +404,7 @@ bool IDictionary.Contains(object key) private static bool IsCompatibleKey(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -559,7 +559,7 @@ public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCol public KeyCollection(SortedDictionary dictionary) { - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } @@ -583,7 +583,7 @@ IEnumerator IEnumerable.GetEnumerator() public void CopyTo(TKey[] array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -603,7 +603,7 @@ public void CopyTo(TKey[] array, int index) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -629,7 +629,7 @@ void ICollection.CopyTo(Array array, int index) } TKey[]? keys = array as TKey[]; - if (keys != null) + if (keys is not null) { CopyTo(keys, index); } @@ -742,7 +742,7 @@ public sealed class ValueCollection : ICollection, ICollection, IReadOnl public ValueCollection(SortedDictionary dictionary) { - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } @@ -766,7 +766,7 @@ IEnumerator IEnumerable.GetEnumerator() public void CopyTo(TValue[] array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -786,7 +786,7 @@ public void CopyTo(TValue[] array, int index) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -812,7 +812,7 @@ void ICollection.CopyTo(Array array, int index) } TValue[]? values = array as TValue[]; - if (values != null) + if (values is not null) { CopyTo(values, index); } @@ -924,7 +924,7 @@ public sealed class KeyValuePairComparer : Comparer> public KeyValuePairComparer(IComparer? keyComparer) { - if (keyComparer == null) + if (keyComparer is null) { this.keyComparer = Comparer.Default; } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs index 220de76fca1690..700dca2ad68797 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -107,7 +107,7 @@ public SortedList(int capacity) public SortedList(IComparer? comparer) : this() { - if (comparer != null) + if (comparer is not null) { this.comparer = comparer; } @@ -148,9 +148,9 @@ public SortedList(IDictionary dictionary) // subsequently added to the sorted list. // public SortedList(IDictionary dictionary, IComparer? comparer) - : this((dictionary != null ? dictionary.Count : 0), comparer) + : this(dictionary is not null ? dictionary.Count : 0, comparer) { - if (dictionary == null) + if (dictionary is null) throw new ArgumentNullException(nameof(dictionary)); int count = dictionary.Count; @@ -182,7 +182,7 @@ public SortedList(IDictionary dictionary, IComparer? compare // public void Add(TKey key, TValue value) { - if (key == null) throw new ArgumentNullException(nameof(key)); + if (key is null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); @@ -267,16 +267,16 @@ public IComparer Comparer void IDictionary.Add(object key, object? value) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); - if (value == null && !(default(TValue) == null)) // null is an invalid value for Value types + if (value is null && !(default(TValue) is null)) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); if (!(key is TKey)) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); - if (!(value is TValue) && value != null) // null is a valid value for Reference Types + if (!(value is TValue) && value is not null) // null is a valid value for Reference Types throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); Add((TKey)key, (TValue)value!); @@ -364,14 +364,14 @@ IEnumerable IReadOnlyDictionary.Values private KeyList GetKeyListHelper() { - if (keyList == null) + if (keyList is null) keyList = new KeyList(this); return keyList; } private ValueList GetValueListHelper() { - if (valueList == null) + if (valueList is null) valueList = new ValueList(this); return valueList; } @@ -444,7 +444,7 @@ public bool ContainsValue(TValue value) // Copies the values in this SortedList to an array. void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -468,7 +468,7 @@ void ICollection>.CopyTo(KeyValuePair[] void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -494,7 +494,7 @@ void ICollection.CopyTo(Array array, int index) } KeyValuePair[]? keyValuePairArray = array as KeyValuePair[]; - if (keyValuePairArray != null) + if (keyValuePairArray is not null) { for (int i = 0; i < Count; i++) { @@ -504,7 +504,7 @@ void ICollection.CopyTo(Array array, int index) else { object[]? objects = array as object[]; - if (objects == null) + if (objects is null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } @@ -588,7 +588,7 @@ public TValue this[TKey key] } set { - if (((object)key) == null) throw new ArgumentNullException(nameof(key)); + if (key is null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) { @@ -622,7 +622,7 @@ public TValue this[TKey key] throw new ArgumentNullException(nameof(key)); } - if (value == null && !(default(TValue) == null)) + if (value is null && !(default(TValue) is null)) throw new ArgumentNullException(nameof(value)); TKey tempKey = (TKey)key; @@ -645,7 +645,7 @@ public TValue this[TKey key] // key value. public int IndexOfKey(TKey key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; @@ -750,7 +750,7 @@ public void TrimExcess() private static bool IsCompatibleKey(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -1062,7 +1062,7 @@ public void CopyTo(TKey[] array, int arrayIndex) void ICollection.CopyTo(Array array, int arrayIndex) { - if (array != null && array.Rank != 1) + if (array is not null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try @@ -1105,7 +1105,7 @@ IEnumerator IEnumerable.GetEnumerator() public int IndexOf(TKey key) { - if (((object)key) == null) + if (key is null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch(_dict.keys, 0, @@ -1181,7 +1181,7 @@ public void CopyTo(TValue[] array, int arrayIndex) void ICollection.CopyTo(Array array, int index) { - if (array != null && array.Rank != 1) + if (array is not null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs index 91745e21d058f3..f00485c7caba3e 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs @@ -129,7 +129,7 @@ internal override T MinInternal Node? current = root; T? result = default; - while (current != null) + while (current is not null) { int comp = _lBoundActive ? Comparer.Compare(_min, current.Item) : -1; @@ -159,7 +159,7 @@ internal override T MaxInternal Node? current = root; T? result = default; - while (current != null) + while (current is not null) { int comp = _uBoundActive ? Comparer.Compare(_max, current.Item) : 1; if (comp == -1) @@ -185,7 +185,7 @@ internal override bool InOrderTreeWalk(TreeWalkPredicate action) { VersionCheck(); - if (root == null) + if (root is null) { return true; } @@ -194,7 +194,7 @@ internal override bool InOrderTreeWalk(TreeWalkPredicate action) // See page 264 of "Introduction to algorithms" by Thomas H. Cormen Stack stack = new Stack(2 * (int)SortedSet.Log2(count + 1)); // this is not exactly right if count is out of date, but the stack can grow Node? current = root; - while (current != null) + while (current is not null) { if (IsWithinRange(current.Item)) { @@ -220,7 +220,7 @@ internal override bool InOrderTreeWalk(TreeWalkPredicate action) } Node? node = current.Right; - while (node != null) + while (node is not null) { if (IsWithinRange(node.Item)) { @@ -244,7 +244,7 @@ internal override bool BreadthFirstTreeWalk(TreeWalkPredicate action) { VersionCheck(); - if (root == null) + if (root is null) { return true; } @@ -260,11 +260,11 @@ internal override bool BreadthFirstTreeWalk(TreeWalkPredicate action) { return false; } - if (current.Left != null && (!_lBoundActive || Comparer.Compare(_min, current.Item) < 0)) + if (current.Left is not null && (!_lBoundActive || Comparer.Compare(_min, current.Item) < 0)) { processQueue.Enqueue(current.Left); } - if (current.Right != null && (!_uBoundActive || Comparer.Compare(_max, current.Item) > 0)) + if (current.Right is not null && (!_uBoundActive || Comparer.Compare(_max, current.Item) > 0)) { processQueue.Enqueue(current.Right); } @@ -311,7 +311,7 @@ internal override int InternalIndexOf(T item) private void VersionCheckImpl(bool updateCount) { - Debug.Assert(_underlying != null); + Debug.Assert(_underlying is not null); if (version != _underlying.version) { root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive); @@ -331,7 +331,7 @@ private void VersionCheckImpl(bool updateCount) /// internal override int TotalCount() { - Debug.Assert(_underlying != null); + Debug.Assert(_underlying is not null); return _underlying.Count; } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs index 3d2989a86c8bd6..28668ae2d6f380 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -82,7 +82,7 @@ public SortedSet(IEnumerable collection) : this(collection, Comparer.Defau public SortedSet(IEnumerable collection, IComparer? comparer) : this(comparer) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -90,11 +90,11 @@ public SortedSet(IEnumerable collection, IComparer? comparer) // These are explicit type checks in the mold of HashSet. It would have worked better with // something like an ISorted interface. (We could make this work for SortedList.Keys, etc.) SortedSet? sortedSet = collection as SortedSet; - if (sortedSet != null && !(sortedSet is TreeSubSet) && HasEqualComparer(sortedSet)) + if (sortedSet is not null && !(sortedSet is TreeSubSet) && HasEqualComparer(sortedSet)) { if (sortedSet.Count > 0) { - Debug.Assert(sortedSet.root != null); + Debug.Assert(sortedSet.root is not null); this.count = sortedSet.count; root = sortedSet.root.DeepClone(this.count); } @@ -180,7 +180,7 @@ private bool ContainsAllElements(IEnumerable collection) /// true if the entire tree has been walked; otherwise, false. internal virtual bool InOrderTreeWalk(TreeWalkPredicate action) { - if (root == null) + if (root is null) { return true; } @@ -193,7 +193,7 @@ internal virtual bool InOrderTreeWalk(TreeWalkPredicate action) var stack = new Stack(2 * (int)Log2(Count + 1)); Node? current = root; - while (current != null) + while (current is not null) { stack.Push(current); current = current.Left; @@ -208,7 +208,7 @@ internal virtual bool InOrderTreeWalk(TreeWalkPredicate action) } Node? node = current.Right; - while (node != null) + while (node is not null) { stack.Push(node); node = node.Left; @@ -228,7 +228,7 @@ internal virtual bool InOrderTreeWalk(TreeWalkPredicate action) /// true if the entire tree has been walked; otherwise, false. internal virtual bool BreadthFirstTreeWalk(TreeWalkPredicate action) { - if (root == null) + if (root is null) { return true; } @@ -245,11 +245,11 @@ internal virtual bool BreadthFirstTreeWalk(TreeWalkPredicate action) return false; } - if (current.Left != null) + if (current.Left is not null) { processQueue.Enqueue(current.Left); } - if (current.Right != null) + if (current.Right is not null) { processQueue.Enqueue(current.Right); } @@ -301,7 +301,7 @@ internal virtual void VersionCheck(bool updateCount = false) { } internal virtual bool AddIfNotPresent(T item) { - if (root == null) + if (root is null) { // The tree is empty and this is the first item. root = new Node(item, NodeColor.Black); @@ -323,7 +323,7 @@ internal virtual bool AddIfNotPresent(T item) version++; int order = 0; - while (current != null) + while (current is not null) { order = comparer.Compare(item, current.Item); if (order == 0) @@ -351,7 +351,7 @@ internal virtual bool AddIfNotPresent(T item) current = (order < 0) ? current.Left : current.Right; } - Debug.Assert(parent != null); + Debug.Assert(parent is not null); // We're ready to insert the new node. Node node = new Node(item, NodeColor.Red); if (order > 0) @@ -379,7 +379,7 @@ internal virtual bool AddIfNotPresent(T item) internal virtual bool DoRemove(T item) { - if (root == null) + if (root is null) { return false; } @@ -402,12 +402,12 @@ internal virtual bool DoRemove(T item) Node? match = null; Node? parentOfMatch = null; bool foundMatch = false; - while (current != null) + while (current is not null) { if (current.Is2Node) { // Fix up 2-node - if (parent == null) + if (parent is null) { // `current` is the root. Mark it red. current.ColorRed(); @@ -487,7 +487,7 @@ internal virtual bool DoRemove(T item) } // Move successor to the matching node position and replace links. - if (match != null) + if (match is not null) { ReplaceNode(match, parentOfMatch!, parent!, grandParent!); --count; @@ -504,7 +504,7 @@ public virtual void Clear() ++version; } - public virtual bool Contains(T item) => FindNode(item) != null; + public virtual bool Contains(T item) => FindNode(item) is not null; public void CopyTo(T[] array) => CopyTo(array, 0, Count); @@ -512,7 +512,7 @@ public virtual void Clear() public void CopyTo(T[] array, int index, int count) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -548,7 +548,7 @@ public void CopyTo(T[] array, int index, int count) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -574,14 +574,14 @@ void ICollection.CopyTo(Array array, int index) } T[]? tarray = array as T[]; - if (tarray != null) + if (tarray is not null) { CopyTo(tarray, index); } else { object?[]? objects = array as object[]; - if (objects == null) + if (objects is null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } @@ -621,8 +621,8 @@ void ICollection.CopyTo(Array array, int index) // By the time we need to split again, everything will be correctly set. private void InsertionBalance(Node current, ref Node parent, Node grandParent, Node greatGrandParent) { - Debug.Assert(parent != null); - Debug.Assert(grandParent != null); + Debug.Assert(parent is not null); + Debug.Assert(grandParent is not null); bool parentIsOnRight = grandParent.Right == parent; bool currentIsOnRight = parent.Right == current; @@ -656,7 +656,7 @@ private void InsertionBalance(Node current, ref Node parent, Node grandParent, N /// The node to replace with. private void ReplaceChildOrRoot(Node? parent, Node child, Node newChild) { - if (parent != null) + if (parent is not null) { parent.ReplaceChild(child, newChild); } @@ -671,19 +671,19 @@ private void ReplaceChildOrRoot(Node? parent, Node child, Node newChild) /// private void ReplaceNode(Node match, Node parentOfMatch, Node successor, Node parentOfSuccessor) { - Debug.Assert(match != null); + Debug.Assert(match is not null); if (successor == match) { // This node has no successor. This can only happen if the right child of the match is null. - Debug.Assert(match.Right == null); + Debug.Assert(match.Right is null); successor = match.Left!; } else { - Debug.Assert(parentOfSuccessor != null); - Debug.Assert(successor.Left == null); - Debug.Assert((successor.Right == null && successor.IsRed) || (successor.Right!.IsRed && successor.IsBlack)); + Debug.Assert(parentOfSuccessor is not null); + Debug.Assert(successor.Left is null); + Debug.Assert((successor.Right is null && successor.IsRed) || (successor.Right!.IsRed && successor.IsBlack)); successor.Right?.ColorBlack(); @@ -697,7 +697,7 @@ private void ReplaceNode(Node match, Node parentOfMatch, Node successor, Node pa successor.Left = match.Left; } - if (successor != null) + if (successor is not null) { successor.Color = match.Color; } @@ -708,7 +708,7 @@ private void ReplaceNode(Node match, Node parentOfMatch, Node successor, Node pa internal virtual Node? FindNode(T item) { Node? current = root; - while (current != null) + while (current is not null) { int order = comparer.Compare(item, current.Item); if (order == 0) @@ -740,7 +740,7 @@ internal virtual int InternalIndexOf(T item) { Node? current = root; int count = 0; - while (current != null) + while (current is not null) { int order = comparer.Compare(item, current.Item); if (order == 0) @@ -760,7 +760,7 @@ internal virtual int InternalIndexOf(T item) internal Node? FindRange(T? from, T? to, bool lowerBoundActive, bool upperBoundActive) { Node? current = root; - while (current != null) + while (current is not null) { if (lowerBoundActive && comparer.Compare(from, current.Item) > 0) { @@ -806,14 +806,14 @@ public static IEqualityComparer> CreateSetComparer(IEqualityCompare /// true if the sets have equal contents; otherwise, false. internal static bool SortedSetEquals(SortedSet? set1, SortedSet? set2, IComparer comparer) { - if (set1 == null) + if (set1 is null) { - return set2 == null; + return set2 is null; } - if (set2 == null) + if (set2 is null) { - Debug.Assert(set1 != null); + Debug.Assert(set1 is not null); return false; } @@ -860,7 +860,7 @@ private bool HasEqualComparer(SortedSet other) public void UnionWith(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -868,10 +868,10 @@ public void UnionWith(IEnumerable other) SortedSet? asSorted = other as SortedSet; TreeSubSet? treeSubset = this as TreeSubSet; - if (treeSubset != null) + if (treeSubset is not null) VersionCheck(); - if (asSorted != null && treeSubset == null && Count == 0) + if (asSorted is not null && treeSubset is null && Count == 0) { SortedSet dummy = new SortedSet(asSorted, comparer); root = dummy.root; @@ -881,7 +881,7 @@ public void UnionWith(IEnumerable other) } // This actually hurts if N is much greater than M. The / 2 is arbitrary. - if (asSorted != null && treeSubset == null && HasEqualComparer(asSorted) && (asSorted.Count > this.Count / 2)) + if (asSorted is not null && treeSubset is null && HasEqualComparer(asSorted) && (asSorted.Count > this.Count / 2)) { // First do a merge sort to an array. T[] merged = new T[asSorted.Count + this.Count]; @@ -964,7 +964,7 @@ public void UnionWith(IEnumerable other) return null; case 1: root = new Node(arr[startIndex], NodeColor.Black); - if (redNode != null) + if (redNode is not null) { root.Left = redNode; } @@ -973,7 +973,7 @@ public void UnionWith(IEnumerable other) root = new Node(arr[startIndex], NodeColor.Black); root.Right = new Node(arr[endIndex], NodeColor.Black); root.Right.ColorRed(); - if (redNode != null) + if (redNode is not null) { root.Left = redNode; } @@ -982,7 +982,7 @@ public void UnionWith(IEnumerable other) root = new Node(arr[startIndex + 1], NodeColor.Black); root.Left = new Node(arr[startIndex], NodeColor.Black); root.Right = new Node(arr[endIndex], NodeColor.Black); - if (redNode != null) + if (redNode is not null) { root.Left.Left = redNode; } @@ -1003,7 +1003,7 @@ public void UnionWith(IEnumerable other) public virtual void IntersectWith(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1020,10 +1020,10 @@ public virtual void IntersectWith(IEnumerable other) SortedSet? asSorted = other as SortedSet; TreeSubSet? treeSubset = this as TreeSubSet; - if (treeSubset != null) + if (treeSubset is not null) VersionCheck(); - if (asSorted != null && treeSubset == null && HasEqualComparer(asSorted)) + if (asSorted is not null && treeSubset is null && HasEqualComparer(asSorted)) { // First do a merge sort to an array. T[] merged = new T[this.Count]; @@ -1088,7 +1088,7 @@ internal virtual void IntersectWithEnumerable(IEnumerable other) public void ExceptWith(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1104,7 +1104,7 @@ public void ExceptWith(IEnumerable other) SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { // Outside range, no point in doing anything if (comparer.Compare(asSorted.Max, Min) >= 0 && comparer.Compare(asSorted.Min, Max) <= 0) @@ -1129,7 +1129,7 @@ public void ExceptWith(IEnumerable other) public void SymmetricExceptWith(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1148,7 +1148,7 @@ public void SymmetricExceptWith(IEnumerable other) SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { SymmetricExceptWithSameComparer(asSorted); } @@ -1163,7 +1163,7 @@ public void SymmetricExceptWith(IEnumerable other) private void SymmetricExceptWithSameComparer(SortedSet other) { - Debug.Assert(other != null); + Debug.Assert(other is not null); Debug.Assert(HasEqualComparer(other)); foreach (T item in other) @@ -1175,7 +1175,7 @@ private void SymmetricExceptWithSameComparer(SortedSet other) private void SymmetricExceptWithSameComparer(T[] other, int count) { - Debug.Assert(other != null); + Debug.Assert(other is not null); Debug.Assert(count >= 0 && count <= other.Length); if (count == 0) @@ -1199,7 +1199,7 @@ private void SymmetricExceptWithSameComparer(T[] other, int count) public bool IsSubsetOf(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1210,7 +1210,7 @@ public bool IsSubsetOf(IEnumerable other) } SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { if (Count > asSorted.Count) return false; @@ -1237,7 +1237,7 @@ private bool IsSubsetOfSortedSetWithSameComparer(SortedSet asSorted) public bool IsProperSubsetOf(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1250,7 +1250,7 @@ public bool IsProperSubsetOf(IEnumerable other) // another for sorted sets with the same comparer SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { if (Count >= asSorted.Count) return false; @@ -1264,7 +1264,7 @@ public bool IsProperSubsetOf(IEnumerable other) public bool IsSupersetOf(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1275,7 +1275,7 @@ public bool IsSupersetOf(IEnumerable other) // do it one way for HashSets // another for sorted sets with the same comparer SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { if (Count < asSorted.Count) return false; @@ -1294,7 +1294,7 @@ public bool IsSupersetOf(IEnumerable other) public bool IsProperSupersetOf(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1307,7 +1307,7 @@ public bool IsProperSupersetOf(IEnumerable other) // another way for sorted sets SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { if (asSorted.Count >= Count) return false; @@ -1329,13 +1329,13 @@ public bool IsProperSupersetOf(IEnumerable other) public bool SetEquals(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted)) + if (asSorted is not null && HasEqualComparer(asSorted)) { Enumerator mine = GetEnumerator(); Enumerator theirs = asSorted.GetEnumerator(); @@ -1360,7 +1360,7 @@ public bool SetEquals(IEnumerable other) public bool Overlaps(IEnumerable other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -1372,7 +1372,7 @@ public bool Overlaps(IEnumerable other) return false; SortedSet? asSorted = other as SortedSet; - if (asSorted != null && HasEqualComparer(asSorted) && (comparer.Compare(Min, asSorted.Max) > 0 || comparer.Compare(Max, asSorted.Min) < 0)) + if (asSorted is not null && HasEqualComparer(asSorted) && (comparer.Compare(Min, asSorted.Max) > 0 || comparer.Compare(Max, asSorted.Min) < 0)) { return false; } @@ -1472,7 +1472,7 @@ private unsafe ElementCount CheckUniqueAndUnfoundElements(IEnumerable other, public int RemoveWhere(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } @@ -1510,13 +1510,13 @@ internal virtual T? MinInternal { get { - if (root == null) + if (root is null) { return default; } Node current = root; - while (current.Left != null) + while (current.Left is not null) { current = current.Left; } @@ -1531,13 +1531,13 @@ internal virtual T? MaxInternal { get { - if (root == null) + if (root is null) { return default; } Node current = root; - while (current.Right != null) + while (current.Right is not null) { current = current.Right; } @@ -1579,7 +1579,7 @@ internal virtual bool versionUpToDate() protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -1588,7 +1588,7 @@ protected virtual void GetObjectData(SerializationInfo info, StreamingContext co info.AddValue(ComparerName, comparer, typeof(IComparer)); info.AddValue(VersionName, version); - if (root != null) + if (root is not null) { T[] items = new T[Count]; CopyTo(items, 0); @@ -1600,12 +1600,12 @@ protected virtual void GetObjectData(SerializationInfo info, StreamingContext co protected virtual void OnDeserialization(object? sender) { - if (comparer != null) + if (comparer is not null) { return; // Somebody had a dependency on this class and fixed us up before the ObjectManager got to it. } - if (siInfo == null) + if (siInfo is null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } @@ -1617,7 +1617,7 @@ protected virtual void OnDeserialization(object? sender) { T[]? items = (T[]?)siInfo.GetValue(ItemsName, typeof(T[])); - if (items == null) + if (items is null) { throw new SerializationException(SR.Serialization_MissingValues); } @@ -1649,11 +1649,11 @@ public Node(T item, NodeColor color) Color = color; } - public static bool IsNonNullBlack(Node? node) => node != null && node.IsBlack; + public static bool IsNonNullBlack(Node? node) => node is not null && node.IsBlack; - public static bool IsNonNullRed(Node? node) => node != null && node.IsRed; + public static bool IsNonNullRed(Node? node) => node is not null && node.IsRed; - public static bool IsNullOrBlack(Node? node) => node == null || node.IsBlack; + public static bool IsNullOrBlack(Node? node) => node is null || node.IsBlack; public T Item { get; set; } @@ -1690,7 +1690,7 @@ public Node DeepClone(int count) Node? originalCurrent = this; Node newCurrent = newRoot; - while (originalCurrent != null) + while (originalCurrent is not null) { originalNodes.Push(originalCurrent); newNodes.Push(newCurrent); @@ -1708,7 +1708,7 @@ public Node DeepClone(int count) Node? newRight = originalRight?.ShallowClone(); newCurrent.Right = newRight; - while (originalRight != null) + while (originalRight is not null) { originalNodes.Push(originalRight); newNodes.Push(newRight!); @@ -1742,7 +1742,7 @@ public TreeRotation GetRotation(Node current, Node sibling) /// public Node GetSibling(Node node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); Debug.Assert(node == Left ^ node == Right); return node == Left ? Right! : Left!; @@ -1752,8 +1752,8 @@ public Node GetSibling(Node node) public void Split4Node() { - Debug.Assert(Left != null); - Debug.Assert(Right != null); + Debug.Assert(Left is not null); + Debug.Assert(Right is not null); ColorRed(); Left.ColorBlack(); @@ -1937,7 +1937,7 @@ private void Initialize() _current = null; Node? node = _tree.root; Node? next = null, other = null; - while (node != null) + while (node is not null) { next = (_reverse ? node.Right : node.Left); other = (_reverse ? node.Left : node.Right); @@ -1946,7 +1946,7 @@ private void Initialize() _stack.Push(node); node = next; } - else if (next == null || !_tree.IsWithinRange(next.Item)) + else if (next is null || !_tree.IsWithinRange(next.Item)) { node = other; } @@ -1976,7 +1976,7 @@ public bool MoveNext() _current = _stack.Pop(); Node? node = (_reverse ? _current.Left : _current.Right); Node? next = null, other = null; - while (node != null) + while (node is not null) { next = (_reverse ? node.Right : node.Left); other = (_reverse ? node.Left : node.Right); @@ -1985,7 +1985,7 @@ public bool MoveNext() _stack.Push(node); node = next; } - else if (other == null || !_tree.IsWithinRange(other.Item)) + else if (other is null || !_tree.IsWithinRange(other.Item)) { node = next; } @@ -2003,7 +2003,7 @@ public T Current { get { - if (_current != null) + if (_current is not null) { return _current.Item; } @@ -2015,7 +2015,7 @@ public T Current { get { - if (_current == null) + if (_current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -2024,7 +2024,7 @@ public T Current } } - internal bool NotStartedOrEnded => _current == null; + internal bool NotStartedOrEnded => _current is null; internal void Reset() { @@ -2065,7 +2065,7 @@ internal struct ElementCount public bool TryGetValue(T equalValue, [MaybeNullWhen(false)] out T actualValue) { Node? node = FindNode(equalValue); - if (node != null) + if (node is not null) { actualValue = node.Item; return true; diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSetEqualityComparer.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSetEqualityComparer.cs index ffc0b8bafd2731..2d011775e6a9aa 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSetEqualityComparer.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSetEqualityComparer.cs @@ -32,11 +32,11 @@ private SortedSetEqualityComparer(IComparer? comparer, IEqualityComparer? public int GetHashCode(SortedSet obj) { int hashCode = 0; - if (obj != null) + if (obj is not null) { foreach (T t in obj) { - if (t != null) + if (t is not null) { hashCode ^= (_memberEqualityComparer.GetHashCode(t) & 0x7FFFFFFF); } @@ -50,7 +50,7 @@ public int GetHashCode(SortedSet obj) public override bool Equals(object? obj) { SortedSetEqualityComparer? comparer = obj as SortedSetEqualityComparer; - return comparer != null && _comparer == comparer._comparer; + return comparer is not null && _comparer == comparer._comparer; } public override int GetHashCode() => _comparer.GetHashCode() ^ _memberEqualityComparer.GetHashCode(); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs index 8f191eed51e48c..bc4c5c654e324b 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs @@ -50,7 +50,7 @@ public Stack(int capacity) // pushed onto the stack in the same order they are read by the enumerator. public Stack(IEnumerable collection) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); } @@ -96,7 +96,7 @@ public bool Contains(T item) // Copies the stack into an array. public void CopyTo(T[] array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -122,7 +122,7 @@ public void CopyTo(T[] array, int arrayIndex) void ICollection.CopyTo(Array array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs b/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs index 92709a55ca6419..38f68094fbb066 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs @@ -11,7 +11,7 @@ internal sealed class StackDebugView public StackDebugView(Stack stack) { - if (stack == null) + if (stack is null) { throw new ArgumentNullException(nameof(stack)); } diff --git a/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs b/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs index 792d495ca6242f..9c8a8a975584e0 100644 --- a/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs +++ b/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs @@ -15,7 +15,7 @@ public static IComparer StructuralComparer get { IComparer? comparer = s_StructuralComparer; - if (comparer == null) + if (comparer is null) { comparer = new StructuralComparer(); s_StructuralComparer = comparer; @@ -29,7 +29,7 @@ public static IEqualityComparer StructuralEqualityComparer get { IEqualityComparer? comparer = s_StructuralEqualityComparer; - if (comparer == null) + if (comparer is null) { comparer = new StructuralEqualityComparer(); s_StructuralEqualityComparer = comparer; @@ -43,16 +43,16 @@ internal sealed class StructuralEqualityComparer : IEqualityComparer { public new bool Equals(object? x, object? y) { - if (x != null) + if (x is not null) { IStructuralEquatable? seObj = x as IStructuralEquatable; - if (seObj != null) + if (seObj is not null) { return seObj.Equals(y, this); } - if (y != null) + if (y is not null) { return x.Equals(y); } @@ -61,17 +61,17 @@ internal sealed class StructuralEqualityComparer : IEqualityComparer return false; } } - if (y != null) return false; + if (y is not null) return false; return true; } public int GetHashCode(object obj) { - if (obj == null) return 0; + if (obj is null) return 0; IStructuralEquatable? seObj = obj as IStructuralEquatable; - if (seObj != null) + if (seObj is not null) { return seObj.GetHashCode(this); } @@ -84,12 +84,12 @@ internal sealed class StructuralComparer : IComparer { public int Compare(object? x, object? y) { - if (x == null) return y == null ? 0 : -1; - if (y == null) return 1; + if (x is null) return y is null ? 0 : -1; + if (y is null) return 1; IStructuralComparable? scX = x as IStructuralComparable; - if (scX != null) + if (scX is not null) { return scX.CompareTo(y, this); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs index fc7b7e456b9b9c..ac00559fd64bf5 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs @@ -34,7 +34,7 @@ public AssociatedMetadataTypeTypeDescriptionProvider(Type type) public AssociatedMetadataTypeTypeDescriptionProvider(Type type, Type associatedMetadataType) : this(type) { - if (associatedMetadataType == null) + if (associatedMetadataType is null) { throw new ArgumentNullException(nameof(associatedMetadataType)); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptor.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptor.cs index 2bc82d50a6e343..cf100f78f14566 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptor.cs @@ -23,7 +23,7 @@ public AssociatedMetadataTypeTypeDescriptor(ICustomTypeDescriptor parent, Type t { AssociatedMetadataType = associatedMetadataType ?? TypeDescriptorCache.GetAssociatedMetadataType(type); IsSelfAssociated = (type == AssociatedMetadataType); - if (AssociatedMetadataType != null) + if (AssociatedMetadataType is not null) { TypeDescriptorCache.ValidateMetadataType(type, AssociatedMetadataType); } @@ -41,7 +41,7 @@ public override PropertyDescriptorCollection GetProperties() private PropertyDescriptorCollection GetPropertiesWithMetadata(PropertyDescriptorCollection originalCollection) { - if (AssociatedMetadataType == null) + if (AssociatedMetadataType is null) { return originalCollection; } @@ -75,7 +75,7 @@ public override AttributeCollection GetAttributes() // calls to GetAttributes, we must be sure below to use the TD APIs to get both // the base and associated attributes AttributeCollection attributes = base.GetAttributes(); - if (AssociatedMetadataType != null && !IsSelfAssociated) + if (AssociatedMetadataType is not null && !IsSelfAssociated) { // Note that the use of TypeDescriptor.GetAttributes here opens up the possibility of // infinite recursion, in the corner case of two Types referencing each other as @@ -118,7 +118,7 @@ public static Type GetAssociatedMetadataType(Type type) // Try association attribute MetadataTypeAttribute attribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(type, typeof(MetadataTypeAttribute)); - if (attribute != null) + if (attribute is not null) { associatedMetadataType = attribute.MetadataClassType; } @@ -163,7 +163,7 @@ public static Attribute[] GetAssociatedMetadata(Type type, string memberName) BindingFlags searchFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; // Try to find a matching member on type MemberInfo matchingMember = type.GetMember(memberName, allowedMemberTypes, searchFlags).FirstOrDefault(); - if (matchingMember != null) + if (matchingMember is not null) { attributes = Attribute.GetCustomAttributes(matchingMember, true /* inherit */); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs index 41078c03f41960..16b9fe2b969ed3 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs @@ -70,7 +70,7 @@ public AssociationAttribute(string name, string thisKey, string otherKey) /// Array of individual key members private static string[] GetKeyMembers(string? key) { - if (key == null) + if (key is null) { return Array.Empty(); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs index dab56c6018e6e5..61412c428e8a32 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs @@ -28,7 +28,7 @@ public override string FormatErrorMessage(string name) => protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { var otherPropertyInfo = validationContext.ObjectType.GetRuntimeProperty(OtherProperty); - if (otherPropertyInfo == null) + if (otherPropertyInfo is null) { return new ValidationResult(SR.Format(SR.CompareAttribute_UnknownProperty, OtherProperty)); } @@ -40,12 +40,12 @@ public override string FormatErrorMessage(string name) => object? otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (!Equals(value, otherPropertyValue)) { - if (OtherPropertyDisplayName == null) + if (OtherPropertyDisplayName is null) { OtherPropertyDisplayName = GetDisplayNameForProperty(otherPropertyInfo); } - string[]? memberNames = validationContext.MemberName != null + string[]? memberNames = validationContext.MemberName is not null ? new[] { validationContext.MemberName } : null; return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames); @@ -58,7 +58,7 @@ public override string FormatErrorMessage(string name) => { var attributes = CustomAttributeExtensions.GetCustomAttributes(property, true); var display = attributes.OfType().FirstOrDefault(); - if (display != null) + if (display is not null) { // TODO-NULLABLE: This will return null if [DisplayName] is specified but no Name has been defined - probably a bug. // Should fall back to OtherProperty in this case instead. diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CreditCardAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CreditCardAttribute.cs index 4715007eaf8b37..3bf233e6cedd48 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CreditCardAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CreditCardAttribute.cs @@ -17,7 +17,7 @@ public CreditCardAttribute() public override bool IsValid(object? value) { - if (value == null) + if (value is null) { return true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs index 67c7077102be92..50d88612f5c887 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs @@ -157,7 +157,7 @@ public override bool RequiresValidationContext if (!TryConvertValue(value, out convertedValue)) { return new ValidationResult(SR.Format(SR.CustomValidationAttribute_Type_Conversion_Failed, - (value != null ? value.GetType().ToString() : "null"), + (value is not null ? value.GetType().ToString() : "null"), _firstParameterType, ValidatorType, Method)); @@ -180,7 +180,7 @@ public override bool RequiresValidationContext // otherwise we use the normal message supplied via the ctor _lastMessage = null; - if (result != null) + if (result is not null) { _lastMessage = result.ErrorMessage; } @@ -225,7 +225,7 @@ public override string FormatErrorMessage(string name) /// null or the appropriate error message. private string? ValidateValidatorTypeParameter() { - if (ValidatorType == null) + if (ValidatorType is null) { return SR.CustomValidationAttribute_ValidatorType_Required; } @@ -253,7 +253,7 @@ public override string FormatErrorMessage(string name) var methodInfo = ValidatorType.GetRuntimeMethods() .SingleOrDefault(m => string.Equals(m.Name, Method, StringComparison.Ordinal) && m.IsPublic && m.IsStatic); - if (methodInfo == null) + if (methodInfo is null) { return SR.Format(SR.CustomValidationAttribute_Method_Not_Found, Method, ValidatorType.Name); } @@ -296,7 +296,7 @@ public override string FormatErrorMessage(string name) private void ThrowIfAttributeNotWellFormed() { string? errorMessage = _malformedErrorMessage.Value; - if (errorMessage != null) + if (errorMessage is not null) { throw new InvalidOperationException(errorMessage); } @@ -315,7 +315,7 @@ private bool TryConvertValue(object? value, out object? convertedValue) var expectedValueType = _firstParameterType!; // Null is permitted for reference types or for Nullable<>'s only - if (value == null) + if (value is null) { if (expectedValueType.IsValueType && (!expectedValueType.IsGenericType diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EmailAddressAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EmailAddressAttribute.cs index 2e28b0cb6ac3df..61d0d14a1a575a 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EmailAddressAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EmailAddressAttribute.cs @@ -17,7 +17,7 @@ public EmailAddressAttribute() public override bool IsValid(object? value) { - if (value == null) + if (value is null) { return true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs index 18dd723deb304f..1da35af5e3b7a5 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs @@ -22,7 +22,7 @@ public EnumDataTypeAttribute(Type enumType) public override bool IsValid(object? value) { - if (EnumType == null) + if (EnumType is null) { throw new InvalidOperationException(SR.EnumDataTypeAttribute_TypeCannotBeNull); } @@ -31,7 +31,7 @@ public override bool IsValid(object? value) throw new InvalidOperationException(SR.Format(SR.EnumDataTypeAttribute_TypeNeedsToBeAnEnum, EnumType.FullName)); } - if (value == null) + if (value is null) { return true; } @@ -74,7 +74,7 @@ public override bool IsValid(object? value) { try { - convertedValue = stringValue != null + convertedValue = stringValue is not null ? Enum.Parse(EnumType, stringValue, false) : Enum.ToObject(EnumType, value); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs index e66e2807e51a36..5d3380a3fd22fc 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs @@ -43,7 +43,7 @@ public override string FormatErrorMessage(string name) => string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, ExtensionsFormatted); public override bool IsValid(object? value) => - value == null || value is string valueAsString && ValidateExtension(valueAsString); + value is null || value is string valueAsString && ValidateExtension(valueAsString); private bool ValidateExtension(string fileName) { diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs index 5c8dfca6b56d47..bcd4a67b98af12 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs @@ -110,11 +110,11 @@ private void ClearCache() /// public string? GetLocalizableValue() { - if (_cachedResult == null) + if (_cachedResult is null) { // If the property value is null, then just cache that value // If the resource type is null, then property value is literal, so cache it - if (_propertyValue == null || _resourceType == null) + if (_propertyValue is null || _resourceType is null) { _cachedResult = () => _propertyValue; } @@ -127,7 +127,7 @@ private void ClearCache() var badlyConfigured = false; // Make sure we found the property and it's the correct type, and that the type itself is public - if (!_resourceType.IsVisible || property == null || + if (!_resourceType.IsVisible || property is null || property.PropertyType != typeof(string)) { badlyConfigured = true; @@ -138,7 +138,7 @@ private void ClearCache() // TODO - check that GetMethod returns the same as old GetGetMethod() // in all situations regardless of modifiers var getter = property.GetMethod; - if (getter == null || !(getter.IsPublic && getter.IsStatic)) + if (getter is null || !(getter.IsPublic && getter.IsStatic)) { badlyConfigured = true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs index 903112d41fa84f..e52f1f6aa7b3d8 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs @@ -66,7 +66,7 @@ public override bool IsValid(object? value) int length; // Automatically pass if value is null. RequiredAttribute should be used to assert a value is not null. - if (value == null) + if (value is null) { return true; } @@ -112,7 +112,7 @@ internal static class CountPropertyHelper { public static bool TryGetCount(object value, out int count) { - Debug.Assert(value != null); + Debug.Assert(value is not null); if (value is ICollection collection) { @@ -121,7 +121,7 @@ public static bool TryGetCount(object value, out int count) } PropertyInfo? property = value.GetType().GetRuntimeProperty("Count"); - if (property != null && property.CanRead && property.PropertyType == typeof(int)) + if (property is not null && property.CanRead && property.PropertyType == typeof(int)) { count = (int)property.GetValue(value)!; return true; diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataPropertyDescriptorWrapper.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataPropertyDescriptorWrapper.cs index 95df5e1f1a82b8..05dfbbb4ce673d 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataPropertyDescriptorWrapper.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataPropertyDescriptorWrapper.cs @@ -17,7 +17,7 @@ public MetadataPropertyDescriptorWrapper(PropertyDescriptor descriptor, Attribut { _descriptor = descriptor; var readOnlyAttribute = newAttributes.OfType().FirstOrDefault(); - _isReadOnly = (readOnlyAttribute != null ? readOnlyAttribute.IsReadOnly : false); + _isReadOnly = (readOnlyAttribute is not null ? readOnlyAttribute.IsReadOnly : false); } public override void AddValueChanged(object component, EventHandler handler) { _descriptor.AddValueChanged(component, handler); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataTypeAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataTypeAttribute.cs index b4e3b568bccdf9..8bc6524aeec36d 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataTypeAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MetadataTypeAttribute.cs @@ -31,7 +31,7 @@ public Type MetadataClassType { get { - if (_metadataClassType == null) + if (_metadataClassType is null) { throw new InvalidOperationException(SR.MetadataTypeAttribute_TypeCannotBeNull); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs index 7b0e09f659050f..7e0d125f3d59c3 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs @@ -50,7 +50,7 @@ public override bool IsValid(object? value) int length; // Automatically pass if value is null. RequiredAttribute should be used to assert a value is not null. - if (value == null) + if (value is null) { return true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/PhoneAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/PhoneAttribute.cs index cec872c27f4c3c..12312aedc50fc8 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/PhoneAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/PhoneAttribute.cs @@ -22,7 +22,7 @@ public PhoneAttribute() public override bool IsValid(object? value) { - if (value == null) + if (value is null) { return true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs index a3b2e0b96c5119..f9025be3b24c18 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs @@ -110,7 +110,7 @@ public override bool IsValid(object? value) SetupConversion(); // Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty. - if (value == null || (value as string)?.Length == 0) + if (value is null || (value as string)?.Length == 0) { return true; } @@ -160,12 +160,12 @@ public override string FormatErrorMessage(string name) /// private void SetupConversion() { - if (Conversion == null) + if (Conversion is null) { object minimum = Minimum; object maximum = Maximum; - if (minimum == null || maximum == null) + if (minimum is null || maximum is null) { throw new InvalidOperationException(SR.RangeAttribute_Must_Set_Min_And_Max); } @@ -187,7 +187,7 @@ private void SetupConversion() else { Type type = OperandType; - if (type == null) + if (type is null) { throw new InvalidOperationException(SR.RangeAttribute_Must_Set_Operand_Type); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs index e7f4eb1db432e4..d52215e2a48ec7 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs @@ -92,7 +92,7 @@ public override string FormatErrorMessage(string name) /// zero or greater than approximately 24 days private void SetupRegex() { - if (Regex == null) + if (Regex is null) { if (string.IsNullOrEmpty(Pattern)) { diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs index a5003f0d2d3188..843929cb3a1c3a 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs @@ -38,7 +38,7 @@ public RequiredAttribute() /// public override bool IsValid(object? value) { - if (value == null) + if (value is null) { return false; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs index 17e39eec4b3c34..e24c3eba8bf567 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs @@ -49,7 +49,7 @@ public override bool IsValid(object? value) // Automatically pass if value is null. RequiredAttribute should be used to assert a value is not null. // We expect a cast exception if a non-string was passed in. - if (value == null) + if (value is null) { return true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs index 4b4819886fd16e..555d591c7c756f 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs @@ -77,7 +77,7 @@ public UIHintImplementation(string uiHint, string? presentationLayer, params obj { UIHint = uiHint; PresentationLayer = presentationLayer; - if (controlParameters != null) + if (controlParameters is not null) { _inputControlParameters = new object[controlParameters.Length]; Array.Copy(controlParameters, _inputControlParameters, controlParameters.Length); @@ -142,8 +142,8 @@ public override bool Equals(object? obj) return false; } - Debug.Assert(leftParams != null, "leftParams shouldn't be null"); - Debug.Assert(rightParams != null, "rightParams shouldn't be null"); + Debug.Assert(leftParams is not null, "leftParams shouldn't be null"); + Debug.Assert(rightParams is not null, "rightParams shouldn't be null"); if (leftParams.Count != rightParams.Count) { return false; @@ -164,7 +164,7 @@ public override bool Equals(object? obj) object?[]? inputControlParameters = _inputControlParameters; - if (inputControlParameters == null || inputControlParameters.Length == 0) + if (inputControlParameters is null || inputControlParameters.Length == 0) { return controlParameters; } @@ -177,7 +177,7 @@ public override bool Equals(object? obj) { object? key = inputControlParameters[i]; object? value = inputControlParameters[i + 1]; - if (key == null) + if (key is null) { throw new InvalidOperationException(SR.Format(SR.UIHintImplementation_ControlParameterKeyIsNull, i)); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UrlAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UrlAttribute.cs index 9913f1883e7636..6739ee24ff22f0 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UrlAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UrlAttribute.cs @@ -17,7 +17,7 @@ public UrlAttribute() public override bool IsValid(object? value) { - if (value == null) + if (value is null) { return true; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs index 01ec012f20de99..8592843d44bc99 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs @@ -140,7 +140,7 @@ public string? ErrorMessage // Explicitly setting ErrorMessage also sets DefaultErrorMessage if null. // This prevents subsequent read of ErrorMessage from returning default. - if (value == null) + if (value is null) { _defaultErrorMessage = null; } @@ -197,12 +197,12 @@ public Type? ErrorMessageResourceType /// is thrown if the current attribute is malformed. private void SetupResourceAccessor() { - if (_errorMessageResourceAccessor == null) + if (_errorMessageResourceAccessor is null) { string? localErrorMessage = ErrorMessage; bool resourceNameSet = !string.IsNullOrEmpty(_errorMessageResourceName); bool errorMessageSet = !string.IsNullOrEmpty(_errorMessage); - bool resourceTypeSet = _errorMessageResourceType != null; + bool resourceTypeSet = _errorMessageResourceType is not null; bool defaultMessageSet = !string.IsNullOrEmpty(_defaultErrorMessage); // The following combinations are illegal and throw InvalidOperationException: @@ -238,28 +238,28 @@ private void SetupResourceAccessor() private void SetResourceAccessorByPropertyLookup() { - Debug.Assert(_errorMessageResourceType != null); + Debug.Assert(_errorMessageResourceType is not null); Debug.Assert(!string.IsNullOrEmpty(_errorMessageResourceName)); var property = _errorMessageResourceType .GetTypeInfo().GetDeclaredProperty(_errorMessageResourceName); - if (property != null && !ValidationAttributeStore.IsStatic(property)) + if (property is not null && !ValidationAttributeStore.IsStatic(property)) { property = null; } - if (property != null) + if (property is not null) { var propertyGetter = property.GetMethod; // We only support internal and public properties - if (propertyGetter == null || (!propertyGetter.IsAssembly && !propertyGetter.IsPublic)) + if (propertyGetter is null || (!propertyGetter.IsAssembly && !propertyGetter.IsPublic)) { // Set the property to null so the exception is thrown as if the property wasn't found property = null; } } - if (property == null) + if (property is null) { throw new InvalidOperationException(SR.Format(SR.ValidationAttribute_ResourceTypeDoesNotHaveProperty, _errorMessageResourceType.FullName, @@ -411,7 +411,7 @@ public virtual bool IsValid(object? value) /// public ValidationResult? GetValidationResult(object? value, ValidationContext validationContext) { - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } @@ -419,7 +419,7 @@ public virtual bool IsValid(object? value) var result = IsValid(value, validationContext); // If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage - if (result != null) + if (result is not null) { if (string.IsNullOrEmpty(result.ErrorMessage)) { @@ -481,14 +481,14 @@ public void Validate(object? value, string name) /// public void Validate(object? value, ValidationContext validationContext) { - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } ValidationResult? result = GetValidationResult(value, validationContext); - if (result != null) + if (result is not null) { // Convenience -- if implementation did not fill in an error message, throw new ValidationException(result, this, value); diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs index db3b57bd0be181..056273e8201c8b 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs @@ -112,7 +112,7 @@ internal bool IsPropertyContext(ValidationContext validationContext) /// The type store item. It will not be null. private TypeStoreItem GetTypeStoreItem(Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); lock (_typeStoreItems) { @@ -134,17 +134,17 @@ private TypeStoreItem GetTypeStoreItem(Type type) /// The context to check private static void EnsureValidationContext(ValidationContext validationContext) { - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } } internal static bool IsPublic(PropertyInfo p) => - (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic); + (p.GetMethod is not null && p.GetMethod.IsPublic) || (p.SetMethod is not null && p.SetMethod.IsPublic); internal static bool IsStatic(PropertyInfo p) => - (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic); + (p.GetMethod is not null && p.GetMethod.IsStatic) || (p.SetMethod is not null && p.SetMethod.IsStatic); /// /// Private abstract class for all store items @@ -195,11 +195,11 @@ internal bool TryGetPropertyStoreItem(string propertyName, [NotNullWhen(true)] o throw new ArgumentNullException(nameof(propertyName)); } - if (_propertyStoreItems == null) + if (_propertyStoreItems is null) { lock (_syncRoot) { - if (_propertyStoreItems == null) + if (_propertyStoreItems is null) { _propertyStoreItems = CreatePropertyStoreItems(); } @@ -236,7 +236,7 @@ private class PropertyStoreItem : StoreItem internal PropertyStoreItem(Type propertyType, IEnumerable attributes) : base(attributes) { - Debug.Assert(propertyType != null); + Debug.Assert(propertyType is not null); PropertyType = propertyType; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs index f12578ac9d6ec8..c94cd28580b3a9 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs @@ -80,17 +80,17 @@ public ValidationContext(object instance, IDictionary? items) /// When is null public ValidationContext(object instance, IServiceProvider? serviceProvider, IDictionary? items) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } - if (serviceProvider != null) + if (serviceProvider is not null) { InitializeServiceProvider(serviceType => serviceProvider.GetService(serviceType)); } - _items = items != null ? new Dictionary(items) : new Dictionary(); + _items = items is not null ? new Dictionary(items) : new Dictionary(); ObjectInstance = instance; } @@ -189,7 +189,7 @@ public string DisplayName displayAttribute = store.GetPropertyDisplayAttribute(this); } - if (displayAttribute != null) + if (displayAttribute is not null) { displayName = displayAttribute.GetName(); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs index fa26fd83bd1816..c8ee178ad2ca01 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs @@ -67,7 +67,7 @@ public ValidationResult(string? errorMessage, IEnumerable? memberNames) /// The is null. protected ValidationResult(ValidationResult validationResult) { - if (validationResult == null) + if (validationResult is null) { throw new ArgumentNullException(nameof(validationResult)); } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs index b6251f53451f37..e13d587eab972e 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs @@ -56,7 +56,7 @@ public static bool TryValidateProperty(object? value, ValidationContext validati EnsureValidPropertyType(propertyName, propertyType, value); var result = true; - var breakOnFirstError = (validationResults == null); + var breakOnFirstError = (validationResults is null); var attributes = _store.GetPropertyValidationAttributes(validationContext); @@ -132,19 +132,19 @@ public static bool TryValidateObject( public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection? validationResults, bool validateAllProperties) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } // TODO-NULLABLE: null validationContext isn't supported (GetObjectValidationErrors will throw), remove that check - if (validationContext != null && instance != validationContext.ObjectInstance) + if (validationContext is not null && instance != validationContext.ObjectInstance) { throw new ArgumentException(SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); } var result = true; - var breakOnFirstError = (validationResults == null); + var breakOnFirstError = (validationResults is null); foreach (ValidationError err in GetObjectValidationErrors(instance, validationContext!, validateAllProperties, breakOnFirstError)) { @@ -189,7 +189,7 @@ public static bool TryValidateValue(object value, ValidationContext validationCo ICollection? validationResults, IEnumerable validationAttributes) { var result = true; - var breakOnFirstError = validationResults == null; + var breakOnFirstError = validationResults is null; foreach ( var err in @@ -271,11 +271,11 @@ public static void ValidateObject(object instance, ValidationContext validationC public static void ValidateObject(object instance, ValidationContext validationContext, bool validateAllProperties) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } @@ -307,7 +307,7 @@ public static void ValidateObject(object instance, ValidationContext validationC public static void ValidateValue(object value, ValidationContext validationContext, IEnumerable validationAttributes) { - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } @@ -328,7 +328,7 @@ public static void ValidateValue(object value, ValidationContext validationConte /// When is null. private static ValidationContext CreateValidationContext(object instance, ValidationContext validationContext) { - Debug.Assert(validationContext != null); + Debug.Assert(validationContext is not null); // Create a new context using the existing ValidationContext that acts as an IServiceProvider and contains our existing items. var context = new ValidationContext(instance, validationContext, validationContext.Items); @@ -347,7 +347,7 @@ private static ValidationContext CreateValidationContext(object instance, Valida /// When is null. private static bool CanBeAssigned(Type destinationType, object? value) { - if (value == null) + if (value is null) { // Null can be assigned only to reference types or Nullable or Nullable<> return !destinationType.IsValueType || @@ -395,9 +395,9 @@ private static void EnsureValidPropertyType(string propertyName, Type propertyTy private static IEnumerable GetObjectValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError) { - Debug.Assert(instance != null); + Debug.Assert(instance is not null); - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } @@ -428,7 +428,7 @@ private static IEnumerable GetObjectValidationErrors(object ins { var results = validatable.Validate(validationContext); - if (results != null) + if (results is not null) { foreach (var result in results.Where(r => r != ValidationResult.Success)) { @@ -471,7 +471,7 @@ private static IEnumerable GetObjectPropertyValidationErrors(ob { // only validate the Required attributes var reqAttr = attributes.OfType().FirstOrDefault(); - if (reqAttr != null) + if (reqAttr is not null) { // Note: we let the [Required] attribute do its own null testing, // since the user may have subclassed it and have a deeper meaning to what 'required' means @@ -542,7 +542,7 @@ private static IEnumerable GetObjectPropertyValidationErrors(ob private static IEnumerable GetValidationErrors(object? value, ValidationContext validationContext, IEnumerable attributes, bool breakOnFirstError) { - if (validationContext == null) + if (validationContext is null) { throw new ArgumentNullException(nameof(validationContext)); } @@ -552,7 +552,7 @@ private static IEnumerable GetValidationErrors(object? value, // Get the required validator if there is one and test it first, aborting on failure var required = attributes.OfType().FirstOrDefault(); - if (required != null) + if (required is not null) { if (!TryValidate(value, validationContext, required, out validationError)) { @@ -597,7 +597,7 @@ private static IEnumerable GetValidationErrors(object? value, private static bool TryValidate(object? value, ValidationContext validationContext, ValidationAttribute attribute, [NotNullWhen(false)] out ValidationError? validationError) { - Debug.Assert(validationContext != null); + Debug.Assert(validationContext is not null); var validationResult = attribute.GetValidationResult(value, validationContext); if (validationResult != ValidationResult.Success) diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs index 77b84b7cb45ee4..c85fe3ade6b4b2 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs @@ -40,7 +40,7 @@ public ExportBuilder Inherited() public ExportBuilder AddMetadata(string name, object value) { - if (_metadataItems == null) + if (_metadataItems is null) { _metadataItems = new List>(); } @@ -51,7 +51,7 @@ public ExportBuilder AddMetadata(string name, object value) public ExportBuilder AddMetadata(string name, Func itemFunc) { - if (_metadataItemFuncs == null) + if (_metadataItemFuncs is null) { _metadataItemFuncs = new List>>(); } @@ -62,7 +62,7 @@ public ExportBuilder AddMetadata(string name, Func itemFunc) internal void BuildAttributes(Type type, ref List attributes) { - if (attributes == null) + if (attributes is null) { attributes = new List(); } @@ -79,7 +79,7 @@ internal void BuildAttributes(Type type, ref List attributes) } //Add metadata attributes from direct specification - if (_metadataItems != null) + if (_metadataItems is not null) { foreach (Tuple item in _metadataItems) { @@ -88,12 +88,12 @@ internal void BuildAttributes(Type type, ref List attributes) } //Add metadata attributes from func specification - if (_metadataItemFuncs != null) + if (_metadataItemFuncs is not null) { foreach (Tuple> item in _metadataItemFuncs) { string name = item.Item1; - object value = (item.Item2 != null) ? item.Item2(type.UnderlyingSystemType) : null; + object value = (item.Item2 is not null) ? item.Item2(type.UnderlyingSystemType) : null; attributes.Add(new ExportMetadataAttribute(name, value)); } } diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs index 1b969983415679..143a5e9bd167cb 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs @@ -94,7 +94,7 @@ internal void BuildAttributes(Type type, ref List attributes) }; } - if (attributes == null) + if (attributes is null) { attributes = new List(); } diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs index c7296f9543e596..533a3b76583c46 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs @@ -101,7 +101,7 @@ public PartBuilder ExportInterfaces() public PartBuilder ExportInterfaces(Predicate interfaceFilter, Action exportConfiguration) { - if (interfaceFilter == null) + if (interfaceFilter is null) throw new ArgumentNullException(nameof(interfaceFilter)); _interfaceExports.Add(Tuple.Create(interfaceFilter, exportConfiguration)); @@ -111,7 +111,7 @@ public PartBuilder ExportInterfaces(Predicate interfaceFilter, // Choose a property to export then configure it public PartBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); return ExportProperties(propertyFilter, null); @@ -120,7 +120,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter) public PartBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, default(Type))); @@ -131,7 +131,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter, // Choose a property to export then configure it public PartBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); return ExportProperties(propertyFilter, null); @@ -140,7 +140,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter) public PartBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, typeof(T))); @@ -151,7 +151,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter, // Choose a property to export then configure it public PartBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); return ImportProperties(propertyFilter, null); @@ -160,7 +160,7 @@ public PartBuilder ImportProperties(Predicate propertyFilter) public PartBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration, default(Type))); @@ -170,7 +170,7 @@ public PartBuilder ImportProperties(Predicate propertyFilter, // Choose a property to export then configure it public PartBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); return ImportProperties(propertyFilter, null); @@ -179,7 +179,7 @@ public PartBuilder ImportProperties(Predicate propertyFilter) public PartBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration, typeof(T))); @@ -195,7 +195,7 @@ public PartBuilder SetCreationPolicy(CreationPolicy creationPolicy) public PartBuilder AddMetadata(string name, object value) { - if (_metadataItems == null) + if (_metadataItems is null) { _metadataItems = new List>(); } @@ -206,7 +206,7 @@ public PartBuilder AddMetadata(string name, object value) public PartBuilder AddMetadata(string name, Func itemFunc) { - if (_metadataItemFuncs == null) + if (_metadataItemFuncs is null) { _metadataItemFuncs = new List>>(); } @@ -240,9 +240,9 @@ internal IEnumerable BuildTypeAttributes(Type type) { var attributes = new List(); - if (_typeExportBuilders != null) + if (_typeExportBuilders is not null) { - bool isConfigured = type.GetCustomAttributes(typeof(ExportAttribute), false).FirstOrDefault() != null || MemberHasExportMetadata(type); + bool isConfigured = type.GetCustomAttributes(typeof(ExportAttribute), false).FirstOrDefault() is not null || MemberHasExportMetadata(type); if (isConfigured) { CompositionTrace.Registration_TypeExportConventionOverridden(type); @@ -261,7 +261,7 @@ internal IEnumerable BuildTypeAttributes(Type type) // Check if there is already a PartCreationPolicyAttribute // If found Trace a warning and do not add the registered part creationpolicy // otherwise add new one - bool isConfigured = type.GetCustomAttributes(typeof(PartCreationPolicyAttribute), false).FirstOrDefault() != null; + bool isConfigured = type.GetCustomAttributes(typeof(PartCreationPolicyAttribute), false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_PartCreationConventionOverridden(type); @@ -273,9 +273,9 @@ internal IEnumerable BuildTypeAttributes(Type type) } //Add metadata attributes from direct specification - if (_metadataItems != null) + if (_metadataItems is not null) { - bool isConfigured = type.GetCustomAttributes(typeof(PartMetadataAttribute), false).FirstOrDefault() != null; + bool isConfigured = type.GetCustomAttributes(typeof(PartMetadataAttribute), false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_PartMetadataConventionOverridden(type); @@ -290,9 +290,9 @@ internal IEnumerable BuildTypeAttributes(Type type) } //Add metadata attributes from func specification - if (_metadataItemFuncs != null) + if (_metadataItemFuncs is not null) { - bool isConfigured = type.GetCustomAttributes(typeof(PartMetadataAttribute), false).FirstOrDefault() != null; + bool isConfigured = type.GetCustomAttributes(typeof(PartMetadataAttribute), false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_PartMetadataConventionOverridden(type); @@ -302,7 +302,7 @@ internal IEnumerable BuildTypeAttributes(Type type) foreach (Tuple> item in _metadataItemFuncs) { var name = item.Item1; - var value = (item.Item2 != null) ? item.Item2(type) : null; + var value = (item.Item2 is not null) ? item.Item2(type) : null; attributes.Add(new PartMetadataAttribute(name, value)); } } @@ -310,9 +310,9 @@ internal IEnumerable BuildTypeAttributes(Type type) if (_interfaceExports.Any()) { - if (_typeExportBuilders != null) + if (_typeExportBuilders is not null) { - bool isConfigured = type.GetCustomAttributes(typeof(ExportAttribute), false).FirstOrDefault() != null || MemberHasExportMetadata(type); + bool isConfigured = type.GetCustomAttributes(typeof(ExportAttribute), false).FirstOrDefault() is not null || MemberHasExportMetadata(type); if (isConfigured) { CompositionTrace.Registration_TypeExportConventionOverridden(type); @@ -331,7 +331,7 @@ internal IEnumerable BuildTypeAttributes(Type type) // Run through the export specifications see if any match foreach (Tuple, Action> exportSpecification in _interfaceExports) { - if (exportSpecification.Item1 != null && exportSpecification.Item1(underlyingType)) + if (exportSpecification.Item1 is not null && exportSpecification.Item1(underlyingType)) { ExportBuilder exportBuilder = new ExportBuilder(); exportBuilder.AsContractType((Type)iface); @@ -364,17 +364,17 @@ internal bool BuildConstructorAttributes(Type type, ref List>> configuredMembers, Action configureConstuctorImports) { - if (configuredMembers == null) + if (configuredMembers is null) { configuredMembers = new List>>(); } @@ -413,7 +413,7 @@ private static void ConfigureConstructorAttributes(ConstructorInfo constructorIn ParameterInfo[] parameterInfos = constructorInfo.GetParameters(); foreach (ParameterInfo pi in parameterInfos) { - bool isConfigured = pi.GetCustomAttributes(typeof(ImportAttribute), false).FirstOrDefault() != null || pi.GetCustomAttributes(typeof(ImportManyAttribute), false).FirstOrDefault() != null; + bool isConfigured = pi.GetCustomAttributes(typeof(ImportAttribute), false).FirstOrDefault() is not null || pi.GetCustomAttributes(typeof(ImportManyAttribute), false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_ParameterImportConventionOverridden(pi, constructorInfo); @@ -448,11 +448,11 @@ internal void BuildPropertyAttributes(Type type, ref List, Action, Type> importSpecification in _propertyImports) { - if (importSpecification.Item1 != null && importSpecification.Item1(declaredPi)) + if (importSpecification.Item1 is not null && importSpecification.Item1(declaredPi)) { var importBuilder = new ImportBuilder(); - if (importSpecification.Item3 != null) + if (importSpecification.Item3 is not null) { importBuilder.AsContractType(importSpecification.Item3); } @@ -461,7 +461,7 @@ internal void BuildPropertyAttributes(Type type, ref List, Action, Type> exportSpecification in _propertyExports) { - if (exportSpecification.Item1 != null && exportSpecification.Item1(declaredPi)) + if (exportSpecification.Item1 is not null && exportSpecification.Item1(declaredPi)) { var exportBuilder = new ExportBuilder(); - if (exportSpecification.Item3 != null) + if (exportSpecification.Item3 is not null) { exportBuilder.AsContractType(exportSpecification.Item3); } @@ -501,7 +501,7 @@ internal void BuildPropertyAttributes(Type type, ref List>>(); } diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs index 9fbc89b096b53b..26f578b771940e 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs @@ -41,7 +41,7 @@ public void ConfigureExport(PropertyInfo propertyInfo, ExportBuilder exportBuild private static PropertyInfo SelectProperties(Expression> propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); Expression expr = Reduce(propertyFilter).Body; @@ -85,7 +85,7 @@ public ConstructorInfo SelectConstructor(ConstructorInfo[] constructorInfos) public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportBuilder importBuilder) { - if (_importBuilders != null && + if (_importBuilders is not null && _importBuilders.TryGetValue(parameterInfo, out Action parameterImportBuilder)) { parameterImportBuilder(importBuilder); @@ -94,7 +94,7 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportBuild private void ParseSelectConstructor(Expression> constructorFilter) { - if (constructorFilter == null) + if (constructorFilter is null) throw new ArgumentNullException(nameof(constructorFilter)); Expression expr = Reduce(constructorFilter).Body; @@ -122,7 +122,7 @@ private void ParseSelectConstructor(Expression> var lambdaExpression = (LambdaExpression)parameter; Delegate importDelegate = lambdaExpression.Compile(); - if (_importBuilders == null) + if (_importBuilders is null) { _importBuilders = new Dictionary>(); } @@ -152,7 +152,7 @@ internal PartBuilder(Predicate selectType) : base(selectType) public PartBuilder SelectConstructor(Expression> constructorFilter) { - if (constructorFilter == null) + if (constructorFilter is null) throw new ArgumentNullException(nameof(constructorFilter)); var adapter = new ConstructorExpressionAdapter(constructorFilter); @@ -171,7 +171,7 @@ public PartBuilder ExportProperty( Expression> propertyFilter, Action exportConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); @@ -188,7 +188,7 @@ public PartBuilder ExportProperty(Expression> prop public PartBuilder ExportProperty(Expression> propertyFilter, Action exportConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); @@ -205,7 +205,7 @@ public PartBuilder ImportProperty(Expression> propertyFilter) public PartBuilder ImportProperty(Expression> propertyFilter, Action importConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); @@ -222,7 +222,7 @@ public PartBuilder ImportProperty(Expression> prop public PartBuilder ImportProperty(Expression> propertyFilter, Action importConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) throw new ArgumentNullException(nameof(propertyFilter)); var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs index 3b3c31d2dd712b..6f5dec7230d3dd 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs @@ -40,7 +40,7 @@ public PartBuilder ForTypesDerivedFrom() public PartBuilder ForTypesDerivedFrom(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); var partBuilder = new PartBuilder((t) => type != t && type.IsAssignableFrom(t)); @@ -59,7 +59,7 @@ public PartBuilder ForType() public PartBuilder ForType(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); var partBuilder = new PartBuilder((t) => t == type); @@ -70,7 +70,7 @@ public PartBuilder ForType(Type type) public PartBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter == null) + if (typeFilter is null) throw new ArgumentNullException(nameof(typeFilter)); var partBuilder = new PartBuilder(typeFilter); @@ -81,7 +81,7 @@ public PartBuilder ForTypesMatching(Predicate typeFilter) public PartBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter == null) + if (typeFilter is null) throw new ArgumentNullException(nameof(typeFilter)); var partBuilder = new PartBuilder(typeFilter); @@ -134,7 +134,7 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Mem _memberInfos.TryGetValue(underlyingMemberType, out cachedAttributes); } - if (cachedAttributes == null) + if (cachedAttributes is null) { using (new WriteLock(_lock)) { @@ -145,7 +145,7 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Mem foreach (Tuple> element in EvaluateThisTypeAgainstTheConvention((Type)member)) { attributeList = element.Item2; - if (attributeList != null) + if (attributeList is not null) { if (element.Item1 is MemberInfo) { @@ -206,7 +206,7 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Mem cachedAttributes = ReadMemberCustomAttributes(member); } - return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes); + return cachedAttributes is null ? attributes : attributes.Concat(cachedAttributes); } //This is where ParameterImports will be handled @@ -215,7 +215,7 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Par IEnumerable attributes = base.GetCustomAttributes(parameter, declaredAttributes); List cachedAttributes = ReadParameterCustomAttributes(parameter); - return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes); + return cachedAttributes is null ? attributes : attributes.Concat(cachedAttributes); } private List ReadMemberCustomAttributes(MemberInfo member) diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs index 4a2e6838843f79..b1ddf255c8cd3f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs @@ -11,12 +11,12 @@ internal static partial class CollectionServices { public static ICollection GetCollectionWrapper(Type itemType, object collectionObject) { - if (itemType == null) + if (itemType is null) { throw new ArgumentNullException(nameof(itemType)); } - if (collectionObject == null) + if (collectionObject is null) { throw new ArgumentNullException(nameof(collectionObject)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs index c41333296127f1..7955b82b6ba2f4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs @@ -58,7 +58,7 @@ public static bool IsEnumerableOfT(Type type) public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -68,12 +68,12 @@ public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable public static IEnumerable? ConcatAllowingNull(this IEnumerable? source, IEnumerable? second) { - if (second == null || !second.Any()) + if (second is null || !second.Any()) { return source; } - if (source == null || !source.Any()) + if (source is null || !source.Any()) { return second; } @@ -83,12 +83,12 @@ public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable public static ICollection? ConcatAllowingNull(this ICollection? source, ICollection? second) { - if (second == null || (second.Count == 0)) + if (second is null || (second.Count == 0)) { return source; } - if (source == null || (source.Count == 0)) + if (source is null || (source.Count == 0)) { return second; } @@ -101,13 +101,13 @@ public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable public static List? FastAppendToListAllowNulls(this List? source, IEnumerable? second) { - if (second == null) + if (second is null) { return source; } // if there's nothing in the source, return the second - if ((source == null) || (source.Count == 0)) + if ((source is null) || (source.Count == 0)) { return second.AsList(); } @@ -134,7 +134,7 @@ public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable private static List FastAppendToListAllowNulls(this List? source, T value) { - if (source == null) + if (source is null) { source = new List(); } @@ -148,9 +148,9 @@ private static List FastAppendToListAllowNulls(this List? source, T val IEnumerable? second) where T : class { - if (second == null) + if (second is null) { - Debug.Assert(value != null); + Debug.Assert(value is not null); source = source.FastAppendToListAllowNulls(value); } else @@ -170,7 +170,7 @@ public static void ForEach(this IEnumerable source, Action action) public static EnumerableCardinality GetCardinality(this IEnumerable source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -204,7 +204,7 @@ public static EnumerableCardinality GetCardinality(this IEnumerable source public static Stack Copy(this Stack stack) { - if (stack == null) + if (stack is null) { throw new ArgumentNullException(nameof(stack)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs index 25826cde0b362f..100394f8b756cb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs @@ -10,7 +10,7 @@ internal static class ContractServices { public static bool TryCast(Type contractType, object? value, out object? result) { - if (value == null) + if (value is null) { result = null; return true; @@ -27,7 +27,7 @@ public static bool TryCast(Type contractType, object? value, out object? result) if (value is ExportedDelegate exportedDelegate) { result = exportedDelegate.CreateDelegate(contractType.UnderlyingSystemType); - return (result != null); + return (result is not null); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs index 036811b5ae93cb..45423fb8cb3468 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs @@ -68,12 +68,12 @@ public static ILGenerator CreateGeneratorForPublicConstructor(this TypeBuilder t /// public static void LoadValue(this ILGenerator ilGenerator, object? value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); // // Get nulls out of the way - they are basically typeless, so we just load null // - if (value == null) + if (value is null) { ilGenerator.LoadNull(); return; @@ -164,19 +164,19 @@ public static void LoadValue(this ILGenerator ilGenerator, object? value) /// public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, object value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -194,19 +194,19 @@ public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalB /// public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, LocalBuilder value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); - if (dictionary == null) + if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); } - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -223,14 +223,14 @@ public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, Local /// public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, LocalBuilder exception, LocalBuilder dataStore) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); - if (exception == null) + if (exception is null) { throw new ArgumentNullException(nameof(exception)); } - if (dataStore == null) + if (dataStore is null) { throw new ArgumentNullException(nameof(dataStore)); } @@ -242,9 +242,9 @@ public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); - if (enumerable == null) + if (enumerable is null) { throw new ArgumentNullException(nameof(enumerable)); } @@ -292,7 +292,7 @@ private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enu private static bool IsBoxingRequiredForValue(object? value) { - if (value == null) + if (value is null) { return false; } @@ -309,9 +309,9 @@ private static void LoadNull(this ILGenerator ilGenerator) private static void LoadString(this ILGenerator ilGenerator, string s) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); - if (s == null) + if (s is null) { ilGenerator.LoadNull(); } @@ -323,35 +323,35 @@ private static void LoadString(this ILGenerator ilGenerator, string s) private static void LoadInt(this ILGenerator ilGenerator, int value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); ilGenerator.Emit(OpCodes.Ldc_I4, value); } private static void LoadLong(this ILGenerator ilGenerator, long value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); ilGenerator.Emit(OpCodes.Ldc_I8, value); } private static void LoadFloat(this ILGenerator ilGenerator, float value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); ilGenerator.Emit(OpCodes.Ldc_R4, value); } private static void LoadDouble(this ILGenerator ilGenerator, double value) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); ilGenerator.Emit(OpCodes.Ldc_R8, value); } private static void LoadTypeOf(this ILGenerator ilGenerator, Type type) { - Debug.Assert(ilGenerator != null); + Debug.Assert(ilGenerator is not null); //typeofs() translate into ldtoken and Type::GetTypeFromHandle call ilGenerator.Emit(OpCodes.Ldtoken, type); diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs index 0e8ecae85fa8ed..90eb0fbaafc46c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs @@ -11,13 +11,13 @@ internal static class LazyServices public static T GetNotNullValue(this Lazy lazy, string argument) where T : class { - if (lazy == null) + if (lazy is null) { throw new ArgumentNullException(nameof(lazy)); } T value = lazy.Value; - if (value == null) + if (value is null) { throw new InvalidOperationException(SR.Format(SR.LazyServices_LazyResolvesToNull, typeof(T), argument)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs index d6ec08259a05b8..fd8ef0b82a9f59 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs @@ -20,7 +20,7 @@ public static Assembly Assembly(this MemberInfo member) return type.Assembly; } - Debug.Assert(member.DeclaringType != null); + Debug.Assert(member.DeclaringType is not null); return member.DeclaringType.Assembly; } @@ -31,13 +31,13 @@ public static bool IsVisible(this ConstructorInfo constructor) public static bool IsVisible(this FieldInfo field) { - Debug.Assert(field.DeclaringType != null); + Debug.Assert(field.DeclaringType is not null); return field.DeclaringType.IsVisible && field.IsPublic; } public static bool IsVisible(this MethodInfo method) { - Debug.Assert(method.DeclaringType != null); + Debug.Assert(method.DeclaringType is not null); if (!method.DeclaringType.IsVisible) return false; @@ -59,7 +59,7 @@ public static bool IsVisible(this MethodInfo method) public static string GetDisplayName(Type declaringType, string? name) { - if (declaringType == null) + if (declaringType is null) { throw new ArgumentNullException(nameof(name)); } @@ -69,7 +69,7 @@ public static string GetDisplayName(Type declaringType, string? name) public static string GetDisplayName(this MemberInfo member) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -111,7 +111,7 @@ internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOp // takign the chance that there aren't too many types which implement multiple // interfaces by the same name... Type? targetInterface = instanceType.GetInterface(targetOpenInterfaceType.Name, false); - if (targetInterface != null && + if (targetInterface is not null && targetInterface.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType) { targetClosedInterfaceType = targetInterface; @@ -137,7 +137,7 @@ internal static IEnumerable GetAllMethods(this Type type) IEnumerable declaredMethods = type.GetDeclaredMethods(); Type? baseType = type.BaseType; - Debug.Assert(baseType != null); + Debug.Assert(baseType is not null); if (baseType.UnderlyingSystemType != typeof(object)) { return declaredMethods.Concat(baseType.GetAllMethods()); @@ -161,7 +161,7 @@ public static IEnumerable GetAllFields(this Type type) IEnumerable declaredFields = type.GetDeclaredFields(); Type? baseType = type.BaseType; - Debug.Assert(baseType != null); + Debug.Assert(baseType is not null); if (baseType.UnderlyingSystemType != typeof(object)) { return declaredFields.Concat(baseType.GetAllFields()); @@ -187,7 +187,7 @@ internal static bool HasBaseclassOf(this Type? type, Type baseClass) return false; } - while (type != null) + while (type is not null) { if (type == baseClass) return true; diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs index 972892242e8251..3a8189562f42ed 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs @@ -39,7 +39,7 @@ public static void NullOrNotNullElements(IEnumerable? values, string param private static void NotNullElements(IEnumerable? values, string parameterName) where T : class { - if (values != null) + if (values is not null) { foreach (T value in values) { @@ -62,11 +62,11 @@ public static void NullOrNotNullElements(T[]? values, string parameterName) private static void NotNullElements(T[]? values, string parameterName) where T : class { - if (values != null) + if (values is not null) { foreach (var value in values) { - if (value == null) + if (value is null) { throw ExceptionBuilder.CreateContainsNullElement(parameterName); } @@ -79,7 +79,7 @@ private static void NotNullElements(IEnumerable keyValue in values) { @@ -104,7 +104,7 @@ public static void IsInMembertypeSet(MemberTypes value, string parameterName, Me public static void NotNull(T value, string parameterName) where T : class { - if (value == null) + if (value is null) { throw new ArgumentNullException(parameterName); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs index deaedb46ed8883..d4fc527b4b977c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs @@ -21,17 +21,17 @@ internal class AttributedExportDefinition : ExportDefinition public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type? typeIdentityType, string contractName) : base(contractName, (IDictionary?)null) { - if (partCreationInfo == null) + if (partCreationInfo is null) { throw new ArgumentNullException(nameof(partCreationInfo)); } - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } - if (exportAttribute == null) + if (exportAttribute is null) { throw new ArgumentNullException(nameof(exportAttribute)); } @@ -46,7 +46,7 @@ public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, M { get { - if (_metadata == null) + if (_metadata is null) { _member.TryExportMetadataForMember(out IDictionary metadata); @@ -57,12 +57,12 @@ public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, M metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity); var partMetadata = _partCreationInfo.GetMetadata(); - if (partMetadata != null && partMetadata.ContainsKey(CompositionConstants.PartCreationPolicyMetadataName)) + if (partMetadata is not null && partMetadata.ContainsKey(CompositionConstants.PartCreationPolicyMetadataName)) { metadata.Add(CompositionConstants.PartCreationPolicyMetadataName, partMetadata[CompositionConstants.PartCreationPolicyMetadataName]); } - if ((_typeIdentityType != null) && (_member.MemberType != MemberTypes.Method) && _typeIdentityType.ContainsGenericParameters) + if ((_typeIdentityType is not null) && (_member.MemberType != MemberTypes.Method) && _typeIdentityType.ContainsGenericParameters) { metadata.Add(CompositionConstants.GenericExportParametersOrderMetadataName, GenericServices.GetGenericParametersOrder(_typeIdentityType)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs index f2f498827c0b51..82631fe5a59574 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs @@ -26,7 +26,7 @@ internal static class AttributedModelDiscovery public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -38,7 +38,7 @@ public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, public static ReflectionComposablePart CreatePart(object attributedPart) { - if (attributedPart == null) + if (attributedPart is null) { throw new ArgumentNullException(nameof(attributedPart)); } @@ -51,12 +51,12 @@ public static ReflectionComposablePart CreatePart(object attributedPart) public static ReflectionComposablePart CreatePart(object attributedPart, ReflectionContext reflectionContext) { - if (attributedPart == null) + if (attributedPart is null) { throw new ArgumentNullException(nameof(attributedPart)); } - if (reflectionContext == null) + if (reflectionContext is null) { throw new ArgumentNullException(nameof(reflectionContext)); } @@ -75,12 +75,12 @@ public static ReflectionComposablePart CreatePart(object attributedPart, Reflect public static ReflectionComposablePart CreatePart(ComposablePartDefinition partDefinition, object attributedPart) { - if (partDefinition == null) + if (partDefinition is null) { throw new ArgumentNullException(nameof(partDefinition)); } - if (attributedPart == null) + if (attributedPart is null) { throw new ArgumentNullException(nameof(attributedPart)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs index af82945c98b6c0..59c6037eda02e3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs @@ -26,7 +26,7 @@ internal class AttributedPartCreationInfo : IReflectionPartCreationInfo public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -49,7 +49,7 @@ public Lazy GetLazyPartType() public ConstructorInfo? GetConstructor() { - if (_constructor == null && !_ignoreConstructorImports) + if (_constructor is null && !_ignoreConstructorImports) { _constructor = SelectPartConstructor(_type); } @@ -178,7 +178,7 @@ private CreationPolicy CreationPolicy { get { - if (_partCreationPolicy == null) + if (_partCreationPolicy is null) { _partCreationPolicy = _type.GetFirstAttribute() ?? PartCreationPolicyAttribute.Default; } @@ -189,7 +189,7 @@ private CreationPolicy CreationPolicy private static ConstructorInfo? SelectPartConstructor(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -224,7 +224,7 @@ private CreationPolicy CreationPolicy // an importing constructor found if (constructor.IsAttributeDefined()) { - if (importingConstructor != null) + if (importingConstructor is not null) { // more that one importing constructor - return null ot error out on creation return null; @@ -235,7 +235,7 @@ private CreationPolicy CreationPolicy } } // otherwise if we havent seen the default constructor yet, check if this one is it - else if (defaultConstructor == null) + else if (defaultConstructor is null) { if (constructor.GetParameters().Length == 0) { @@ -252,7 +252,7 @@ private void DiscoverExportsAndImports() // NOTE : in most cases both of these will be null or not null at the same time // the only situation when that is not the case is when there was a failure during the previous discovery // and one of them ended up not being set. In that case we will force the discovery again so that the same exception is thrown. - if ((_exports != null) && (_imports != null)) + if ((_exports is not null) && (_imports is not null)) { return; } @@ -387,7 +387,7 @@ private IEnumerable GetInheritedExports(Type type) Type? currentType = type.BaseType; - if (currentType == null) + if (currentType is null) { yield break; } @@ -395,7 +395,7 @@ private IEnumerable GetInheritedExports(Type type) // Stopping at object instead of null to help with performance. It is a noticable performance // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object. // We also need the null check in case we're passed a type that doesn't live in the runtime context. - while (currentType != null && currentType.UnderlyingSystemType != CompositionServices.ObjectType) + while (currentType is not null && currentType.UnderlyingSystemType != CompositionServices.ObjectType) { if (IsInheritedExport(currentType)) { @@ -435,7 +435,7 @@ private IEnumerable GetImportDefinitions() ConstructorInfo? constructor = GetConstructor(); - if (constructor != null) + if (constructor is not null) { foreach (ParameterInfo parameter in constructor.GetParameters()) { @@ -460,14 +460,14 @@ private IEnumerable GetImportMembers(Type type) } // Walk up the type chain until you hit object. - if (type.BaseType != null) + if (type.BaseType is not null) { Type? baseType = type.BaseType; // Stopping at object instead of null to help with performance. It is a noticable performance // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object. // We also need the null check in case we're passed a type that doesn't live in the runtime context. - while (baseType != null && baseType.UnderlyingSystemType != CompositionServices.ObjectType) + while (baseType is not null && baseType.UnderlyingSystemType != CompositionServices.ObjectType) { foreach (MemberInfo member in GetDeclaredOnlyImportMembers(baseType)) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs index 3763bb90e2d4c1..a928d36fc7e85f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs @@ -44,7 +44,7 @@ public static ComposablePart CreatePart(ComposablePartDefinition partDefinition, Requires.NotNull(attributedPart, nameof(attributedPart)); var reflectionComposablePartDefinition = partDefinition as ReflectionComposablePartDefinition; - if (reflectionComposablePartDefinition == null) + if (reflectionComposablePartDefinition is null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); } @@ -141,7 +141,7 @@ public static ComposablePart AddPart(this CompositionBatch batch, object attribu batch.AddPart(part); - Debug.Assert(part != null); + Debug.Assert(part is not null); return part; } @@ -183,7 +183,7 @@ public static ComposablePart SatisfyImportsOnce(this ICompositionService composi ComposablePart part = AttributedModelServices.CreatePart(attributedPart); compositionService.SatisfyImportsOnce(part); - Debug.Assert(part != null); + Debug.Assert(part is not null); return part; } @@ -215,7 +215,7 @@ public static ComposablePart SatisfyImportsOnce(this ICompositionService composi ComposablePart part = AttributedModelServices.CreatePart(attributedPart, reflectionContext); compositionService.SatisfyImportsOnce(part); - Debug.Assert(part != null); + Debug.Assert(part is not null); return part; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs index ac8af71eaae142..31a88e402bd245 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs @@ -24,7 +24,7 @@ public CatalogReflectionContextAttribute(Type reflectionContextType) public ReflectionContext CreateReflectionContext() { - if (_reflectionContextType == null) + if (_reflectionContextType is null) { throw new ArgumentNullException(nameof(_reflectionContextType)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs index 37d2e01cc0dfee..b71b06280727af 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs @@ -92,7 +92,7 @@ internal CompositionException(string? message, Exception? innerException, IEnume : base(message, innerException) { Requires.NullOrNotNullElements(errors, nameof(errors)); - _errors = new ReadOnlyCollection(errors == null ? Array.Empty() : errors.ToArray()); + _errors = new ReadOnlyCollection(errors is null ? Array.Empty() : errors.ToArray()); } /// @@ -140,7 +140,7 @@ public ReadOnlyCollection RootCauses // In here return a collection of all of the exceptions in the Errors collection foreach (var error in Errors) { - if (error.Exception != null) + if (error.Exception is not null) { if (error.Exception is CompositionException ce) { @@ -237,7 +237,7 @@ private static void WriteError(StringBuilder writer, CompositionError error) { writer.AppendLine(error.Description); - if (error.Element != null) + if (error.Element is not null) { WriteElementGraph(writer, error.Element); } @@ -282,7 +282,7 @@ private static void VisitCompositionException(CompositionException exception, Vi VisitError(error, context); } - if (exception.InnerException != null) + if (exception.InnerException is not null) { VisitException(exception.InnerException, context); } @@ -292,7 +292,7 @@ private static void VisitError(CompositionError error, VisitContext context) { context.Path.Push(error); - if (error.Exception == null) + if (error.Exception is null) { // This error is a root cause, so write // out the stack from this point diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionExceptionDebuggerProxy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionExceptionDebuggerProxy.cs index b06aff734a3029..39d37a8c65552e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionExceptionDebuggerProxy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionExceptionDebuggerProxy.cs @@ -29,7 +29,7 @@ public ReadOnlyCollection Exceptions // In here return a collection of all of the exceptions in the Errors collection foreach (var error in _exception.Errors) { - if (error.Exception != null) + if (error.Exception is not null) { errors.Add(error.Exception); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs index 2d0bee2f608a43..722971b8bc5bb1 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs @@ -25,7 +25,7 @@ public CompositionResult(IEnumerable? errors) public bool Succeeded { - get { return _errors == null || !_errors.Any(); } + get { return _errors is null || !_errors.Any(); } } public IEnumerable Errors @@ -70,7 +70,7 @@ public void ThrowOnErrors(AtomicComposition? atomicComposition) { if (!Succeeded) { - if (atomicComposition == null) + if (atomicComposition is null) { throw new CompositionException(_errors); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs index 9c66e1817b8956..c49fe347ec6f74 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs @@ -36,7 +36,7 @@ internal CompositionResult(T? value, IEnumerable? errors) public bool Succeeded { - get { return _errors == null || !_errors.Any(); } + get { return _errors is null || !_errors.Any(); } } public IEnumerable Errors diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs index c7e74e85cc5e20..d3b8c925cd39c8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs @@ -33,10 +33,10 @@ public static Expression> CreateConstraint(string c constraintBody = Expression.AndAlso(constraintBody, typeIdentityConstraintBody); } - if (requiredMetadata != null) + if (requiredMetadata is not null) { Expression? metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter); - if (metadataConstraintBody != null) + if (metadataConstraintBody is not null) { constraintBody = Expression.AndAlso(constraintBody, metadataConstraintBody); } @@ -55,7 +55,7 @@ public static Expression> CreateConstraint(string c private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter) { - if (parameter == null) + if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } @@ -68,12 +68,12 @@ private static Expression CreateContractConstraintBody(string contractName, Para private static Expression? CreateMetadataConstraintBody(IEnumerable> requiredMetadata, ParameterExpression parameter) { - if (requiredMetadata == null) + if (requiredMetadata is null) { throw new ArgumentNullException(nameof(requiredMetadata)); } - if (parameter == null) + if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } @@ -84,7 +84,7 @@ private static Expression CreateContractConstraintBody(string contractName, Para // export.Metadata.ContainsKey() Expression metadataItemExpression = CreateMetadataContainsKeyExpression(parameter, requiredMetadataItem.Key); - body = (body != null) ? Expression.AndAlso(body, metadataItemExpression) : metadataItemExpression; + body = (body is not null) ? Expression.AndAlso(body, metadataItemExpression) : metadataItemExpression; body = Expression.AndAlso(body, CreateMetadataOfTypeExpression(parameter, requiredMetadataItem.Key, requiredMetadataItem.Value)); } @@ -98,7 +98,7 @@ private static Expression CreateCreationPolicyContraint(CreationPolicy policy, P throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - if (parameter == null) + if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } @@ -116,12 +116,12 @@ private static Expression CreateCreationPolicyContraint(CreationPolicy policy, P private static Expression CreateTypeIdentityContraint(string requiredTypeIdentity, ParameterExpression parameter) { - if (requiredTypeIdentity == null) + if (requiredTypeIdentity is null) { throw new ArgumentNullException(requiredTypeIdentity); } - if (parameter == null) + if (parameter is null) { throw new ArgumentException(nameof(parameter)); } @@ -136,12 +136,12 @@ private static Expression CreateTypeIdentityContraint(string requiredTypeIdentit private static Expression CreateMetadataContainsKeyExpression(ParameterExpression parameter, string constantKey) { - if (parameter == null) + if (parameter is null) { throw new ArgumentException(nameof(parameter)); } - if (constantKey == null) + if (constantKey is null) { throw new ArgumentException(nameof(constantKey)); } @@ -155,17 +155,17 @@ private static Expression CreateMetadataContainsKeyExpression(ParameterExpressio private static Expression CreateMetadataOfTypeExpression(ParameterExpression parameter, string constantKey, Type constantType) { - if (parameter == null) + if (parameter is null) { throw new ArgumentException(nameof(parameter)); } - if (constantKey == null) + if (constantKey is null) { throw new ArgumentException(nameof(constantKey)); } - if (constantType == null) + if (constantType is null) { throw new ArgumentException(nameof(constantType)); } @@ -183,12 +183,12 @@ private static Expression CreateMetadataOfTypeExpression(ParameterExpression par private static Expression CreateMetadataValueEqualsExpression(ParameterExpression parameter, object constantValue, string metadataName) { - if (parameter == null) + if (parameter is null) { throw new ArgumentException(nameof(parameter)); } - if (constantValue == null) + if (constantValue is null) { throw new ArgumentException(nameof(constantValue)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs index 08c4bfb717e068..96938e6c3f631c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs @@ -43,7 +43,7 @@ internal static string GetTypeIdentity(Type type) internal static string GetTypeIdentity(Type type, bool formatGenericName) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -146,7 +146,7 @@ private static void WriteNonGenericType(StringBuilder typeName, Type type, bool // // Writes non-generic type // - if (type.DeclaringType != null) + if (type.DeclaringType is not null) { WriteType(typeName, type.DeclaringType, formatGenericName); typeName.Append(NestedClassSeparator); @@ -226,7 +226,7 @@ private static void WriteGenericType(StringBuilder typeName, Type type, bool isD // genericTypeArguments contains type arguments obtained from the most nested type // isDefinition parameter indicates if we are dealing with generic type definition // - if (type.DeclaringType != null) + if (type.DeclaringType is not null) { if (type.DeclaringType.IsGenericType) { @@ -338,7 +338,7 @@ private static string FindGenericTypeName(string genericName) private static int GetGenericArity(Type type) { - if (type.DeclaringType == null) + if (type.DeclaringType is null) { return type.GetGenericArguments().Length; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs index 80a171cc1b776d..e45ebafb35a7b1 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs @@ -34,12 +34,12 @@ public static CompositionError ComposeTookTooManyIterations(int maximumNumberOfC public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception, ImportDefinition definition) { - if (exception == null) + if (exception is null) { throw new ArgumentNullException(nameof(exception)); } - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } @@ -53,12 +53,12 @@ public static CompositionError CreateImportCardinalityMismatch(ImportCardinality public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } - if (innerException == null) + if (innerException is null) { throw new ArgumentNullException(nameof(innerException)); } @@ -74,17 +74,17 @@ public static CompositionError CreatePartCannotActivate(ComposablePart part, Exc public static CompositionError CreatePartCannotSetImport(ComposablePart part, ImportDefinition definition, Exception innerException) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } - if (innerException == null) + if (innerException is null) { throw new ArgumentNullException(nameof(innerException)); } @@ -101,17 +101,17 @@ public static CompositionError CreatePartCannotSetImport(ComposablePart part, Im public static CompositionError CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } - if (innerException == null) + if (innerException is null) { throw new ArgumentNullException(nameof(innerException)); } @@ -128,7 +128,7 @@ public static CompositionError CreateCannotGetExportedValue(ComposablePart part, public static CompositionError CreatePartCycle(ComposablePart part) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs index dea39fb6e6f43f..6b4f26bd5ac8e6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs @@ -18,7 +18,7 @@ public static Exception CreateDiscoveryException(string messageFormat, params st public static ArgumentException CreateContainsNullElement(string parameterName) { - if (parameterName == null) + if (parameterName is null) { throw new ArgumentNullException(nameof(parameterName)); } @@ -30,7 +30,7 @@ public static ArgumentException CreateContainsNullElement(string parameterName) public static ObjectDisposedException CreateObjectDisposed(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -40,7 +40,7 @@ public static ObjectDisposedException CreateObjectDisposed(object instance) public static NotImplementedException CreateNotOverriddenByDerived(string memberName) { - if (memberName == null) + if (memberName is null) { throw new ArgumentNullException(nameof(memberName)); } @@ -57,7 +57,7 @@ public static NotImplementedException CreateNotOverriddenByDerived(string member public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName) { - if (parameterName == null) + if (parameterName is null) { throw new ArgumentNullException(nameof(parameterName)); } @@ -75,7 +75,7 @@ public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(st public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName) { - if (parameterName == null) + if (parameterName is null) { throw new ArgumentNullException(nameof(parameterName)); } @@ -92,17 +92,17 @@ public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(st public static CompositionException CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } - if (innerException == null) + if (innerException is null) { throw new ArgumentNullException(nameof(innerException)); } @@ -113,7 +113,7 @@ public static CompositionException CreateCannotGetExportedValue(ComposablePart p public static ArgumentException CreateReflectionModelInvalidPartDefinition(string parameterName, Type partDefinitionType) { - if (parameterName == null) + if (parameterName is null) { throw new ArgumentNullException(nameof(parameterName)); } @@ -123,7 +123,7 @@ public static ArgumentException CreateReflectionModelInvalidPartDefinition(strin throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(parameterName)), nameof(parameterName)); } - if (partDefinitionType == null) + if (partDefinitionType is null) { throw new ArgumentNullException(nameof(partDefinitionType)); } @@ -133,7 +133,7 @@ public static ArgumentException CreateReflectionModelInvalidPartDefinition(strin public static ArgumentException ExportFactory_TooManyGenericParameters(string typeName) { - if (typeName == null) + if (typeName is null) { throw new ArgumentNullException(nameof(typeName)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs index a5547d23532306..a6bb93847bb276 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs @@ -9,7 +9,7 @@ public class ExportFactory public ExportFactory(Func> exportLifetimeContextCreator) { - if (exportLifetimeContextCreator == null) + if (exportLifetimeContextCreator is null) { throw new ArgumentNullException(nameof(exportLifetimeContextCreator)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs index fd0fce5ac6a5fe..33f72e47fc2fac 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs @@ -24,7 +24,7 @@ public T Value public void Dispose() { - if (_disposeAction != null) + if (_disposeAction is not null) { _disposeAction.Invoke(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs index 09470da51de2fc..35d71b3f825eb7 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs @@ -14,7 +14,7 @@ private sealed class DisposableLazy : Lazy, public DisposableLazy(Func valueFactory, TMetadataView metadataView, IDisposable disposable, LazyThreadSafetyMode mode) : base(valueFactory, metadataView, mode) { - if (disposable == null) + if (disposable is null) { throw new ArgumentNullException(nameof(disposable)); } @@ -35,7 +35,7 @@ private sealed class DisposableLazy : Lazy, IDisposable public DisposableLazy(Func valueFactory, IDisposable disposable, LazyThreadSafetyMode mode) : base(valueFactory, mode) { - if (disposable == null) + if (disposable is null) { throw new ArgumentNullException(nameof(disposable)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs index af5e86056da17b..15aa7317b6e729 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs @@ -25,7 +25,7 @@ internal static partial class ExportServices internal static bool IsDefaultMetadataViewType(Type metadataViewType) { - if (metadataViewType == null) + if (metadataViewType is null) { throw new ArgumentNullException(nameof(metadataViewType)); } @@ -38,7 +38,7 @@ internal static bool IsDefaultMetadataViewType(Type metadataViewType) internal static bool IsDictionaryConstructorViewType(Type metadataViewType) { - if (metadataViewType == null) + if (metadataViewType is null) { throw new ArgumentNullException(nameof(metadataViewType)); } @@ -47,13 +47,13 @@ internal static bool IsDictionaryConstructorViewType(Type metadataViewType) return metadataViewType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(IDictionary) }, - Array.Empty()) != null; + Array.Empty()) is not null; } internal static Func CreateStronglyTypedLazyFactory(Type? exportType, Type? metadataViewType) { MethodInfo genericMethod; - if (metadataViewType != null) + if (metadataViewType is not null) { genericMethod = _createStronglyTypedLazyOfTM.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType, metadataViewType); } @@ -62,7 +62,7 @@ internal static Func CreateStronglyTypedLazyFactory(Type? export genericMethod = _createStronglyTypedLazyOfT.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType); } - if (genericMethod == null) + if (genericMethod is null) { throw new ArgumentNullException(nameof(genericMethod)); } @@ -75,7 +75,7 @@ internal static Func> CreateSemiStronglyTypedLazyFa MethodInfo genericMethod = _createSemiStronglyTypedLazy.MakeGenericMethod( exportType ?? ExportServices.DefaultExportedValueType, metadataViewType ?? ExportServices.DefaultMetadataViewType); - if (genericMethod == null) + if (genericMethod is null) { throw new ArgumentNullException(nameof(genericMethod)); } @@ -156,7 +156,7 @@ internal static T CastExportedValue(ICompositionElement element, object? expo internal static ExportCardinalityCheckResult CheckCardinality(ImportDefinition definition, IEnumerable? enumerable) { - EnumerableCardinality actualCardinality = (enumerable != null) ? enumerable.GetCardinality() : EnumerableCardinality.Zero; + EnumerableCardinality actualCardinality = (enumerable is not null) ? enumerable.GetCardinality() : EnumerableCardinality.Zero; return MatchCardinality(actualCardinality, definition.Cardinality); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs index b705f1a9cc120e..3fa13c0ded58c3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs @@ -133,14 +133,14 @@ public override IEnumerable> G if (catalogExports != ComposablePartCatalog._EmptyExportsList) { // ideally this is the case we will always hit - if (result == null) + if (result is null) { result = catalogExports; } else { // sadly the result has already been assigned, which means we are in the aggregate case - if (aggregateResult == null) + if (aggregateResult is null) { aggregateResult = new List>(result); result = aggregateResult; @@ -167,7 +167,7 @@ public ICollection Catalogs get { ThrowIfDisposed(); - Debug.Assert(_catalogs != null); + Debug.Assert(_catalogs is not null); return _catalogs; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs index f85e1f2fe75ff2..3d8328924eb467 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs @@ -39,13 +39,13 @@ public AggregateExportProvider(params ExportProvider[]? providers) // NOTE : we optimize for the array case here, because the collection of providers is typically tiny // Arrays are much more compact to store and much faster to create and enumerate ExportProvider[]? copiedProviders = null; - if (providers != null) + if (providers is not null) { copiedProviders = new ExportProvider[providers.Length]; for (int i = 0; i < providers.Length; i++) { ExportProvider provider = providers[i]; - if (provider == null) + if (provider is null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(providers)); } @@ -80,7 +80,7 @@ public AggregateExportProvider(params ExportProvider[]? providers) /// /// public AggregateExportProvider(IEnumerable? providers) - : this((providers != null) ? providers.AsArray() : null) + : this((providers is not null) ? providers.AsArray() : null) { } @@ -127,7 +127,7 @@ public ReadOnlyCollection Providers get { ThrowIfDisposed(); - Debug.Assert(_readOnlyProviders != null); + Debug.Assert(_readOnlyProviders is not null); return _readOnlyProviders; } @@ -178,7 +178,7 @@ protected override IEnumerable GetExportsCore(ImportDefinition definitio foreach (ExportProvider provider in _providers) { bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out IEnumerable? exports); - Debug.Assert(exports != null); + Debug.Assert(exports is not null); bool anyExports = exports.Any(); if (cardinalityCheckResult && anyExports) { @@ -195,7 +195,7 @@ protected override IEnumerable GetExportsCore(ImportDefinition definitio // but no information is lost. if (anyExports) { - allExports = (allExports != null) ? allExports.Concat(exports) : exports; + allExports = (allExports is not null) ? allExports.Concat(exports) : exports; } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs index 2443d92f3048f6..38cc7a1fcec8ca 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs @@ -47,13 +47,13 @@ public ApplicationCatalog(ReflectionContext reflectionContext, ICompositionEleme internal ComposablePartCatalog CreateCatalog(string location, string pattern) { - if (_reflectionContext != null) + if (_reflectionContext is not null) { - return (_definitionOrigin != null) + return (_definitionOrigin is not null) ? new DirectoryCatalog(location, pattern, _reflectionContext, _definitionOrigin) : new DirectoryCatalog(location, pattern, _reflectionContext); } - return (_definitionOrigin != null) + return (_definitionOrigin is not null) ? new DirectoryCatalog(location, pattern, _definitionOrigin) : new DirectoryCatalog(location, pattern); } @@ -65,14 +65,14 @@ private AggregateCatalog InnerCatalog { get { - if (_innerCatalog == null) + if (_innerCatalog is null) { lock (_thisLock) { - if (_innerCatalog == null) + if (_innerCatalog is null) { var location = AppDomain.CurrentDomain.BaseDirectory; - if (location == null) + if (location is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -117,7 +117,7 @@ protected override void Dispose(bool disposing) _innerCatalog = null; _isDisposed = true; } - if (innerCatalog != null) + if (innerCatalog is not null) { innerCatalog.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs index 026b2df76de5ed..48b3cfccbcb4ca 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs @@ -433,17 +433,17 @@ private ComposablePartCatalog InnerCatalog { ThrowIfDisposed(); - if (_innerCatalog == null) + if (_innerCatalog is null) { var catalogReflectionContextAttribute = _assembly.GetFirstAttribute(); - var assembly = (catalogReflectionContextAttribute != null) + var assembly = (catalogReflectionContextAttribute is not null) ? catalogReflectionContextAttribute.CreateReflectionContext().MapAssembly(_assembly) : _assembly; lock (_thisLock) { - if (_innerCatalog == null) + if (_innerCatalog is null) { - var catalog = (_reflectionContext != null) + var catalog = (_reflectionContext is not null) ? new TypeCatalog(assembly.GetTypes(), _reflectionContext, _definitionOrigin) : new TypeCatalog(assembly.GetTypes(), _definitionOrigin); Thread.MemoryBarrier(); @@ -467,7 +467,7 @@ public Assembly Assembly { get { - Debug.Assert(_assembly != null); + Debug.Assert(_assembly is not null); return _assembly; } @@ -514,7 +514,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_innerCatalog != null) + if (_innerCatalog is not null) { _innerCatalog.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs index 752d817a0507fd..656776f4a46d29 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs @@ -52,7 +52,7 @@ public AtomicComposition(AtomicComposition? outerAtomicComposition) { // Lock the inner atomicComposition so that we can assume nothing changes except on // the innermost scope, and thereby optimize the query path - if (outerAtomicComposition != null) + if (outerAtomicComposition is not null) { _outerAtomicComposition = outerAtomicComposition; _outerAtomicComposition.ContainsInnerAtomicComposition = true; @@ -93,7 +93,7 @@ public void AddCompleteAction(Action completeAction) Requires.NotNull(completeAction, nameof(completeAction)); - if (_completeActionList == null) + if (_completeActionList is null) { _completeActionList = new List(); } @@ -108,7 +108,7 @@ public void AddRevertAction(Action revertAction) Requires.NotNull(revertAction, nameof(revertAction)); - if (_revertActionList == null) + if (_revertActionList is null) { _revertActionList = new List(); } @@ -120,7 +120,7 @@ public void Complete() ThrowIfDisposed(); ThrowIfCompleted(); - if (_outerAtomicComposition == null) + if (_outerAtomicComposition is null) { // Execute all the complete actions FinalComplete(); } @@ -143,7 +143,7 @@ protected virtual void Dispose(bool disposing) ThrowIfDisposed(); _isDisposed = true; - if (_outerAtomicComposition != null) + if (_outerAtomicComposition is not null) { _outerAtomicComposition.ContainsInnerAtomicComposition = false; } @@ -152,7 +152,7 @@ protected virtual void Dispose(bool disposing) // exceuting any appropriate revert actions if (!_isCompleted) { - if (_revertActionList != null) + if (_revertActionList is not null) { List? exceptions = null; @@ -172,7 +172,7 @@ protected virtual void Dispose(bool disposing) } catch (Exception e) { - if (exceptions == null) + if (exceptions is null) { //If any exceptions leak through the actions we will swallow them for now // complete processing the list @@ -183,7 +183,7 @@ protected virtual void Dispose(bool disposing) } } _revertActionList = null; - if (exceptions != null) + if (exceptions is not null) { throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions)); } @@ -194,7 +194,7 @@ protected virtual void Dispose(bool disposing) private void FinalComplete() { // Completeting the outer most scope is easy, just execute all the actions - if (_completeActionList != null) + if (_completeActionList is not null) { List? exceptions = null; @@ -211,7 +211,7 @@ private void FinalComplete() } catch (Exception e) { - if (exceptions == null) + if (exceptions is null) { //If any exceptions leak through the actions we will swallow them for now complete processing the list // and we will throw InvalidOperationException with an AggregateException as it's innerException @@ -221,7 +221,7 @@ private void FinalComplete() } } _completeActionList = null; - if (exceptions != null) + if (exceptions is not null) { throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions)); } @@ -230,7 +230,7 @@ private void FinalComplete() private void CopyComplete() { - if (_outerAtomicComposition == null) + if (_outerAtomicComposition is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -240,7 +240,7 @@ private void CopyComplete() // Inner scopes are much odder, because completeting them means coalescing them into the // outer scope - the complete or revert actions are deferred until the outermost scope completes // or any intermediate rolls back - if (_completeActionList != null) + if (_completeActionList is not null) { foreach (Action action in _completeActionList) { @@ -248,7 +248,7 @@ private void CopyComplete() } } - if (_revertActionList != null) + if (_revertActionList is not null) { foreach (Action action in _revertActionList) { @@ -290,7 +290,7 @@ private bool TryGetValueInternal(object key, bool localAtomicCompositionOnly, // If there's no atomicComposition available then recurse until we hit the outermost // scope, where upon we go ahead and return null - if (!localAtomicCompositionOnly && _outerAtomicComposition != null) + if (!localAtomicCompositionOnly && _outerAtomicComposition is not null) { return _outerAtomicComposition.TryGetValueInternal(key, localAtomicCompositionOnly, out value); } @@ -312,10 +312,10 @@ private void SetValueInternal(object key, object? value) } // Expand storage when needed - if (_values == null || _valueCount == _values.Length) + if (_values is null || _valueCount == _values.Length) { var newQueries = new KeyValuePair[_valueCount == 0 ? 5 : _valueCount * 2]; - if (_values != null) + if (_values is not null) { Array.Copy(_values, newQueries, _valueCount); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs index c3be4d17df16cf..8d1599ed9d4963 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs @@ -8,7 +8,7 @@ internal static class AtomicCompositionExtensions { internal static T GetValueAllowNull(this AtomicComposition? atomicComposition, T defaultResultAndKey) where T : class { - if (defaultResultAndKey == null) + if (defaultResultAndKey is null) { throw new ArgumentNullException(nameof(defaultResultAndKey)); } @@ -19,7 +19,7 @@ internal static T GetValueAllowNull(this AtomicComposition? atomicComposition internal static T GetValueAllowNull(this AtomicComposition? atomicComposition, object key, T defaultResult) { T result; - if (atomicComposition != null && atomicComposition.TryGetValue(key, out result)) + if (atomicComposition is not null && atomicComposition.TryGetValue(key, out result)) { return result; } @@ -29,12 +29,12 @@ internal static T GetValueAllowNull(this AtomicComposition? atomicComposition internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComposition, Action action) { - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } - if (atomicComposition == null) + if (atomicComposition is null) { action(); } @@ -46,12 +46,12 @@ internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComp internal static void AddCompleteActionAllowNull(this AtomicComposition? atomicComposition, Action action) { - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } - if (atomicComposition == null) + if (atomicComposition is null) { action(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs index 4802034132495c..152361c9168660 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs @@ -130,13 +130,13 @@ public NonSharedCatalogExport(CatalogExportProvider catalogExportProvider, protected override CatalogPart GetPart() { // we need to ensure that the part gets created only once, as the export contract requires that the same value be returned on subsequent calls - if (_part == null) + if (_part is null) { CatalogPart? part = GetPartCore(); lock (_lock) { - if (_part == null) + if (_part is null) { Thread.MemoryBarrier(); _part = part; @@ -144,7 +144,7 @@ protected override CatalogPart GetPart() } } - if (part != null) + if (part is not null) { DisposePartCore(part, null); } @@ -163,7 +163,7 @@ protected override bool IsSharedPart void IDisposable.Dispose() { - if (_part != null) + if (_part is not null) { DisposePartCore(_part, Value); _part = null; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs index da5100beaf70e8..a4db59becaa46e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs @@ -31,7 +31,7 @@ public override ExportDefinition Definition protected override object GetExportedValueCore() { - if (_factoryExportPartDefinition == null) + if (_factoryExportPartDefinition is null) { _factoryExportPartDefinition = new FactoryExportPartDefinition(this); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs index 62164694a1dd73..e30c02e075d242 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs @@ -48,15 +48,15 @@ public override ExportDefinition Definition protected override object? GetExportedValueCore() { - if (_export == null) + if (_export is null) { CompositionContainer? childContainer = _scopeFactoryExport._scopeManager.CreateChildContainer(_scopeFactoryExport._catalog); - Debug.Assert(childContainer.CatalogExportProvider != null); + Debug.Assert(childContainer.CatalogExportProvider is not null); Export? export = childContainer.CatalogExportProvider.CreateExport(_scopeFactoryExport.UnderlyingPartDefinition, _scopeFactoryExport.UnderlyingExportDefinition, false, CreationPolicy.Any); lock (_lock) { - if (_export == null) + if (_export is null) { _childContainer = childContainer; Thread.MemoryBarrier(); @@ -66,7 +66,7 @@ public override ExportDefinition Definition export = null; } } - if (childContainer != null) + if (childContainer is not null) { childContainer.Dispose(); } @@ -80,7 +80,7 @@ public void Dispose() CompositionContainer? childContainer = null; Export? export = null; - if (_export != null) + if (_export is not null) { lock (_lock) { @@ -93,7 +93,7 @@ public void Dispose() } } - if (childContainer != null) + if (childContainer is not null) { childContainer.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs index 6c421fcb5a35d9..badcedd01b99e2 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs @@ -15,11 +15,11 @@ internal class ScopeManager : ExportProvider public ScopeManager(CatalogExportProvider catalogExportProvider, CompositionScopeDefinition scopeDefinition) { - if (catalogExportProvider == null) + if (catalogExportProvider is null) { throw new ArgumentNullException(nameof(catalogExportProvider)); } - if (scopeDefinition == null) + if (scopeDefinition is null) { throw new ArgumentNullException(nameof(scopeDefinition)); } @@ -33,7 +33,7 @@ protected override IEnumerable GetExportsCore(ImportDefinition definitio List exports = new List(); ImportDefinition? queryImport = TranslateImport(definition); - if (queryImport == null) + if (queryImport is null) { return exports; } @@ -84,7 +84,7 @@ internal CompositionContainer CreateChildContainer(ComposablePartCatalog childCa private static ImportDefinition? TranslateImport(ImportDefinition definition) { IPartCreatorImportDefinition? factoryDefinition = definition as IPartCreatorImportDefinition; - if (factoryDefinition == null) + if (factoryDefinition is null) { return null; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs index 74132a63a2202e..fbc54cfa64b31e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs @@ -24,7 +24,7 @@ private class InnerCatalogExportProvider : ExportProvider public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider) { - if (outerExportProvider == null) + if (outerExportProvider is null) { throw new ArgumentNullException(nameof(outerExportProvider)); } @@ -115,7 +115,7 @@ public ComposablePartCatalog Catalog get { ThrowIfDisposed(); - Debug.Assert(_catalog != null); + Debug.Assert(_catalog is not null); return _catalog; } @@ -192,7 +192,7 @@ public ExportProvider? SourceProvider { sourceProvider.ExportsChanging -= OnExportsChangingInternal; newImportEngine!.Dispose(); - if (aggregateExportProvider != null) + if (aggregateExportProvider is not null) { aggregateExportProvider.Dispose(); } @@ -253,27 +253,27 @@ protected virtual void Dispose(bool disposing) } finally { - if (catalogToUnsubscribeFrom != null) + if (catalogToUnsubscribeFrom is not null) { catalogToUnsubscribeFrom.Changing -= OnCatalogChanging; } - if (aggregateExportProvider != null) + if (aggregateExportProvider is not null) { aggregateExportProvider.Dispose(); } - if (sourceProvider != null) + if (sourceProvider is not null) { sourceProvider.ExportsChanging -= OnExportsChangingInternal; } - if (importEngine != null) + if (importEngine is not null) { importEngine.Dispose(); } - if (partsToDispose != null) + if (partsToDispose is not null) { foreach (var part in partsToDispose) { @@ -310,7 +310,7 @@ protected override IEnumerable GetExportsCore(ImportDefinition definitio ThrowIfDisposed(); EnsureRunning(); - if (_innerExportProvider == null) + if (_innerExportProvider is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -498,7 +498,7 @@ private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) { catalogPart = new CatalogPart(newPart); _activatedParts.Add(partDefinition, catalogPart); - if (disposableNewPart != null) + if (disposableNewPart is not null) { _partsToDispose.Add(disposableNewPart); } @@ -509,9 +509,9 @@ private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) } } - // if disposableNewPart != null, this means we have created a new instance of something disposable and not used it + // if disposableNewPart is not null, this means we have created a new instance of something disposable and not used it // Dispose of it now - if (disposableNewPart != null) + if (disposableNewPart is not null) { disposableNewPart.Dispose(); } @@ -523,12 +523,12 @@ private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) { ThrowIfDisposed(); EnsureRunning(); - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } - if (export == null) + if (export is null) { throw new ArgumentNullException(nameof(export)); } @@ -550,7 +550,7 @@ private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) // Only hold conditional references for recomposable non-shared parts because we are // already holding strong references to the shared parts. - if (exportedValue != null && !isSharedPart && part.Part.IsRecomposable()) + if (exportedValue is not null && !isSharedPart && part.Part.IsRecomposable()) { PreventPartCollection(exportedValue, part.Part); } @@ -568,7 +568,7 @@ private void ReleasePart(object exportedValue, CatalogPart catalogPart, AtomicCo private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicComposition? atomicComposition) { - if (catalogPart == null) + if (catalogPart is null) { throw new ArgumentNullException(nameof(catalogPart)); } @@ -584,11 +584,11 @@ private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicC importEngine = _importEngine; } - if (importEngine != null) + if (importEngine is not null) { importEngine.ReleaseImports(catalogPart.Part, atomicComposition); } - if (exportedValue != null) + if (exportedValue is not null) { atomicComposition.AddCompleteActionAllowNull(() => { @@ -622,12 +622,12 @@ private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicC private void PreventPartCollection(object exportedValue, ComposablePart part) { - if (exportedValue == null) + if (exportedValue is null) { throw new ArgumentNullException(nameof(exportedValue)); } - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } @@ -637,7 +637,7 @@ private void PreventPartCollection(object exportedValue, ComposablePart part) List? partList; ConditionalWeakTable>? gcRoots = _gcRoots; - if (gcRoots == null) + if (gcRoots is null) { gcRoots = new ConditionalWeakTable>(); } @@ -650,7 +650,7 @@ private void PreventPartCollection(object exportedValue, ComposablePart part) partList.Add(part); - if (_gcRoots == null) + if (_gcRoots is null) { Thread.MemoryBarrier(); _gcRoots = gcRoots; @@ -660,7 +660,7 @@ private void PreventPartCollection(object exportedValue, ComposablePart part) private void AllowPartCollection(object gcRoot) { - if (_gcRoots != null) + if (_gcRoots is not null) { using (_lock.LockStateForWrite()) { @@ -676,7 +676,7 @@ private bool IsRejected(ComposablePartDefinition definition, AtomicComposition? // been rejected - because if it is we can discard all decisions that were based // on the faulty assumption in the first place. var forceRejectionTest = false; - if (atomicComposition != null) + if (atomicComposition is not null) { AtomicCompositionQueryState state = QueryPartState(atomicComposition, definition); switch (state) @@ -722,7 +722,7 @@ private bool IsRejected(ComposablePartDefinition definition, AtomicComposition? private bool EnsureRejection(AtomicComposition? atomicComposition) { - return !(_disableSilentRejection && (atomicComposition == null)); + return !(_disableSilentRejection && (atomicComposition is null)); } private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition? parentAtomicComposition) @@ -754,7 +754,7 @@ private bool DetermineRejection(ComposablePartDefinition definition, AtomicCompo var newPart = definition.CreatePart(); try { - Debug.Assert(_importEngine != null); + Debug.Assert(_importEngine is not null); _importEngine.PreviewImports(newPart, localAtomicComposition); // Reuse the partially-fleshed out part the next time we need a shared @@ -802,7 +802,7 @@ private bool DetermineRejection(ComposablePartDefinition definition, AtomicCompo CompositionTrace.PartDefinitionRejected(definition, exception); }); - if (parentAtomicComposition != null) + if (parentAtomicComposition is not null) { UpdateAtomicCompositionQueryForPartEquals(parentAtomicComposition, definition, AtomicCompositionQueryState.TreatAsRejected); @@ -899,7 +899,7 @@ private void ThrowIfDisposed() [DebuggerStepThrough] private void EnsureCanRun() { - if ((_sourceProvider == null) || (_importEngine == null)) + if ((_sourceProvider is null) || (_importEngine is null)) { throw new InvalidOperationException(SR.Format(SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC } @@ -930,7 +930,7 @@ private void EnsureRunning() private void EnsureCanSet(T? currentValue) where T : class { - if ((_isRunning) || (currentValue != null)) + if ((_isRunning) || (currentValue is not null)) { throw new InvalidOperationException(SR.ObjectAlreadyInitialized); } @@ -939,7 +939,7 @@ private void EnsureCanSet(T? currentValue) private AtomicCompositionQueryState QueryPartState(AtomicComposition atomicComposition, ComposablePartDefinition definition) { PartQueryStateNode? node = GetPartQueryStateNode(atomicComposition); - if (node == null) + if (node is null) { return AtomicCompositionQueryState.Unknown; } @@ -1006,7 +1006,7 @@ public AtomicCompositionQueryState GetQueryState(ComposablePartDefinition defini } node = node._previousNode; } - while (node != null); + while (node is not null); return AtomicCompositionQueryState.Unknown; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs index f8484b859a4a9d..16607996b25b60 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs @@ -60,7 +60,7 @@ public IEnumerable AddedDefinitions { get { - Debug.Assert(_addedDefinitions != null); + Debug.Assert(_addedDefinitions is not null); return _addedDefinitions; } @@ -77,7 +77,7 @@ public IEnumerable RemovedDefinitions { get { - Debug.Assert(_removedDefinitions != null); + Debug.Assert(_removedDefinitions is not null); return _removedDefinitions; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs index f6d9da22f1841c..fe49195413e8d6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs @@ -276,7 +276,7 @@ protected virtual void Dispose(bool disposing) } finally { - if (catalogs != null) + if (catalogs is not null) { UnsubscribeFromCatalogNotifications(catalogs); catalogs.ForEach(catalog => catalog.Dispose()); @@ -295,13 +295,13 @@ private void RaiseChangedEvent( Lazy>? addedDefinitions, Lazy>? removedDefinitions) { - if (_onChanged == null || Changed == null) + if (_onChanged is null || Changed is null) { return; } - var added = (addedDefinitions == null ? Enumerable.Empty() : addedDefinitions.Value); - var removed = (removedDefinitions == null ? Enumerable.Empty() : removedDefinitions.Value); + var added = (addedDefinitions is null ? Enumerable.Empty() : addedDefinitions.Value); + var removed = (removedDefinitions is null ? Enumerable.Empty() : removedDefinitions.Value); _onChanged.Invoke(new ComposablePartCatalogChangeEventArgs(added, removed, null)); } @@ -309,7 +309,7 @@ private void RaiseChangedEvent( public void OnChanged(object sender, ComposablePartCatalogChangeEventArgs e) { var changedEvent = Changed; - if (changedEvent != null) + if (changedEvent is not null) { changedEvent(sender, e); } @@ -320,12 +320,12 @@ private void RaiseChangingEvent( Lazy>? removedDefinitions, AtomicComposition? atomicComposition) { - if (_onChanging == null || Changing == null) + if (_onChanging is null || Changing is null) { return; } - var added = (addedDefinitions == null ? Enumerable.Empty() : addedDefinitions.Value); - var removed = (removedDefinitions == null ? Enumerable.Empty() : removedDefinitions.Value); + var added = (addedDefinitions is null ? Enumerable.Empty() : addedDefinitions.Value); + var removed = (removedDefinitions is null ? Enumerable.Empty() : removedDefinitions.Value); _onChanging.Invoke(new ComposablePartCatalogChangeEventArgs(added, removed, atomicComposition)); } @@ -333,7 +333,7 @@ private void RaiseChangingEvent( public void OnChanging(object sender, ComposablePartCatalogChangeEventArgs e) { var changingEvent = Changing; - if (changingEvent != null) + if (changingEvent is not null) { changingEvent(sender, e); } @@ -341,7 +341,7 @@ public void OnChanging(object sender, ComposablePartCatalogChangeEventArgs e) private void OnContainedCatalogChanged(object? sender, ComposablePartCatalogChangeEventArgs e) { - if (_onChanged == null || Changed == null) + if (_onChanged is null || Changed is null) { return; } @@ -351,7 +351,7 @@ private void OnContainedCatalogChanged(object? sender, ComposablePartCatalogChan private void OnContainedCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e) { - if (_onChanging == null || Changing == null) + if (_onChanging is null || Changing is null) { return; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs index 8e17e23540e164..b65bb4e019456b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs @@ -85,7 +85,7 @@ protected virtual void Dispose(bool disposing) } finally { - if (importEngine != null) + if (importEngine is not null) { importEngine.Dispose(); } @@ -152,16 +152,16 @@ private ImportEngine ImportEngine { get { - if (_importEngine == null) + if (_importEngine is null) { - if (_sourceProvider == null) + if (_sourceProvider is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } ImportEngine? importEngine = new ImportEngine(_sourceProvider, _compositionOptions); using (_lock.LockStateForWrite()) { - if (_importEngine == null) + if (_importEngine is null) { Thread.MemoryBarrier(); _importEngine = importEngine; @@ -170,7 +170,7 @@ private ImportEngine ImportEngine } // if we have created an engine and didn't set it because of a race condition, we need to dispose of it - if (importEngine != null) + if (importEngine is not null) { importEngine.Dispose(); } @@ -320,7 +320,7 @@ public void Compose(CompositionBatch batch) private List GetUpdatedPartsList(ref CompositionBatch batch) { - if (batch == null) + if (batch is null) { throw new ArgumentNullException(nameof(batch)); } @@ -345,7 +345,7 @@ private List GetUpdatedPartsList(ref CompositionBatch batch) { if (parts.Remove(part)) { - if (partsToRemove == null) + if (partsToRemove is null) { partsToRemove = new List(); } @@ -363,7 +363,7 @@ private List GetUpdatedPartsList(ref CompositionBatch batch) private void Recompose(CompositionBatch batch, AtomicComposition atomicComposition) { - if (batch == null) + if (batch is null) { throw new ArgumentNullException(nameof(batch)); } @@ -417,7 +417,7 @@ private void ThrowIfDisposed() [DebuggerStepThrough] private void EnsureCanRun() { - if (_sourceProvider == null) + if (_sourceProvider is null) { throw new InvalidOperationException(SR.Format(SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC } @@ -443,7 +443,7 @@ private void EnsureRunning() private void EnsureCanSet(T? currentValue) where T : class { - if ((_isRunning) || (currentValue != null)) + if ((_isRunning) || (currentValue is not null)) { throw new InvalidOperationException(SR.ObjectAlreadyInitialized); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs index 8e6944034a803a..cc68b5d51f4206 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs @@ -17,7 +17,7 @@ private class SingleExportComposablePart : ComposablePart public SingleExportComposablePart(Export export) { - if (export == null) + if (export is null) { throw new ArgumentNullException(nameof(export)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs index 0c746ce7cf7c89..7c069247afb3bc 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs @@ -35,11 +35,11 @@ public CompositionBatch() : public CompositionBatch(IEnumerable? partsToAdd, IEnumerable? partsToRemove) { _partsToAdd = new List(); - if (partsToAdd != null) + if (partsToAdd is not null) { foreach (var part in partsToAdd) { - if (part == null) + if (part is null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(partsToAdd)); } @@ -49,11 +49,11 @@ public CompositionBatch(IEnumerable? partsToAdd, IEnumerable(); - if (partsToRemove != null) + if (partsToRemove is not null) { foreach (var part in partsToRemove) { - if (part == null) + if (part is null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(partsToRemove)); } @@ -74,7 +74,7 @@ public ReadOnlyCollection PartsToAdd lock (_lock) { _copyNeededForAdd = true; - Debug.Assert(_readOnlyPartsToAdd != null); + Debug.Assert(_readOnlyPartsToAdd is not null); return _readOnlyPartsToAdd; } } @@ -91,7 +91,7 @@ public ReadOnlyCollection PartsToRemove lock (_lock) { _copyNeededForRemove = true; - Debug.Assert(_readOnlyPartsToRemove != null); + Debug.Assert(_readOnlyPartsToRemove is not null); return _readOnlyPartsToRemove; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs index 755a334349ca65..525f18c9073ad8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs @@ -13,7 +13,7 @@ private class CompositionServiceShim : ICompositionService public CompositionServiceShim(CompositionContainer innerContainer) { - if (innerContainer == null) + if (innerContainer is null) { throw new ArgumentNullException(nameof(innerContainer)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs index ca373b9c881bd7..663f0e972e1187 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs @@ -147,14 +147,14 @@ public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions c _partExportProvider.SourceProvider = this; // Create the catalog export provider, only if necessary - if (catalog != null) + if (catalog is not null) { _catalogExportProvider = new CatalogExportProvider(catalog, compositionOptions); _catalogExportProvider.SourceProvider = this; } // Set the local export provider - if (_catalogExportProvider != null) + if (_catalogExportProvider is not null) { _localExportProvider = new AggregateExportProvider(_partExportProvider, _catalogExportProvider); _disposableLocalExportProvider = _localExportProvider as IDisposable; @@ -165,7 +165,7 @@ public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions c } // Set the ancestor export provider, if ancestors are supplied - if ((providers != null) && (providers.Length > 0)) + if ((providers is not null) && (providers.Length > 0)) { // Aggregate ancestors if and only if more than one passed if (providers.Length > 1) @@ -175,7 +175,7 @@ public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions c } else { - if (providers[0] == null) + if (providers[0] is null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(providers)); } @@ -184,25 +184,25 @@ public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions c } // finally set the root provider - if (_ancestorExportProvider == null) + if (_ancestorExportProvider is null) { // if no ancestors are passed, the local and the root are the same _rootProvider = _localExportProvider; } else { - int exportProviderCount = 1 + ((catalog != null) ? 1 : 0) + ((providers != null) ? providers.Length : 0); + int exportProviderCount = 1 + ((catalog is not null) ? 1 : 0) + ((providers is not null) ? providers.Length : 0); ExportProvider[] rootProviders = new ExportProvider[exportProviderCount]; rootProviders[0] = _partExportProvider; int customProviderStartIndex = 1; - if (catalog != null) + if (catalog is not null) { rootProviders[1] = _catalogExportProvider!; customProviderStartIndex = 2; } - if (providers != null) + if (providers is not null) { for (int i = 0; i < providers.Length; i++) { @@ -223,7 +223,7 @@ public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions c _rootProvider.ExportsChanged += OnExportsChangedInternal; _rootProvider.ExportsChanging += OnExportsChangingInternal; - _providers = (providers != null) ? new ReadOnlyCollection((ExportProvider[])providers.Clone()) : EmptyProviders; + _providers = (providers is not null) ? new ReadOnlyCollection((ExportProvider[])providers.Clone()) : EmptyProviders; } internal CompositionOptions CompositionOptions @@ -253,7 +253,7 @@ public ComposablePartCatalog? Catalog { ThrowIfDisposed(); - return (_catalogExportProvider != null) ? _catalogExportProvider.Catalog : null; + return (_catalogExportProvider is not null) ? _catalogExportProvider.Catalog : null; } } @@ -284,7 +284,7 @@ public ReadOnlyCollection Providers get { ThrowIfDisposed(); - Debug.Assert(_providers != null); + Debug.Assert(_providers is not null); return _providers; } @@ -348,38 +348,38 @@ protected virtual void Dispose(bool disposing) } } - if (rootProvider != null) + if (rootProvider is not null) { rootProvider.ExportsChanged -= OnExportsChangedInternal; rootProvider.ExportsChanging -= OnExportsChangingInternal; } - if (disposableRootProvider != null) + if (disposableRootProvider is not null) { disposableRootProvider.Dispose(); } - if (disposableAncestorExportProvider != null) + if (disposableAncestorExportProvider is not null) { disposableAncestorExportProvider.Dispose(); } - if (disposableLocalExportProvider != null) + if (disposableLocalExportProvider is not null) { disposableLocalExportProvider.Dispose(); } - if (catalogExportProvider != null) + if (catalogExportProvider is not null) { catalogExportProvider.Dispose(); } - if (partExportProvider != null) + if (partExportProvider is not null) { partExportProvider.Dispose(); } - if (importEngine != null) + if (importEngine is not null) { importEngine.Dispose(); } @@ -538,20 +538,20 @@ public void SatisfyImportsOnce(ComposablePart part) { ThrowIfDisposed(); - if (_importEngine == null) + if (_importEngine is null) { ImportEngine? importEngine = new ImportEngine(this, _compositionOptions); lock (_lock) { - if (_importEngine == null) + if (_importEngine is null) { Thread.MemoryBarrier(); _importEngine = importEngine; importEngine = null; } } - if (importEngine != null) + if (importEngine is not null) { importEngine.Dispose(); } @@ -603,21 +603,21 @@ internal void OnExportsChangingInternal(object? sender, ExportsChangeEventArgs e switch ((ImportSource)source!) { case ImportSource.Any: - if (_rootProvider == null) + if (_rootProvider is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } _rootProvider.TryGetExports(definition, atomicComposition, out exports); break; case ImportSource.Local: - if (_localExportProvider == null) + if (_localExportProvider is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } _localExportProvider.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports); break; case ImportSource.NonLocal: - if (_ancestorExportProvider != null) + if (_ancestorExportProvider is not null) { _ancestorExportProvider.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs index ee9b9d80eb4565..e3ed23266f1b74 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs @@ -60,11 +60,11 @@ public CompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable? children, IEnumerable? publicSurface) { _catalog = catalog; - if (children != null) + if (children is not null) { _children = children.ToArray(); } - if (publicSurface != null) + if (publicSurface is not null) { _publicSurface = publicSurface; } @@ -133,7 +133,7 @@ public virtual IEnumerable PublicSurface get { ThrowIfDisposed(); - if (_publicSurface == null) + if (_publicSurface is null) { return this.SelectMany((p) => p.ExportDefinitions); } @@ -148,7 +148,7 @@ public virtual IEnumerable PublicSurface /// The children. public override IEnumerator GetEnumerator() { - Debug.Assert(_catalog != null); + Debug.Assert(_catalog is not null); return _catalog.GetEnumerator(); } @@ -180,13 +180,13 @@ public override IEnumerable> G { ThrowIfDisposed(); - Debug.Assert(_catalog != null); + Debug.Assert(_catalog is not null); return _catalog.GetExports(definition); } internal IEnumerable> GetExportsFromPublicSurface(ImportDefinition definition) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } @@ -227,7 +227,7 @@ internal IEnumerable> GetExpor protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { EventHandler? changedEvent = Changed; - if (changedEvent != null) + if (changedEvent is not null) { changedEvent.Invoke(this, e); } @@ -240,7 +240,7 @@ protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { EventHandler? changingEvent = Changing; - if (changingEvent != null) + if (changingEvent is not null) { changingEvent.Invoke(this, e); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs index 624adf905b8f5b..86a7e52cfaa15b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs @@ -19,7 +19,7 @@ public class CompositionService : ICompositionService, IDisposable internal CompositionService(ComposablePartCatalog composablePartCatalog) { - if (composablePartCatalog == null) + if (composablePartCatalog is null) { throw new ArgumentNullException(nameof(composablePartCatalog)); } @@ -27,7 +27,7 @@ internal CompositionService(ComposablePartCatalog composablePartCatalog) _notifyCatalog = composablePartCatalog as INotifyComposablePartCatalogChanged; try { - if (_notifyCatalog != null) + if (_notifyCatalog is not null) { _notifyCatalog.Changing += OnCatalogChanging; } @@ -39,7 +39,7 @@ internal CompositionService(ComposablePartCatalog composablePartCatalog) } catch { - if (_notifyCatalog != null) + if (_notifyCatalog is not null) { _notifyCatalog.Changing -= OnCatalogChanging; } @@ -50,7 +50,7 @@ internal CompositionService(ComposablePartCatalog composablePartCatalog) public void SatisfyImportsOnce(ComposablePart part) { Requires.NotNull(part, nameof(part)); - if (_compositionContainer == null) + if (_compositionContainer is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -59,13 +59,13 @@ public void SatisfyImportsOnce(ComposablePart part) public void Dispose() { - if (_compositionContainer == null) + if (_compositionContainer is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } // Delegates are cool there is no concern if you try to remove an item from them and they don't exist - if (_notifyCatalog != null) + if (_notifyCatalog is not null) { _notifyCatalog.Changing -= OnCatalogChanging; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs index 5fe99342cf96e2..bdf260642f3cf3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs @@ -25,7 +25,7 @@ internal static class CompositionServices internal static Type GetDefaultTypeFromMember(this MemberInfo member) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -63,12 +63,12 @@ internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContract internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type? memberType) { - if (specifiedContractType == null) + if (specifiedContractType is null) { throw new ArgumentNullException(nameof(specifiedContractType)); } - if ((memberType != null) && memberType.IsGenericType && specifiedContractType.IsGenericType) + if ((memberType is not null) && memberType.IsGenericType && specifiedContractType.IsGenericType) { // if the memeber type is closed and the specified contract type is open and they have exatly the same number of parameters // we will close the specfied contract type @@ -116,7 +116,7 @@ internal static void GetContractInfoFromExport(this MemberInfo member, ExportAtt internal static string GetTypeIdentityFromExport(this MemberInfo member, Type? typeIdentityType) { - if (typeIdentityType != null) + if (typeIdentityType is not null) { string typeIdentity = AttributedModelServices.GetTypeIdentity(typeIdentityType); if (typeIdentityType.ContainsGenericParameters) @@ -128,7 +128,7 @@ internal static string GetTypeIdentityFromExport(this MemberInfo member, Type? t else { MethodInfo? method = member as MethodInfo; - if (method == null) + if (method is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -138,7 +138,7 @@ internal static string GetTypeIdentityFromExport(this MemberInfo member, Type? t private static Type? GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export) { - if (export.ContractType != null) + if (export.ContractType is not null) { return export.ContractType.AdjustSpecifiedTypeIdentityType(member); } @@ -155,7 +155,7 @@ internal static bool IsContractNameSameAsTypeIdentity(this ExportAttribute expor internal static Type GetContractTypeFromImport(this IAttributedImport import, ImportType importType) { - if (import.ContractType != null) + if (import.ContractType is not null) { return import.ContractType.AdjustSpecifiedTypeIdentityType(importType.ContractType); } @@ -235,7 +235,7 @@ internal static string GetContractNameFromImport(this IAttributedImport import, GenericParameterAttributes attributes = genericArgument.GenericParameterAttributes; - if ((constraints != null) || (attributes != GenericParameterAttributes.None)) + if ((constraints is not null) || (attributes != GenericParameterAttributes.None)) { genericParameterConstraints[i] = constraints; genericParameterAttributes[i] = attributes; @@ -268,7 +268,7 @@ internal static void TryExportMetadataForMember(this MemberInfo member, out IDic { var provider = attr as ExportMetadataAttribute; - if (provider != null) + if (provider is not null) { if (reservedMetadataNames.Contains(provider.Name, StringComparers.MetadataKeyNames)) { @@ -291,7 +291,7 @@ internal static void TryExportMetadataForMember(this MemberInfo member, out IDic bool allowsMultiple = false; AttributeUsageAttribute? usage = attrType.GetFirstAttribute(true); - if (usage != null) + if (usage is not null) { allowsMultiple = usage.AllowMultiple; } @@ -311,7 +311,7 @@ internal static void TryExportMetadataForMember(this MemberInfo member, out IDic object? value = pi.GetValue(attr, null); - if (value != null && !IsValidAttributeType(value.GetType())) + if (value is not null && !IsValidAttributeType(value.GetType())) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_MetadataContainsValueWithInvalidType, pi.GetDisplayName(), value.GetType().GetDisplayName()); } @@ -329,7 +329,7 @@ internal static void TryExportMetadataForMember(this MemberInfo member, out IDic foreach (var key in dictionary.Keys.ToArray()) { var list = dictionary[key] as MetadataList; - if (list != null) + if (list is not null) { dictionary[key] = list.ToArray(); } @@ -354,7 +354,7 @@ private static bool TryContributeMetadataValue(this IDictionary else { var list = metadataValue as MetadataList; - if (!allowsMultiple || list == null) + if (!allowsMultiple || list is null) { // Either single value already found when should be multiple // or a duplicate name already exists @@ -377,7 +377,7 @@ private class MetadataList public void Add(object? item, Type? itemType) { - _containsNulls |= (item == null); + _containsNulls |= (item is null); // if we've been passed typeof(object), we basically have no type inmformation if (itemType == ObjectType) @@ -386,7 +386,7 @@ public void Add(object? item, Type? itemType) } // if we have no type information, get it from the item, if we can - if ((itemType == null) && (item != null)) + if ((itemType is null) && (item is not null)) { itemType = item.GetType(); } @@ -398,7 +398,7 @@ public void Add(object? item, Type? itemType) } // only try to call this if we got a meaningful type - if (itemType != null) + if (itemType is not null) { InferArrayType(itemType); } @@ -408,12 +408,12 @@ public void Add(object? item, Type? itemType) private void InferArrayType(Type itemType) { - if (itemType == null) + if (itemType is null) { throw new ArgumentNullException(nameof(itemType)); } - if (_arrayType == null) + if (_arrayType is null) { // this is the first typed element we've been given, it sets the type of the array _arrayType = itemType; @@ -432,7 +432,7 @@ private void InferArrayType(Type itemType) public Array ToArray() { - if (_arrayType == null) + if (_arrayType is null) { // if the array type has not been set, assume Object _arrayType = ObjectType; @@ -456,12 +456,12 @@ public Array ToArray() //UNDONE: Need to add these warnings somewhere...Dev10:472538 should address //internal static CompositionResult MatchRequiredMetadata(this IDictionary metadata, IEnumerable requiredMetadata, string contractName) //{ - // Assumes.IsTrue(metadata != null); + // Assumes.IsTrue(metadata is not null); // var result = CompositionResult.SucceededResult; - // var missingMetadata = (requiredMetadata == null) ? null : requiredMetadata.Except(metadata.Keys); - // if (missingMetadata != null && missingMetadata.Any()) + // var missingMetadata = (requiredMetadata is null) ? null : requiredMetadata.Except(metadata.Keys); + // if (missingMetadata is not null && missingMetadata.Any()) // { // result = result.MergeIssue( // CompositionError.CreateIssueAsWarning(CompositionErrorId.RequiredMetadataNotFound, @@ -477,7 +477,7 @@ public Array ToArray() internal static IEnumerable> GetRequiredMetadata(Type? metadataViewType) { - if ((metadataViewType == null) || + if ((metadataViewType is null) || ExportServices.IsDefaultMetadataViewType(metadataViewType) || ExportServices.IsDictionaryConstructorViewType(metadataViewType) || !metadataViewType.IsInterface) @@ -487,7 +487,7 @@ internal static IEnumerable> GetRequiredMetadata(Type // A metadata view is required to be an Intrerface, and therefore only properties are allowed List properties = metadataViewType.GetAllProperties(). - Where(property => property.GetFirstAttribute() == null). + Where(property => property.GetFirstAttribute() is null). ToList(); // NOTE : this is a carefully found balance between eager and delay-evaluation - the properties are filtered once and upfront @@ -522,16 +522,16 @@ internal static IEnumerable> GetRequiredMetadata(Type } // Default value is ImportSource.Any - if (attributedImport != null && attributedImport.Source != ImportSource.Any) + if (attributedImport is not null && attributedImport.Source != ImportSource.Any) { - if (metadata == null) + if (metadata is null) { metadata = new Dictionary(); } metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source; } - if (metadata != null) + if (metadata is not null) { return metadata.AsReadOnly(); } @@ -543,7 +543,7 @@ internal static IEnumerable> GetRequiredMetadata(Type internal static object? GetExportedValueFromComposedPart(ImportEngine? engine, ComposablePart part, ExportDefinition definition) { - if (engine != null) + if (engine is not null) { try { @@ -629,7 +629,7 @@ private static bool IsValidAttributeType(Type type) private static bool IsValidAttributeType(Type type, bool arrayAllowed) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs index 7088f00aba17f4..74c9d66662a82b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs @@ -393,7 +393,7 @@ public string FullPath { get { - Debug.Assert(_fullPath != null); + Debug.Assert(_fullPath is not null); return _fullPath; } @@ -408,7 +408,7 @@ public ReadOnlyCollection LoadedFiles { using (new ReadLock(_thisLock)) { - Debug.Assert(_loadedFiles != null); + Debug.Assert(_loadedFiles is not null); return _loadedFiles; } } @@ -421,7 +421,7 @@ public string Path { get { - Debug.Assert(_path != null); + Debug.Assert(_path is not null); return _path; } @@ -479,7 +479,7 @@ protected override void Dispose(bool disposing) } finally { - if (catalogs != null) + if (catalogs is not null) { catalogs.Dispose(); } @@ -540,7 +540,7 @@ public override IEnumerable> G protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { EventHandler? changedEvent = Changed; - if (changedEvent != null) + if (changedEvent is not null) { changedEvent(this, e); } @@ -555,7 +555,7 @@ protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { EventHandler? changingEvent = Changing; - if (changingEvent != null) + if (changingEvent is not null) { changingEvent(this, e); } @@ -577,7 +577,7 @@ protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) public void Refresh() { ThrowIfDisposed(); - if (_loadedFiles == null) + if (_loadedFiles is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -675,7 +675,7 @@ public override string ToString() try { - return (_reflectionContext != null) + return (_reflectionContext is not null) ? new AssemblyCatalog(assemblyFilePath, _reflectionContext, this) : new AssemblyCatalog(assemblyFilePath, this); } @@ -713,7 +713,7 @@ private void DiffChanges(string[] beforeFiles, string[] afterFiles, { AssemblyCatalog? catalog = CreateAssemblyCatalogGuarded(file); - if (catalog != null) + if (catalog is not null) { catalogsToAdd.Add(new Tuple(file, catalog)); } @@ -778,7 +778,7 @@ private void Initialize(string path, string searchPattern) { AssemblyCatalog? assemblyCatalog = CreateAssemblyCatalogGuarded(file); - if (assemblyCatalog != null) + if (assemblyCatalog is not null) { _assemblyCatalogs.Add(file, assemblyCatalog); _catalogCollection.Add(assemblyCatalog); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs index 8ddbd6c5368902..17c71a3a0dd883 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs @@ -729,7 +729,7 @@ private IEnumerable GetExportedValuesCore(string? contractName) Export? export = GetExportsCore(typeof(T), (Type?)null, contractName, cardinality).SingleOrDefault(); - return (export != null) ? ExportServices.GetCastedExportedValue(export) : default; + return (export is not null) ? ExportServices.GetCastedExportedValue(export) : default; } private IEnumerable> GetExportsCore(string? contractName) @@ -760,14 +760,14 @@ private IEnumerable> GetExportsCore(str { Export? export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); - return (export != null) ? ExportServices.CreateStronglyTypedLazyOfTM(export) : null; + return (export is not null) ? ExportServices.CreateStronglyTypedLazyOfTM(export) : null; } private Lazy? GetExportCore(string? contractName) { Export? export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); - return (export != null) ? ExportServices.CreateStronglyTypedLazyOfT(export) : null; + return (export is not null) ? ExportServices.CreateStronglyTypedLazyOfT(export) : null; } private IEnumerable GetExportsCore(Type type, Type? metadataViewType, string? contractName, ImportCardinality cardinality) @@ -780,7 +780,7 @@ private IEnumerable GetExportsCore(Type type, Type? metadataViewType, st contractName = AttributedModelServices.GetContractName(type); } - if (metadataViewType == null) + if (metadataViewType is null) { metadataViewType = ExportServices.DefaultMetadataViewType; } @@ -796,17 +796,17 @@ private IEnumerable GetExportsCore(Type type, Type? metadataViewType, st private static ImportDefinition BuildImportDefinition(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (metadataViewType == null) + if (metadataViewType is null) { throw new ArgumentNullException(nameof(metadataViewType)); } - if (contractName == null) + if (contractName is null) { throw new ArgumentNullException(nameof(contractName)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs index d17e1210684af3..8bcdfffc859cc6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs @@ -102,7 +102,7 @@ public IEnumerable GetExports(ImportDefinition definition, AtomicComposi switch (result) { case ExportCardinalityCheckResult.Match: - Debug.Assert(exports != null); + Debug.Assert(exports is not null); return exports; case ExportCardinalityCheckResult.NoExports: throw new ImportCardinalityMismatchException(SR.Format(SR.CardinalityMismatch_NoExports, definition)); @@ -182,7 +182,7 @@ public bool TryGetExports(ImportDefinition definition, AtomicComposition? atomic protected virtual void OnExportsChanged(ExportsChangeEventArgs e) { EventHandler? changedEvent = ExportsChanged; - if (changedEvent != null) + if (changedEvent is not null) { CompositionResult result = CompositionServices.TryFire(changedEvent, this, e); result.ThrowOnErrors(e.AtomicComposition); @@ -198,7 +198,7 @@ protected virtual void OnExportsChanged(ExportsChangeEventArgs e) protected virtual void OnExportsChanging(ExportsChangeEventArgs e) { EventHandler? changingEvent = ExportsChanging; - if (changingEvent != null) + if (changingEvent is not null) { CompositionResult result = CompositionServices.TryFire(changingEvent, this, e); result.ThrowOnErrors(e.AtomicComposition); @@ -207,7 +207,7 @@ protected virtual void OnExportsChanging(ExportsChangeEventArgs e) private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable? exports) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } @@ -227,7 +227,7 @@ private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definiti exports = null; } - if (exports == null) + if (exports is null) { exports = Array.Empty(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs index 06ed592521ee88..af37523f141dfb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs @@ -63,7 +63,7 @@ public IEnumerable AddedExports { get { - Debug.Assert(_addedExports != null); + Debug.Assert(_addedExports is not null); return _addedExports; } @@ -80,7 +80,7 @@ public IEnumerable RemovedExports { get { - Debug.Assert(_removedExports != null); + Debug.Assert(_removedExports is not null); return _removedExports; } @@ -97,7 +97,7 @@ public IEnumerable ChangedContractNames { get { - if (_changedContractNames == null) + if (_changedContractNames is null) { _changedContractNames = AddedExports .Concat(RemovedExports) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs index 9f3b0a41836da0..3edc4bbcc7f541 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs @@ -19,12 +19,12 @@ internal class DependenciesTraversal : IComposablePartCatalogTraversal public DependenciesTraversal(FilteredCatalog catalog, Func importFilter) { - if (catalog == null) + if (catalog is null) { throw new ArgumentNullException(nameof(catalog)); } - if (importFilter == null) + if (importFilter is null) { throw new ArgumentNullException(nameof(importFilter)); } @@ -69,7 +69,7 @@ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out I { // Find all parts that we know will import each export List? candidateReachableParts = null; - Debug.Assert(_exportersIndex != null); + Debug.Assert(_exportersIndex is not null); foreach (var contractName in import.GetCandidateContractNames(part)) { if (_exportersIndex.TryGetValue(contractName, out candidateReachableParts)) @@ -81,7 +81,7 @@ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out I { if (import.IsImportDependentOnPart(candidateReachablePart, export, part.IsGeneric() != candidateReachablePart.IsGeneric())) { - if (reachablePartList == null) + if (reachablePartList is null) { reachablePartList = new List(); } @@ -94,7 +94,7 @@ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out I } reachableParts = reachablePartList; - return (reachableParts != null); + return (reachableParts is not null); } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs index bb80dafa4026b4..2853f300330417 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs @@ -25,11 +25,11 @@ internal class DependentsTraversal : IComposablePartCatalogTraversal public DependentsTraversal(FilteredCatalog catalog, Func importFilter) { - if (catalog == null) + if (catalog is null) { throw new ArgumentNullException(nameof(catalog)); } - if (importFilter == null) + if (importFilter is null) { throw new ArgumentNullException(nameof(importFilter)); } @@ -73,7 +73,7 @@ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out I reachableParts = null; List? reachablePartList = null; - Debug.Assert(_importersIndex != null); + Debug.Assert(_importersIndex is not null); // Go through all part exports foreach (ExportDefinition export in part.ExportDefinitions) { @@ -88,7 +88,7 @@ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out I { if (import.IsImportDependentOnPart(part, export, part.IsGeneric() != candidateReachablePart.IsGeneric())) { - if (reachablePartList == null) + if (reachablePartList is null) { reachablePartList = new List(); } @@ -100,7 +100,7 @@ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out I } reachableParts = reachablePartList; - return (reachableParts != null); + return (reachableParts is not null); } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs index aaffa2ccc6feb1..374624738ebf1f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs @@ -58,7 +58,7 @@ public FilteredCatalog IncludeDependents(Func importFilt private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal) { - if (traversal == null) + if (traversal is null) { throw new ArgumentNullException(nameof(traversal)); } @@ -82,7 +82,7 @@ private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal) private static HashSet GetTraversalClosure(IEnumerable parts, IComposablePartCatalogTraversal traversal) { - if (traversal == null) + if (traversal is null) { throw new ArgumentNullException(nameof(traversal)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs index 279fe06e3693c3..58fd7b903e3f53 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs @@ -72,7 +72,7 @@ protected override void Dispose(bool disposing) } finally { - if (notifyCatalog != null) + if (notifyCatalog is not null) { notifyCatalog.Changed -= OnChangedInternal; notifyCatalog.Changing -= OnChangingInternal; @@ -102,12 +102,12 @@ public FilteredCatalog Complement { ThrowIfDisposed(); - if (_complement == null) + if (_complement is null) { FilteredCatalog? complement = new FilteredCatalog(_innerCatalog, p => !_filter(p), this); lock (_lock) { - if (_complement == null) + if (_complement is null) { Thread.MemoryBarrier(); _complement = complement; @@ -115,7 +115,7 @@ public FilteredCatalog Complement } } - if (complement != null) + if (complement is not null) { complement.Dispose(); } @@ -183,7 +183,7 @@ public override IEnumerable> G protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { EventHandler? changedEvent = Changed; - if (changedEvent != null) + if (changedEvent is not null) { changedEvent.Invoke(this, e); } @@ -196,7 +196,7 @@ protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { EventHandler? changingEvent = Changing; - if (changingEvent != null) + if (changingEvent is not null) { changingEvent.Invoke(this, e); } @@ -205,7 +205,7 @@ protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e) { var processedArgs = ProcessEventArgs(e); - if (processedArgs != null) + if (processedArgs is not null) { OnChanged(ProcessEventArgs(processedArgs)!); } @@ -214,7 +214,7 @@ private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventA private void OnChangingInternal(object? sender, ComposablePartCatalogChangeEventArgs e) { var processedArgs = ProcessEventArgs(e); - if (processedArgs != null) + if (processedArgs is not null) { OnChanging(ProcessEventArgs(processedArgs)!); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs index ccbd268ab29cb0..5206e2d6191de6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs @@ -27,7 +27,7 @@ public EngineContext(ImportEngine importEngine, EngineContext? parentEngineConte public void AddPartManager(PartManager part) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } @@ -40,7 +40,7 @@ public void AddPartManager(PartManager part) public void RemovePartManager(PartManager part) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } @@ -53,7 +53,7 @@ public void RemovePartManager(PartManager part) public IEnumerable? GetAddedPartManagers() { - if (_parentEngineContext != null) + if (_parentEngineContext is not null) { return _addedPartManagers.ConcatAllowingNull(_parentEngineContext.GetAddedPartManagers()); } @@ -62,7 +62,7 @@ public void RemovePartManager(PartManager part) public IEnumerable? GetRemovedPartManagers() { - if (_parentEngineContext != null) + if (_parentEngineContext is not null) { return _removedPartManagers.ConcatAllowingNull(_parentEngineContext.GetRemovedPartManagers()); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs index 68e91edada55c6..d2497fb75e9e32 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs @@ -60,12 +60,12 @@ public ImportState State public IEnumerable GetImportedContractNames() { - if (Part == null) + if (Part is null) { return Enumerable.Empty(); } - if (_importedContractNames == null) + if (_importedContractNames is null) { _importedContractNames = Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray(); } @@ -96,7 +96,7 @@ public CompositionResult TrySetImport(ImportDefinition import, Export[] exports) public void SetSavedImport(ImportDefinition import, Export[]? exports, AtomicComposition? atomicComposition) { - if (atomicComposition != null) + if (atomicComposition is not null) { var savedExports = GetSavedImport(import); @@ -106,7 +106,7 @@ public void SetSavedImport(ImportDefinition import, Export[]? exports, AtomicCom SetSavedImport(import, savedExports, null)); } - if (_importCache == null) + if (_importCache is null) { _importCache = new Dictionary(); } @@ -117,7 +117,7 @@ public void SetSavedImport(ImportDefinition import, Export[]? exports, AtomicCom public Export[]? GetSavedImport(ImportDefinition import) { Export[]? exports = null; - if (_importCache != null) + if (_importCache is not null) { // We don't care about the return value we just want the exports // and if it isn't present we just return the initialized null value @@ -154,7 +154,7 @@ public void UpdateDisposableDependencies(ImportDefinition import, Export[] expor { if (export is IDisposable disposableExport) { - if (disposableExports == null) + if (disposableExports is null) { disposableExports = new List(); } @@ -164,13 +164,13 @@ public void UpdateDisposableDependencies(ImportDefinition import, Export[] expor // Dispose any existing references previously set on this import List? oldDisposableExports = null; - if (_importedDisposableExports != null && + if (_importedDisposableExports is not null && _importedDisposableExports.TryGetValue(import, out oldDisposableExports)) { oldDisposableExports.ForEach(disposable => disposable.Dispose()); // If there aren't any replacements, get rid of the old storage - if (disposableExports == null) + if (disposableExports is null) { _importedDisposableExports.Remove(import); if (!_importedDisposableExports.Any()) @@ -183,9 +183,9 @@ public void UpdateDisposableDependencies(ImportDefinition import, Export[] expor } // Record the new collection - if (disposableExports != null) + if (disposableExports is not null) { - if (_importedDisposableExports == null) + if (_importedDisposableExports is null) { _importedDisposableExports = new Dictionary>(); } @@ -195,7 +195,7 @@ public void UpdateDisposableDependencies(ImportDefinition import, Export[] expor public void DisposeAllDependencies() { - if (_importedDisposableExports != null) + if (_importedDisposableExports is not null) { IEnumerable dependencies = _importedDisposableExports.Values .SelectMany(exports => exports); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs index 3d1b942eb24d95..b8c2b4f5ebab23 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs @@ -141,7 +141,7 @@ private void UpdateImportIndex() foreach (var partManager in partsToUnindex) { - if (partManager != null) + if (partManager is not null) { RemoveIndexEntries(partManager); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs index 36df11b809a622..3d46e4111f68f8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs @@ -102,11 +102,11 @@ public void PreviewImports(ComposablePart part, AtomicComposition? atomicComposi // This will take the lock, if necesary IDisposable? compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null; - bool compositionLockTaken = (compositionLockHolder != null); + bool compositionLockTaken = (compositionLockHolder is not null); try { // revert actions are processed in the reverse order, so we have to add the "release lock" action now - if (compositionLockTaken && (atomicComposition != null)) + if (compositionLockTaken && (atomicComposition is not null)) { atomicComposition.AddRevertAction(() => compositionLockHolder!.Dispose()); } @@ -118,7 +118,7 @@ public void PreviewImports(ComposablePart part, AtomicComposition? atomicComposi StartSatisfyingImports(partManager, atomicComposition); // Add the "release lock" to the commit actions - if (compositionLockTaken && (atomicComposition != null)) + if (compositionLockTaken && (atomicComposition is not null)) { atomicComposition.AddCompleteAction(() => compositionLockHolder!.Dispose()); } @@ -126,7 +126,7 @@ public void PreviewImports(ComposablePart part, AtomicComposition? atomicComposi finally { // We haven't updated the queues, so we can release the lock now - if (compositionLockTaken && (atomicComposition == null)) + if (compositionLockTaken && (atomicComposition is null)) { compositionLockHolder!.Dispose(); } @@ -233,7 +233,7 @@ public void ReleaseImports(ComposablePart part, AtomicComposition? atomicComposi using (_lock.LockComposition()) { PartManager? partManager = GetPartManager(part, false); - if (partManager != null) + if (partManager is not null) { StopSatisfyingImports(partManager, atomicComposition); } @@ -274,7 +274,7 @@ protected virtual void Dispose(bool disposing) } } - if (sourceProviderToUnsubscribeFrom != null) + if (sourceProviderToUnsubscribeFrom is not null) { sourceProviderToUnsubscribeFrom.ExportsChanging -= OnExportsChanging; } @@ -409,7 +409,7 @@ private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part, bool shouldTrackImports) { - if (part == null) + if (part is null) { throw new ArgumentNullException(nameof(part)); } @@ -459,7 +459,7 @@ private CompositionResult TrySatisfyImportSubset(PartManager partManager, { var exports = partManager.GetSavedImport(import); - if (exports == null) + if (exports is null) { CompositionResult> exportsResult = TryGetExports( _sourceProvider, part, import, atomicComposition); @@ -472,7 +472,7 @@ private CompositionResult TrySatisfyImportSubset(PartManager partManager, exports = exportsResult.Value.AsArray(); } - if (atomicComposition == null) + if (atomicComposition is null) { result = result.MergeResult( partManager.TrySetImport(import, exports)); @@ -496,7 +496,7 @@ private void OnExportsChanging(object? sender, ExportsChangeEventArgs e) // When in a atomicComposition account for everything that isn't yet reflected in the // index - if (atomicComposition != null) + if (atomicComposition is not null) { if (atomicComposition.TryGetValue(this, out EngineContext? engineContext)) { @@ -553,7 +553,7 @@ private CompositionResult TryRecomposeImports(PartManager partManager, // schedule it for later if (result.Succeeded && recomposedImport && partComposed) { - if (atomicComposition == null) + if (atomicComposition is null) { result = result.MergeResult(partManager.TryOnComposed()); } @@ -588,7 +588,7 @@ private CompositionResult TryRecomposeImport(PartManager partManager, bool partC // Knowing that the part has already been composed before and that the only possible // changes are to recomposable imports, we can safely go ahead and do this now or // schedule it for later - if (atomicComposition == null) + if (atomicComposition is null) { return partManager.TrySetImport(import, exports); } @@ -609,7 +609,7 @@ private void StartSatisfyingImports(PartManager partManager, AtomicComposition? { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant addition - if (atomicComposition == null) + if (atomicComposition is null) { if (!partManager.TrackingImports) { @@ -629,7 +629,7 @@ private void StopSatisfyingImports(PartManager partManager, AtomicComposition? a { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant removal - if (atomicComposition == null) + if (atomicComposition is null) { ConditionalWeakTable? partManagers = null; RecompositionManager? recompositionManager = null; @@ -639,7 +639,7 @@ private void StopSatisfyingImports(PartManager partManager, AtomicComposition? a partManagers = _partManagers; recompositionManager = _recompositionManager; } - if (partManagers != null) // Disposal race may have been won by dispose + if (partManagers is not null) // Disposal race may have been won by dispose { partManagers.Remove(partManager.Part); @@ -688,7 +688,7 @@ private void StopSatisfyingImports(PartManager partManager, AtomicComposition? a private EngineContext GetEngineContext(AtomicComposition atomicComposition) { - if (atomicComposition == null) + if (atomicComposition is null) { throw new ArgumentNullException(nameof(atomicComposition)); } @@ -745,7 +745,7 @@ private static CompositionResult> TryGetExports(ExportProvid try { IEnumerable? exports = null; - if (provider != null) + if (provider is not null) { exports = provider.GetExports(definition, atomicComposition).AsArray(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs index 825da007d85206..caea76bb0eb99d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs @@ -15,7 +15,7 @@ internal static class ImportSourceImportDefinitionHelpers public static ImportDefinition RemoveImportSource(this ImportDefinition definition) { var contractBasedDefinition = definition as ContractBasedImportDefinition; - if (contractBasedDefinition == null) + if (contractBasedDefinition is null) { return definition; } @@ -32,7 +32,7 @@ internal class NonImportSourceImportDefinition : ContractBasedImportDefinition public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition) { - if (sourceDefinition == null) + if (sourceDefinition is null) { throw new ArgumentNullException(nameof(sourceDefinition)); } @@ -50,14 +50,14 @@ public override string ContractName get { var reply = _metadata; - if (reply == null) + if (reply is null) { reply = new Dictionary(_sourceDefinition.Metadata); reply.Remove(CompositionConstants.ImportSourceMetadataName); _metadata = reply; } - Debug.Assert(reply != null); + Debug.Assert(reply is not null); return reply; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs index aba54f989ee05f..7afd51388738ed 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs @@ -113,9 +113,9 @@ public static bool ContainsPartMetadata(this ComposablePartDefinition part, s if (part.Metadata.TryGetValue(key, out object? untypedValue)) { - if (value == null) + if (value is null) { - return (untypedValue == null); + return (untypedValue is null); } else { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs index 2a0d7eb1fc1ac0..0e97d5e12fd1de 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs @@ -176,7 +176,7 @@ private void InitializeTypeCatalog(IEnumerable types, ReflectionContext re var typesList = new List(); foreach (var type in types) { - if (type == null) + if (type is null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(types)); } @@ -185,10 +185,10 @@ private void InitializeTypeCatalog(IEnumerable types, ReflectionContext re throw new ArgumentException(SR.Format(SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types)); } var typeInfo = type.GetTypeInfo(); - var lclType = (reflectionContext != null) ? reflectionContext.MapType(typeInfo) : typeInfo; + var lclType = (reflectionContext is not null) ? reflectionContext.MapType(typeInfo) : typeInfo; // It is valid for the reflectionContext to delete types by mapping them to null - if (lclType != null) + if (lclType is not null) { // The final mapped type may be activated so we check to see if it is in a reflect only assembly if (lclType.Assembly.ReflectionOnly) @@ -205,7 +205,7 @@ private void InitializeTypeCatalog(IEnumerable types) { foreach (var type in types) { - if (type == null) + if (type is null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(types)); } @@ -249,13 +249,13 @@ private IEnumerable PartsInternal { get { - if (_parts == null) + if (_parts is null) { lock (_thisLock) { - if (_parts == null) + if (_parts is null) { - if (_types == null) + if (_types is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -264,7 +264,7 @@ private IEnumerable PartsInternal foreach (Type type in _types) { var definition = AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, _definitionOrigin); - if (definition != null) + if (definition is not null) { collection.Add(definition); } @@ -283,7 +283,7 @@ private IEnumerable PartsInternal internal override IEnumerable? GetCandidateParts(ImportDefinition definition) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } @@ -304,7 +304,7 @@ private IEnumerable PartsInternal private List? GetCandidateParts(string? contractName) { - if (contractName == null) + if (contractName is null) { return null; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs index 25d362e457d7d4..3ae46ac43a151f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs @@ -13,7 +13,7 @@ internal static class MetadataServices public static IDictionary AsReadOnly(this IDictionary? metadata) { - if (metadata == null) + if (metadata is null) { return EmptyMetadata; } @@ -28,7 +28,7 @@ internal static class MetadataServices public static T? GetValue(this IDictionary metadata, string key) { - if (metadata == null) + if (metadata is null) { throw new ArgumentNullException(nameof(metadata)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs index 18c02522793308..7349dfc2b86f67 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs @@ -28,7 +28,7 @@ namespace System.ComponentModel.Composition // // public __Foo__MedataViewProxy (IDictionary metadata) // { - // if (metadata == null) + // if (metadata is null) // { // throw InvalidArgumentException("metadata"); // } @@ -78,7 +78,7 @@ internal static class MetadataViewGenerator // Must be called with _lock held private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical) { - if (transparentProxyModuleBuilder == null) + if (transparentProxyModuleBuilder is null) { // make a new assemblybuilder and modulebuilder var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(ProxyAssemblyName, AssemblyBuilderAccess.Run); @@ -90,7 +90,7 @@ private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical) public static MetadataViewFactory GetMetadataViewFactory(Type viewType) { - if (viewType == null) + if (viewType is null) { throw new ArgumentNullException(nameof(viewType)); } @@ -113,14 +113,14 @@ public static MetadataViewFactory GetMetadataViewFactory(Type viewType) { // Try again under a write lock if still none generate the proxy Type? generatedProxyType = GenerateInterfaceViewProxyType(viewType); - if (generatedProxyType == null) + if (generatedProxyType is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } MetadataViewFactory generatedMetadataViewFactory = (MetadataViewFactory)Delegate.CreateDelegate( typeof(MetadataViewFactory), generatedProxyType.GetMethod(MetadataViewGenerator.MetadataViewFactoryName, BindingFlags.Public | BindingFlags.Static)!); - if (generatedMetadataViewFactory == null) + if (generatedMetadataViewFactory is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -139,7 +139,7 @@ public static MetadataViewFactory GetMetadataViewFactory(Type viewType) public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory, IDictionary metadata) { - if (metadataViewFactory == null) + if (metadataViewFactory is null) { throw new ArgumentNullException(nameof(metadataViewFactory)); } @@ -160,7 +160,7 @@ private static void GenerateLocalAssignmentFromDefaultAttribute(this ILGenerator { DefaultValueAttribute defaultAttribute = attrs[0]; IL.LoadValue(defaultAttribute.Value); - if ((defaultAttribute.Value != null) && (defaultAttribute.Value.GetType().IsValueType)) + if ((defaultAttribute.Value is not null) && (defaultAttribute.Value.GetType().IsValueType)) { IL.Emit(OpCodes.Box, defaultAttribute.Value.GetType()); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs index c4514fdc9a8ad3..d3aaa5f97acc1e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs @@ -14,7 +14,7 @@ internal static class MetadataViewProvider { public static TMetadataView GetMetadataView(IDictionary metadata) { - if (metadata == null) + if (metadata is null) { throw new ArgumentNullException(nameof(metadata)); } @@ -47,9 +47,9 @@ public static TMetadataView GetMetadataView(IDictionary(); - Debug.Assert(implementationAttribute != null); + Debug.Assert(implementationAttribute is not null); proxyType = implementationAttribute.ImplementationType; - if (proxyType == null) + if (proxyType is null) { throw new CompositionContractMismatchException(SR.Format( SR.ContractMismatch_MetadataViewImplementationCanNotBeNull, @@ -75,13 +75,13 @@ public static TMetadataView GetMetadataView(IDictionary(metadataViewFactory, metadata); } else { - if (proxyType == null) + if (proxyType is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -128,7 +128,7 @@ public static TMetadataView GetMetadataView(IDictionary Parts get { ThrowIfDisposed(); - if (_queryableParts == null) + if (_queryableParts is null) { // Guarantee one time only set _queryableParts var p = this.AsQueryable(); Interlocked.CompareExchange(ref _queryableParts, p, null); - if (_queryableParts == null) + if (_queryableParts is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -102,7 +102,7 @@ public virtual IEnumerable> Ge List>? exports = null; var candidateParts = GetCandidateParts(definition); - if (candidateParts != null) + if (candidateParts is not null) { foreach (var part in candidateParts) { @@ -113,7 +113,7 @@ public virtual IEnumerable> Ge } } - Debug.Assert(exports != null || _EmptyExportsList != null); + Debug.Assert(exports is not null || _EmptyExportsList is not null); return exports ?? _EmptyExportsList; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs index dcb37adb742c79..9c18511e29d794 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs @@ -115,13 +115,13 @@ internal virtual bool TryGetExports(ImportDefinition definition, out Tuple(this, export); } else { - if (multipleExports == null) + if (multipleExports is null) { multipleExports = new List>(); multipleExports.Add(singleExport); @@ -136,7 +136,7 @@ internal virtual bool TryGetExports(ImportDefinition definition, out Tuple> RequiredMetadata // NOTE : unlike other arguments, we validate this one as late as possible, because its validation may lead to type loading ValidateRequiredMetadata(); - Debug.Assert(_requiredMetadata != null); + Debug.Assert(_requiredMetadata is not null); return _requiredMetadata; } } @@ -223,7 +223,7 @@ private void ValidateRequiredMetadata() { foreach (KeyValuePair metadataItem in _requiredMetadata) { - if ((metadataItem.Key == null) || (metadataItem.Value == null)) + if ((metadataItem.Key is null) || (metadataItem.Value is null)) { throw new InvalidOperationException( SR.Format(SR.Argument_NullElement, "requiredMetadata")); @@ -273,7 +273,7 @@ public override Expression> Constraint { get { - if (_constraint == null) + if (_constraint is null) { _constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy); } @@ -336,7 +336,7 @@ private bool MatchRequiredMetadata(ExportDefinition definition) return false; } - if (metadataValue != null) + if (metadataValue is not null) { // the metadata value is not null, we can rely on IsInstanceOfType to do the right thing if (!metadataValueType.IsInstanceOfType(metadataValue)) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs index cbfc1f51412b65..d71736d84eb1ea 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs @@ -141,7 +141,7 @@ public virtual ExportDefinition Definition { get { - if (_definition != null) + if (_definition is not null) { return _definition; } @@ -170,7 +170,7 @@ public virtual ExportDefinition Definition { get { - Debug.Assert(Definition.Metadata != null); + Debug.Assert(Definition.Metadata is not null); return Definition.Metadata; } @@ -234,7 +234,7 @@ public object? Value /// protected virtual object? GetExportedValueCore() { - if (_exportedValueGetter != null) + if (_exportedValueGetter is not null) { return _exportedValueGetter.Invoke(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs index 94eee6ca884d86..0d7f3f0d14ff63 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs @@ -57,7 +57,7 @@ public ExportDefinition(string contractName, IDictionary? metad _contractName = contractName; - if (metadata != null) + if (metadata is not null) { _metadata = metadata.AsReadOnly(); } @@ -83,7 +83,7 @@ public virtual string ContractName { get { - if (_contractName != null) + if (_contractName is not null) { return _contractName; } @@ -116,7 +116,7 @@ public virtual string ContractName { get { - Debug.Assert(_metadata != null); + Debug.Assert(_metadata is not null); return _metadata; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs index 7a3be926e316f0..a5e92e0082986a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs @@ -111,7 +111,7 @@ internal ImportDefinition(string? contractName, ImportCardinality cardinality, b _isPrerequisite = isPrerequisite; //Metadata on imports was added in 4.5, prior to that it was ignored. - if (metadata != null) + if (metadata is not null) { _metadata = metadata; } @@ -130,7 +130,7 @@ public virtual string ContractName { get { - Debug.Assert(_contractName != null); + Debug.Assert(_contractName is not null); return _contractName; } @@ -160,7 +160,7 @@ public virtual string ContractName { get { - Debug.Assert(_metadata != null); + Debug.Assert(_metadata is not null); return _metadata; } @@ -201,7 +201,7 @@ public virtual Expression> Constraint { get { - if (_constraint != null) + if (_constraint is not null) { return _constraint; } @@ -263,7 +263,7 @@ public virtual bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition) { Requires.NotNull(exportDefinition, nameof(exportDefinition)); - if (_compiledConstraint == null) + if (_compiledConstraint is null) { _compiledConstraint = Constraint.Compile(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs index 3154a585f0db9a..8754e6c262b9c9 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs @@ -32,7 +32,7 @@ internal static IEnumerable GetCandidateContractNames(this ImportDefinit string contractName = import.ContractName; string? genericContractName = import.Metadata.GetValue(CompositionConstants.GenericContractMetadataName); int[]? importParametersOrder = import.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); - if (importParametersOrder != null) + if (importParametersOrder is not null) { int partArity = part.Metadata.GetValue(CompositionConstants.GenericPartArityMetadataName); if (partArity > 0) @@ -64,13 +64,13 @@ internal static bool IsImportDependentOnPart(this ImportDefinition import, Compo private static ImportDefinition TranslateImport(ImportDefinition import, ComposablePartDefinition part) { ContractBasedImportDefinition? contractBasedImport = import as ContractBasedImportDefinition; - if (contractBasedImport == null) + if (contractBasedImport is null) { return import; } int[]? importParametersOrder = contractBasedImport.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); - if (importParametersOrder == null) + if (importParametersOrder is null) { return import; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs index 7e5fd59a6cbb0c..7c8debfc88ebdc 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs @@ -30,7 +30,7 @@ public SerializableCompositionElement(string displayName, ICompositionElement? o [return: NotNullIfNotNull("element")] public static ICompositionElement? FromICompositionElement(ICompositionElement? element) { - if (element == null) + if (element is null) { return null; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs index 4d24c8f5328681..0a5025f5b3ec1c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs @@ -45,7 +45,7 @@ public Tuple GetExportLifetimeContextFromExport(Export export) } } - if (disposable != null) + if (disposable is not null) { disposeAction = () => disposable.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs index 9965579a538414..c872b28f41a8d0 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs @@ -15,7 +15,7 @@ internal sealed partial class ExportFactoryCreator public ExportFactoryCreator(Type exportFactoryType) { - if (exportFactoryType == null) + if (exportFactoryType is null) { throw new ArgumentNullException(nameof(exportFactoryType)); } @@ -26,7 +26,7 @@ public ExportFactoryCreator(Type exportFactoryType) public Func CreateStronglyTypedExportFactoryFactory(Type exportType, Type? metadataViewType) { MethodInfo genericMethod; - if (metadataViewType == null) + if (metadataViewType is null) { genericMethod = _createStronglyTypedExportFactoryOfT.MakeGenericMethod(exportType); } @@ -35,7 +35,7 @@ public Func CreateStronglyTypedExportFactoryFactory(Type exportT genericMethod = _createStronglyTypedExportFactoryOfTM.MakeGenericMethod(exportType, metadataViewType); } - if (genericMethod == null) + if (genericMethod is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs index bfd87de6789b32..a06d324e48ed5c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs @@ -17,12 +17,12 @@ internal class ExportingMember public ExportingMember(ExportDefinition definition, ReflectionMember member) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs index 907b838a8f70ff..cea4695c02f3ea 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs @@ -13,7 +13,7 @@ internal static class GenericServices { internal static IList GetPureGenericParameters(this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -38,7 +38,7 @@ internal static IList GetPureGenericParameters(this Type type) internal static int GetPureGenericArity(this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -97,7 +97,7 @@ public static T[] Reorder(T[] original, int[] genericParametersOrder) [return: NotNullIfNotNull("types")] public static IEnumerable? CreateTypeSpecializations(this Type[]? types, Type[] specializationTypes) { - if (types == null) + if (types is null) { return null; } @@ -146,7 +146,7 @@ public static bool CanSpecialize(Type? type, IEnumerable? constraints, Gen public static bool CanSpecialize(Type? type, IEnumerable? constraintTypes) { - if (constraintTypes == null) + if (constraintTypes is null) { return true; } @@ -155,7 +155,7 @@ public static bool CanSpecialize(Type? type, IEnumerable? constraintTypes) // a part of where T : struct is also handled here as T : ValueType foreach (Type constraintType in constraintTypes) { - if ((constraintType != null) && !constraintType.IsAssignableFrom(type)) + if ((constraintType is not null) && !constraintType.IsAssignableFrom(type)) { return false; } @@ -184,7 +184,7 @@ public static bool CanSpecialize(Type type, GenericParameterAttributes attribute if ((attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { // value types always have default constructors - if (!type.IsValueType && (type.GetConstructor(Type.EmptyTypes) == null)) + if (!type.IsValueType && (type.GetConstructor(Type.EmptyTypes) is null)) { return false; } @@ -201,7 +201,7 @@ public static bool CanSpecialize(Type type, GenericParameterAttributes attribute // Make sure that the type is not nullable // this is salways guaranteed in C#, but other languages may be different - if (Nullable.GetUnderlyingType(type) != null) + if (Nullable.GetUnderlyingType(type) is not null) { return false; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs index 9a12670095cb00..5e9c58c5b3d217 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs @@ -31,17 +31,17 @@ internal class GenericSpecializationPartCreationInfo : IReflectionPartCreationIn public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo, ReflectionComposablePartDefinition originalPart, Type[] specialization) { - if (originalPartCreationInfo == null) + if (originalPartCreationInfo is null) { throw new ArgumentNullException(nameof(originalPartCreationInfo)); } - if (originalPart == null) + if (originalPart is null) { throw new ArgumentNullException(nameof(originalPart)); } - if (specialization == null) + if (specialization is null) { throw new ArgumentNullException(nameof(specialization)); } @@ -80,11 +80,11 @@ public Lazy GetLazyPartType() public ConstructorInfo? GetConstructor() { - if (_constructor == null) + if (_constructor is null) { ConstructorInfo? genericConstuctor = _originalPartCreationInfo.GetConstructor(); ConstructorInfo? result = null; - if (genericConstuctor != null) + if (genericConstuctor is not null) { foreach (ConstructorInfo constructor in GetPartType().GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { @@ -99,7 +99,7 @@ public Lazy GetLazyPartType() Thread.MemoryBarrier(); lock (_lock) { - if (_constructor == null) + if (_constructor is null) { _constructor = result; } @@ -123,7 +123,7 @@ public Lazy GetLazyPartType() private MemberInfo[] GetAccessors(LazyMemberInfo originalLazyMember) { BuildTables(); - if (_membersTable == null) + if (_membersTable is null) { throw new ArgumentNullException(nameof(_membersTable)); } @@ -134,7 +134,7 @@ private MemberInfo[] GetAccessors(LazyMemberInfo originalLazyMember) private ParameterInfo GetParameter(Lazy originalParameter) { BuildTables(); - if (_parametersTable == null) + if (_parametersTable is null) { throw new ArgumentNullException(nameof(_parametersTable)); } @@ -144,7 +144,7 @@ private ParameterInfo GetParameter(Lazy originalParameter) private void BuildTables() { - if (_membersTable != null) + if (_membersTable is not null) { return; } @@ -155,12 +155,12 @@ private void BuildTables() List>? parameters = null; lock (_lock) { - if (_membersTable == null) + if (_membersTable is null) { members = _members; parameters = _parameters; - if (members == null) + if (members is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -175,7 +175,7 @@ private void BuildTables() lock (_lock) { - if (_membersTable == null) + if (_membersTable is null) { _membersTable = membersTable; _parametersTable = parametersTable; @@ -190,7 +190,7 @@ private void BuildTables() private Dictionary BuildMembersTable(List members) { - if (members == null) + if (members is null) { throw new ArgumentNullException(nameof(members)); } @@ -223,7 +223,7 @@ private Dictionary BuildMembersTable(List BuildMembersTable(List BuildMembersTable(List, ParameterInfo>? BuildParametersTable(List>? parameters) { - if (parameters != null) + if (parameters is not null) { Dictionary, ParameterInfo> parametersTable = new Dictionary, ParameterInfo>(); // GENTODO - error case @@ -283,7 +283,7 @@ private List PopulateImports(List members, Lis foreach (ImportDefinition originalImport in _originalPartCreationInfo.GetImports()) { ReflectionImportDefinition? reflectionImport = originalImport as ReflectionImportDefinition; - if (reflectionImport == null) + if (reflectionImport is null) { // we always ignore these continue; @@ -351,7 +351,7 @@ private ImportDefinition TranslateImport(ReflectionImportDefinition reflectionIm else { ReflectionParameterImportDefinition? parameterImport = reflectionImport as ReflectionParameterImportDefinition; - if (parameterImport == null) + if (parameterImport is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -400,7 +400,7 @@ private List PopulateExports(List members) foreach (ExportDefinition originalExport in _originalPartCreationInfo.GetExports()) { ReflectionMemberExportDefinition? reflectionExport = originalExport as ReflectionMemberExportDefinition; - if (reflectionExport == null) + if (reflectionExport is null) { // we always ignore these continue; @@ -436,7 +436,7 @@ public ExportDefinition TranslateExpot(ReflectionMemberExportDefinition reflecti private string Translate(string originalValue, int[]? genericParametersOrder) { - if (genericParametersOrder != null) + if (genericParametersOrder is not null) { string[] specializationIdentities = GenericServices.Reorder(_specializationIdentities, genericParametersOrder); return string.Format(CultureInfo.InvariantCulture, originalValue, specializationIdentities); @@ -455,7 +455,7 @@ private string Translate(string originalValue) private IDictionary TranslateImportMetadata(ContractBasedImportDefinition originalImport) { int[]? importParametersOrder = originalImport.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); - if (importParametersOrder != null) + if (importParametersOrder is not null) { Dictionary metadata = new Dictionary(originalImport.Metadata, StringComparers.MetadataKeyNames); @@ -488,7 +488,7 @@ private string Translate(string originalValue) private void PopulateImportsAndExports() { - if ((_exports == null) || (_imports == null)) + if ((_exports is null) || (_imports is null)) { List members = new List(); List> parameters = new List>(); @@ -500,7 +500,7 @@ private void PopulateImportsAndExports() lock (_lock) { - if ((_exports == null) || (_imports == null)) + if ((_exports is null) || (_imports is null)) { _members = members; if (parameters.Count > 0) @@ -574,17 +574,17 @@ public static bool CanSpecialize(IDictionary partMetadata, Type GenericParameterAttributes[]? genericParameterAttributes = partMetadata.GetValue(CompositionConstants.GenericParameterAttributesMetadataName); // if no constraints and attributes been specifed, anything can be created - if ((genericParameterConstraints == null) && (genericParameterAttributes == null)) + if ((genericParameterConstraints is null) && (genericParameterAttributes is null)) { return true; } - if ((genericParameterConstraints != null) && (genericParameterConstraints.Length != partArity)) + if ((genericParameterConstraints is not null) && (genericParameterConstraints.Length != partArity)) { return false; } - if ((genericParameterAttributes != null) && (genericParameterAttributes.Length != partArity)) + if ((genericParameterAttributes is not null) && (genericParameterAttributes.Length != partArity)) { return false; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs index 18edae8dc4f462..84533da08ffd67 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs @@ -34,7 +34,7 @@ private static Dictionary?> CastSingleValueCache public ImportType(Type type, ImportCardinality cardinality) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -86,7 +86,7 @@ public Func? CastExport private Type CheckForCollection(Type type) { ElementType = CollectionServices.GetEnumerableElementType(type); - if (ElementType != null) + if (ElementType is not null) { return ElementType; } @@ -95,7 +95,7 @@ private Type CheckForCollection(Type type) private static bool IsGenericDescendentOf(Type? type, Type baseGenericTypeDefinition) { - if (type == typeof(object) || type == null) + if (type == typeof(object) || type is null) { return false; } @@ -110,12 +110,12 @@ private static bool IsGenericDescendentOf(Type? type, Type baseGenericTypeDefini public static bool IsDescendentOf(Type type, Type baseType) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (baseType == null) + if (baseType is null) { throw new ArgumentNullException(nameof(baseType)); } @@ -157,7 +157,7 @@ private void Initialize(Type type) // we have found the cast function, which means, that we have found either Lazy of EF // in this case the contract is always argument[0] and the metadata view is always argument[1] - IsPartCreator = !IsLazyGenericType(genericType) && (genericType != null); + IsPartCreator = !IsLazyGenericType(genericType) && (genericType is not null); _contractType = arguments[0]; if (arguments.Length == 2) { @@ -192,7 +192,7 @@ private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Typ return true; } - if (genericType != null && IsDescendentOf(genericType, ExportFactoryOfTType)) + if (genericType is not null && IsDescendentOf(genericType, ExportFactoryOfTType)) { if (arguments.Length == 1) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs index b47301619caaec..402058cebf9dc5 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs @@ -14,7 +14,7 @@ internal abstract class ImportingItem protected ImportingItem(ContractBasedImportDefinition definition, ImportType importType) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } @@ -47,7 +47,7 @@ public ImportType ImportType private object CastExportsToCollectionImportType(Export[] exports) { - if (exports == null) + if (exports is null) { throw new ArgumentNullException(nameof(exports)); } @@ -70,7 +70,7 @@ private object CastExportsToCollectionImportType(Export[] exports) private object? CastExportsToSingleImportType(Export[] exports) { - if (exports == null) + if (exports is null) { throw new ArgumentNullException(nameof(exports)); } @@ -90,7 +90,7 @@ private object CastExportsToCollectionImportType(Export[] exports) private object? CastSingleExportToImportType(Type type, Export export) { - if (ImportType.CastExport != null) + if (ImportType.CastExport is not null) { return ImportType.CastExport(export); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs index b4ba138c577d8f..a61ffd9768b145 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs @@ -19,7 +19,7 @@ internal class ImportingMember : ImportingItem public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member, ImportType importType) : base(definition, importType) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -107,14 +107,14 @@ private void EnsureWritable() private void SetCollectionMemberValue(object? instance, IEnumerable values) { - if (values == null) + if (values is null) { throw new ArgumentNullException(nameof(values)); } ICollection? collection = null; Type? itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType); - if (itemType != null) + if (itemType is not null) { collection = GetNormalizedCollection(itemType, instance); } @@ -125,7 +125,7 @@ private void SetCollectionMemberValue(object? instance, IEnumerable values) private ICollection GetNormalizedCollection(Type itemType, object? instance) { - if (itemType == null) + if (itemType is null) { throw new ArgumentNullException(nameof(itemType)); } @@ -149,12 +149,12 @@ private ICollection GetNormalizedCollection(Type itemType, object? insta } } - if (collectionObject == null) + if (collectionObject is null) { ConstructorInfo? constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes); // If it contains a default public constructor create a new instance. - if (constructor != null) + if (constructor is not null) { try { @@ -175,7 +175,7 @@ private ICollection GetNormalizedCollection(Type itemType, object? insta } } - if (collectionObject == null) + if (collectionObject is null) { throw new ComposablePartException( SR.Format( @@ -193,7 +193,7 @@ private void EnsureCollectionIsWritable(ICollection? collection) try { - if (collection != null) + if (collection is not null) { isReadOnly = collection.IsReadOnly; } @@ -221,12 +221,12 @@ private void EnsureCollectionIsWritable(ICollection? collection) private void PopulateCollection(ICollection collection, IEnumerable values) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } - if (values == null) + if (values is null) { throw new ArgumentNullException(nameof(values)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs index 14124ff46f5cfa..1f336936276117 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs @@ -26,7 +26,7 @@ public LazyMemberInfo(MemberInfo member) { case MemberTypes.Property: PropertyInfo property = (PropertyInfo)member; - if (property == null) + if (property is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -75,7 +75,7 @@ public MemberTypes MemberType public MemberInfo[] GetAccessors() { - if ((_accessors == null) && (_accessorsCreator != null)) + if ((_accessors is null) && (_accessorsCreator is not null)) { MemberInfo[] accessors = _accessorsCreator.Invoke(); @@ -93,13 +93,13 @@ public MemberInfo[] GetAccessors() public override int GetHashCode() { - if (_accessorsCreator != null) + if (_accessorsCreator is not null) { return MemberType.GetHashCode() ^ _accessorsCreator.GetHashCode(); } else { - if (_accessors == null || _accessors[0] == null) + if (_accessors is null || _accessors[0] is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -118,13 +118,13 @@ public override bool Equals(object? obj) } // if any of the lazy memebers create accessors in a delay-loaded fashion, we simply compare the creators - if ((_accessorsCreator != null) || (that._accessorsCreator != null)) + if ((_accessorsCreator is not null) || (that._accessorsCreator is not null)) { return object.Equals(_accessorsCreator, that._accessorsCreator); } // we are dealing with explicitly passed accessors in both cases - if (_accessors == null || that._accessors == null) + if (_accessors is null || that._accessors is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -149,13 +149,13 @@ private static void EnsureSupportedMemberType(MemberTypes memberType, string arg private static bool AreAccessorsValid(MemberTypes memberType, MemberInfo[] accessors, out string errorMessage) { errorMessage = string.Empty; - if (accessors == null) + if (accessors is null) { errorMessage = SR.LazyMemberInfo_AccessorsNull; return false; } - if (accessors.All(accessor => accessor == null)) + if (accessors.All(accessor => accessor is null)) { errorMessage = SR.LazyMemberInfo_NoAccessors; return false; @@ -170,7 +170,7 @@ private static bool AreAccessorsValid(MemberTypes memberType, MemberInfo[] acces return false; } - if (accessors.Where(accessor => (accessor != null) && (accessor.MemberType != MemberTypes.Method)).Any()) + if (accessors.Where(accessor => (accessor is not null) && (accessor.MemberType != MemberTypes.Method)).Any()) { errorMessage = SR.LazyMemberinfo_InvalidPropertyAccessors_AccessorType; return false; @@ -185,7 +185,7 @@ private static bool AreAccessorsValid(MemberTypes memberType, MemberInfo[] acces return false; } - if (accessors.Where(accessor => (accessor != null) && (accessor.MemberType != MemberTypes.Method)).Any()) + if (accessors.Where(accessor => (accessor is not null) && (accessor.MemberType != MemberTypes.Method)).Any()) { errorMessage = SR.LazyMemberinfo_InvalidEventAccessors_AccessorType; return false; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs index 6896cba737dbd1..f42a13ad0f5919 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs @@ -30,7 +30,7 @@ public override string ContractName { get { - if (_metadata == null) + if (_metadata is null) { var metadata = new Dictionary(_productDefinition.Metadata); metadata[CompositionConstants.ExportTypeIdentityMetadataName] = CompositionConstants.PartCreatorTypeIdentity; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs index 411975988ebef2..ba1415453861f7 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs @@ -19,7 +19,7 @@ public PartCreatorMemberImportDefinition( : base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, false, productImportDefinition.RequiredCreationPolicy, MetadataServices.EmptyMetadata, origin) { - if (productImportDefinition == null) + if (productImportDefinition is null) { throw new ArgumentNullException(nameof(productImportDefinition)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs index 88f5352545dfba..35d4aceeb3d534 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs @@ -20,7 +20,7 @@ public PartCreatorParameterImportDefinition( : base(importingLazyParameter, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, CreationPolicy.Any, MetadataServices.EmptyMetadata, origin) { - if (productImportDefinition == null) + if (productImportDefinition is null) { throw new ArgumentNullException(nameof(productImportDefinition)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs index e42af67590f428..de6afd228b7efd 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs @@ -62,12 +62,12 @@ protected virtual void ReleaseInstanceIfNecessary(object? instance) get { var value = _importValues; - if (value == null) + if (value is null) { lock (_lock) { value = _importValues; - if (value == null) + if (value is null) { value = new Dictionary(); _importValues = value; @@ -83,11 +83,11 @@ private Dictionary ImportsCache get { var value = _importsCache; - if (value == null) + if (value is null) { lock (_lock) { - if (value == null) + if (value is null) { value = new Dictionary(); _importsCache = value; @@ -173,7 +173,7 @@ ICompositionElement ICompositionElement.Origin lock (_lock) { member = GetExportingMemberFromDefinition(definition); - if (member == null) + if (member is null) { throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart(nameof(definition)); } @@ -190,7 +190,7 @@ public override void SetImport(ImportDefinition definition, IEnumerable Requires.NotNull(exports, nameof(exports)); ImportingItem? item = GetImportingItemFromDefinition(definition); - if (item == null) + if (item is null) { throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart(nameof(definition)); } @@ -252,7 +252,7 @@ private void SetImport(ImportingItem item, Export[] exports) { var cachedInstance = _cachedInstance; - if (cachedInstance != null) + if (cachedInstance is not null) { return cachedInstance; } @@ -270,7 +270,7 @@ private void SetImport(ImportingItem item, Export[] exports) } constructor = Definition.GetConstructor(); - if (constructor == null) + if (constructor is null) { throw new ComposablePartException( SR.Format( @@ -287,11 +287,11 @@ private void SetImport(ImportingItem item, Export[] exports) SetPrerequisiteImports(); // set the created instance - if (_cachedInstance == null) + if (_cachedInstance is null) { lock (_lock) { - if (_cachedInstance == null) + if (_cachedInstance is null) { _cachedInstance = createdInstance; createdInstance = null; @@ -300,7 +300,7 @@ private void SetImport(ImportingItem item, Export[] exports) } // if the instance has been already set - if (createdInstance != null) + if (createdInstance is not null) { ReleaseInstanceIfNecessary(createdInstance); } @@ -350,7 +350,7 @@ private bool RequiresActivation() return ExportDefinitions.Any(definition => { ExportingMember? member = GetExportingMemberFromDefinition(definition); - Debug.Assert(member != null); + Debug.Assert(member is not null); return member.RequiresInstance; }); } @@ -368,7 +368,7 @@ private void EnsureGettable() // Make sure all pre-req imports have been set foreach (ImportDefinition definition in ImportDefinitions.Where(definition => definition.IsPrerequisite)) { - if (_importValues == null || !ImportValues.ContainsKey(definition)) + if (_importValues is null || !ImportValues.ContainsKey(definition)) { throw new InvalidOperationException(SR.Format( SR.InvalidOperation_GetExportedValueBeforePrereqImportSet, @@ -429,7 +429,7 @@ private object CreateInstance(ConstructorInfo constructor, object?[] arguments) exception = ex.InnerException; } - if (exception != null) + if (exception is not null) { throw new ComposablePartException( SR.Format( @@ -475,7 +475,7 @@ private void UseImportedValues(IEnumerable foreach (var definition in definitions) { ImportingItem? import = GetImportingItemFromDefinition(definition); - Debug.Assert(import != null); + Debug.Assert(import is not null); if (!TryGetImportValue(definition, out object? value)) { @@ -510,7 +510,7 @@ private bool TryGetImportValue(ImportDefinition definition, out object? value) { lock (_lock) { - if (_importValues != null && ImportValues.TryGetValue(definition, out value)) + if (_importValues is not null && ImportValues.TryGetValue(definition, out value)) { ImportValues.Remove(definition); return true; @@ -537,7 +537,7 @@ private void NotifyImportSatisfied() _invokeImportsSatisfied = false; } - if (notify != null) + if (notify is not null) { try { @@ -560,20 +560,20 @@ private void NotifyImportSatisfied() private ExportingMember? GetExportingMemberFromDefinition(ExportDefinition definition) { ReflectionMemberExportDefinition? reflectionExport = definition as ReflectionMemberExportDefinition; - if (reflectionExport == null) + if (reflectionExport is null) { return null; } int exportIndex = reflectionExport.GetIndex(); - if (_exportsCache == null) + if (_exportsCache is null) { _exportsCache = new Dictionary(); } if (!_exportsCache.TryGetValue(exportIndex, out ExportingMember? result)) { result = GetExportingMember(definition); - if (result != null) + if (result is not null) { _exportsCache[exportIndex] = result; } @@ -587,7 +587,7 @@ private void NotifyImportSatisfied() if (!ImportsCache.TryGetValue(definition, out ImportingItem? result)) { result = GetImportingItem(definition); - if (result != null) + if (result is not null) { ImportsCache[definition] = result; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs index f8e027358a2454..7ea3c2c6c0cf26 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs @@ -23,7 +23,7 @@ internal class ReflectionComposablePartDefinition : ComposablePartDefinition, IC public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo) { - if (creationInfo == null) + if (creationInfo is null) { throw new ArgumentNullException(nameof(creationInfo)); } @@ -42,12 +42,12 @@ public Lazy GetLazyPartType() public ConstructorInfo? GetConstructor() { - if (_constructor == null) + if (_constructor is null) { ConstructorInfo? constructor = _creationInfo.GetConstructor(); lock (_lock) { - if (_constructor == null) + if (_constructor is null) { _constructor = constructor; } @@ -61,12 +61,12 @@ private ExportDefinition[] ExportDefinitionsInternal { get { - if (_exports == null) + if (_exports is null) { ExportDefinition[] exports = _creationInfo.GetExports().ToArray(); lock (_lock) { - if (_exports == null) + if (_exports is null) { _exports = exports; } @@ -88,12 +88,12 @@ public override IEnumerable ImportDefinitions { get { - if (_imports == null) + if (_imports is null) { ImportDefinition[] imports = _creationInfo.GetImports().ToArray(); lock (_lock) { - if (_imports == null) + if (_imports is null) { _imports = imports; } @@ -107,12 +107,12 @@ public override IEnumerable ImportDefinitions { get { - if (_metadata == null) + if (_metadata is null) { IDictionary metadata = _creationInfo.GetMetadata().AsReadOnly(); lock (_lock) { - if (_metadata == null) + if (_metadata is null) { _metadata = metadata; } @@ -163,7 +163,7 @@ internal override bool TryGetExports(ImportDefinition definition, out Tuple 0) ? definition.Metadata.GetValue>(CompositionConstants.GenericParametersMetadataName) : null; // if and only if generic parameters have been supplied can we attempt to "close" the generic - if (genericParameters != null) + if (genericParameters is not null) { // we only understand types if (TryGetGenericTypeParameters(genericParameters, out Type?[]? genericTypeParameters)) @@ -177,9 +177,9 @@ internal override bool TryGetExports(ImportDefinition definition, out Tuple(this, export); } else { - if (multipleExports == null) + if (multipleExports is null) { multipleExports = new List>(); multipleExports.Add(singleExport); @@ -271,7 +271,7 @@ private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple GetCandidateParameters(Type[] genericParameters) foreach (ExportDefinition export in ExportDefinitionsInternal) { var genericParametersOrder = export.Metadata.GetValue(CompositionConstants.GenericExportParametersOrderMetadataName); - if ((genericParametersOrder != null) && (genericParametersOrder.Length == genericParameters.Length)) + if ((genericParametersOrder is not null) && (genericParametersOrder.Length == genericParameters.Length)) { yield return GenericServices.Reorder(genericParameters, genericParametersOrder); } @@ -299,14 +299,14 @@ private IEnumerable GetCandidateParameters(Type[] genericParameters) private static bool TryGetGenericTypeParameters(IEnumerable genericParameters, [NotNullWhen(true)] out Type?[]? genericTypeParameters) { genericTypeParameters = genericParameters as Type[]; - if (genericTypeParameters == null) + if (genericTypeParameters is null) { object[] genericParametersAsArray = genericParameters.AsArray(); genericTypeParameters = new Type[genericParametersAsArray.Length]; for (int i = 0; i < genericParametersAsArray.Length; i++) { genericTypeParameters[i] = genericParametersAsArray[i] as Type; - if (genericTypeParameters[i] == null) + if (genericTypeParameters[i] is null) { return false; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs index 144603f65ecf6a..8f1bc9f12ce2ce 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs @@ -43,7 +43,7 @@ public static ReflectionMember ToReflectionMember(this LazyMemberInfo lazyMember public static LazyMemberInfo ToLazyMember(this MemberInfo member) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -51,7 +51,7 @@ public static LazyMemberInfo ToLazyMember(this MemberInfo member) if (member.MemberType == MemberTypes.Property) { PropertyInfo? property = member as PropertyInfo; - if (property == null) + if (property is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -73,7 +73,7 @@ public static ReflectionWritableMember ToReflectionWriteableMember(this LazyMemb } ReflectionWritableMember? reflectionMember = lazyMember.ToReflectionMember() as ReflectionWritableMember; - if (reflectionMember == null) + if (reflectionMember is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -83,7 +83,7 @@ public static ReflectionWritableMember ToReflectionWriteableMember(this LazyMemb public static ReflectionProperty ToReflectionProperty(this PropertyInfo property) { - if (property == null) + if (property is null) { throw new ArgumentNullException(nameof(property)); } @@ -93,7 +93,7 @@ public static ReflectionProperty ToReflectionProperty(this PropertyInfo property public static ReflectionProperty CreateReflectionProperty(MethodInfo getMethod, MethodInfo setMethod) { - if (getMethod == null && setMethod == null) + if (getMethod is null && setMethod is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -103,7 +103,7 @@ public static ReflectionProperty CreateReflectionProperty(MethodInfo getMethod, public static ReflectionParameter ToReflectionParameter(this ParameterInfo parameter) { - if (parameter == null) + if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } @@ -113,7 +113,7 @@ public static ReflectionParameter ToReflectionParameter(this ParameterInfo param public static ReflectionMethod ToReflectionMethod(this MethodInfo method) { - if (method == null) + if (method is null) { throw new ArgumentNullException(nameof(method)); } @@ -123,7 +123,7 @@ public static ReflectionMethod ToReflectionMethod(this MethodInfo method) public static ReflectionField ToReflectionField(this FieldInfo field) { - if (field == null) + if (field is null) { throw new ArgumentNullException(nameof(field)); } @@ -133,7 +133,7 @@ public static ReflectionField ToReflectionField(this FieldInfo field) public static ReflectionType ToReflectionType(this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -143,7 +143,7 @@ public static ReflectionType ToReflectionType(this Type type) public static ReflectionWritableMember ToReflectionWritableMember(this MemberInfo member) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs index 8a612922013869..6e5d0ee4324c6c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs @@ -12,7 +12,7 @@ internal class ReflectionField : ReflectionWritableMember public ReflectionField(FieldInfo field) { - if (field == null) + if (field is null) { throw new ArgumentNullException(nameof(field)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs index 3fd081422962a6..488a94c8ffa2e5 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs @@ -16,7 +16,7 @@ internal class ReflectionMemberExportDefinition : ExportDefinition, IComposition public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement? origin) { - if (exportDefinition == null) + if (exportDefinition is null) { throw new ArgumentNullException(nameof(exportDefinition)); } @@ -40,7 +40,7 @@ public LazyMemberInfo ExportingLazyMember { get { - if (_metadata == null) + if (_metadata is null) { _metadata = _exportDefinition.Metadata.AsReadOnly(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs index f9e437f05a4ab9..9bef3f8bcc0bbb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs @@ -24,7 +24,7 @@ public ReflectionMemberImportDefinition( ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin) { - if (contractName == null) + if (contractName is null) { throw new ArgumentNullException(nameof(contractName)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs index d27d7d4f289709..956d0dbd5dd89f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs @@ -12,7 +12,7 @@ internal partial class ReflectionMethod : ReflectionMember public ReflectionMethod(MethodInfo method) { - if (method == null) + if (method is null) { throw new ArgumentNullException(nameof(method)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs index c7a47b3f65fc02..97078684034213 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs @@ -19,7 +19,7 @@ public static Lazy GetPartType(ComposablePartDefinition partDefinition) Requires.NotNull(partDefinition, nameof(partDefinition)); ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; - if (reflectionPartDefinition == null) + if (reflectionPartDefinition is null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); } @@ -32,7 +32,7 @@ public static bool IsDisposalRequired(ComposablePartDefinition partDefinition) Requires.NotNull(partDefinition, nameof(partDefinition)); ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; - if (reflectionPartDefinition == null) + if (reflectionPartDefinition is null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); } @@ -45,7 +45,7 @@ public static LazyMemberInfo GetExportingMember(ExportDefinition exportDefinitio Requires.NotNull(exportDefinition, nameof(exportDefinition)); ReflectionMemberExportDefinition? reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition; - if (reflectionExportDefinition == null) + if (reflectionExportDefinition is null) { throw new ArgumentException( SR.Format(SR.ReflectionModel_InvalidExportDefinition, exportDefinition.GetType()), @@ -60,7 +60,7 @@ public static LazyMemberInfo GetImportingMember(ImportDefinition importDefinitio Requires.NotNull(importDefinition, nameof(importDefinition)); ReflectionMemberImportDefinition? reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition; - if (reflectionMemberImportDefinition == null) + if (reflectionMemberImportDefinition is null) { throw new ArgumentException( SR.Format(SR.ReflectionModel_InvalidMemberImportDefinition, importDefinition.GetType()), @@ -75,14 +75,14 @@ public static Lazy GetImportingParameter(ImportDefinition importD Requires.NotNull(importDefinition, nameof(importDefinition)); ReflectionParameterImportDefinition? reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition; - if (reflectionParameterImportDefinition == null) + if (reflectionParameterImportDefinition is null) { throw new ArgumentException( SR.Format(SR.ReflectionModel_InvalidParameterImportDefinition, importDefinition.GetType()), nameof(importDefinition)); } - Debug.Assert(reflectionParameterImportDefinition.ImportingLazyParameter != null); + Debug.Assert(reflectionParameterImportDefinition.ImportingLazyParameter is not null); return reflectionParameterImportDefinition.ImportingLazyParameter; } @@ -91,7 +91,7 @@ public static bool IsImportingParameter(ImportDefinition importDefinition) Requires.NotNull(importDefinition, nameof(importDefinition)); ReflectionImportDefinition? reflectionImportDefinition = importDefinition as ReflectionImportDefinition; - if (reflectionImportDefinition == null) + if (reflectionImportDefinition is null) { throw new ArgumentException( SR.Format(SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()), @@ -113,7 +113,7 @@ public static ContractBasedImportDefinition GetExportFactoryProductImportDefinit Requires.NotNull(importDefinition, nameof(importDefinition)); IPartCreatorImportDefinition? partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition; - if (partCreatorImportDefinition == null) + if (partCreatorImportDefinition is null) { throw new ArgumentException( SR.Format(SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()), @@ -305,7 +305,7 @@ public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDef specialization = null; ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; - if (reflectionPartDefinition == null) + if (reflectionPartDefinition is null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); } @@ -332,7 +332,7 @@ public ReflectionPartCreationInfo( Lazy>? metadata, ICompositionElement? origin) { - if (partType == null) + if (partType is null) { throw new ArgumentNullException(nameof(partType)); } @@ -357,7 +357,7 @@ public Lazy GetLazyPartType() public ConstructorInfo? GetConstructor() { - if (_constructor == null) + if (_constructor is null) { ConstructorInfo[]? constructors = null; constructors = GetImports() @@ -397,19 +397,19 @@ public bool IsIdentityComparison public IDictionary? GetMetadata() { - return (_metadata != null) ? _metadata.Value : null; + return (_metadata is not null) ? _metadata.Value : null; } public IEnumerable GetExports() { - if (_exports == null) + if (_exports is null) { yield break; } IEnumerable exports = _exports.Value; - if (exports == null) + if (exports is null) { yield break; } @@ -417,7 +417,7 @@ public IEnumerable GetExports() foreach (ExportDefinition export in exports) { ReflectionMemberExportDefinition? reflectionExport = export as ReflectionMemberExportDefinition; - if (reflectionExport == null) + if (reflectionExport is null) { throw new InvalidOperationException( SR.Format(SR.ReflectionModel_InvalidExportDefinition, export.GetType())); @@ -428,14 +428,14 @@ public IEnumerable GetExports() public IEnumerable GetImports() { - if (_imports == null) + if (_imports is null) { yield break; } IEnumerable imports = _imports.Value; - if (imports == null) + if (imports is null) { yield break; } @@ -443,7 +443,7 @@ public IEnumerable GetImports() foreach (ImportDefinition import in imports) { ReflectionImportDefinition? reflectionImport = import as ReflectionImportDefinition; - if (reflectionImport == null) + if (reflectionImport is null) { throw new InvalidOperationException( SR.Format(SR.ReflectionModel_InvalidMemberImportDefinition, import.GetType())); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs index 69ef96e5dd66e2..3599f51fb57461 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs @@ -13,7 +13,7 @@ internal class ReflectionParameter : ReflectionItem public ReflectionParameter(ParameterInfo parameter) { - if (parameter == null) + if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs index 5808012f63991b..0dc87301bb4984 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs @@ -24,7 +24,7 @@ public ReflectionParameterImportDefinition( ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, metadata, origin) { - if (importingLazyParameter == null) + if (importingLazyParameter is null) { throw new ArgumentNullException(nameof(importingLazyParameter)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs index 78e4f478735922..4b221796845162 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs @@ -21,7 +21,7 @@ internal class ReflectionProperty : ReflectionWritableMember public ReflectionProperty(MethodInfo? getMethod, MethodInfo? setMethod) { - if (getMethod == null && setMethod == null) + if (getMethod is null && setMethod is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -37,12 +37,12 @@ public override MemberInfo UnderlyingMember public override bool CanRead { - get { return UnderlyingGetMethod != null; } + get { return UnderlyingGetMethod is not null; } } public override bool CanWrite { - get { return UnderlyingSetMethod != null; } + get { return UnderlyingSetMethod is not null; } } public MethodInfo? UnderlyingGetMethod @@ -93,7 +93,7 @@ public override Type ReturnType { get { - if (UnderlyingGetMethod != null) + if (UnderlyingGetMethod is not null) { return UnderlyingGetMethod.ReturnType; } @@ -115,7 +115,7 @@ public override ReflectionItemType ItemType public override object? GetValue(object? instance) { - if (_getMethod == null) + if (_getMethod is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -125,7 +125,7 @@ public override ReflectionItemType ItemType public override void SetValue(object? instance, object? value) { - if (_setMethod == null) + if (_setMethod is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs index aa1c154a992997..59174e8c27475a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs @@ -11,7 +11,7 @@ internal class ReflectionType : ReflectionMember public ReflectionType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs b/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs index 1bdc9a906861cb..4db8060acc0acb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs @@ -14,7 +14,7 @@ internal static class CompositionTrace { internal static void PartDefinitionResurrected(ComposablePartDefinition definition) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } @@ -29,12 +29,12 @@ internal static void PartDefinitionResurrected(ComposablePartDefinition definiti internal static void PartDefinitionRejected(ComposablePartDefinition definition, ChangeRejectedException exception) { - if (definition == null) + if (definition is null) { throw new ArgumentNullException(nameof(definition)); } - if (exception == null) + if (exception is null) { throw new ArgumentNullException(nameof(exception)); } @@ -51,17 +51,17 @@ internal static void PartDefinitionRejected(ComposablePartDefinition definition, internal static void AssemblyLoadFailed(DirectoryCatalog catalog, string fileName, Exception exception) { - if (catalog == null) + if (catalog is null) { throw new ArgumentNullException(nameof(catalog)); } - if (exception == null) + if (exception is null) { throw new ArgumentNullException(nameof(exception)); } - if (fileName == null) + if (fileName is null) { throw new ArgumentNullException(nameof(fileName)); } @@ -83,7 +83,7 @@ internal static void AssemblyLoadFailed(DirectoryCatalog catalog, string fileNam internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -98,12 +98,12 @@ internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type) internal static void DefinitionMismatchedExportArity(Type type, MemberInfo member) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -118,7 +118,7 @@ internal static void DefinitionMismatchedExportArity(Type type, MemberInfo membe internal static void DefinitionContainsNoExports(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -133,7 +133,7 @@ internal static void DefinitionContainsNoExports(Type type) internal static void MemberMarkedWithMultipleImportAndImportMany(ReflectionItem item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } diff --git a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncCompletedEvent.cs b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncCompletedEvent.cs index 70ee4d6d308289..6ac95f698f33b9 100644 --- a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncCompletedEvent.cs +++ b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncCompletedEvent.cs @@ -18,7 +18,7 @@ public AsyncCompletedEventArgs(Exception? error, bool cancelled, object? userSta protected void RaiseExceptionIfNecessary() { - if (Error != null) + if (Error is not null) { throw new TargetInvocationException(SR.Async_ExceptionOccurred, Error); } diff --git a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs index 8c90014be5d255..1088263f1a2539 100644 --- a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs +++ b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs @@ -27,7 +27,7 @@ private AsyncOperation(object? userSuppliedState, SynchronizationContext syncCon /// ~AsyncOperation() { - if (!_alreadyCompleted && _syncContext != null) + if (!_alreadyCompleted && _syncContext is not null) { _syncContext.OperationCompleted(); } @@ -98,7 +98,7 @@ private void VerifyNotCompleted() private void VerifyDelegateNotNull(SendOrPostCallback d) { - if (d == null) + if (d is null) { throw new ArgumentNullException(nameof(d), SR.Async_NullDelegate); } diff --git a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperationManager.cs b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperationManager.cs index fe032b6fdfffd6..1d0d52a3d54a96 100644 --- a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperationManager.cs +++ b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperationManager.cs @@ -19,7 +19,7 @@ public static SynchronizationContext SynchronizationContext { get { - if (SynchronizationContext.Current == null) + if (SynchronizationContext.Current is null) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); } diff --git a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/BackgroundWorker.cs b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/BackgroundWorker.cs index 552ef1de2523db..a966824f905237 100644 --- a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/BackgroundWorker.cs +++ b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/BackgroundWorker.cs @@ -99,7 +99,7 @@ public void ReportProgress(int percentProgress, object? userState) ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState); - if (_asyncOperation != null) + if (_asyncOperation is not null) { _asyncOperation.Post(_progressReporter, args); } @@ -164,7 +164,7 @@ public bool WorkerSupportsCancellation private void WorkerThreadStart(object? argument) { - Debug.Assert(_asyncOperation != null, "_asyncOperation not initialized"); + Debug.Assert(_asyncOperation is not null, "_asyncOperation not initialized"); object? workerResult = null; Exception? error = null; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs b/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs index 9b98716a366c3e..1aad81b3f67c55 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs @@ -36,7 +36,7 @@ public override PropertyDescriptorCollection GetProperties() public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptorCollection properties = new PropertyDescriptorCollection(null); - if (attributes == null) + if (attributes is null) { if (typeof(T) == typeof(XElement)) { @@ -88,12 +88,12 @@ public override bool SupportsChangeEvents public override void AddValueChanged(object component, EventHandler handler) { - bool hasValueChangedHandler = GetValueChangedHandler(component) != null; + bool hasValueChangedHandler = GetValueChangedHandler(component) is not null; base.AddValueChanged(component, handler); if (hasValueChangedHandler) return; T c = component as T; - if (c != null && GetValueChangedHandler(component) != null) + if (c is not null && GetValueChangedHandler(component) is not null) { c.Changing += new EventHandler(OnChanging); c.Changed += new EventHandler(OnChanged); @@ -109,7 +109,7 @@ public override void RemoveValueChanged(object component, EventHandler handler) { base.RemoveValueChanged(component, handler); T c = component as T; - if (c != null && GetValueChangedHandler(component) == null) + if (c is not null && GetValueChangedHandler(component) is null) { c.Changing -= new EventHandler(OnChanging); c.Changed -= new EventHandler(OnChanged); @@ -154,20 +154,20 @@ public override object GetValue(object component) protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Add: XAttribute a = sender as XAttribute; - if (a != null && _value.element == a.Parent && _value.name == a.Name) + if (a is not null && _value.element == a.Parent && _value.name == a.Name) { OnValueChanged(_value.element, EventArgs.Empty); } break; case XObjectChange.Remove: a = sender as XAttribute; - if (a != null && _changeState == a) + if (a is not null && _changeState == a) { _changeState = null; OnValueChanged(_value.element, EventArgs.Empty); @@ -178,13 +178,13 @@ protected override void OnChanged(object sender, XObjectChangeEventArgs args) protected override void OnChanging(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Remove: XAttribute a = sender as XAttribute; - _changeState = a != null && _value.element == a.Parent && _value.name == a.Name ? a : null; + _changeState = a is not null && _value.element == a.Parent && _value.name == a.Name ? a : null; break; } } @@ -201,26 +201,26 @@ public XElementDescendantsPropertyDescriptor() : base("Descendants") public override object GetValue(object component) { - return _value = new XDeferredAxis((e, n) => n != null ? e.Descendants(n) : e.Descendants(), component as XElement, null); + return _value = new XDeferredAxis((e, n) => n is not null ? e.Descendants(n) : e.Descendants(), component as XElement, null); } protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Add: case XObjectChange.Remove: XElement e = sender as XElement; - if (e != null && (_value.name == e.Name || _value.name == null)) + if (e is not null && (_value.name == e.Name || _value.name is null)) { OnValueChanged(_value.element, EventArgs.Empty); } break; case XObjectChange.Name: e = sender as XElement; - if (e != null && _value.element != e && _value.name != null && (_value.name == e.Name || _value.name == _changeState)) + if (e is not null && _value.element != e && _value.name is not null && (_value.name == e.Name || _value.name == _changeState)) { _changeState = null; OnValueChanged(_value.element, EventArgs.Empty); @@ -231,13 +231,13 @@ protected override void OnChanged(object sender, XObjectChangeEventArgs args) protected override void OnChanging(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Name: XElement e = sender as XElement; - _changeState = e != null ? e.Name : null; + _changeState = e is not null ? e.Name : null; break; } } @@ -259,20 +259,20 @@ public override object GetValue(object component) protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Add: XElement e = sender as XElement; - if (e != null && _value.element == e.Parent && _value.name == e.Name && _value.element.Element(_value.name) == e) + if (e is not null && _value.element == e.Parent && _value.name == e.Name && _value.element.Element(_value.name) == e) { OnValueChanged(_value.element, EventArgs.Empty); } break; case XObjectChange.Remove: e = sender as XElement; - if (e != null && _changeState == e) + if (e is not null && _changeState == e) { _changeState = null; OnValueChanged(_value.element, EventArgs.Empty); @@ -280,7 +280,7 @@ protected override void OnChanged(object sender, XObjectChangeEventArgs args) break; case XObjectChange.Name: e = sender as XElement; - if (e != null) + if (e is not null) { if (_value.element == e.Parent && _value.name == e.Name && _value.element.Element(_value.name) == e) { @@ -298,14 +298,14 @@ protected override void OnChanged(object sender, XObjectChangeEventArgs args) protected override void OnChanging(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Remove: case XObjectChange.Name: XElement e = sender as XElement; - _changeState = e != null && _value.element == e.Parent && _value.name == e.Name && _value.element.Element(_value.name) == e ? e : null; + _changeState = e is not null && _value.element == e.Parent && _value.name == e.Name && _value.element.Element(_value.name) == e ? e : null; break; } } @@ -322,25 +322,25 @@ public XElementElementsPropertyDescriptor() : base("Elements") public override object GetValue(object component) { - return _value = new XDeferredAxis((e, n) => n != null ? e.Elements(n) : e.Elements(), component as XElement, null); + return _value = new XDeferredAxis((e, n) => n is not null ? e.Elements(n) : e.Elements(), component as XElement, null); } protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Add: XElement e = sender as XElement; - if (e != null && _value.element == e.Parent && (_value.name == e.Name || _value.name == null)) + if (e is not null && _value.element == e.Parent && (_value.name == e.Name || _value.name is null)) { OnValueChanged(_value.element, EventArgs.Empty); } break; case XObjectChange.Remove: e = sender as XElement; - if (e != null && _value.element == (_changeState as XContainer) && (_value.name == e.Name || _value.name == null)) + if (e is not null && _value.element == (_changeState as XContainer) && (_value.name == e.Name || _value.name is null)) { _changeState = null; OnValueChanged(_value.element, EventArgs.Empty); @@ -348,7 +348,7 @@ protected override void OnChanged(object sender, XObjectChangeEventArgs args) break; case XObjectChange.Name: e = sender as XElement; - if (e != null && _value.element == e.Parent && _value.name != null && (_value.name == e.Name || _value.name == (_changeState as XName))) + if (e is not null && _value.element == e.Parent && _value.name is not null && (_value.name == e.Name || _value.name == (_changeState as XName))) { _changeState = null; OnValueChanged(_value.element, EventArgs.Empty); @@ -359,17 +359,17 @@ protected override void OnChanged(object sender, XObjectChangeEventArgs args) protected override void OnChanging(object sender, XObjectChangeEventArgs args) { - if (_value == null) + if (_value is null) return; switch (args.ObjectChange) { case XObjectChange.Remove: XElement e = sender as XElement; - _changeState = e != null ? e.Parent : null; + _changeState = e is not null ? e.Parent : null; break; case XObjectChange.Name: e = sender as XElement; - _changeState = e != null ? e.Name : null; + _changeState = e is not null ? e.Name : null; break; } } @@ -391,7 +391,7 @@ public override bool IsReadOnly public override object GetValue(object component) { _element = component as XElement; - if (_element == null) + if (_element is null) return string.Empty; return _element.Value; } @@ -399,14 +399,14 @@ public override object GetValue(object component) public override void SetValue(object component, object value) { _element = component as XElement; - if (_element == null) + if (_element is null) return; _element.Value = value as string; } protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_element == null) + if (_element is null) return; switch (args.ObjectChange) { @@ -438,14 +438,14 @@ public XElementXmlPropertyDescriptor() : base("Xml") public override object GetValue(object component) { _element = component as XElement; - if (_element == null) + if (_element is null) return string.Empty; return _element.ToString(SaveOptions.DisableFormatting); } protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_element == null) + if (_element is null) return; OnValueChanged(_element, EventArgs.Empty); } @@ -467,7 +467,7 @@ public override bool IsReadOnly public override object GetValue(object component) { _attribute = component as XAttribute; - if (_attribute == null) + if (_attribute is null) return string.Empty; return _attribute.Value; } @@ -475,14 +475,14 @@ public override object GetValue(object component) public override void SetValue(object component, object value) { _attribute = component as XAttribute; - if (_attribute == null) + if (_attribute is null) return; _attribute.Value = value as string; } protected override void OnChanged(object sender, XObjectChangeEventArgs args) { - if (_attribute == null) + if (_attribute is null) return; if (args.ObjectChange == XObjectChange.Value) { @@ -499,9 +499,9 @@ internal class XDeferredAxis : IEnumerable, IEnumerable where T : XObject public XDeferredAxis(Func> func, XElement element, XName name) { - if (func == null) + if (func is null) throw new ArgumentNullException(nameof(func)); - if (element == null) + if (element is null) throw new ArgumentNullException(nameof(element)); _func = func; this.element = element; @@ -522,9 +522,9 @@ public IEnumerable this[string expandedName] { get { - if (expandedName == null) + if (expandedName is null) throw new ArgumentNullException(nameof(expandedName)); - if (name == null) + if (name is null) { name = expandedName; } @@ -545,9 +545,9 @@ internal class XDeferredSingleton where T : XObject public XDeferredSingleton(Func func, XElement element, XName name) { - if (func == null) + if (func is null) throw new ArgumentNullException(nameof(func)); - if (element == null) + if (element is null) throw new ArgumentNullException(nameof(element)); _func = func; this.element = element; @@ -558,9 +558,9 @@ public T this[string expandedName] { get { - if (expandedName == null) + if (expandedName is null) throw new ArgumentNullException(nameof(expandedName)); - if (name == null) + if (name is null) { name = expandedName; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs index d592d19730531a..953fcc67fdaaa2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs @@ -133,7 +133,7 @@ public override bool Equals(object obj) if (obj is AmbientValueAttribute other) { - return Value != null ? Value.Equals(other.Value) : other.Value == null; + return Value is not null ? Value.Equals(other.Value) : other.Value is null; } return false; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ArrayConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ArrayConverter.cs index 0405be41d76d7e..d8405a166a6b92 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ArrayConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ArrayConverter.cs @@ -29,7 +29,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { - if (value == null) + if (value is null) { return null; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs index 49b1c4f9d5127b..a866596b1b0883 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs @@ -44,7 +44,7 @@ public AttributeCollection(params Attribute[] attributes) for (int idx = 0; idx < _attributes.Length; idx++) { - if (_attributes[idx] == null) + if (_attributes[idx] is null) { throw new ArgumentNullException(nameof(attributes)); } @@ -60,12 +60,12 @@ protected AttributeCollection() : this(Array.Empty()) /// public static AttributeCollection FromExisting(AttributeCollection existing, params Attribute[] newAttributes) { - if (existing == null) + if (existing is null) { throw new ArgumentNullException(nameof(existing)); } - if (newAttributes == null) + if (newAttributes is null) { newAttributes = Array.Empty(); } @@ -76,7 +76,7 @@ public static AttributeCollection FromExisting(AttributeCollection existing, par for (int idx = 0; idx < newAttributes.Length; idx++) { - if (newAttributes[idx] == null) + if (newAttributes[idx] is null) { throw new ArgumentNullException(nameof(newAttributes)); } @@ -150,7 +150,7 @@ public virtual Attribute this[Type attributeType] // a relatively expensive call and we try to avoid it // since we rarely encounter derived attribute types // and this list is usually short. - if (_foundAttributeTypes == null) + if (_foundAttributeTypes is null) { _foundAttributeTypes = new AttributeEntry[FoundTypesLimit]; } @@ -171,7 +171,7 @@ public virtual Attribute this[Type attributeType] return GetDefaultAttribute(attributeType); } } - if (_foundAttributeTypes[ind].type == null) + if (_foundAttributeTypes[ind].type is null) break; } @@ -224,7 +224,7 @@ public bool Contains(Attribute attribute) } Attribute attr = this[attribute.GetType()]; - return attr != null && attr.Equals(attribute); + return attr is not null && attr.Equals(attribute); } /// @@ -233,7 +233,7 @@ public bool Contains(Attribute attribute) /// public bool Contains(Attribute[] attributes) { - if (attributes == null) + if (attributes is null) { return true; } @@ -262,7 +262,7 @@ protected Attribute GetDefaultAttribute(Type attributeType) lock (s_internalSyncObject) { - if (s_defaultAttributes == null) + if (s_defaultAttributes is null) { s_defaultAttributes = new Hashtable(); } @@ -279,14 +279,14 @@ protected Attribute GetDefaultAttribute(Type attributeType) Type reflect = TypeDescriptor.GetReflectionType(attributeType); FieldInfo field = reflect.GetField("Default", BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField); - if (field != null && field.IsStatic) + if (field is not null && field.IsStatic) { attr = (Attribute)field.GetValue(null); } else { ConstructorInfo ci = reflect.UnderlyingSystemType.GetConstructor(Array.Empty()); - if (ci != null) + if (ci is not null) { attr = (Attribute)ci.Invoke(Array.Empty()); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs index df28b8e2290964..b42c7a7e0a5109 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs @@ -30,7 +30,7 @@ public AttributeProviderAttribute(string typeName, string propertyName) /// public AttributeProviderAttribute(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs index 1133a73dc49f7a..f8804f7b0ed64b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs @@ -68,7 +68,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } else { - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -91,14 +91,14 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(string) && value != null && TargetType.IsInstanceOfType(value)) + if (destinationType == typeof(string) && value is not null && TargetType.IsInstanceOfType(value)) { - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -117,7 +117,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType != null && destinationType.IsPrimitive) + if (destinationType is not null && destinationType.IsPrimitive) { return true; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs index 7e13fec0e86e29..65a526f34b4dd6 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs @@ -81,7 +81,7 @@ private bool ItemTypeHasDefaultConstructor } const BindingFlags BindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance; - return itemType.GetConstructor(BindingFlags, null, Array.Empty(), null) != null; + return itemType.GetConstructor(BindingFlags, null, Array.Empty(), null) is not null; } } @@ -287,13 +287,13 @@ object IBindingList.AddNew() object newItem = AddNewCore(); // Record position of new item (to support cancellation later on) - addNewPos = (newItem != null) ? IndexOf((T)newItem) : -1; + addNewPos = (newItem is not null) ? IndexOf((T)newItem) : -1; // Return new item to caller return newItem; } - private bool AddingNewHandled => _onAddingNew != null && _onAddingNew.GetInvocationList().Length > 0; + private bool AddingNewHandled => _onAddingNew is not null && _onAddingNew.GetInvocationList().Length > 0; /// /// Creates a new item and adds it to the list. @@ -308,7 +308,7 @@ protected virtual object AddNewCore() object newItem = FireAddingNew(); // If event hander did not supply new item, create one ourselves - if (newItem == null) + if (newItem is null) { newItem = Activator.CreateInstance(typeof(T)); } @@ -448,7 +448,7 @@ private void HookPropertyChanged(T item) // Note: inpc may be null if item is null, so always check. if (item is INotifyPropertyChanged inpc) { - if (_propertyChangedEventHandler == null) + if (_propertyChangedEventHandler is null) { _propertyChangedEventHandler = new PropertyChangedEventHandler(Child_PropertyChanged); } @@ -459,7 +459,7 @@ private void HookPropertyChanged(T item) private void UnhookPropertyChanged(T item) { // Note: inpc may be null if item is null, so always check. - if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler != null) + if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler is not null) { inpc.PropertyChanged -= _propertyChangedEventHandler; } @@ -469,7 +469,7 @@ private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (RaiseListChangedEvents) { - if (sender == null || e == null || string.IsNullOrEmpty(e.PropertyName)) + if (sender is null || e is null || string.IsNullOrEmpty(e.PropertyName)) { // Fire reset event (per INotifyPropertyChanged spec) ResetBindings(); @@ -516,7 +516,7 @@ private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { // Get Shape _itemTypeProperties = TypeDescriptor.GetProperties(typeof(T)); - Debug.Assert(_itemTypeProperties != null); + Debug.Assert(_itemTypeProperties is not null); } PropertyDescriptor pd = _itemTypeProperties.Find(e.PropertyName, true); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs index 034be51fafca73..b5da4a0b8500d1 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs @@ -35,7 +35,7 @@ private CultureInfo NeutralResourcesCulture { get { - if (_neutralResourcesCulture == null && MainAssembly != null) + if (_neutralResourcesCulture is null && MainAssembly is not null) { _neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } @@ -62,15 +62,15 @@ private CultureInfo NeutralResourcesCulture /// public virtual void ApplyResources(object value, string objectName, CultureInfo culture) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } - if (objectName == null) + if (objectName is null) { throw new ArgumentNullException(nameof(objectName)); } - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentUICulture; } @@ -88,7 +88,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo // in an order consistent with codedom deserialization. SortedList resources; - if (_resourceSets == null) + if (_resourceSets is null) { _resourceSets = new Hashtable(); resources = FillResources(culture, out ResourceSet dummy); @@ -97,7 +97,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo else { resources = (SortedList)_resourceSets[culture]; - if (resources == null || (resources.Comparer.Equals(StringComparer.OrdinalIgnoreCase) != IgnoreCase)) + if (resources is null || (resources.Comparer.Equals(StringComparer.OrdinalIgnoreCase) != IgnoreCase)) { resources = FillResources(culture, out ResourceSet dummy); _resourceSets[culture] = resources; @@ -114,7 +114,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo if (value is IComponent) { ISite site = ((IComponent)value).Site; - if (site != null && site.DesignMode) + if (site is not null && site.DesignMode) { componentReflect = true; } @@ -155,7 +155,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo { PropertyDescriptor prop = TypeDescriptor.GetProperties(value).Find(propName, IgnoreCase); - if (prop != null && !prop.IsReadOnly && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value))) + if (prop is not null && !prop.IsReadOnly && (kvp.Value is null || prop.PropertyType.IsInstanceOfType(kvp.Value))) { prop.SetValue(value, kvp.Value); } @@ -177,10 +177,10 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo { prop = t.GetProperty(propName, flags | BindingFlags.DeclaredOnly); t = t.BaseType; - } while (prop == null && t != null && t != typeof(object)); + } while (prop is null && t is not null && t != typeof(object)); } - if (prop != null && prop.CanWrite && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value))) + if (prop is not null && prop.CanWrite && (kvp.Value is null || prop.PropertyType.IsInstanceOfType(kvp.Value))) { prop.SetValue(value, kvp.Value, null); } @@ -227,7 +227,7 @@ private SortedList FillResources(CultureInfo culture, out Resour // parent resource set's instance was -- if they are the // same, we're looking at a cache we've already applied. resourceSet = GetResourceSet(culture, true, true); - if (resourceSet != null && !ReferenceEquals(resourceSet, parentResourceSet)) + if (resourceSet is not null && !ReferenceEquals(resourceSet, parentResourceSet)) { foreach (DictionaryEntry de in resourceSet) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs index cc0a8015d79249..1e39532bfd8703 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs @@ -33,18 +33,18 @@ public virtual void Add(IComponent component, string name) { lock (_syncObj) { - if (component == null) + if (component is null) { return; } ISite site = component.Site; - if (site != null && site.Container == this) + if (site is not null && site.Container == this) { return; } - if (_sites == null) + if (_sites is null) { _sites = new ISite[4]; } @@ -134,7 +134,7 @@ public virtual ComponentCollection Components { lock (_syncObj) { - if (_components == null) + if (_components is null) { IComponent[] result = new IComponent[_siteCount]; for (int i = 0; i < _siteCount; i++) @@ -145,7 +145,7 @@ public virtual ComponentCollection Components // At each component add, if we don't yet have a filter, look for one. // Components may add filters. - if (_filter == null && _checkedFilter) + if (_filter is null && _checkedFilter) { _checkedFilter = false; } @@ -157,10 +157,10 @@ public virtual ComponentCollection Components _checkedFilter = true; } - if (_filter != null) + if (_filter is not null) { ComponentCollection filteredComponents = _filter.FilterComponents(_components); - if (filteredComponents != null) + if (filteredComponents is not null) { _components = filteredComponents; } @@ -181,7 +181,7 @@ private void Remove(IComponent component, bool preserveSite) lock (_syncObj) { ISite site = component?.Site; - if (site == null || site.Container != this) + if (site is null || site.Container != this) { return; } @@ -214,18 +214,18 @@ private void Remove(IComponent component, bool preserveSite) /// protected virtual void ValidateName(IComponent component, string name) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } - if (name != null) + if (name is not null) { for (int i = 0; i < Math.Min(_siteCount, _sites.Length); i++) { ISite s = _sites[i]; - if (s?.Name != null && string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase) && s.Component != component) + if (s?.Name is not null && string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase) && s.Component != component) { InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(s.Component)[typeof(InheritanceAttribute)]; if (inheritanceAttribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly) @@ -276,7 +276,7 @@ public string Name get => _name; set { - if (value == null || _name == null || !value.Equals(_name)) + if (value is null || _name is null || !value.Equals(_name)) { ((Container)Container).ValidateName(Component, value); _name = value; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs index 4a8b77db038df0..d02a91e861d958 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs @@ -30,7 +30,7 @@ public class CultureInfoConverter : TypeConverter /// protected virtual string GetCultureName(CultureInfo culture) { - if (culture == null) + if (culture is null) { throw new ArgumentNullException(nameof(culture)); } @@ -73,7 +73,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } string defaultCultureString = DefaultCultureString; - if (culture != null && culture.Equals(CultureInfo.InvariantCulture)) + if (culture is not null && culture.Equals(CultureInfo.InvariantCulture)) { defaultCultureString = DefaultInvariantCultureString; } @@ -86,11 +86,11 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Now look in our set of installed cultures. - if (retVal == null) + if (retVal is null) { foreach (CultureInfo info in GetStandardValues(context)) { - if (info != null && string.Equals(GetCultureName(info), text, StringComparison.Ordinal)) + if (info is not null && string.Equals(GetCultureName(info), text, StringComparison.Ordinal)) { retVal = info; break; @@ -99,7 +99,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Now try to create a new culture info from this value. - if (retVal == null) + if (retVal is null) { try { @@ -111,11 +111,11 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Finally, try to find a partial match. - if (retVal == null) + if (retVal is null) { foreach (CultureInfo info in _values) { - if (info != null && GetCultureName(info).StartsWith(text, StringComparison.CurrentCulture)) + if (info is not null && GetCultureName(info).StartsWith(text, StringComparison.CurrentCulture)) { retVal = info; break; @@ -124,7 +124,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // No good. We can't support it. - if (retVal == null) + if (retVal is null) { throw new ArgumentException(SR.Format(SR.CultureInfoConverterInvalidCulture, (string)value), nameof(value)); } @@ -143,12 +143,12 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(string)) { string defaultCultureString = DefaultCultureString; - if (culture != null && culture.Equals(CultureInfo.InvariantCulture)) + if (culture is not null && culture.Equals(CultureInfo.InvariantCulture)) { defaultCultureString = DefaultInvariantCultureString; } - if (value == null || value == CultureInfo.InvariantCulture) + if (value is null || value == CultureInfo.InvariantCulture) { return defaultCultureString; } @@ -174,7 +174,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (_values == null) + if (_values is null) { CultureInfo[] installedCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures | CultureTypes.NeutralCultures); int invariantIndex = Array.IndexOf(installedCultures, CultureInfo.InvariantCulture); @@ -193,8 +193,8 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex Array.Copy(installedCultures, array, installedCultures.Length); Array.Sort(array, new CultureComparer(this)); - Debug.Assert(array[0] == null); - if (array[0] == null) + Debug.Assert(array[0] is null); + if (array[0] is null) { //we replace null with the real default culture because there are code paths // where the propgrid will send values from this returned array directly -- instead @@ -230,16 +230,16 @@ private class CultureComparer : IComparer public CultureComparer(CultureInfoConverter cultureConverter) { - Debug.Assert(cultureConverter != null); + Debug.Assert(cultureConverter is not null); _converter = cultureConverter; } public int Compare(object item1, object item2) { - if (item1 == null) + if (item1 is null) { // If both are null, then they are equal. - if (item2 == null) + if (item2 is null) { return 0; } @@ -248,7 +248,7 @@ public int Compare(object item1, object item2) return -1; } - if (item2 == null) + if (item2 is null) { // item2 is null, so item 1 is greater. return 1; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CustomTypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CustomTypeDescriptor.cs index 79d0e80b3dd0bd..cf67e65ddff704 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CustomTypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CustomTypeDescriptor.cs @@ -41,7 +41,7 @@ protected CustomTypeDescriptor(ICustomTypeDescriptor parent) /// public virtual AttributeCollection GetAttributes() { - if (_parent != null) + if (_parent is not null) { return _parent.GetAttributes(); } @@ -69,7 +69,7 @@ public virtual AttributeCollection GetAttributes() /// public virtual TypeConverter GetConverter() { - if (_parent != null) + if (_parent is not null) { return _parent.GetConverter(); } @@ -104,7 +104,7 @@ public virtual TypeConverter GetConverter() /// public virtual EventDescriptorCollection GetEvents() { - if (_parent != null) + if (_parent is not null) { return _parent.GetEvents(); } @@ -121,7 +121,7 @@ public virtual EventDescriptorCollection GetEvents() /// public virtual EventDescriptorCollection GetEvents(Attribute[] attributes) { - if (_parent != null) + if (_parent is not null) { return _parent.GetEvents(attributes); } @@ -138,7 +138,7 @@ public virtual EventDescriptorCollection GetEvents(Attribute[] attributes) /// public virtual PropertyDescriptorCollection GetProperties() { - if (_parent != null) + if (_parent is not null) { return _parent.GetProperties(); } @@ -155,7 +155,7 @@ public virtual PropertyDescriptorCollection GetProperties() /// public virtual PropertyDescriptorCollection GetProperties(Attribute[] attributes) { - if (_parent != null) + if (_parent is not null) { return _parent.GetProperties(attributes); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs index e879aaa221f4d6..496b95aade1d7c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs @@ -50,12 +50,12 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c // See if we have a culture info to parse with. If so, then use it. DateTimeFormatInfo formatInfo = null; - if (culture != null) + if (culture is not null) { formatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); } - if (formatInfo != null) + if (formatInfo is not null) { return DateTime.Parse(text, formatInfo); } @@ -87,7 +87,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul return string.Empty; } - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs index d9500ccff113af..e87e78221cd8de 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs @@ -50,12 +50,12 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c // See if we have a culture info to parse with. If so, then use it. DateTimeFormatInfo formatInfo = null; - if (culture != null) + if (culture is not null) { formatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); } - if (formatInfo != null) + if (formatInfo is not null) { return DateTimeOffset.Parse(text, formatInfo); } @@ -89,7 +89,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul return string.Empty; } - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs index 524c2bdddcd265..8fb08d72f755ab 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs @@ -45,7 +45,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(InstanceDescriptor) && value is decimal decimalValue) { ConstructorInfo ctor = typeof(decimal).GetConstructor(new Type[] { typeof(int[]) }); - Debug.Assert(ctor != null, "Expected constructor to exist."); + Debug.Assert(ctor is not null, "Expected constructor to exist."); return new InstanceDescriptor(ctor, new object[] { decimal.GetBits(decimalValue) }); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerCollection.cs index 04fb3e9454130b..e77032f065b274 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerCollection.cs @@ -19,7 +19,7 @@ public class DesignerCollection : ICollection /// public DesignerCollection(IDesignerHost[] designers) { - if (designers != null) + if (designers is not null) { _designers = new ArrayList(designers); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index 3c19b44028fcc7..a476465c4a1294 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -34,12 +34,12 @@ public DesignerOptionCollection Options /// protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent, string name, object value) { - if (parent == null) + if (parent is null) { throw new ArgumentNullException(nameof(parent)); } - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -58,12 +58,12 @@ protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollecti /// private PropertyDescriptor GetOptionProperty(string pageName, string valueName) { - if (pageName == null) + if (pageName is null) { throw new ArgumentNullException(nameof(pageName)); } - if (valueName == null) + if (valueName is null) { throw new ArgumentNullException(nameof(valueName)); } @@ -74,7 +74,7 @@ private PropertyDescriptor GetOptionProperty(string pageName, string valueName) foreach (string optionName in optionNames) { options = options[optionName]; - if (options == null) + if (options is null) { return null; } @@ -140,10 +140,10 @@ internal DesignerOptionCollection(DesignerOptionService service, DesignerOptionC Name = name; _value = value; - if (Parent != null) + if (Parent is not null) { parent._properties = null; - if (Parent._children == null) + if (Parent._children is null) { Parent._children = new ArrayList(1); } @@ -187,11 +187,11 @@ public PropertyDescriptorCollection Properties { get { - if (_properties == null) + if (_properties is null) { ArrayList propList; - if (_value != null) + if (_value is not null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_value); propList = new ArrayList(props.Count); @@ -269,10 +269,10 @@ public void CopyTo(Array array, int index) /// private void EnsurePopulated() { - if (_children == null) + if (_children is null) { _service.PopulateOptionCollection(this); - if (_children == null) + if (_children is null) { _children = new ArrayList(1); } @@ -302,7 +302,7 @@ public int IndexOf(DesignerOptionCollection value) /// private static object RecurseFindValue(DesignerOptionCollection options) { - if (options._value != null) + if (options._value is not null) { return options._value; } @@ -310,7 +310,7 @@ private static object RecurseFindValue(DesignerOptionCollection options) foreach (DesignerOptionCollection child in options) { object value = RecurseFindValue(child); - if (value != null) + if (value is not null) { return value; } @@ -327,7 +327,7 @@ public bool ShowDialog() { object value = RecurseFindValue(this); - if (value == null) + if (value is null) { return false; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerb.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerb.cs index 5294587965e760..ad292bf17190ff 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerb.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerb.cs @@ -16,7 +16,7 @@ public class DesignerVerb : MenuCommand /// public DesignerVerb(string text, EventHandler handler) : base(handler, StandardCommands.VerbFirst) { - Properties["Text"] = text == null ? null : Regex.Replace(text, @"\(\&.\)", ""); + Properties["Text"] = text is null ? null : Regex.Replace(text, @"\(\&.\)", ""); } /// @@ -25,7 +25,7 @@ public DesignerVerb(string text, EventHandler handler) : base(handler, StandardC /// public DesignerVerb(string text, EventHandler handler, CommandID startCommandID) : base(handler, startCommandID) { - Properties["Text"] = text == null ? null : Regex.Replace(text, @"\(\&.\)", ""); + Properties["Text"] = text is null ? null : Regex.Replace(text, @"\(\&.\)", ""); } /// @@ -36,7 +36,7 @@ public string Description get { object result = Properties["Description"]; - if (result == null) + if (result is null) { return string.Empty; } @@ -54,7 +54,7 @@ public string Text get { object result = Properties["Text"]; - if (result == null) + if (result is null) { return string.Empty; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs index b53eb3ea6d6483..9dcf1ff78158c6 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs @@ -23,7 +23,7 @@ public DesignerVerb this[int index] public void AddRange(DesignerVerb[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -36,7 +36,7 @@ public void AddRange(DesignerVerb[] value) public void AddRange(DesignerVerbCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs index c650b38372f750..8b71695df95034 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs @@ -31,7 +31,7 @@ public class DesigntimeLicenseContext : LicenseContext /// public override void SetSavedLicenseKey(Type type, string key) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -51,7 +51,7 @@ internal class RuntimeLicenseContext : LicenseContext /// private string GetLocalPath(string fileName) { - Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get local path, fileName is not valid"); + Debug.Assert(fileName is not null && fileName.Length > 0, "Cannot get local path, fileName is not valid"); Uri uri = new Uri(fileName); return uri.LocalPath + uri.Fragment; @@ -59,19 +59,19 @@ private string GetLocalPath(string fileName) public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) { - if (_savedLicenseKeys == null || _savedLicenseKeys[type.AssemblyQualifiedName] == null) + if (_savedLicenseKeys is null || _savedLicenseKeys[type.AssemblyQualifiedName] is null) { - if (_savedLicenseKeys == null) + if (_savedLicenseKeys is null) { _savedLicenseKeys = new Hashtable(); } - if (resourceAssembly == null) + if (resourceAssembly is null) { resourceAssembly = Assembly.GetEntryAssembly(); } - if (resourceAssembly == null) + if (resourceAssembly is null) { // If Assembly.EntryAssembly returns null, then we will // try everything. @@ -85,14 +85,14 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) string fileName = new FileInfo(location).Name; Stream s = asm.GetManifestResourceStream(fileName + ".licenses"); - if (s == null) + if (s is null) { // Since the casing may be different depending on how the assembly was loaded, // we'll do a case insensitive lookup for this manifest resource stream... s = CaseInsensitiveManifestResourceStreamLookup(asm, fileName + ".licenses"); } - if (s != null) + if (s is not null) { DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpperInvariant(), this); break; @@ -109,7 +109,7 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) // First try the filename Stream s = resourceAssembly.GetManifestResourceStream(licResourceName); - if (s == null) + if (s is null) { string resolvedName = null; CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; @@ -126,12 +126,12 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) break; } } - if (resolvedName != null) + if (resolvedName is not null) { s = resourceAssembly.GetManifestResourceStream(resolvedName); } } - if (s != null) + if (s is not null) { DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpperInvariant(), this); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs index 28ec5125ecb250..332cb8872a289e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs @@ -68,7 +68,7 @@ public HelpKeywordAttribute(string keyword) /// public HelpKeywordAttribute(Type t) { - if (t == null) + if (t is null) { throw new ArgumentNullException(nameof(t)); } @@ -90,7 +90,7 @@ public override bool Equals(object obj) { return true; } - if ((obj != null) && (obj is HelpKeywordAttribute)) + if ((obj is not null) && (obj is HelpKeywordAttribute)) { return ((HelpKeywordAttribute)obj).HelpKeyword == HelpKeyword; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/MenuCommand.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/MenuCommand.cs index abd7d8d3fdfcd6..8e17056999e58d 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/MenuCommand.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/MenuCommand.cs @@ -125,7 +125,7 @@ public virtual bool Visible /// public virtual void Invoke() { - if (_execHandler != null) + if (_execHandler is not null) { try { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs index 19038d77f08d53..62a55e15a84c30 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs @@ -77,7 +77,7 @@ public Type[] TabClasses { get { - if (_tabClasses == null && _tabClassNames != null) + if (_tabClasses is null && _tabClassNames is not null) { _tabClasses = new Type[_tabClassNames.Length]; for (int i = 0; i < _tabClassNames.Length; i++) @@ -98,12 +98,12 @@ public Type[] TabClasses _tabClasses[i] = Type.GetType(className, false); - if (_tabClasses[i] == null) + if (_tabClasses[i] is null) { - if (assemblyName != null) + if (assemblyName is not null) { Assembly a = Assembly.Load(assemblyName); - if (a != null) + if (a is not null) { _tabClasses[i] = a.GetType(className, true); } @@ -182,29 +182,29 @@ protected void InitializeArrays(Type[] tabClasses, PropertyTabScope[] tabScopes) private void InitializeArrays(string[] tabClassNames, Type[] tabClasses, PropertyTabScope[] tabScopes) { - if (tabClasses != null) + if (tabClasses is not null) { - if (tabScopes != null && tabClasses.Length != tabScopes.Length) + if (tabScopes is not null && tabClasses.Length != tabScopes.Length) { throw new ArgumentException(SR.PropertyTabAttributeArrayLengthMismatch); } _tabClasses = (Type[])tabClasses.Clone(); } - else if (tabClassNames != null) + else if (tabClassNames is not null) { - if (tabScopes != null && tabClassNames.Length != tabScopes.Length) + if (tabScopes is not null && tabClassNames.Length != tabScopes.Length) { throw new ArgumentException(SR.PropertyTabAttributeArrayLengthMismatch); } _tabClassNames = (string[])tabClassNames.Clone(); _tabClasses = null; } - else if (_tabClasses == null && _tabClassNames == null) + else if (_tabClasses is null && _tabClassNames is null) { throw new ArgumentException(SR.PropertyTabAttributeParamsBothNull); } - if (tabScopes != null) + if (tabScopes is not null) { for (int i = 0; i < tabScopes.Length; i++) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs index 16b59f14830080..faa88368e1810d 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs @@ -33,7 +33,7 @@ public object Current { get { - if (_contextStack != null && _contextStack.Count > 0) + if (_contextStack is not null && _contextStack.Count > 0) { return _contextStack[_contextStack.Count - 1]; } @@ -53,7 +53,7 @@ public object this[int level] { throw new ArgumentOutOfRangeException(nameof(level)); } - if (_contextStack != null && level < _contextStack.Count) + if (_contextStack is not null && level < _contextStack.Count) { return _contextStack[_contextStack.Count - 1 - level]; } @@ -70,12 +70,12 @@ public object this[Type type] { get { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (_contextStack != null) + if (_contextStack is not null) { int level = _contextStack.Count; while (level > 0) @@ -101,12 +101,12 @@ public object this[Type type] /// public void Append(object context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } - if (_contextStack == null) + if (_contextStack is null) { _contextStack = new ArrayList(); } @@ -121,7 +121,7 @@ public object Pop() { object context = null; - if (_contextStack != null && _contextStack.Count > 0) + if (_contextStack is not null && _contextStack.Count > 0) { int idx = _contextStack.Count - 1; context = _contextStack[idx]; @@ -136,12 +136,12 @@ public object Pop() /// public void Push(object context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } - if (_contextStack == null) + if (_contextStack is null) { _contextStack = new ArrayList(); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs index a539d1a2bbf8d5..1b25650599a9c5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs @@ -18,7 +18,7 @@ public sealed class DefaultSerializationProviderAttribute : Attribute /// public DefaultSerializationProviderAttribute(Type providerType) { - if (providerType == null) + if (providerType is null) { throw new ArgumentNullException(nameof(providerType)); } @@ -31,7 +31,7 @@ public DefaultSerializationProviderAttribute(Type providerType) /// public DefaultSerializationProviderAttribute(string providerTypeName) { - if (providerTypeName == null) + if (providerTypeName is null) { throw new ArgumentNullException(nameof(providerTypeName)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs index c1391c2e804fdb..84f47520e89055 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs @@ -28,7 +28,7 @@ public InstanceDescriptor(MemberInfo member, ICollection arguments, bool isCompl MemberInfo = member; IsComplete = isComplete; - if (arguments == null) + if (arguments is null) { Arguments = Array.Empty(); } @@ -79,7 +79,7 @@ public InstanceDescriptor(MemberInfo member, ICollection arguments, bool isCompl throw new ArgumentException(SR.InstanceDescriptorMustBeReadable); } MethodInfo getMethod = pi.GetGetMethod(); - if (getMethod != null && !getMethod.IsStatic) + if (getMethod is not null && !getMethod.IsStatic) { throw new ArgumentException(SR.InstanceDescriptorMustBeStatic); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index 52f691564f215c..34907241a9a144 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -41,12 +41,12 @@ public MemberRelationship this[MemberRelationship source] // The Owner and Member properties can be null if the MemberRelationship is constructed // using the default constructor. However there is no situation in which one is null // and not the other as the main constructor performs argument validation. - if (source.Owner == null) + if (source.Owner is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source)); } - Debug.Assert(source.Member != null); + Debug.Assert(source.Member is not null); return GetRelationship(source); } set @@ -54,12 +54,12 @@ public MemberRelationship this[MemberRelationship source] // The Owner and Member properties can be null if the MemberRelationship is constructed // using the default constructor. However there is no situation in which one is null // and not the other as the main constructor performs argument validation. - if (source.Owner == null) + if (source.Owner is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source)); } - Debug.Assert(source.Member != null); + Debug.Assert(source.Member is not null); SetRelationship(source, value); } } @@ -73,11 +73,11 @@ public MemberRelationship this[MemberRelationship source] { get { - if (sourceOwner == null) + if (sourceOwner is null) { throw new ArgumentNullException(nameof(sourceOwner)); } - if (sourceMember == null) + if (sourceMember is null) { throw new ArgumentNullException(nameof(sourceMember)); } @@ -86,11 +86,11 @@ public MemberRelationship this[MemberRelationship source] } set { - if (sourceOwner == null) + if (sourceOwner is null) { throw new ArgumentNullException(nameof(sourceOwner)); } - if (sourceMember == null) + if (sourceMember is null) { throw new ArgumentNullException(nameof(sourceMember)); } @@ -124,11 +124,11 @@ protected virtual void SetRelationship(MemberRelationship source, MemberRelation { string sourceName = TypeDescriptor.GetComponentName(source.Owner); string relName = TypeDescriptor.GetComponentName(relationship.Owner); - if (sourceName == null) + if (sourceName is null) { sourceName = source.Owner.ToString(); } - if (relName == null) + if (relName is null) { relName = relationship.Owner.ToString(); } @@ -156,7 +156,7 @@ internal RelationshipEntry(MemberRelationship rel) { _owner = new WeakReference(rel.Owner); _member = rel.Member; - _hashCode = rel.Owner == null ? 0 : rel.Owner.GetHashCode(); + _hashCode = rel.Owner is null ? 0 : rel.Owner.GetHashCode(); } public override bool Equals(object o) @@ -200,7 +200,7 @@ public MemberRelationship(object owner, MemberDescriptor member) /// /// Returns true if this relationship is empty. /// - public bool IsEmpty => Owner == null; + public bool IsEmpty => Owner is null; /// /// The member in this relationship. @@ -225,7 +225,7 @@ public override bool Equals(object obj) /// public override int GetHashCode() { - if (Owner == null) + if (Owner is null) { return base.GetHashCode(); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs index bfcca80487bd23..54b54f136e652e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs @@ -19,11 +19,11 @@ public sealed class RootDesignerSerializerAttribute : Attribute /// public RootDesignerSerializerAttribute(Type serializerType, Type baseSerializerType, bool reloadable) { - if (serializerType == null) + if (serializerType is null) { throw new ArgumentNullException(nameof(serializerType)); } - if (baseSerializerType == null) + if (baseSerializerType is null) { throw new ArgumentNullException(nameof(baseSerializerType)); } @@ -38,7 +38,7 @@ public RootDesignerSerializerAttribute(Type serializerType, Type baseSerializerT /// public RootDesignerSerializerAttribute(string serializerTypeName, Type baseSerializerType, bool reloadable) { - if (baseSerializerType == null) + if (baseSerializerType is null) { throw new ArgumentNullException(nameof(baseSerializerType)); } @@ -86,7 +86,7 @@ public override object TypeId { get { - if (_typeId == null) + if (_typeId is null) { string baseType = SerializerBaseTypeName ?? string.Empty; int comma = baseType.IndexOf(','); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs index d5cedfba0f33ba..764e6682f1d72c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs @@ -68,7 +68,7 @@ public virtual void AddService(Type serviceType, object serviceInstance, bool pr if (promote) { IServiceContainer container = Container; - if (container != null) + if (container is not null) { container.AddService(serviceType, serviceInstance, promote); return; @@ -78,8 +78,8 @@ public virtual void AddService(Type serviceType, object serviceInstance, bool pr // We're going to add this locally. Ensure that the service instance // is correct. // - if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); - if (serviceInstance == null) throw new ArgumentNullException(nameof(serviceInstance)); + if (serviceType is null) throw new ArgumentNullException(nameof(serviceType)); + if (serviceInstance is null) throw new ArgumentNullException(nameof(serviceInstance)); if (!(serviceInstance is ServiceCreatorCallback) && !serviceInstance.GetType().IsCOMObject && !serviceType.IsInstanceOfType(serviceInstance)) { throw new ArgumentException(SR.Format(SR.ErrorInvalidServiceInstance, serviceType.FullName)); @@ -109,7 +109,7 @@ public virtual void AddService(Type serviceType, ServiceCreatorCallback callback if (promote) { IServiceContainer container = Container; - if (container != null) + if (container is not null) { container.AddService(serviceType, callback, promote); return; @@ -119,8 +119,8 @@ public virtual void AddService(Type serviceType, ServiceCreatorCallback callback // We're going to add this locally. Ensure that the service instance // is correct. // - if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (serviceType is null) throw new ArgumentNullException(nameof(serviceType)); + if (callback is null) throw new ArgumentNullException(nameof(callback)); if (Services.ContainsKey(serviceType)) { @@ -149,7 +149,7 @@ protected virtual void Dispose(bool disposing) { ServiceCollection serviceCollection = _services; _services = null; - if (serviceCollection != null) + if (serviceCollection is not null) { foreach (object o in serviceCollection.Values) { @@ -174,14 +174,14 @@ public virtual object GetService(Type serviceType) Type[] defaults = DefaultServices; for (int idx = 0; idx < defaults.Length; idx++) { - if (serviceType != null && serviceType.IsEquivalentTo(defaults[idx])) + if (serviceType is not null && serviceType.IsEquivalentTo(defaults[idx])) { service = this; break; } } - if (service == null && serviceType != null) + if (service is null && serviceType is not null) { Services.TryGetValue(serviceType, out service); } @@ -190,7 +190,7 @@ public virtual object GetService(Type serviceType) if (service is ServiceCreatorCallback) { service = ((ServiceCreatorCallback)service)(this, serviceType); - if (service != null && !service.GetType().IsCOMObject && !serviceType.IsInstanceOfType(service)) + if (service is not null && !service.GetType().IsCOMObject && !serviceType.IsInstanceOfType(service)) { // Callback passed us a bad service. NULL it, rather than throwing an exception. // Callers here do not need to be prepared to handle bad callback implemetations. @@ -201,7 +201,7 @@ public virtual object GetService(Type serviceType) Services[serviceType] = service; } - if (service == null && _parentProvider != null) + if (service is null && _parentProvider is not null) { service = _parentProvider.GetService(serviceType); } @@ -225,7 +225,7 @@ public virtual void RemoveService(Type serviceType, bool promote) if (promote) { IServiceContainer container = Container; - if (container != null) + if (container is not null) { container.RemoveService(serviceType, promote); return; @@ -233,7 +233,7 @@ public virtual void RemoveService(Type serviceType, bool promote) } // We're going to remove this from our local list. - if (serviceType == null) + if (serviceType is null) { throw new ArgumentNullException(nameof(serviceType)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs index 38c7932c1653b2..01f7bb6e910e19 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs @@ -115,12 +115,12 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(string) && value != null) + if (destinationType == typeof(string) && value is not null) { // Raise an argument exception if the value isn't defined and if // the enum isn't a flags style. @@ -132,7 +132,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul return Enum.Format(EnumType, value, "G"); } - if (destinationType == typeof(InstanceDescriptor) && value != null) + if (destinationType == typeof(InstanceDescriptor) && value is not null) { string enumName = ConvertToInvariantString(context, value); @@ -149,7 +149,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul object convertedValue = ((IConvertible)value).ToType(underlyingType, culture); MethodInfo method = typeof(Enum).GetMethod("ToObject", new Type[] { typeof(Type), underlyingType }); - if (method != null) + if (method is not null) { return new InstanceDescriptor(method, new object[] { EnumType, convertedValue }); } @@ -158,14 +158,14 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul else { FieldInfo info = EnumType.GetField(enumName); - if (info != null) + if (info is not null) { return new InstanceDescriptor(info, null); } } } - if (destinationType == typeof(Enum[]) && value != null) + if (destinationType == typeof(Enum[]) && value is not null) { if (EnumType.IsDefined(typeof(FlagsAttribute), false)) { @@ -223,7 +223,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (Values == null) + if (Values is null) { // We need to get the enum values in this rather round-about way so we can filter // out fields marked Browsable(false). Note that if multiple fields have the same value, @@ -233,12 +233,12 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex FieldInfo[] fields = reflectType.GetFields(BindingFlags.Public | BindingFlags.Static); ArrayList objValues = null; - if (fields != null && fields.Length > 0) + if (fields is not null && fields.Length > 0) { objValues = new ArrayList(fields.Length); } - if (objValues != null) + if (objValues is not null) { foreach (FieldInfo field in fields) { @@ -248,13 +248,13 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex browsableAttr = attr as BrowsableAttribute; } - if (browsableAttr == null || browsableAttr.Browsable) + if (browsableAttr is null || browsableAttr.Browsable) { object value = null; try { - if (field.Name != null) + if (field.Name is not null) { value = Enum.Parse(EnumType, field.Name); } @@ -264,7 +264,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex // Hmm, for some reason, the parse threw. Let us ignore this value. } - if (value != null) + if (value is not null) { objValues.Add(value); } @@ -272,7 +272,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex } IComparer comparer = Comparer; - if (comparer != null) + if (comparer is not null) { objValues.Sort(comparer); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EventDescriptorCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EventDescriptorCollection.cs index 52631639bc53e1..498f2fa6c6e444 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EventDescriptorCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EventDescriptorCollection.cs @@ -30,7 +30,7 @@ public class EventDescriptorCollection : ICollection, IList /// public EventDescriptorCollection(EventDescriptor[] events) { - if (events == null) + if (events is null) { _events = Array.Empty(); } @@ -54,7 +54,7 @@ public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer) { _eventsOwned = false; - if (namedSort != null) + if (namedSort is not null) { _namedSort = (string[])namedSort.Clone(); } @@ -125,7 +125,7 @@ private void EnsureEventsOwned() if (!_eventsOwned) { _eventsOwned = true; - if (_events != null) + if (_events is not null) { EventDescriptor[] newEvents = new EventDescriptor[Count]; Array.Copy(_events, newEvents, Count); @@ -309,7 +309,7 @@ protected void InternalSort(string[] names) InternalSort(_comparer); - if (names != null && names.Length > 0) + if (names is not null && names.Length > 0) { List eventList = new List(_events); int foundCount = 0; @@ -324,7 +324,7 @@ protected void InternalSort(string[] names) // Found a matching event. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // - if (currentEvent != null && currentEvent.Name.Equals(names[i])) + if (currentEvent is not null && currentEvent.Name.Equals(names[i])) { _events[foundCount++] = currentEvent; eventList[j] = null; @@ -340,7 +340,7 @@ protected void InternalSort(string[] names) // for (int i = 0; i < eventCount; i++) { - if (eventList[i] != null) + if (eventList[i] is not null) { _events[foundCount++] = eventList[i]; } @@ -355,7 +355,7 @@ protected void InternalSort(string[] names) /// protected void InternalSort(IComparer sorter) { - if (sorter == null) + if (sorter is null) { TypeDescriptor.SortDescriptorArray(this); } @@ -418,8 +418,8 @@ private class ArraySubsetEnumerator : IEnumerator public ArraySubsetEnumerator(Array array, int count) { - Debug.Assert(count == 0 || array != null, "if array is null, count should be 0"); - Debug.Assert(array == null || count <= array.Length, "Trying to enumerate more than the array contains"); + Debug.Assert(count == 0 || array is not null, "if array is null, count should be 0"); + Debug.Assert(array is null || count <= array.Length, "Trying to enumerate more than the array contains"); _array = array; _total = count; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs index 12c86e0e8dd9a8..e85de86b74e064 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs @@ -22,8 +22,8 @@ internal sealed class ExtendedPropertyDescriptor : PropertyDescriptor public ExtendedPropertyDescriptor(ReflectPropertyDescriptor extenderInfo, Type receiverType, IExtenderProvider provider, Attribute[] attributes) : base(extenderInfo, attributes) { - Debug.Assert(extenderInfo != null, "ExtendedPropertyDescriptor must have extenderInfo"); - Debug.Assert(provider != null, "ExtendedPropertyDescriptor must have provider"); + Debug.Assert(extenderInfo is not null, "ExtendedPropertyDescriptor must have extenderInfo"); + Debug.Assert(provider is not null, "ExtendedPropertyDescriptor must have provider"); List attrList = new List(AttributeArray) { @@ -44,16 +44,16 @@ public ExtendedPropertyDescriptor(ReflectPropertyDescriptor extenderInfo, Type r public ExtendedPropertyDescriptor(PropertyDescriptor extender, Attribute[] attributes) : base(extender, attributes) { - Debug.Assert(extender != null, "The original PropertyDescriptor must be non-null"); + Debug.Assert(extender is not null, "The original PropertyDescriptor must be non-null"); ExtenderProvidedPropertyAttribute attr = extender.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; - Debug.Assert(attr != null, "The original PropertyDescriptor does not have an ExtenderProvidedPropertyAttribute"); + Debug.Assert(attr is not null, "The original PropertyDescriptor does not have an ExtenderProvidedPropertyAttribute"); ReflectPropertyDescriptor reflectDesc = attr.ExtenderProperty as ReflectPropertyDescriptor; - Debug.Assert(reflectDesc != null, "The original PropertyDescriptor has an invalid ExtenderProperty"); + Debug.Assert(reflectDesc is not null, "The original PropertyDescriptor has an invalid ExtenderProperty"); _extenderInfo = reflectDesc; _provider = attr.Provider; @@ -97,7 +97,7 @@ public override string DisplayName { ISite site = GetSite(_provider); string providerName = site?.Name; - if (providerName != null && providerName.Length > 0) + if (providerName is not null && providerName.Length > 0) { name = SR.Format(SR.MetaExtenderName, name, providerName); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtenderProvidedPropertyAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtenderProvidedPropertyAttribute.cs index 2c5f58e6eb5216..630e97d32a9b8f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtenderProvidedPropertyAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtenderProvidedPropertyAttribute.cs @@ -63,14 +63,14 @@ public override bool Equals(object obj) // are null (and are immutable), so we only need to check the // nullability of one property to know about the nullability // of the rest. - if (other.ExtenderProperty == null) + if (other.ExtenderProperty is null) { - Debug.Assert(other.Provider == null); - Debug.Assert(other.ReceiverType == null); - Debug.Assert(Provider == null); - Debug.Assert(ReceiverType == null); + Debug.Assert(other.Provider is null); + Debug.Assert(other.ReceiverType is null); + Debug.Assert(Provider is null); + Debug.Assert(ReceiverType is null); - return ExtenderProperty == null; + return ExtenderProperty is null; } return other.ExtenderProperty.Equals(ExtenderProperty) @@ -80,6 +80,6 @@ public override bool Equals(object obj) public override int GetHashCode() => base.GetHashCode(); - public override bool IsDefaultAttribute() => ReceiverType == null; + public override bool IsDefaultAttribute() => ReceiverType is null; } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/GuidConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/GuidConverter.cs index 61d87530eed30a..49be74471946b1 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/GuidConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/GuidConverter.cs @@ -57,7 +57,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(InstanceDescriptor) && value is Guid) { ConstructorInfo ctor = typeof(Guid).GetConstructor(new Type[] { typeof(string) }); - Debug.Assert(ctor != null, "Expected constructor to exist."); + Debug.Assert(ctor is not null, "Expected constructor to exist."); return new InstanceDescriptor(ctor, new object[] { value.ToString() }); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs index d88952b15c829f..a560d0508b6716 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs @@ -18,7 +18,7 @@ public class InstallerTypeAttribute : Attribute /// public InstallerTypeAttribute(Type installerType) { - if (installerType == null) + if (installerType is null) { throw new ArgumentNullException(nameof(installerType)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs index 70e6728d729c56..e6ce9c654fc65f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs @@ -20,7 +20,7 @@ public class LicFileLicenseProvider : LicenseProvider /// protected virtual bool IsKeyValid(string key, Type type) { - if (key != null) + if (key is not null) { return key.StartsWith(GetKey(type)); } @@ -44,32 +44,32 @@ public override License GetLicense(LicenseContext context, Type type, object ins { LicFileLicense lic = null; - Debug.Assert(context != null, "No context provided!"); - if (context != null) + Debug.Assert(context is not null, "No context provided!"); + if (context is not null) { if (context.UsageMode == LicenseUsageMode.Runtime) { string key = context.GetSavedLicenseKey(type, null); - if (key != null && IsKeyValid(key, type)) + if (key is not null && IsKeyValid(key, type)) { lic = new LicFileLicense(this, key); } } - if (lic == null) + if (lic is null) { string modulePath = null; - if (context != null) + if (context is not null) { ITypeResolutionService resolver = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService)); - if (resolver != null) + if (resolver is not null) { modulePath = resolver.GetPathOfAssembly(type.Assembly.GetName()); } } - if (modulePath == null) + if (modulePath is null) { modulePath = type.Module.FullyQualifiedName; } @@ -90,7 +90,7 @@ public override License GetLicense(LicenseContext context, Type type, object ins } } - if (lic != null) + if (lic is not null) { context.SetSavedLicenseKey(type, lic.LicenseKey); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs index 01ef7f2b3dbb7c..48ae33135271e9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs @@ -32,7 +32,7 @@ public static CLRLicenseContext CreateDesignContext(Type type) public static CLRLicenseContext CreateRuntimeContext(Type type, string key) { var cxt = new CLRLicenseContext(type, LicenseUsageMode.Runtime); - if (key != null) + if (key is not null) { cxt.SetSavedLicenseKey(type, key); } @@ -90,7 +90,7 @@ public static bool ValidateAndRetrieveLicenseDetails( out License license, out string licenseKey) { - if (context == null) + if (context is null) { context = LicenseManager.CurrentContext; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs index c340d12247eeef..cd89f949bfb494 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs @@ -37,11 +37,11 @@ public static LicenseContext CurrentContext { get { - if (s_context == null) + if (s_context is null) { lock (s_internalSyncObject) { - if (s_context == null) + if (s_context is null) { s_context = new RuntimeLicenseContext(); } @@ -53,7 +53,7 @@ public static LicenseContext CurrentContext { lock (s_internalSyncObject) { - if (s_contextLockHolder != null) + if (s_contextLockHolder is not null) { throw new InvalidOperationException(SR.LicMgrContextCannotBeChanged); } @@ -71,7 +71,7 @@ public static LicenseUsageMode UsageMode { get { - if (s_context != null) + if (s_context is not null) { return s_context.UsageMode; } @@ -86,7 +86,7 @@ public static LicenseUsageMode UsageMode /// private static void CacheProvider(Type type, LicenseProvider provider) { - if (s_providers == null) + if (s_providers is null) { Interlocked.CompareExchange(ref s_providers, new Hashtable(), null); } @@ -96,9 +96,9 @@ private static void CacheProvider(Type type, LicenseProvider provider) s_providers[type] = provider; } - if (provider != null) + if (provider is not null) { - if (s_providerInstances == null) + if (s_providerInstances is null) { Interlocked.CompareExchange(ref s_providerInstances, new Hashtable(), null); } @@ -166,7 +166,7 @@ public static object CreateWithContext(Type type, LicenseContext creationContext /// private static bool GetCachedNoLicenseProvider(Type type) { - if (s_providers != null) + if (s_providers is not null) { return s_providers.ContainsKey(type); } @@ -190,7 +190,7 @@ private static LicenseProvider GetCachedProvider(Type type) /// private static LicenseProvider GetCachedProviderInstance(Type providerType) { - Debug.Assert(providerType != null, "Type cannot ever be null"); + Debug.Assert(providerType is not null, "Type cannot ever be null"); return (LicenseProvider)s_providerInstances?[providerType]; } @@ -199,9 +199,9 @@ private static LicenseProvider GetCachedProviderInstance(Type providerType) /// public static bool IsLicensed(Type type) { - Debug.Assert(type != null, "IsValid Type cannot ever be null"); + Debug.Assert(type is not null, "IsValid Type cannot ever be null"); bool value = ValidateInternal(type, null, false, out License license); - if (license != null) + if (license is not null) { license.Dispose(); license = null; @@ -214,9 +214,9 @@ public static bool IsLicensed(Type type) /// public static bool IsValid(Type type) { - Debug.Assert(type != null, "IsValid Type cannot ever be null"); + Debug.Assert(type is not null, "IsValid Type cannot ever be null"); bool value = ValidateInternal(type, null, false, out License license); - if (license != null) + if (license is not null) { license.Dispose(); license = null; @@ -237,7 +237,7 @@ public static void LockContext(object contextUser) { lock (s_internalSyncObject) { - if (s_contextLockHolder != null) + if (s_contextLockHolder is not null) { throw new InvalidOperationException(SR.LicMgrAlreadyLocked); } @@ -279,12 +279,12 @@ private static bool ValidateInternal(Type type, object instance, bool allowExcep private static bool ValidateInternalRecursive(LicenseContext context, Type type, object instance, bool allowExceptions, out License license, out string licenseKey) { LicenseProvider provider = GetCachedProvider(type); - if (provider == null && !GetCachedNoLicenseProvider(type)) + if (provider is null && !GetCachedNoLicenseProvider(type)) { // NOTE : Must look directly at the class, we want no inheritance. LicenseProviderAttribute attr = (LicenseProviderAttribute)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false); - if (attr != null) + if (attr is not null) { Type providerType = attr.LicenseProvider; provider = GetCachedProviderInstance(providerType) ?? (LicenseProvider)Activator.CreateInstance(providerType); @@ -297,10 +297,10 @@ private static bool ValidateInternalRecursive(LicenseContext context, Type type, bool isValid = true; licenseKey = null; - if (provider != null) + if (provider is not null) { license = provider.GetLicense(context, type, instance, allowExceptions); - if (license == null) + if (license is null) { isValid = false; } @@ -315,19 +315,19 @@ private static bool ValidateInternalRecursive(LicenseContext context, Type type, // When looking only at a type, we need to recurse up the inheritence // chain, however, we can't give out the license, since this may be // from more than one provider. - if (isValid && instance == null) + if (isValid && instance is null) { Type baseType = type.BaseType; - if (baseType != typeof(object) && baseType != null) + if (baseType != typeof(object) && baseType is not null) { - if (license != null) + if (license is not null) { license.Dispose(); license = null; } string temp; isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out temp); - if (license != null) + if (license is not null) { license.Dispose(); license = null; @@ -349,7 +349,7 @@ public static void Validate(Type type) throw new LicenseException(type); } - if (lic != null) + if (lic is not null) { lic.Dispose(); lic = null; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseProviderAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseProviderAttribute.cs index 9760e6eeaed5e5..9ce57f1491b6f8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseProviderAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseProviderAttribute.cs @@ -53,7 +53,7 @@ public Type LicenseProvider { get { - if (_licenseProviderType == null && _licenseProviderName != null) + if (_licenseProviderType is null && _licenseProviderName is not null) { _licenseProviderType = Type.GetType(_licenseProviderName); } @@ -74,7 +74,7 @@ public override object TypeId { string typeName = _licenseProviderName; - if (typeName == null && _licenseProviderType != null) + if (typeName is null && _licenseProviderType is not null) { typeName = _licenseProviderType.FullName; } @@ -84,7 +84,7 @@ public override object TypeId public override bool Equals(object value) { - if (value is LicenseProviderAttribute && value != null) + if (value is LicenseProviderAttribute && value is not null) { Type type = ((LicenseProviderAttribute)value).LicenseProvider; if (type == LicenseProvider) @@ -93,7 +93,7 @@ public override bool Equals(object value) } else { - if (type != null && type.Equals(LicenseProvider)) + if (type is not null && type.Equals(LicenseProvider)) { return true; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ListSortDescriptionCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ListSortDescriptionCollection.cs index b61e04cd161db1..222c3acb44f0bb 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ListSortDescriptionCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ListSortDescriptionCollection.cs @@ -15,7 +15,7 @@ public ListSortDescriptionCollection() public ListSortDescriptionCollection(ListSortDescription[] sorts) { - if (sorts != null) + if (sorts is not null) { for (int i = 0; i < sorts.Length; i++) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs index 93d3485b1ec131..a78dbde9413da6 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs @@ -86,7 +86,7 @@ public void Dispose() /// /// protected virtual void Dispose(bool disposing) { /// if (disposing) { - /// if (myobject != null) { + /// if (myobject is not null) { /// myobject.Dispose(); /// myobject = null; /// } @@ -109,7 +109,7 @@ public void Dispose() /// /// protected override void Dispose(bool disposing) { /// if (disposing) { - /// if (myobject != null) { + /// if (myobject is not null) { /// myobject.Dispose(); /// myobject = null; /// } @@ -160,7 +160,7 @@ public override string ToString() { ISite s = _site; - if (s != null) + if (s is not null) return s.Name + " [" + GetType().FullName + "]"; else return GetType().FullName; 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 46e996946fbab9..476b46fd291360 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -239,7 +239,7 @@ public MaskedTextProvider(string mask, CultureInfo culture, bool allowPromptAsIn } } - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -266,7 +266,7 @@ public MaskedTextProvider(string mask, CultureInfo culture, bool allowPromptAsIn } // Last resort use invariant culture. - if (Culture == null) + if (Culture is null) { Culture = CultureInfo.InvariantCulture; } @@ -888,7 +888,7 @@ public bool Add(string input) /// public bool Add(string input, out int testPosition, out MaskedTextResultHint resultHint) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -1267,7 +1267,7 @@ public bool InsertAt(string input, int position) /// public bool InsertAt(string input, int position, out int testPosition, out MaskedTextResultHint resultHint) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -1294,7 +1294,7 @@ public bool InsertAt(string input, int position, out int testPosition, out Maske /// private bool InsertAtInt(string input, int position, out int testPosition, out MaskedTextResultHint resultHint, bool testOnly) { - Debug.Assert(input != null && position >= 0 && position < _testString.Length, "input param out of range."); + Debug.Assert(input is not null && position >= 0 && position < _testString.Length, "input param out of range."); if (input.Length == 0) // nothing to insert. { @@ -1836,7 +1836,7 @@ public bool Replace(string input, int position) /// public bool Replace(string input, int position, out int testPosition, out MaskedTextResultHint resultHint) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -1875,7 +1875,7 @@ public bool Replace(string input, int position, out int testPosition, out Masked /// public bool Replace(string input, int startPosition, int endPosition, out int testPosition, out MaskedTextResultHint resultHint) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -2064,7 +2064,7 @@ public bool Set(string input) /// public bool Set(string input, out int testPosition, out MaskedTextResultHint resultHint) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -2113,7 +2113,7 @@ private void SetChar(char input, int position) private void SetChar(char input, int position, CharDescriptor charDescriptor) { Debug.Assert(position >= 0 && position < _testString.Length, "Position out of range."); - Debug.Assert(charDescriptor != null, "Null character descriptor."); + Debug.Assert(charDescriptor is not null, "Null character descriptor."); // Get the character info from the char descriptor table. CharDescriptor charDex = _stringDescriptor[position]; @@ -2495,7 +2495,7 @@ private bool TestSetString(string input, int position, out int testPosition, out /// private bool TestString(string input, int position, out int testPosition, out MaskedTextResultHint resultHint) { - Debug.Assert(input != null, "null input."); + Debug.Assert(input is not null, "null input."); Debug.Assert(position >= 0, "Position out of range."); resultHint = MaskedTextResultHint.Unknown; @@ -2795,7 +2795,7 @@ public bool VerifyString(string input, out int testPosition, out MaskedTextResul { testPosition = 0; - if (input == null || input.Length == 0) // nothing to verify. + if (input is null || input.Length == 0) // nothing to verify. { resultHint = MaskedTextResultHint.NoEffect; return true; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs index 910d36aeb90778..df5a9113b34674 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs @@ -39,7 +39,7 @@ protected MemberDescriptor(string name) : this(name, null) /// protected MemberDescriptor(string name, Attribute[] attributes) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -52,7 +52,7 @@ protected MemberDescriptor(string name, Attribute[] attributes) _displayName = name; _nameHash = name.GetHashCode(); - if (attributes != null) + if (attributes is not null) { _attributes = attributes; _attributesFiltered = false; @@ -66,7 +66,7 @@ protected MemberDescriptor(string name, Attribute[] attributes) /// protected MemberDescriptor(MemberDescriptor descr) { - if (descr == null) + if (descr is null) { throw new ArgumentNullException(nameof(descr)); } @@ -90,7 +90,7 @@ protected MemberDescriptor(MemberDescriptor descr) /// protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] newAttributes) { - if (oldMemberDescriptor == null) + if (oldMemberDescriptor is null) { throw new ArgumentNullException(nameof(oldMemberDescriptor)); } @@ -109,7 +109,7 @@ protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] new } } - if (newAttributes != null) + if (newAttributes is not null) { foreach (Attribute o in newAttributes) { @@ -156,7 +156,7 @@ public virtual AttributeCollection Attributes { CheckAttributesValid(); AttributeCollection attrs = _attributeCollection; - if (attrs == null) + if (attrs is null) { lock (_lockCookie) { @@ -254,7 +254,7 @@ public override bool Equals(object obj) { return true; } - if (obj == null) + if (obj is null) { return false; } @@ -273,26 +273,26 @@ public override bool Equals(object obj) return false; } - if ((mdObj._category == null) != (_category == null) || - (_category != null && !mdObj._category.Equals(_category))) + if ((mdObj._category is null) != (_category is null) || + (_category is not null && !mdObj._category.Equals(_category))) { return false; } - if ((mdObj._description == null) != (_description == null) || - (_description != null && !mdObj._description.Equals(_description))) + if ((mdObj._description is null) != (_description is null) || + (_description is not null && !mdObj._description.Equals(_description))) { return false; } - if ((mdObj._attributes == null) != (_attributes == null)) + if ((mdObj._attributes is null) != (_attributes is null)) { return false; } bool sameAttrs = true; - if (_attributes != null) + if (_attributes is not null) { if (_attributes.Length != mdObj._attributes.Length) { @@ -317,12 +317,12 @@ public override bool Equals(object obj) /// protected virtual void FillAttributes(IList attributeList) { - if (attributeList == null) + if (attributeList is null) { throw new ArgumentNullException(nameof(attributeList)); } - if (_originalAttributes != null) + if (_originalAttributes is not null) { foreach (Attribute attr in _originalAttributes) { @@ -359,7 +359,7 @@ private void FilterAttributesIfNeeded() { int savedIndex = -1; object typeId = list[i]?.TypeId; - if (typeId == null) + if (typeId is null) { list.RemoveAt(i); } @@ -400,7 +400,7 @@ protected static MethodInfo FindMethod(Type componentClass, string name, Type[] /// protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType, bool publicOnly) { - if (componentClass == null) + if (componentClass is null) { throw new ArgumentNullException(nameof(componentClass)); } @@ -414,7 +414,7 @@ protected static MethodInfo FindMethod(Type componentClass, string name, Type[] { result = componentClass.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); } - if (result != null && !result.ReturnType.IsEquivalentTo(returnType)) + if (result is not null && !result.ReturnType.IsEquivalentTo(returnType)) { result = null; } @@ -435,12 +435,12 @@ protected static MethodInfo FindMethod(Type componentClass, string name, Type[] /// protected virtual object GetInvocationTarget(Type type, object instance) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -457,12 +457,12 @@ protected virtual object GetInvocationTarget(Type type, object instance) protected static object GetInvokee(Type componentClass, object component) { - if (componentClass == null) + if (componentClass is null) { throw new ArgumentNullException(nameof(componentClass)); } - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs index 735b4799cb5732..df8895a6e12d8f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs @@ -15,7 +15,7 @@ public class MultilineStringConverter : TypeConverter /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs index 21e3b57861c5c5..37ad2f71e3aa38 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs @@ -39,7 +39,7 @@ protected virtual string OwnerName get { string ownerName = null; - if (Owner != null && Owner.Site != null) + if (Owner is not null && Owner.Site is not null) { if (Owner.Site is INestedSite nestedOwnerSite) { @@ -60,7 +60,7 @@ protected virtual string OwnerName /// protected override ISite CreateSite(IComponent component, string name) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } @@ -128,7 +128,7 @@ public bool DesignMode get { IComponent owner = ((NestedContainer)Container).Owner; - if (owner != null && owner.Site != null) + if (owner is not null && owner.Site is not null) { return owner.Site.DesignMode; } @@ -140,11 +140,11 @@ public string FullName { get { - if (_name != null) + if (_name is not null) { string ownerName = ((NestedContainer)Container).OwnerName; string childName = _name; - if (ownerName != null) + if (ownerName is not null) { childName = ownerName + "." + childName; } @@ -162,7 +162,7 @@ public string Name get => _name; set { - if (value == null || _name == null || !value.Equals(_name)) + if (value is null || _name is null || !value.Equals(_name)) { ((NestedContainer)Container).ValidateName(Component, value); _name = value; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs index e5eb919d6eaa30..1f48d9c81e6de8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs @@ -22,7 +22,7 @@ public NullableConverter(Type type) NullableType = type; UnderlyingType = Nullable.GetUnderlyingType(type); - if (UnderlyingType == null) + if (UnderlyingType is null) { throw new ArgumentException(SR.NullableConverterBadCtorArg, nameof(type)); } @@ -40,7 +40,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT { return true; } - else if (UnderlyingTypeConverter != null) + else if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.CanConvertFrom(context, sourceType); } @@ -53,7 +53,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value == null || value.GetType() == UnderlyingType) + if (value is null || value.GetType() == UnderlyingType) { return value; } @@ -61,7 +61,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c { return null; } - else if (UnderlyingTypeConverter != null) + else if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.ConvertFrom(context, culture, value); } @@ -82,7 +82,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati { return true; } - else if (UnderlyingTypeConverter != null) + else if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.CanConvertTo(context, destinationType); } @@ -95,22 +95,22 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == UnderlyingType && value != null && NullableType.IsInstanceOfType(value)) + if (destinationType == UnderlyingType && value is not null && NullableType.IsInstanceOfType(value)) { return value; } else if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ci = NullableType.GetConstructor(new Type[] { UnderlyingType }); - Debug.Assert(ci != null, "Couldn't find constructor"); + Debug.Assert(ci is not null, "Couldn't find constructor"); return new InstanceDescriptor(ci, new object[] { value }, true); } - else if (value == null) + else if (value is null) { // Handle our own nulls here if (destinationType == typeof(string)) @@ -118,7 +118,7 @@ public override object ConvertTo(ITypeDescriptorContext context, System.Globaliz return string.Empty; } } - else if (UnderlyingTypeConverter != null) + else if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.ConvertTo(context, culture, value, destinationType); } @@ -130,7 +130,7 @@ public override object ConvertTo(ITypeDescriptorContext context, System.Globaliz /// public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { object instance = UnderlyingTypeConverter.CreateInstance(context, propertyValues); return instance; @@ -146,7 +146,7 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar /// public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.GetCreateInstanceSupported(context); } @@ -160,7 +160,7 @@ public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) /// public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { object unwrappedValue = value; return UnderlyingTypeConverter.GetProperties(context, unwrappedValue, attributes); @@ -174,7 +174,7 @@ public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContex /// public override bool GetPropertiesSupported(ITypeDescriptorContext context) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.GetPropertiesSupported(context); } @@ -187,10 +187,10 @@ public override bool GetPropertiesSupported(ITypeDescriptorContext context) /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { StandardValuesCollection values = UnderlyingTypeConverter.GetStandardValues(context); - if (GetStandardValuesSupported(context) && values != null) + if (GetStandardValuesSupported(context) && values is not null) { // Create a set of standard values around nullable instances. object[] wrappedValues = new object[values.Count + 1]; @@ -216,7 +216,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.GetStandardValuesExclusive(context); } @@ -230,7 +230,7 @@ public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) /// public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { return UnderlyingTypeConverter.GetStandardValuesSupported(context); } @@ -243,10 +243,10 @@ public override bool GetStandardValuesSupported(ITypeDescriptorContext context) /// public override bool IsValid(ITypeDescriptorContext context, object value) { - if (UnderlyingTypeConverter != null) + if (UnderlyingTypeConverter is not null) { object unwrappedValue = value; - if (unwrappedValue == null) + if (unwrappedValue is null) { return true; // null is valid for nullable. } 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 3f8d7047ad6708..ce72bfc0118980 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs @@ -63,19 +63,19 @@ public virtual TypeConverter Converter // changes it will invalidate our type converter cache. AttributeCollection attrs = Attributes; - if (_converter == null) + if (_converter is null) { TypeConverterAttribute attr = (TypeConverterAttribute)attrs[typeof(TypeConverterAttribute)]; - if (attr.ConverterTypeName != null && attr.ConverterTypeName.Length > 0) + if (attr.ConverterTypeName is not null && attr.ConverterTypeName.Length > 0) { Type converterType = GetTypeFromName(attr.ConverterTypeName); - if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) + if (converterType is not null && typeof(TypeConverter).IsAssignableFrom(converterType)) { _converter = (TypeConverter)CreateInstance(converterType); } } - if (_converter == null) + if (_converter is null) { _converter = TypeDescriptor.GetConverter(PropertyType); } @@ -120,16 +120,16 @@ public DesignerSerializationVisibility SerializationVisibility /// public virtual void AddValueChanged(object component, EventHandler handler) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } - if (handler == null) + if (handler is null) { throw new ArgumentNullException(nameof(handler)); } - if (_valueChangedHandlers == null) + if (_valueChangedHandlers is null) { _valueChangedHandlers = new Hashtable(); } @@ -159,7 +159,7 @@ public override bool Equals(object obj) return true; } - if (obj == null) + if (obj is null) { return false; } @@ -187,7 +187,7 @@ protected object CreateInstance(Type type) { Type[] typeArgs = new Type[] { typeof(Type) }; ConstructorInfo ctor = type.GetConstructor(typeArgs); - if (ctor != null) + if (ctor is not null) { return TypeDescriptor.CreateInstance(null, type, typeArgs, new object[] { PropertyType }); } @@ -223,7 +223,7 @@ protected override void FillAttributes(IList attributeList) /// public virtual PropertyDescriptorCollection GetChildProperties(object instance, Attribute[] filter) { - if (instance == null) + if (instance is null) { return TypeDescriptor.GetProperties(PropertyType, filter); } @@ -246,7 +246,7 @@ public virtual object GetEditor(Type editorBaseType) AttributeCollection attrs = Attributes; // Check the editors we've already created for this type. - if (_editorTypes != null) + if (_editorTypes is not null) { for (int i = 0; i < _editorCount; i++) { @@ -258,7 +258,7 @@ public virtual object GetEditor(Type editorBaseType) } // If one wasn't found, then we must go through the attributes. - if (editor == null) + if (editor is null) { for (int i = 0; i < attrs.Count; i++) { @@ -272,7 +272,7 @@ public virtual object GetEditor(Type editorBaseType) if (editorBaseType == editorType) { Type type = GetTypeFromName(attr.EditorTypeName); - if (type != null) + if (type is not null) { editor = CreateInstance(type); break; @@ -282,13 +282,13 @@ public virtual object GetEditor(Type editorBaseType) // Now, if we failed to find it in our own attributes, go to the // component descriptor. - if (editor == null) + if (editor is null) { editor = TypeDescriptor.GetEditor(PropertyType, editorBaseType); } // Now, another slot in our editor cache for next time - if (_editorTypes == null) + if (_editorTypes is null) { _editorTypes = new Type[5]; _editors = new object[5]; @@ -339,7 +339,7 @@ protected override object GetInvocationTarget(Type type, object instance) /// protected Type GetTypeFromName(string typeName) { - if (typeName == null || typeName.Length == 0) + if (typeName is null || typeName.Length == 0) { return null; } @@ -351,9 +351,9 @@ protected Type GetTypeFromName(string typeName) // in is the same as our Component's assembly, use or Component's assembly instead. This is // because the CLR may have cached an older version if the assembly's version number didn't change Type typeFromComponent = null; - if (ComponentType != null) + if (ComponentType is not null) { - if ((typeFromGetType == null) || + if ((typeFromGetType is null) || (ComponentType.Assembly.FullName.Equals(typeFromGetType.Assembly.FullName))) { int comma = typeName.IndexOf(','); @@ -379,7 +379,7 @@ protected Type GetTypeFromName(string typeName) /// protected virtual void OnValueChanged(object component, EventArgs e) { - if (component != null) + if (component is not null) { ((EventHandler)_valueChangedHandlers?[component])?.Invoke(component, e); } @@ -390,20 +390,20 @@ protected virtual void OnValueChanged(object component, EventArgs e) /// public virtual void RemoveValueChanged(object component, EventHandler handler) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } - if (handler == null) + if (handler is null) { throw new ArgumentNullException(nameof(handler)); } - if (_valueChangedHandlers != null) + if (_valueChangedHandlers is not null) { EventHandler h = (EventHandler)_valueChangedHandlers[component]; h = (EventHandler)Delegate.Remove(h, handler); - if (h != null) + if (h is not null) { _valueChangedHandlers[component] = h; } @@ -421,7 +421,7 @@ public virtual void RemoveValueChanged(object component, EventHandler handler) /// protected internal EventHandler GetValueChangedHandler(object component) { - if (component != null && _valueChangedHandlers != null) + if (component is not null && _valueChangedHandlers is not null) { return (EventHandler)_valueChangedHandlers[component]; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs index 00ec16d76b6e24..eab73364d6af2e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs @@ -35,7 +35,7 @@ public class PropertyDescriptorCollection : ICollection, IList, IDictionary /// public PropertyDescriptorCollection(PropertyDescriptor[] properties) { - if (properties == null) + if (properties is null) { _properties = Array.Empty(); Count = 0; @@ -60,7 +60,7 @@ public PropertyDescriptorCollection(PropertyDescriptor[] properties, bool readOn private PropertyDescriptorCollection(PropertyDescriptor[] properties, int propCount, string[] namedSort, IComparer comparer) { _propsOwned = false; - if (namedSort != null) + if (namedSort is not null) { _namedSort = (string[])namedSort.Clone(); } @@ -132,7 +132,7 @@ private void EnsurePropsOwned() if (!_propsOwned) { _propsOwned = true; - if (_properties != null) + if (_properties is not null) { PropertyDescriptor[] newProps = new PropertyDescriptor[Count]; Array.Copy(_properties, newProps, Count); @@ -178,7 +178,7 @@ public virtual PropertyDescriptor Find(string name, bool ignoreCase) { PropertyDescriptor p = null; - if (_cachedFoundProperties == null || _cachedIgnoreCase != ignoreCase) + if (_cachedFoundProperties is null || _cachedIgnoreCase != ignoreCase) { _cachedIgnoreCase = ignoreCase; if (ignoreCase) @@ -195,7 +195,7 @@ public virtual PropertyDescriptor Find(string name, bool ignoreCase) // object cached = _cachedFoundProperties[name]; - if (cached != null) + if (cached is not null) { return (PropertyDescriptor)cached; } @@ -327,7 +327,7 @@ protected void InternalSort(string[] names) InternalSort(_comparer); - if (names != null && names.Length > 0) + if (names is not null && names.Length > 0) { List propList = new List(_properties); int foundCount = 0; @@ -342,7 +342,7 @@ protected void InternalSort(string[] names) // Found a matching property. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // - if (currentProp != null && currentProp.Name.Equals(names[i])) + if (currentProp is not null && currentProp.Name.Equals(names[i])) { _properties[foundCount++] = currentProp; propList[j] = null; @@ -358,7 +358,7 @@ protected void InternalSort(string[] names) // for (int i = 0; i < propCount; i++) { - if (propList[i] != null) + if (propList[i] is not null) { _properties[foundCount++] = propList[i]; } @@ -373,7 +373,7 @@ protected void InternalSort(string[] names) /// protected void InternalSort(IComparer sorter) { - if (sorter == null) + if (sorter is null) { TypeDescriptor.SortDescriptorArray(this); } @@ -426,7 +426,7 @@ bool IDictionary.Contains(object key) { if (key is string) { - return this[(string)key] != null; + return this[(string)key] is not null; } return false; } @@ -455,7 +455,7 @@ object IDictionary.this[object key] throw new NotSupportedException(); } - if (value != null && !(value is PropertyDescriptor)) + if (value is not null && !(value is PropertyDescriptor)) { throw new ArgumentException(nameof(value)); } @@ -495,7 +495,7 @@ object IDictionary.this[object key] { EnsurePropsOwned(); _properties[index] = (PropertyDescriptor)value; - if (_cachedFoundProperties != null && key is string) + if (_cachedFoundProperties is not null && key is string) { _cachedFoundProperties[key] = value; } @@ -539,7 +539,7 @@ void IDictionary.Remove(object key) if (key is string) { PropertyDescriptor pd = this[(string)key]; - if (pd != null) + if (pd is not null) { ((IList)this).Remove(pd); } @@ -576,7 +576,7 @@ object IList.this[int index] } - if (value != null && !(value is PropertyDescriptor)) + if (value is not null && !(value is PropertyDescriptor)) { throw new ArgumentException(nameof(value)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs index 1499556226f935..bc36bd99e69f9b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs @@ -14,7 +14,7 @@ public sealed class ProvidePropertyAttribute : Attribute /// public ProvidePropertyAttribute(string propertyName, Type receiverType) { - if (receiverType == null) + if (receiverType is null) { throw new ArgumentNullException(nameof(receiverType)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReferenceConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReferenceConverter.cs index 43e9ff92464d20..d95286c3d634f2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReferenceConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReferenceConverter.cs @@ -32,7 +32,7 @@ public ReferenceConverter(Type type) /// public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string) && context != null) + if (sourceType == typeof(string) && context is not null) { return true; } @@ -48,13 +48,13 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c if (value is string text) { text = text.Trim(); - if (!string.Equals(text, s_none) && context != null) + if (!string.Equals(text, s_none) && context is not null) { // Try the reference service first. if (context.GetService(typeof(IReferenceService)) is IReferenceService refSvc) { object obj = refSvc.GetReference(text); - if (obj != null) + if (obj is not null) { return obj; } @@ -62,10 +62,10 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c // Now try IContainer IContainer cont = context.Container; - if (cont != null) + if (cont is not null) { object obj = cont.Components[text]; - if (obj != null) + if (obj is not null) { return obj; } @@ -85,13 +85,13 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (destinationType == typeof(string)) { - if (value != null) + if (value is not null) { // Try the reference service first. if (context?.GetService(typeof(IReferenceService)) is IReferenceService refSvc) { string name = refSvc.GetName(value); - if (name != null) + if (name is not null) { return name; } @@ -102,7 +102,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { ISite site = comp.Site; string name = site?.Name; - if (name != null) + if (name is not null) { return name; } @@ -125,7 +125,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex { List components = null; - if (context != null) + if (context is not null) { components = new List { null }; @@ -133,7 +133,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex if (context.GetService(typeof(IReferenceService)) is IReferenceService refSvc) { object[] objs = refSvc.GetReferences(_type); - if (objs != null) + if (objs is not null) { for (int i = 0; i < objs.Length; i++) { @@ -148,12 +148,12 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex { // Now try IContainer. IContainer cont = context.Container; - if (cont != null) + if (cont is not null) { ComponentCollection objs = cont.Components; foreach (IComponent obj in objs) { - if (obj != null && _type != null && _type.IsInstanceOfType(obj) && IsValueAllowed(context, obj)) + if (obj is not null && _type is not null && _type.IsInstanceOfType(obj) && IsValueAllowed(context, obj)) { components.Add(obj); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectEventDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectEventDescriptor.cs index dcc7fa81d1dfb9..ff023ea684441f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectEventDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectEventDescriptor.cs @@ -71,11 +71,11 @@ internal sealed class ReflectEventDescriptor : EventDescriptor public ReflectEventDescriptor(Type componentClass, string name, Type type, Attribute[] attributes) : base(name, attributes) { - if (componentClass == null) + if (componentClass is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass))); } - if (type == null || !(typeof(Delegate)).IsAssignableFrom(type)) + if (type is null || !(typeof(Delegate)).IsAssignableFrom(type)) { throw new ArgumentException(SR.Format(SR.ErrorInvalidEventType, name)); } @@ -139,18 +139,18 @@ public override void AddEventHandler(object component, Delegate value) { FillMethods(); - if (component != null) + if (component is not null) { ISite site = GetSite(component); IComponentChangeService changeService = null; // Announce that we are about to change this component - if (site != null) + if (site is not null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } - if (changeService != null) + if (changeService is not null) { try { @@ -169,7 +169,7 @@ public override void AddEventHandler(object component, Delegate value) bool shadowed = false; - if (site != null && site.DesignMode) + if (site is not null && site.DesignMode) { // Events are final, so just check the class if (EventType != value.GetType()) @@ -177,7 +177,7 @@ public override void AddEventHandler(object component, Delegate value) throw new ArgumentException(SR.Format(SR.ErrorInvalidEventHandler, Name)); } IDictionaryService dict = (IDictionaryService)site.GetService(typeof(IDictionaryService)); - if (dict != null) + if (dict is not null) { Delegate eventdesc = (Delegate)dict.GetValue(this); eventdesc = Delegate.Combine(eventdesc, value); @@ -215,17 +215,17 @@ protected override void FillAttributes(IList attributes) // supercede existing values. FillMethods(); - Debug.Assert(_componentClass != null, "Must have a component class for FilterAttributes"); - if (_realEvent != null) + Debug.Assert(_componentClass is not null, "Must have a component class for FilterAttributes"); + if (_realEvent is not null) { FillEventInfoAttribute(_realEvent, attributes); } else { - Debug.Assert(_removeMethod != null, $"Null remove method for {Name}"); + Debug.Assert(_removeMethod is not null, $"Null remove method for {Name}"); FillSingleMethodAttribute(_removeMethod, attributes); - Debug.Assert(_addMethod != null, $"Null remove method for {Name}"); + Debug.Assert(_addMethod is not null, $"Null remove method for {Name}"); FillSingleMethodAttribute(_addMethod, attributes); } @@ -239,7 +239,7 @@ private void FillEventInfoAttribute(EventInfo realEventInfo, IList attributes) string eventName = realEventInfo.Name; BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly; Type currentReflectType = realEventInfo.ReflectedType; - Debug.Assert(currentReflectType != null, "currentReflectType cannot be null"); + Debug.Assert(currentReflectType is not null, "currentReflectType cannot be null"); int depth = 0; // First, calculate the depth of the object hierarchy. We do this so we can do a single @@ -262,7 +262,7 @@ private void FillEventInfoAttribute(EventInfo realEventInfo, IList attributes) MemberInfo memberInfo = currentReflectType.GetEvent(eventName, bindingFlags); // Get custom attributes for the member info. - if (memberInfo != null) + if (memberInfo is not null) { attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo); } @@ -275,7 +275,7 @@ private void FillEventInfoAttribute(EventInfo realEventInfo, IList attributes) // from base class to most derived. foreach (Attribute[] attributeArray in attributeStack) { - if (attributeArray != null) + if (attributeArray is not null) { foreach (Attribute attr in attributeArray) { @@ -294,21 +294,21 @@ private void FillMethods() { if (_filledMethods) return; - if (_realEvent != null) + if (_realEvent is not null) { _addMethod = _realEvent.GetAddMethod(); _removeMethod = _realEvent.GetRemoveMethod(); EventInfo defined = null; - if (_addMethod == null || _removeMethod == null) + if (_addMethod is null || _removeMethod is null) { Type start = _componentClass.BaseType; - while (start != null && start != typeof(object)) + while (start is not null && start != typeof(object)) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; EventInfo test = start.GetEvent(_realEvent.Name, bindingFlags); - if (test.GetAddMethod() != null) + if (test.GetAddMethod() is not null) { defined = test; break; @@ -316,7 +316,7 @@ private void FillMethods() } } - if (defined != null) + if (defined is not null) { _addMethod = defined.GetAddMethod(); _removeMethod = defined.GetRemoveMethod(); @@ -331,7 +331,7 @@ private void FillMethods() { // first, try to get the eventInfo... _realEvent = _componentClass.GetEvent(Name); - if (_realEvent != null) + if (_realEvent is not null) { // if we got one, just recurse and return. FillMethods(); @@ -341,7 +341,7 @@ private void FillMethods() Type[] argsType = new Type[] { _type }; _addMethod = FindMethod(_componentClass, "AddOn" + Name, argsType, typeof(void)); _removeMethod = FindMethod(_componentClass, "RemoveOn" + Name, argsType, typeof(void)); - if (_addMethod == null || _removeMethod == null) + if (_addMethod is null || _removeMethod is null) { Debug.Fail($"Missing event accessors for {_componentClass.FullName}. {Name}"); throw new ArgumentException(SR.Format(SR.ErrorMissingEventAccessors, Name)); @@ -356,13 +356,13 @@ private void FillSingleMethodAttribute(MethodInfo realMethodInfo, IList attribut string methodName = realMethodInfo.Name; BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly; Type currentReflectType = realMethodInfo.ReflectedType; - Debug.Assert(currentReflectType != null, "currentReflectType cannot be null"); + Debug.Assert(currentReflectType is not null, "currentReflectType cannot be null"); // First, calculate the depth of the object hierarchy. We do this so we can do a single // object create for an array of attributes. // int depth = 0; - while (currentReflectType != null && currentReflectType != typeof(object)) + while (currentReflectType is not null && currentReflectType != typeof(object)) { depth++; currentReflectType = currentReflectType.BaseType; @@ -375,13 +375,13 @@ private void FillSingleMethodAttribute(MethodInfo realMethodInfo, IList attribut currentReflectType = realMethodInfo.ReflectedType; Attribute[][] attributeStack = new Attribute[depth][]; - while (currentReflectType != null && currentReflectType != typeof(object)) + while (currentReflectType is not null && currentReflectType != typeof(object)) { // Fill in our member info so we can get at the custom attributes. MemberInfo memberInfo = currentReflectType.GetMethod(methodName, bindingFlags); // Get custom attributes for the member info. - if (memberInfo != null) + if (memberInfo is not null) { attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo); } @@ -394,7 +394,7 @@ private void FillSingleMethodAttribute(MethodInfo realMethodInfo, IList attribut // from base class to most derived. foreach (Attribute[] attributeArray in attributeStack) { - if (attributeArray != null) + if (attributeArray is not null) { foreach (Attribute attr in attributeArray) { @@ -413,18 +413,18 @@ public override void RemoveEventHandler(object component, Delegate value) { FillMethods(); - if (component != null) + if (component is not null) { ISite site = GetSite(component); IComponentChangeService changeService = null; // Announce that we are about to change this component - if (site != null) + if (site is not null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } - if (changeService != null) + if (changeService is not null) { try { @@ -443,10 +443,10 @@ public override void RemoveEventHandler(object component, Delegate value) bool shadowed = false; - if (site != null && site.DesignMode) + if (site is not null && site.DesignMode) { IDictionaryService dict = (IDictionaryService)site.GetService(typeof(IDictionaryService)); - if (dict != null) + if (dict is not null) { Delegate del = (Delegate)dict.GetValue(this); del = Delegate.Remove(del, value); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs index 1b55a0f17e9435..81dc6e60307313 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs @@ -82,14 +82,14 @@ public ReflectPropertyDescriptor(Type componentClass, string name, Type type, At try { - if (type == null) + if (type is null) { - Debug.WriteLine($"type == null, name == {name}"); + Debug.WriteLine($"type is null, name == {name}"); throw new ArgumentException(SR.Format(SR.ErrorInvalidPropertyType, name)); } - if (componentClass == null) + if (componentClass is null) { - Debug.WriteLine($"componentClass == null, name == {name}"); + Debug.WriteLine($"componentClass is null, name == {name}"); throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass))); } _type = type; @@ -111,7 +111,7 @@ public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Pr _propInfo = propInfo; _getMethod = getMethod; _setMethod = setMethod; - if (getMethod != null && propInfo != null && setMethod == null) + if (getMethod is not null && propInfo is not null && setMethod is null) _state.DangerousSet(s_bitGetQueried | s_bitSetOnDemand, true); else _state.DangerousSet(s_bitGetQueried | s_bitSetQueried, true); @@ -138,7 +138,7 @@ public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldRefl _componentClass = componentClass; _type = oldReflectPropertyDescriptor.PropertyType; - if (componentClass == null) + if (componentClass is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass))); } @@ -163,7 +163,7 @@ public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldRefl // if the caller has provided an new default value attribute. If so, use it. Otherwise, // just let it be and it will be picked up on demand. // - if (attributes != null) + if (attributes is not null) { foreach (Attribute a in attributes) { @@ -171,7 +171,7 @@ public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldRefl { _defaultValue = dva.Value; // Default values for enums are often stored as their underlying integer type: - if (_defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == _defaultValue.GetType()) + if (_defaultValue is not null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == _defaultValue.GetType()) { _defaultValue = Enum.ToObject(PropertyType, _defaultValue); } @@ -198,7 +198,7 @@ private object AmbientValue if (!_state[s_bitAmbientValueQueried]) { Attribute a = Attributes[typeof(AmbientValueAttribute)]; - if (a != null) + if (a is not null) { _ambientValue = ((AmbientValueAttribute)a).Value; } @@ -265,11 +265,11 @@ private object DefaultValue if (!_state[s_bitDefaultValueQueried]) { Attribute a = Attributes[typeof(DefaultValueAttribute)]; - if (a != null) + if (a is not null) { // Default values for enums are often stored as their underlying integer type: object defaultValue = ((DefaultValueAttribute)a).Value; - bool storedAsUnderlyingType = defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType(); + bool storedAsUnderlyingType = defaultValue is not null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType(); _defaultValue = storedAsUnderlyingType ? Enum.ToObject(PropertyType, _defaultValue) : defaultValue; @@ -293,18 +293,18 @@ private MethodInfo GetMethodValue { if (!_state[s_bitGetQueried]) { - if (_receiverType == null) + if (_receiverType is null) { - if (_propInfo == null) + if (_propInfo is null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; _propInfo = _componentClass.GetProperty(Name, bindingFlags, binder: null, PropertyType, Array.Empty(), Array.Empty()); } - if (_propInfo != null) + if (_propInfo is not null) { _getMethod = _propInfo.GetGetMethod(nonPublic: true); } - if (_getMethod == null) + if (_getMethod is null) { throw new InvalidOperationException(SR.Format(SR.ErrorMissingPropertyAccessors, _componentClass.FullName + "." + Name)); } @@ -312,7 +312,7 @@ private MethodInfo GetMethodValue else { _getMethod = FindMethod(_componentClass, "Get" + Name, new Type[] { _receiverType }, _type); - if (_getMethod == null) + if (_getMethod is null) { throw new ArgumentException(SR.Format(SR.ErrorMissingPropertyAccessors, Name)); } @@ -326,12 +326,12 @@ private MethodInfo GetMethodValue /// /// Determines if this property is an extender property. /// - private bool IsExtender => (_receiverType != null); + private bool IsExtender => (_receiverType is not null); /// /// Indicates whether this property is read only. /// - public override bool IsReadOnly => SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; + public override bool IsReadOnly => SetMethodValue is null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; /// /// Retrieves the type of the property. @@ -349,7 +349,7 @@ private MethodInfo ResetMethodValue { Type[] args; - if (_receiverType == null) + if (_receiverType is null) { args = Array.Empty(); } @@ -377,16 +377,16 @@ private MethodInfo SetMethodValue { string name = _propInfo.Name; - if (_setMethod == null) + if (_setMethod is null) { - for (Type t = ComponentType.BaseType; t != null && t != typeof(object); t = t.BaseType) + for (Type t = ComponentType.BaseType; t is not null && t != typeof(object); t = t.BaseType) { BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; PropertyInfo p = t.GetProperty(name, bindingFlags, binder: null, PropertyType, Array.Empty(), null); - if (p != null) + if (p is not null) { _setMethod = p.GetSetMethod(nonPublic: false); - if (_setMethod != null) + if (_setMethod is not null) { break; } @@ -398,14 +398,14 @@ private MethodInfo SetMethodValue } if (!_state[s_bitSetQueried]) { - if (_receiverType == null) + if (_receiverType is null) { - if (_propInfo == null) + if (_propInfo is null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; _propInfo = _componentClass.GetProperty(Name, bindingFlags, binder: null, PropertyType, Array.Empty(), Array.Empty()); } - if (_propInfo != null) + if (_propInfo is not null) { _setMethod = _propInfo.GetSetMethod(nonPublic: true); } @@ -433,7 +433,7 @@ private MethodInfo ShouldSerializeMethodValue { Type[] args; - if (_receiverType == null) + if (_receiverType is null) { args = Array.Empty(); } @@ -454,18 +454,18 @@ private MethodInfo ShouldSerializeMethodValue /// public override void AddValueChanged(object component, EventHandler handler) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } - if (handler == null) + if (handler is null) { throw new ArgumentNullException(nameof(handler)); } // If there's an event called Changed, hook the caller's handler directly up to that on the component EventDescriptor changedEvent = ChangedEventValue; - if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) + if (changedEvent is not null && changedEvent.EventType.IsInstanceOfType(handler)) { changedEvent.AddEventHandler(component, handler); } @@ -475,7 +475,7 @@ public override void AddValueChanged(object component, EventHandler handler) { // Special case: If this will be the FIRST handler added for this component, and the component implements // INotifyPropertyChanged, the property descriptor must START listening to the generic PropertyChanged event - if (GetValueChangedHandler(component) == null) + if (GetValueChangedHandler(component) is null) { EventDescriptor iPropChangedEvent = IPropChangedEventValue; iPropChangedEvent?.AddEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged)); @@ -493,10 +493,10 @@ internal bool ExtenderCanResetValue(IExtenderProvider provider, object component } MethodInfo reset = ResetMethodValue; - if (reset != null) + if (reset is not null) { MethodInfo shouldSerialize = ShouldSerializeMethodValue; - if (shouldSerialize != null) + if (shouldSerialize is not null) { try { @@ -517,7 +517,7 @@ internal bool ExtenderCanResetValue(IExtenderProvider provider, object component internal object ExtenderGetValue(IExtenderProvider provider, object component) { - if (provider != null) + if (provider is not null) { provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); return GetMethodValue.Invoke(provider, new object[] { component }); @@ -535,7 +535,7 @@ internal void ExtenderResetValue(IExtenderProvider provider, object component, P { ExtenderSetValue(provider, component, AmbientValue, notifyDesc); } - else if (ResetMethodValue != null) + else if (ResetMethodValue is not null) { ISite site = GetSite(component); IComponentChangeService changeService = null; @@ -543,13 +543,13 @@ internal void ExtenderResetValue(IExtenderProvider provider, object component, P object newValue; // Announce that we are about to change this component - if (site != null) + if (site is not null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events - if (changeService != null) + if (changeService is not null) { oldValue = ExtenderGetValue(provider, component); try @@ -567,12 +567,12 @@ internal void ExtenderResetValue(IExtenderProvider provider, object component, P } provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); - if (ResetMethodValue != null) + if (ResetMethodValue is not null) { ResetMethodValue.Invoke(provider, new object[] { component }); // Now notify the change service that the change was successful. - if (changeService != null) + if (changeService is not null) { newValue = ExtenderGetValue(provider, component); changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue); @@ -583,20 +583,20 @@ internal void ExtenderResetValue(IExtenderProvider provider, object component, P internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc) { - if (provider != null) + if (provider is not null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; // Announce that we are about to change this component - if (site != null) + if (site is not null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events - if (changeService != null) + if (changeService is not null) { oldValue = ExtenderGetValue(provider, component); try @@ -615,7 +615,7 @@ internal void ExtenderSetValue(IExtenderProvider provider, object component, obj provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); - if (SetMethodValue != null) + if (SetMethodValue is not null) { SetMethodValue.Invoke(provider, new object[] { component, value }); @@ -631,7 +631,7 @@ internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object co if (IsReadOnly) { - if (ShouldSerializeMethodValue != null) + if (ShouldSerializeMethodValue is not null) { try { @@ -643,7 +643,7 @@ internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object co } else if (DefaultValue == s_noValue) { - if (ShouldSerializeMethodValue != null) + if (ShouldSerializeMethodValue is not null) { try { @@ -676,9 +676,9 @@ public override bool CanResetValue(object component) return !Equals(GetValue(component), DefaultValue); } - if (ResetMethodValue != null) + if (ResetMethodValue is not null) { - if (ShouldSerializeMethodValue != null) + if (ShouldSerializeMethodValue is not null) { component = GetInvocationTarget(_componentClass, component); try @@ -700,7 +700,7 @@ public override bool CanResetValue(object component) protected override void FillAttributes(IList attributes) { - Debug.Assert(_componentClass != null, "Must have a component class for FillAttributes"); + Debug.Assert(_componentClass is not null, "Must have a component class for FillAttributes"); // // The order that we fill in attributes is critical. The list of attributes will be @@ -742,7 +742,7 @@ protected override void FillAttributes(IList attributes) // First, calculate the depth of the object hierarchy. We do this so we can do a single // object create for an array of attributes. - while (currentReflectType != null && currentReflectType != typeof(object)) + while (currentReflectType is not null && currentReflectType != typeof(object)) { depth++; currentReflectType = currentReflectType.BaseType; @@ -754,7 +754,7 @@ protected override void FillAttributes(IList attributes) currentReflectType = _componentClass; Attribute[][] attributeStack = new Attribute[depth][]; - while (currentReflectType != null && currentReflectType != typeof(object)) + while (currentReflectType is not null && currentReflectType != typeof(object)) { MemberInfo memberInfo = null; @@ -771,7 +771,7 @@ protected override void FillAttributes(IList attributes) } // Get custom attributes for the member info. - if (memberInfo != null) + if (memberInfo is not null) { attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo); } @@ -783,7 +783,7 @@ protected override void FillAttributes(IList attributes) // Look in the attribute stack for AttributeProviders foreach (Attribute[] attributeArray in attributeStack) { - if (attributeArray != null) + if (attributeArray is not null) { foreach (Attribute attr in attributeArray) { @@ -791,14 +791,14 @@ protected override void FillAttributes(IList attributes) { Type specificType = Type.GetType(sta.TypeName); - if (specificType != null) + if (specificType is not null) { Attribute[] stAttrs = null; if (!string.IsNullOrEmpty(sta.PropertyName)) { MemberInfo[] milist = specificType.GetMember(sta.PropertyName); - if (milist.Length > 0 && milist[0] != null) + if (milist.Length > 0 && milist[0] is not null) { stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(milist[0]); } @@ -807,7 +807,7 @@ protected override void FillAttributes(IList attributes) { stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(specificType); } - if (stAttrs != null) + if (stAttrs is not null) { foreach (Attribute stAttr in stAttrs) { @@ -824,7 +824,7 @@ protected override void FillAttributes(IList attributes) // from base class to most derived. foreach (Attribute[] attributeArray in attributeStack) { - if (attributeArray != null) + if (attributeArray is not null) { foreach (Attribute attr in attributeArray) { @@ -839,7 +839,7 @@ protected override void FillAttributes(IList attributes) base.FillAttributes(attributes); // Finally, override any form of ReadOnlyAttribute. - if (SetMethodValue == null) + if (SetMethodValue is null) { attributes.Add(ReadOnlyAttribute.Yes); } @@ -860,9 +860,9 @@ public override object GetValue(object component) return null; } - Debug.Assert(component != null, "GetValue must be given a component"); + Debug.Assert(component is not null, "GetValue must be given a component"); - if (component != null) + if (component is not null) { component = GetInvocationTarget(_componentClass, component); @@ -876,12 +876,12 @@ public override object GetValue(object component) string name = null; IComponent comp = component as IComponent; ISite site = comp?.Site; - if (site?.Name != null) + if (site?.Name is not null) { name = site.Name; } - if (name == null) + if (name is null) { name = component.GetType().FullName; } @@ -919,7 +919,7 @@ internal void OnINotifyPropertyChanged(object component, PropertyChangedEventArg /// protected override void OnValueChanged(object component, EventArgs e) { - if (_state[s_bitChangedQueried] && _realChangedEvent == null) + if (_state[s_bitChangedQueried] && _realChangedEvent is null) { base.OnValueChanged(component, e); } @@ -930,11 +930,11 @@ protected override void OnValueChanged(object component, EventArgs e) /// public override void RemoveValueChanged(object component, EventHandler handler) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } - if (handler == null) + if (handler is null) { throw new ArgumentNullException(nameof(handler)); } @@ -942,7 +942,7 @@ public override void RemoveValueChanged(object component, EventHandler handler) // If there's an event called Changed, we hooked the caller's // handler directly up to that on the component, so remove it now. EventDescriptor changedEvent = ChangedEventValue; - if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) + if (changedEvent is not null && changedEvent.EventType.IsInstanceOfType(handler)) { changedEvent.RemoveEventHandler(component, handler); } @@ -955,7 +955,7 @@ public override void RemoveValueChanged(object component, EventHandler handler) // Special case: If that was the LAST handler removed for this component, and the component implements // INotifyPropertyChanged, the property descriptor must STOP listening to the generic PropertyChanged event - if (GetValueChangedHandler(component) == null) + if (GetValueChangedHandler(component) is null) { EventDescriptor iPropChangedEvent = IPropChangedEventValue; iPropChangedEvent?.RemoveEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged)); @@ -983,7 +983,7 @@ public override void ResetValue(object component) { SetValue(component, AmbientValue); } - else if (ResetMethodValue != null) + else if (ResetMethodValue is not null) { ISite site = GetSite(component); IComponentChangeService changeService = null; @@ -991,13 +991,13 @@ public override void ResetValue(object component) object newValue; // Announce that we are about to change this component - if (site != null) + if (site is not null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events - if (changeService != null) + if (changeService is not null) { // invokee might be a type from mscorlib or system, GetMethodValue might return a NonPublic method oldValue = GetMethodValue.Invoke(invokee, null); @@ -1015,12 +1015,12 @@ public override void ResetValue(object component) } } - if (ResetMethodValue != null) + if (ResetMethodValue is not null) { ResetMethodValue.Invoke(invokee, null); // Now notify the change service that the change was successful. - if (changeService != null) + if (changeService is not null) { newValue = GetMethodValue.Invoke(invokee, null); changeService.OnComponentChanged(component, this, oldValue, newValue); @@ -1041,7 +1041,7 @@ public override void SetValue(object component, object value) { Debug.WriteLine($"[{Name}]: SetValue({component?.GetType().Name ?? "(null)"}, {value?.GetType().Name ?? "(null)"})"); - if (component != null) + if (component is not null) { ISite site = GetSite(component); object oldValue = null; @@ -1053,13 +1053,13 @@ public override void SetValue(object component, object value) IComponentChangeService changeService = null; // Announce that we are about to change this component - if (site != null) + if (site is not null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events - if (changeService != null) + if (changeService is not null) { oldValue = GetMethodValue.Invoke(invokee, null); try @@ -1094,7 +1094,7 @@ public override void SetValue(object component, object value) // ==> Becomes inner exception of TargetInvocationException // ==> caught here - if (t is TargetInvocationException && t.InnerException != null) + if (t is TargetInvocationException && t.InnerException is not null) { // Propagate the original exception up throw t.InnerException; @@ -1131,7 +1131,7 @@ public override bool ShouldSerializeValue(object component) if (IsReadOnly) { - if (ShouldSerializeMethodValue != null) + if (ShouldSerializeMethodValue is not null) { try { @@ -1143,7 +1143,7 @@ public override bool ShouldSerializeValue(object component) } else if (DefaultValue == s_noValue) { - if (ShouldSerializeMethodValue != null) + if (ShouldSerializeMethodValue is not null) { try { @@ -1162,6 +1162,6 @@ public override bool ShouldSerializeValue(object component) /// from direct calls made to PropertyDescriptor.SetValue (value=false). For example, the component may /// implement the INotifyPropertyChanged interface, or may have an explicit '{name}Changed' event for this property. /// - public override bool SupportsChangeEvents => IPropChangedEventValue != null || ChangedEventValue != null; + public override bool SupportsChangeEvents => IPropChangedEventValue is not null || ChangedEventValue is not null; } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs index 70c8024c825e06..8868ddfc97dd2a 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs @@ -35,7 +35,7 @@ internal ReflectedTypeData(Type type) /// This method returns true if the data cache in this reflection /// type descriptor has data in it. /// - internal bool IsPopulated => (_attributes != null) | (_events != null) | (_properties != null); + internal bool IsPopulated => (_attributes is not null) | (_events is not null) | (_properties is not null); /// /// Retrieves custom attributes. @@ -45,7 +45,7 @@ internal AttributeCollection GetAttributes() // Worst case collision scenario: we don't want the perf hit // of taking a lock, so if we collide we will query for // attributes twice. Not a big deal. - if (_attributes == null) + if (_attributes is null) { // Obtaining attributes follows a very critical order: we must take care that // we merge attributes the right way. Consider this: @@ -82,7 +82,7 @@ internal AttributeCollection GetAttributes() Attribute[] attrArray = ReflectGetAttributes(_type); Type baseType = _type.BaseType; - while (baseType != null && baseType != typeof(object)) + while (baseType is not null && baseType != typeof(object)) { Attribute[] baseArray = ReflectGetAttributes(baseType); Attribute[] temp = new Attribute[attrArray.Length + baseArray.Length]; @@ -160,7 +160,7 @@ internal string GetComponentName(object instance) { IComponent comp = instance as IComponent; ISite site = comp?.Site; - if (site != null) + if (site is not null) { INestedSite nestedSite = site as INestedSite; return (nestedSite?.FullName) ?? site.Name; @@ -183,14 +183,14 @@ internal TypeConverter GetConverter(object instance) // we then search on the same attribute based on type. If the two don't match, then // we cannot cache the value and must re-create every time. It is rare for a designer // to override these attributes, so we want to be smart here. - if (instance != null) + if (instance is not null) { typeAttr = (TypeConverterAttribute)TypeDescriptor.GetAttributes(_type)[typeof(TypeConverterAttribute)]; TypeConverterAttribute instanceAttr = (TypeConverterAttribute)TypeDescriptor.GetAttributes(instance)[typeof(TypeConverterAttribute)]; if (typeAttr != instanceAttr) { Type converterType = GetTypeFromName(instanceAttr.ConverterTypeName); - if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) + if (converterType is not null && typeof(TypeConverter).IsAssignableFrom(converterType)) { return (TypeConverter)ReflectTypeDescriptionProvider.CreateInstance(converterType, _type); } @@ -198,28 +198,28 @@ internal TypeConverter GetConverter(object instance) } // If we got here, we return our type-based converter. - if (_converter == null) + if (_converter is null) { - if (typeAttr == null) + if (typeAttr is null) { typeAttr = (TypeConverterAttribute)TypeDescriptor.GetAttributes(_type)[typeof(TypeConverterAttribute)]; } - if (typeAttr != null) + if (typeAttr is not null) { Type converterType = GetTypeFromName(typeAttr.ConverterTypeName); - if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) + if (converterType is not null && typeof(TypeConverter).IsAssignableFrom(converterType)) { _converter = (TypeConverter)CreateInstance(converterType, _type); } } - if (_converter == null) + if (_converter is null) { // We did not get a converter. Traverse up the base class chain until // we find one in the stock hashtable. _converter = GetIntrinsicTypeConverter(_type); - Debug.Assert(_converter != null, "There is no intrinsic setup in the hashtable for the Object type"); + Debug.Assert(_converter is not null, "There is no intrinsic setup in the hashtable for the Object type"); } } @@ -234,7 +234,7 @@ internal EventDescriptor GetDefaultEvent(object instance) { AttributeCollection attributes; - if (instance != null) + if (instance is not null) { attributes = TypeDescriptor.GetAttributes(instance); } @@ -244,9 +244,9 @@ internal EventDescriptor GetDefaultEvent(object instance) } DefaultEventAttribute attr = (DefaultEventAttribute)attributes[typeof(DefaultEventAttribute)]; - if (attr != null && attr.Name != null) + if (attr is not null && attr.Name is not null) { - if (instance != null) + if (instance is not null) { return TypeDescriptor.GetEvents(instance)[attr.Name]; } @@ -266,7 +266,7 @@ internal PropertyDescriptor GetDefaultProperty(object instance) { AttributeCollection attributes; - if (instance != null) + if (instance is not null) { attributes = TypeDescriptor.GetAttributes(instance); } @@ -276,9 +276,9 @@ internal PropertyDescriptor GetDefaultProperty(object instance) } DefaultPropertyAttribute attr = (DefaultPropertyAttribute)attributes[typeof(DefaultPropertyAttribute)]; - if (attr != null && attr.Name != null) + if (attr is not null && attr.Name is not null) { - if (instance != null) + if (instance is not null) { return TypeDescriptor.GetProperties(instance)[attr.Name]; } @@ -303,14 +303,14 @@ internal object GetEditor(object instance, Type editorBaseType) // we then search on the same attribute based on type. If the two don't match, then // we cannot cache the value and must re-create every time. It is rare for a designer // to override these attributes, so we want to be smart here. - if (instance != null) + if (instance is not null) { typeAttr = GetEditorAttribute(TypeDescriptor.GetAttributes(_type), editorBaseType); EditorAttribute instanceAttr = GetEditorAttribute(TypeDescriptor.GetAttributes(instance), editorBaseType); if (typeAttr != instanceAttr) { Type editorType = GetTypeFromName(instanceAttr.EditorTypeName); - if (editorType != null && editorBaseType.IsAssignableFrom(editorType)) + if (editorType is not null && editorBaseType.IsAssignableFrom(editorType)) { return CreateInstance(editorType, _type); } @@ -333,45 +333,45 @@ internal object GetEditor(object instance, Type editorBaseType) object editor = null; typeAttr = GetEditorAttribute(TypeDescriptor.GetAttributes(_type), editorBaseType); - if (typeAttr != null) + if (typeAttr is not null) { Type editorType = GetTypeFromName(typeAttr.EditorTypeName); - if (editorType != null && editorBaseType.IsAssignableFrom(editorType)) + if (editorType is not null && editorBaseType.IsAssignableFrom(editorType)) { editor = CreateInstance(editorType, _type); } } // Editor is not in the attributes. Search intrinsic tables. - if (editor == null) + if (editor is null) { Hashtable intrinsicEditors = GetEditorTable(editorBaseType); - if (intrinsicEditors != null) + if (intrinsicEditors is not null) { editor = GetIntrinsicTypeEditor(intrinsicEditors, _type); } // As a quick sanity check, check to see that the editor we got back is of // the correct type. - if (editor != null && !editorBaseType.IsInstanceOfType(editor)) + if (editor is not null && !editorBaseType.IsInstanceOfType(editor)) { Debug.Fail($"Editor {editor.GetType().FullName} is not an instance of {editorBaseType.FullName} but it is in that base types table."); editor = null; } } - if (editor != null) + if (editor is not null) { lock (this) { - if (_editorTypes == null || _editorTypes.Length == _editorCount) + if (_editorTypes is null || _editorTypes.Length == _editorCount) { - int newLength = (_editorTypes == null ? 4 : _editorTypes.Length * 2); + int newLength = (_editorTypes is null ? 4 : _editorTypes.Length * 2); Type[] newTypes = new Type[newLength]; object[] newEditors = new object[newLength]; - if (_editorTypes != null) + if (_editorTypes is not null) { _editorTypes.CopyTo(newTypes, 0); _editors.CopyTo(newEditors, 0); @@ -400,7 +400,7 @@ private static EditorAttribute GetEditorAttribute(AttributeCollection attributes { Type attrEditorBaseType = Type.GetType(edAttr.EditorBaseTypeName); - if (attrEditorBaseType != null && attrEditorBaseType == editorBaseType) + if (attrEditorBaseType is not null && attrEditorBaseType == editorBaseType) { return edAttr; } @@ -419,7 +419,7 @@ internal EventDescriptorCollection GetEvents() // of taking a lock, so if we collide we will query for // events twice. Not a big deal. // - if (_events == null) + if (_events is null) { EventDescriptor[] eventArray; Dictionary eventList = new Dictionary(16); @@ -435,7 +435,7 @@ internal EventDescriptorCollection GetEvents() } baseType = baseType.BaseType; } - while (baseType != null && baseType != objType); + while (baseType is not null && baseType != objType); eventArray = new EventDescriptor[eventList.Count]; eventList.Values.CopyTo(eventArray, 0); @@ -453,7 +453,7 @@ internal PropertyDescriptorCollection GetProperties() // Worst case collision scenario: we don't want the perf hit // of taking a lock, so if we collide we will query for // properties twice. Not a big deal. - if (_properties == null) + if (_properties is null) { PropertyDescriptor[] propertyArray; Dictionary propertyList = new Dictionary(10); @@ -469,7 +469,7 @@ internal PropertyDescriptorCollection GetProperties() } baseType = baseType.BaseType; } - while (baseType != null && baseType != objType); + while (baseType is not null && baseType != objType); propertyArray = new PropertyDescriptor[propertyList.Count]; propertyList.Values.CopyTo(propertyArray, 0); @@ -499,12 +499,12 @@ private Type GetTypeFromName(string typeName) t = _type.Assembly.GetType(typeName); } - if (t == null) + if (t is null) { t = Type.GetType(typeName); } - if (t == null && commaIndex != -1) + if (t is null && commaIndex != -1) { // At design time, it's possible for us to reuse // an assembly but add new types. The app domain diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index ff4cd113da6f0c..c8f5acca96c8c9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -194,12 +194,12 @@ private static Dictionary IntrinsicTypeConve /// internal static void AddEditorTable(Type editorBaseType, Hashtable table) { - if (editorBaseType == null) + if (editorBaseType is null) { throw new ArgumentNullException(nameof(editorBaseType)); } - if (table == null) + if (table is null) { Debug.Fail("COMPAT: Editor table should not be null"); // don't throw; RTM didn't so we can't do it either. @@ -220,22 +220,22 @@ internal static void AddEditorTable(Type editorBaseType, Hashtable table) /// public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { - Debug.Assert(objectType != null, "Should have arg-checked before coming in here"); + Debug.Assert(objectType is not null, "Should have arg-checked before coming in here"); object obj = null; - if (argTypes != null) + if (argTypes is not null) { obj = objectType.GetConstructor(argTypes)?.Invoke(args); } else { - if (args != null) + if (args is not null) { argTypes = new Type[args.Length]; for (int idx = 0; idx < args.Length; idx++) { - if (args[idx] != null) + if (args[idx] is not null) { argTypes[idx] = args[idx].GetType(); } @@ -283,13 +283,13 @@ internal AttributeCollection GetAttributes(Type type) public override IDictionary GetCache(object instance) { IComponent comp = instance as IComponent; - if (comp != null && comp.Site != null) + if (comp is not null && comp.Site is not null) { IDictionaryService ds = comp.Site.GetService(typeof(IDictionaryService)) as IDictionaryService; - if (ds != null) + if (ds is not null) { IDictionary dict = ds.GetValue(s_dictionaryKey) as IDictionary; - if (dict == null) + if (dict is null) { dict = new Hashtable(); ds.SetValue(s_dictionaryKey, dict); @@ -366,7 +366,7 @@ private static Hashtable GetEditorTable(Type editorBaseType) Hashtable editorTables = EditorTables; object table = editorTables[editorBaseType]; - if (table == null) + if (table is null) { // Before we give up, it is possible that the // class initializer for editorBaseType hasn't @@ -379,12 +379,12 @@ private static Hashtable GetEditorTable(Type editorBaseType) // sentinel in there so we don't // go through this again. // - if (table == null) + if (table is null) { lock (s_internalSyncObject) { table = editorTables[editorBaseType]; - if (table == null) + if (table is null) { editorTables[editorBaseType] = editorTables; } @@ -512,12 +512,12 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) // PropertyDescriptorCollection properties = null; - if (cache != null) + if (cache is not null) { properties = cache[s_extenderPropertiesKey] as PropertyDescriptorCollection; } - if (properties != null) + if (properties is not null) { return properties; } @@ -531,7 +531,7 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) { PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]); - if (propertyList == null) + if (propertyList is null) { propertyList = new List(propertyArray.Length * extenders.Length); } @@ -541,11 +541,11 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) PropertyDescriptor prop = propertyArray[propIdx]; ExtenderProvidedPropertyAttribute eppa = prop.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; - Debug.Assert(eppa != null, $"Extender property {prop.Name} has no provider attribute. We will skip it."); - if (eppa != null) + Debug.Assert(eppa is not null, $"Extender property {prop.Name} has no provider attribute. We will skip it."); + if (eppa is not null) { Type receiverType = eppa.ReceiverType; - if (receiverType != null) + if (receiverType is not null) { if (receiverType.IsAssignableFrom(componentType)) { @@ -559,7 +559,7 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) // propertyHash now contains ExtendedPropertyDescriptor objects // for each extended property. // - if (propertyList != null) + if (propertyList is not null) { PropertyDescriptor[] fullArray = new PropertyDescriptor[propertyList.Count]; propertyList.CopyTo(fullArray, 0); @@ -570,7 +570,7 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) properties = PropertyDescriptorCollection.Empty; } - if (cache != null) + if (cache is not null) { cache[s_extenderPropertiesKey] = properties; } @@ -580,18 +580,18 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } IComponent component = instance as IComponent; - if (component != null && component.Site != null) + if (component is not null && component.Site is not null) { IExtenderListService extenderList = component.Site.GetService(typeof(IExtenderListService)) as IExtenderListService; IDictionary cache = TypeDescriptor.GetCache(instance); - if (extenderList != null) + if (extenderList is not null) { return GetExtenders(extenderList.GetExtenderProviders(), instance, cache); } @@ -599,7 +599,7 @@ protected internal override IExtenderProvider[] GetExtenderProviders(object inst else { IContainer cont = component.Site.Container; - if (cont != null) + if (cont is not null) { return GetExtenders(cont.Components, instance, cache); } @@ -636,12 +636,12 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i // time a component is asked for its properties. IExtenderProvider[] currentExtenders = components as IExtenderProvider[]; - if (cache != null) + if (cache is not null) { existingExtenders = cache[ExtenderProviderKey] as IExtenderProvider[]; } - if (existingExtenders == null) + if (existingExtenders is null) { newExtenders = true; } @@ -649,7 +649,7 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i int curIdx = 0; int idx = 0; - if (currentExtenders != null) + if (currentExtenders is not null) { for (curIdx = 0; curIdx < currentExtenders.Length; curIdx++) { @@ -666,12 +666,12 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i } } } - else if (components != null) + else if (components is not null) { foreach (object obj in components) { IExtenderProvider prov = obj as IExtenderProvider; - if (prov != null && prov.CanExtend(instance)) + if (prov is not null && prov.CanExtend(instance)) { extenderCount++; if (curIdx < maxCanExtendResults) @@ -684,20 +684,20 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i curIdx++; } } - if (existingExtenders != null && extenderCount != existingExtenders.Length) + if (existingExtenders is not null && extenderCount != existingExtenders.Length) { newExtenders = true; } if (newExtenders) { - if (currentExtenders == null || extenderCount != currentExtenders.Length) + if (currentExtenders is null || extenderCount != currentExtenders.Length) { IExtenderProvider[] newExtenderArray = new IExtenderProvider[extenderCount]; curIdx = 0; idx = 0; - if (currentExtenders != null && extenderCount > 0) + if (currentExtenders is not null && extenderCount > 0) { while (curIdx < currentExtenders.Length) { @@ -717,7 +717,7 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i { IExtenderProvider p = component as IExtenderProvider; - if (p != null && ((curIdx < maxCanExtendResults && (canExtend & ((ulong)1 << curIdx)) != 0) || + if (p is not null && ((curIdx < maxCanExtendResults && (canExtend & ((ulong)1 << curIdx)) != 0) || (curIdx >= maxCanExtendResults && p.CanExtend(instance)))) { Debug.Assert(idx < extenderCount, "There are more extenders than we expect"); @@ -730,7 +730,7 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i currentExtenders = newExtenderArray; } - if (cache != null) + if (cache is not null) { cache[ExtenderProviderKey] = currentExtenders; cache.Remove(s_extenderPropertiesKey); @@ -775,7 +775,7 @@ public override string GetFullComponentName(object component) { IComponent comp = component as IComponent; INestedSite ns = comp?.Site as INestedSite; - if (ns != null) + if (ns is not null) { return ns.FullName; } @@ -831,7 +831,7 @@ internal object GetPropertyOwner(Type type, object instance, PropertyDescriptor /// public override Type GetReflectionType(Type objectType, object instance) { - Debug.Assert(objectType != null, "Should have arg-checked before coming in here"); + Debug.Assert(objectType is not null, "Should have arg-checked before coming in here"); return objectType; } @@ -844,10 +844,10 @@ private ReflectedTypeData GetTypeData(Type type, bool createIfNeeded) { ReflectedTypeData td = null; - if (_typeData != null) + if (_typeData is not null) { td = (ReflectedTypeData)_typeData[type]; - if (td != null) + if (td is not null) { return td; } @@ -855,15 +855,15 @@ private ReflectedTypeData GetTypeData(Type type, bool createIfNeeded) lock (s_internalSyncObject) { - if (_typeData != null) + if (_typeData is not null) { td = (ReflectedTypeData)_typeData[type]; } - if (td == null && createIfNeeded) + if (td is null && createIfNeeded) { td = new ReflectedTypeData(type); - if (_typeData == null) + if (_typeData is null) { _typeData = new Hashtable(); } @@ -895,7 +895,7 @@ private static Type GetTypeFromName(string typeName) { Type t = Type.GetType(typeName); - if (t == null) + if (t is null) { int commaIndex = typeName.IndexOf(','); @@ -924,7 +924,7 @@ private static Type GetTypeFromName(string typeName) internal bool IsPopulated(Type type) { ReflectedTypeData td = GetTypeData(type, false); - if (td != null) + if (td is not null) { return td.IsPopulated; } @@ -942,7 +942,7 @@ internal static Attribute[] ReflectGetAttributes(Type type) { Hashtable attributeCache = AttributeCache; Attribute[] attrs = (Attribute[])attributeCache[type]; - if (attrs != null) + if (attrs is not null) { return attrs; } @@ -950,7 +950,7 @@ internal static Attribute[] ReflectGetAttributes(Type type) lock (s_internalSyncObject) { attrs = (Attribute[])attributeCache[type]; - if (attrs == null) + if (attrs is null) { // Get the type's attributes. // @@ -970,7 +970,7 @@ internal static Attribute[] ReflectGetAttributes(MemberInfo member) { Hashtable attributeCache = AttributeCache; Attribute[] attrs = (Attribute[])attributeCache[member]; - if (attrs != null) + if (attrs is not null) { return attrs; } @@ -978,7 +978,7 @@ internal static Attribute[] ReflectGetAttributes(MemberInfo member) lock (s_internalSyncObject) { attrs = (Attribute[])attributeCache[member]; - if (attrs == null) + if (attrs is null) { // Get the member's attributes. // @@ -998,7 +998,7 @@ private static EventDescriptor[] ReflectGetEvents(Type type) { Hashtable eventCache = EventCache; EventDescriptor[] events = (EventDescriptor[])eventCache[type]; - if (events != null) + if (events is not null) { return events; } @@ -1006,7 +1006,7 @@ private static EventDescriptor[] ReflectGetEvents(Type type) lock (s_internalSyncObject) { events = (EventDescriptor[])eventCache[type]; - if (events == null) + if (events is null) { BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; @@ -1034,7 +1034,7 @@ private static EventDescriptor[] ReflectGetEvents(Type type) continue; } - if (eventInfo.AddMethod != null && eventInfo.RemoveMethod != null) + if (eventInfo.AddMethod is not null && eventInfo.RemoveMethod is not null) { events[eventCount++] = new ReflectEventDescriptor(type, eventInfo); } @@ -1050,7 +1050,7 @@ private static EventDescriptor[] ReflectGetEvents(Type type) #if DEBUG foreach (EventDescriptor dbgEvent in events) { - Debug.Assert(dbgEvent != null, "Holes in event array for type " + type); + Debug.Assert(dbgEvent is not null, "Holes in event array for type " + type); } #endif eventCache[type] = events; @@ -1081,10 +1081,10 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid IDictionary cache = TypeDescriptor.GetCache(provider); PropertyDescriptor[] properties; - if (cache != null) + if (cache is not null) { properties = cache[s_extenderProviderPropertiesKey] as PropertyDescriptor[]; - if (properties != null) + if (properties is not null) { return properties; } @@ -1097,7 +1097,7 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid Type providerType = provider.GetType(); Hashtable extendedPropertyCache = ExtendedPropertyCache; ReflectPropertyDescriptor[] extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType]; - if (extendedProperties == null) + if (extendedProperties is null) { lock (s_internalSyncObject) { @@ -1106,7 +1106,7 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid // Our class-based property store failed as well, so we need to build up the set of // extended properties here. // - if (extendedProperties == null) + if (extendedProperties is null) { AttributeCollection attributes = TypeDescriptor.GetAttributes(providerType); List extendedList = new List(attributes.Count); @@ -1115,19 +1115,19 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid { ProvidePropertyAttribute provideAttr = attr as ProvidePropertyAttribute; - if (provideAttr != null) + if (provideAttr is not null) { Type receiverType = GetTypeFromName(provideAttr.ReceiverTypeName); - if (receiverType != null) + if (receiverType is not null) { MethodInfo getMethod = providerType.GetMethod("Get" + provideAttr.PropertyName, new Type[] { receiverType }); - if (getMethod != null && !getMethod.IsStatic && getMethod.IsPublic) + if (getMethod is not null && !getMethod.IsStatic && getMethod.IsPublic) { MethodInfo setMethod = providerType.GetMethod("Set" + provideAttr.PropertyName, new Type[] { receiverType, getMethod.ReturnType }); - if (setMethod != null && (setMethod.IsStatic || !setMethod.IsPublic)) + if (setMethod is not null && (setMethod.IsStatic || !setMethod.IsPublic)) { setMethod = null; } @@ -1156,7 +1156,7 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid properties[idx] = new ExtendedPropertyDescriptor(rpd, rpd.ExtenderGetReceiverType(), provider, null); } - if (cache != null) + if (cache is not null) { cache[s_extenderProviderPropertiesKey] = properties; } @@ -1172,7 +1172,7 @@ private static PropertyDescriptor[] ReflectGetProperties(Type type) { Hashtable propertyCache = PropertyCache; PropertyDescriptor[] properties = (PropertyDescriptor[])propertyCache[type]; - if (properties != null) + if (properties is not null) { return properties; } @@ -1181,7 +1181,7 @@ private static PropertyDescriptor[] ReflectGetProperties(Type type) { properties = (PropertyDescriptor[])propertyCache[type]; - if (properties == null) + if (properties is null) { BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; @@ -1220,7 +1220,7 @@ private static PropertyDescriptor[] ReflectGetProperties(Type type) // If a property had at least a get method, we consider it. We don't // consider write-only properties. // - if (getMethod != null) + if (getMethod is not null) { properties[propertyCount++] = new ReflectPropertyDescriptor(type, name, propertyInfo.PropertyType, @@ -1236,7 +1236,7 @@ private static PropertyDescriptor[] ReflectGetProperties(Type type) properties = newProperties; } - Debug.Assert(!properties.Any(dbgProp => dbgProp == null), $"Holes in property array for type {type}"); + Debug.Assert(!properties.Any(dbgProp => dbgProp is null), $"Holes in property array for type {type}"); propertyCache[type] = properties; } @@ -1277,7 +1277,7 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) lock (table) { Type baseType = callingType; - while (baseType != null && baseType != typeof(object)) + while (baseType is not null && baseType != typeof(object)) { hashEntry = table[baseType]; @@ -1285,16 +1285,16 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) // resolve it. // string typeString = hashEntry as string; - if (typeString != null) + if (typeString is not null) { hashEntry = Type.GetType(typeString); - if (hashEntry != null) + if (hashEntry is not null) { table[baseType] = hashEntry; } } - if (hashEntry != null) + if (hashEntry is not null) { break; } @@ -1305,7 +1305,7 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) // Now make a scan through each value in the table, looking for interfaces. // If we find one, see if the object implements the interface. // - if (hashEntry == null) + if (hashEntry is null) { // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = table.GetEnumerator(); @@ -1314,21 +1314,21 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) DictionaryEntry de = e.Entry; Type keyType = de.Key as Type; - if (keyType != null && keyType.IsInterface && keyType.IsAssignableFrom(callingType)) + if (keyType is not null && keyType.IsInterface && keyType.IsAssignableFrom(callingType)) { hashEntry = de.Value; string typeString = hashEntry as string; - if (typeString != null) + if (typeString is not null) { hashEntry = Type.GetType(typeString); - if (hashEntry != null) + if (hashEntry is not null) { table[callingType] = hashEntry; } } - if (hashEntry != null) + if (hashEntry is not null) { break; } @@ -1338,7 +1338,7 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) // Special case converters // - if (hashEntry == null) + if (hashEntry is null) { if (callingType.IsGenericType && callingType.GetGenericTypeDefinition() == typeof(Nullable<>)) { @@ -1356,7 +1356,7 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) // Interfaces do not derive from object, so we // must handle the case of no hash entry here. // - if (hashEntry == null) + if (hashEntry is null) { hashEntry = table[typeof(object)]; } @@ -1368,10 +1368,10 @@ private static object GetIntrinsicTypeEditor(Hashtable table, Type callingType) // Type type = hashEntry as Type; - if (type != null) + if (type is not null) { hashEntry = CreateInstance(type, callingType); - if (type.GetConstructor(s_typeConstructor) == null) + if (type.GetConstructor(s_typeConstructor) is null) { table[callingType] = hashEntry; } @@ -1427,7 +1427,7 @@ private static TypeConverter GetIntrinsicTypeConverter(Type callingType) Type key = null; Type baseType = callingType.BaseType; - while (baseType != null && baseType != typeof(object)) + while (baseType is not null && baseType != typeof(object)) { if (baseType == typeof(Uri) || baseType == typeof(CultureInfo)) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs index e5933b100bd2e7..8ff5ab92d60c8a 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs @@ -29,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c { return (string)value; } - if (value == null) + if (value is null) { return string.Empty; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs index 89f6c5235c5b46..3301be9ec6d8f0 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs @@ -16,7 +16,7 @@ public static class SyntaxCheck /// public static bool CheckMachineName(string value) { - if (value == null) + if (value is null) return false; value = value.Trim(); @@ -32,7 +32,7 @@ public static bool CheckMachineName(string value) /// public static bool CheckPath(string value) { - if (value == null) + if (value is null) return false; value = value.TrimStart(); @@ -49,7 +49,7 @@ public static bool CheckPath(string value) /// public static bool CheckRootedPath(string value) { - if (value == null) + if (value is null) return false; value = value.Trim(); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs index 8b7a63387a5f1c..2f34ac606bb74e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs @@ -54,7 +54,7 @@ public ToolboxItemAttribute(string toolboxItemTypeName) /// public ToolboxItemAttribute(Type toolboxItemType) { - if (toolboxItemType == null) + if (toolboxItemType is null) { throw new ArgumentNullException(nameof(toolboxItemType)); } @@ -70,9 +70,9 @@ public Type ToolboxItemType { get { - if (_toolboxItemType == null) + if (_toolboxItemType is null) { - if (_toolboxItemTypeName != null) + if (_toolboxItemTypeName is not null) { try { @@ -102,7 +102,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - if (_toolboxItemTypeName != null) + if (_toolboxItemTypeName is not null) { return _toolboxItemTypeName.GetHashCode(); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs index 09e8cb13e275b2..d975618151bd53 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs @@ -110,19 +110,19 @@ public object ConvertTo(object value, Type destinationType) /// public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { - if (value == null) + if (value is null) { return string.Empty; } - if (culture != null && culture != CultureInfo.CurrentCulture) + if (culture is not null && culture != CultureInfo.CurrentCulture) { if (value is IFormattable formattable) { @@ -192,7 +192,7 @@ public object CreateInstance(IDictionary propertyValues) /// protected Exception GetConvertFromException(object value) { - string valueTypeName = value == null ? SR.Null : value.GetType().FullName; + string valueTypeName = value is null ? SR.Null : value.GetType().FullName; throw new NotSupportedException(SR.Format(SR.ConvertFromException, GetType().Name, valueTypeName)); } @@ -202,7 +202,7 @@ protected Exception GetConvertFromException(object value) /// protected Exception GetConvertToException(object value, Type destinationType) { - string valueTypeName = value == null ? SR.Null : value.GetType().FullName; + string valueTypeName = value is null ? SR.Null : value.GetType().FullName; throw new NotSupportedException(SR.Format(SR.ConvertToException, GetType().Name, valueTypeName, destinationType.FullName)); } @@ -309,7 +309,7 @@ public virtual bool IsValid(ITypeDescriptorContext context, object value) // Because null doesn't have a type, so we couldn't pass this to CanConvertFrom. // Meanwhile, we couldn't silence null value here, such as type converter like // NullableConverter would consider null value as a valid value. - if (value == null || CanConvertFrom(context, value.GetType())) + if (value is null || CanConvertFrom(context, value.GetType())) { ConvertFrom(context, CultureInfo.InvariantCulture, value); } @@ -377,7 +377,7 @@ protected SimplePropertyDescriptor(Type componentType, string name, Type propert public override bool CanResetValue(object component) { DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; - if (attr == null) + if (attr is null) { return false; } @@ -391,7 +391,7 @@ public override bool CanResetValue(object component) public override void ResetValue(object component) { DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; - if (attr != null) + if (attr is not null) { SetValue(component, attr.Value); } @@ -418,7 +418,7 @@ public class StandardValuesCollection : ICollection /// public StandardValuesCollection(ICollection values) { - if (values == null) + if (values is null) { values = Array.Empty(); } @@ -440,7 +440,7 @@ public int Count { get { - if (_valueArray != null) + if (_valueArray is not null) { return _valueArray.Length; } @@ -458,7 +458,7 @@ public object this[int index] { get { - if (_valueArray != null) + if (_valueArray is not null) { return _valueArray.GetValue(index); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs index 565bc42e68f0af..36f71703a5ea26 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs @@ -53,12 +53,12 @@ protected TypeDescriptionProvider(TypeDescriptionProvider parent) [UnsupportedOSPlatform("browser")] public virtual object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { - if (_parent != null) + if (_parent is not null) { return _parent.CreateInstance(provider, objectType, argTypes, args); } - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } @@ -95,7 +95,7 @@ public virtual object CreateInstance(IServiceProvider provider, Type objectType, /// public virtual ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { - if (_parent != null) + if (_parent is not null) { return _parent.GetExtendedTypeDescriptor(instance); } @@ -105,12 +105,12 @@ public virtual ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) protected internal virtual IExtenderProvider[] GetExtenderProviders(object instance) { - if (_parent != null) + if (_parent is not null) { return _parent.GetExtenderProviders(instance); } - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -129,7 +129,7 @@ protected internal virtual IExtenderProvider[] GetExtenderProviders(object insta /// public virtual string GetFullComponentName(object component) { - if (_parent != null) + if (_parent is not null) { return _parent.GetFullComponentName(component); } @@ -155,7 +155,7 @@ public virtual string GetFullComponentName(object component) /// public Type GetReflectionType(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -174,7 +174,7 @@ public Type GetReflectionType(object instance) /// public virtual Type GetReflectionType(Type objectType, object instance) { - if (_parent != null) + if (_parent is not null) { return _parent.GetReflectionType(objectType, instance); } @@ -190,12 +190,12 @@ public virtual Type GetReflectionType(Type objectType, object instance) /// public virtual Type GetRuntimeType(Type reflectionType) { - if (_parent != null) + if (_parent is not null) { return _parent.GetRuntimeType(reflectionType); } - if (reflectionType == null) + if (reflectionType is null) { throw new ArgumentNullException(nameof(reflectionType)); } @@ -231,7 +231,7 @@ public ICustomTypeDescriptor GetTypeDescriptor(Type objectType) /// public ICustomTypeDescriptor GetTypeDescriptor(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -255,7 +255,7 @@ public ICustomTypeDescriptor GetTypeDescriptor(object instance) /// public virtual ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { - if (_parent != null) + if (_parent is not null) { return _parent.GetTypeDescriptor(objectType, instance); } @@ -269,12 +269,12 @@ public virtual ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object i /// public virtual bool IsSupportedType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (_parent != null) + if (_parent is not null) { return _parent.IsSupportedType(type); } 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 a542eb25d86ac6..18359d6d834614 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -114,12 +114,12 @@ public static Type InterfaceType [EditorBrowsable(EditorBrowsableState.Advanced)] public static TypeDescriptionProvider AddAttributes(Type type, params Attribute[] attributes) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (attributes == null) + if (attributes is null) { throw new ArgumentNullException(nameof(attributes)); } @@ -143,12 +143,12 @@ public static TypeDescriptionProvider AddAttributes(Type type, params Attribute[ [EditorBrowsable(EditorBrowsableState.Advanced)] public static TypeDescriptionProvider AddAttributes(object instance, params Attribute[] attributes) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } - if (attributes == null) + if (attributes is null) { throw new ArgumentNullException(nameof(attributes)); } @@ -183,12 +183,12 @@ public static void AddEditorTable(Type editorBaseType, Hashtable table) [EditorBrowsable(EditorBrowsableState.Advanced)] public static void AddProvider(TypeDescriptionProvider provider, Type type) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -216,12 +216,12 @@ public static void AddProvider(TypeDescriptionProvider provider, Type type) [EditorBrowsable(EditorBrowsableState.Advanced)] public static void AddProvider(TypeDescriptionProvider provider, object instance) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -256,12 +256,12 @@ public static void AddProvider(TypeDescriptionProvider provider, object instance [EditorBrowsable(EditorBrowsableState.Advanced)] public static void AddProviderTransparent(TypeDescriptionProvider provider, Type type) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -279,12 +279,12 @@ public static void AddProviderTransparent(TypeDescriptionProvider provider, Type [EditorBrowsable(EditorBrowsableState.Advanced)] public static void AddProviderTransparent(TypeDescriptionProvider provider, object instance) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -329,7 +329,7 @@ private static void CheckDefaultProvider(Type type) { TypeDescriptionProviderAttribute pa = (TypeDescriptionProviderAttribute)attrs[idx]; Type providerType = Type.GetType(pa.TypeName); - if (providerType != null && typeof(TypeDescriptionProvider).IsAssignableFrom(providerType)) + if (providerType is not null && typeof(TypeDescriptionProvider).IsAssignableFrom(providerType)) { TypeDescriptionProvider prov = (TypeDescriptionProvider)Activator.CreateInstance(providerType); AddProvider(prov, type); @@ -341,7 +341,7 @@ private static void CheckDefaultProvider(Type type) if (!providerAdded) { Type baseType = type.BaseType; - if (baseType != null && baseType != type) + if (baseType is not null && baseType != type) { CheckDefaultProvider(baseType); } @@ -359,12 +359,12 @@ private static void CheckDefaultProvider(Type type) [EditorBrowsable(EditorBrowsableState.Advanced)] public static void CreateAssociation(object primary, object secondary) { - if (primary == null) + if (primary is null) { throw new ArgumentNullException(nameof(primary)); } - if (secondary == null) + if (secondary is null) { throw new ArgumentNullException(nameof(secondary)); } @@ -377,12 +377,12 @@ public static void CreateAssociation(object primary, object secondary) WeakHashtable associationTable = AssociationTable; IList associations = (IList)associationTable[primary]; - if (associations == null) + if (associations is null) { lock (associationTable) { associations = (IList)associationTable[primary]; - if (associations == null) + if (associations is null) { associations = new ArrayList(4); associationTable.SetWeak(primary, associations); @@ -432,14 +432,14 @@ public static EventDescriptor CreateEvent(Type componentType, EventDescriptor ol [UnsupportedOSPlatform("browser")] public static object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } - if (argTypes != null) + if (argTypes is not null) { - if (args == null) + if (args is null) { throw new ArgumentNullException(nameof(args)); } @@ -528,7 +528,7 @@ private static ArrayList FilterMembers(IList members, Attribute[] attributes) // We have to hide. If this is the first time, we need to init // newMembers to have all the valid members we have previously // hit. - if (newMembers == null) + if (newMembers is null) { newMembers = new ArrayList(memberCount); for (int validIdx = 0; validIdx < idx; validIdx++) @@ -553,12 +553,12 @@ private static ArrayList FilterMembers(IList members, Attribute[] attributes) [EditorBrowsable(EditorBrowsableState.Advanced)] public static object GetAssociation(Type type, object primary) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (primary == null) + if (primary is null) { throw new ArgumentNullException(nameof(primary)); } @@ -570,7 +570,7 @@ public static object GetAssociation(Type type, object primary) // Check our association table for a match. Hashtable assocTable = AssociationTable; IList associations = (IList)assocTable?[primary]; - if (associations != null) + if (associations is not null) { lock (associations) { @@ -580,7 +580,7 @@ public static object GetAssociation(Type type, object primary) // matches the given type. WeakReference weakRef = (WeakReference)associations[idx]; object secondary = weakRef.Target; - if (secondary == null) + if (secondary is null) { associations.RemoveAt(idx); } @@ -597,14 +597,14 @@ public static object GetAssociation(Type type, object primary) if (associatedObject == primary) { IComponent component = primary as IComponent; - if (component != null) + if (component is not null) { ISite site = component.Site; - if (site != null && site.DesignMode) + if (site is not null && site.DesignMode) { IDesignerHost host = site.GetService(typeof(IDesignerHost)) as IDesignerHost; - if (host != null) + if (host is not null) { object designer = host.GetDesigner(component); @@ -612,7 +612,7 @@ public static object GetAssociation(Type type, object primary) // got here, we're probably hosed because the user just passed in // an object that this PropertyDescriptor can't munch on, but it's // clearer to use that object instance instead of it's designer. - if (designer != null && type.IsInstanceOfType(designer)) + if (designer is not null && type.IsInstanceOfType(designer)) { associatedObject = designer; } @@ -630,7 +630,7 @@ public static object GetAssociation(Type type, object primary) /// public static AttributeCollection GetAttributes(Type componentType) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new AttributeCollection((Attribute[])null); @@ -654,7 +654,7 @@ public static AttributeCollection GetAttributes(object component) [EditorBrowsable(EditorBrowsableState.Advanced)] public static AttributeCollection GetAttributes(object component, bool noCustomTypeDesc) { - if (component == null) + if (component is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new AttributeCollection(null); @@ -696,7 +696,7 @@ public static AttributeCollection GetAttributes(object component, bool noCustomT if (noCustomTypeDesc) { ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component); - if (extDesc != null) + if (extDesc is not null) { ICollection extResults = extDesc.GetAttributes(); results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, component, null); @@ -714,7 +714,7 @@ public static AttributeCollection GetAttributes(object component, bool noCustomT results = PipelineInitialize(PIPELINE_ATTRIBUTES, results, cache); ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component); - if (extDesc != null) + if (extDesc is not null) { ICollection extResults = extDesc.GetAttributes(); results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, component, cache); @@ -808,7 +808,7 @@ private static object ConvertFromInvariantString(Type type, string stringValue) /// public static EventDescriptor GetDefaultEvent(Type componentType) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning null, but you should not pass null here"); return null; @@ -828,7 +828,7 @@ public static EventDescriptor GetDefaultEvent(Type componentType) [EditorBrowsable(EditorBrowsableState.Advanced)] public static EventDescriptor GetDefaultEvent(object component, bool noCustomTypeDesc) { - if (component == null) + if (component is null) { Debug.Fail("COMPAT: Returning null, but you should not pass null here"); return null; @@ -842,7 +842,7 @@ public static EventDescriptor GetDefaultEvent(object component, bool noCustomTyp /// public static PropertyDescriptor GetDefaultProperty(Type componentType) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return null; @@ -862,7 +862,7 @@ public static PropertyDescriptor GetDefaultProperty(Type componentType) [EditorBrowsable(EditorBrowsableState.Advanced)] public static PropertyDescriptor GetDefaultProperty(object component, bool noCustomTypeDesc) { - if (component == null) + if (component is null) { Debug.Fail("COMPAT: Returning null, but you should not pass null here"); return null; @@ -877,7 +877,7 @@ public static PropertyDescriptor GetDefaultProperty(object component, bool noCus /// internal static ICustomTypeDescriptor GetDescriptor(Type type, string typeName) { - if (type == null) + if (type is null) { throw new ArgumentNullException(typeName); } @@ -893,14 +893,14 @@ internal static ICustomTypeDescriptor GetDescriptor(Type type, string typeName) /// internal static ICustomTypeDescriptor GetDescriptor(object component, bool noCustomTypeDesc) { - if (component == null) + if (component is null) { throw new ArgumentException(nameof(component)); } ICustomTypeDescriptor desc = NodeFor(component).GetTypeDescriptor(component); ICustomTypeDescriptor d = component as ICustomTypeDescriptor; - if (!noCustomTypeDesc && d != null) + if (!noCustomTypeDesc && d is not null) { desc = new MergedTypeDescriptor(d, desc); } @@ -913,7 +913,7 @@ internal static ICustomTypeDescriptor GetDescriptor(object component, bool noCus /// internal static ICustomTypeDescriptor GetExtendedDescriptor(object component) { - if (component == null) + if (component is null) { throw new ArgumentException(nameof(component)); } @@ -937,7 +937,7 @@ public static object GetEditor(object component, Type editorBaseType) [EditorBrowsable(EditorBrowsableState.Advanced)] public static object GetEditor(object component, Type editorBaseType, bool noCustomTypeDesc) { - if (editorBaseType == null) + if (editorBaseType is null) { throw new ArgumentNullException(nameof(editorBaseType)); } @@ -950,7 +950,7 @@ public static object GetEditor(object component, Type editorBaseType, bool noCus /// public static object GetEditor(Type type, Type editorBaseType) { - if (editorBaseType == null) + if (editorBaseType is null) { throw new ArgumentNullException(nameof(editorBaseType)); } @@ -963,7 +963,7 @@ public static object GetEditor(Type type, Type editorBaseType) /// public static EventDescriptorCollection GetEvents(Type componentType) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new EventDescriptorCollection(null, true); @@ -978,7 +978,7 @@ public static EventDescriptorCollection GetEvents(Type componentType) /// public static EventDescriptorCollection GetEvents(Type componentType, Attribute[] attributes) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new EventDescriptorCollection(null, true); @@ -986,10 +986,10 @@ public static EventDescriptorCollection GetEvents(Type componentType, Attribute[ EventDescriptorCollection events = GetDescriptor(componentType, nameof(componentType)).GetEvents(attributes); - if (attributes != null && attributes.Length > 0) + if (attributes is not null && attributes.Length > 0) { ArrayList filteredEvents = FilterMembers(events, attributes); - if (filteredEvents != null) + if (filteredEvents is not null) { events = new EventDescriptorCollection((EventDescriptor[])filteredEvents.ToArray(typeof(EventDescriptor)), true); } @@ -1031,7 +1031,7 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[] [EditorBrowsable(EditorBrowsableState.Advanced)] public static EventDescriptorCollection GetEvents(object component, Attribute[] attributes, bool noCustomTypeDesc) { - if (component == null) + if (component is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new EventDescriptorCollection(null, true); @@ -1074,7 +1074,7 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[] if (noCustomTypeDesc) { ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component); - if (extDesc != null) + if (extDesc is not null) { ICollection extResults = extDesc.GetEvents(attributes); results = PipelineMerge(PIPELINE_EVENTS, results, extResults, component, null); @@ -1092,7 +1092,7 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[] results = typeDesc.GetEvents(attributes); results = PipelineInitialize(PIPELINE_EVENTS, results, cache); ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component); - if (extDesc != null) + if (extDesc is not null) { ICollection extResults = extDesc.GetEvents(attributes); results = PipelineMerge(PIPELINE_EVENTS, results, extResults, component, cache); @@ -1127,16 +1127,16 @@ private static string GetExtenderCollisionSuffix(MemberDescriptor member) ExtenderProvidedPropertyAttribute exAttr = member.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; IExtenderProvider prov = exAttr?.Provider; - if (prov != null) + if (prov is not null) { string name = null; - if (prov is IComponent component && component.Site != null) + if (prov is IComponent component && component.Site is not null) { name = component.Site.Name; } - if (name == null || name.Length == 0) + if (name is null || name.Length == 0) { int ci = System.Threading.Interlocked.Increment(ref s_collisionIndex) - 1; name = ci.ToString(CultureInfo.InvariantCulture); @@ -1156,7 +1156,7 @@ private static string GetExtenderCollisionSuffix(MemberDescriptor member) /// public static string GetFullComponentName(object component) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } @@ -1182,7 +1182,7 @@ private static Type GetNodeForBaseType(Type searchType) /// public static PropertyDescriptorCollection GetProperties(Type componentType) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new PropertyDescriptorCollection(null, true); @@ -1197,7 +1197,7 @@ public static PropertyDescriptorCollection GetProperties(Type componentType) /// public static PropertyDescriptorCollection GetProperties(Type componentType, Attribute[] attributes) { - if (componentType == null) + if (componentType is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new PropertyDescriptorCollection(null, true); @@ -1205,10 +1205,10 @@ public static PropertyDescriptorCollection GetProperties(Type componentType, Att PropertyDescriptorCollection properties = GetDescriptor(componentType, nameof(componentType)).GetProperties(attributes); - if (attributes != null && attributes.Length > 0) + if (attributes is not null && attributes.Length > 0) { ArrayList filteredProperties = FilterMembers(properties, attributes); - if (filteredProperties != null) + if (filteredProperties is not null) { properties = new PropertyDescriptorCollection((PropertyDescriptor[])filteredProperties.ToArray(typeof(PropertyDescriptor)), true); } @@ -1261,7 +1261,7 @@ public static PropertyDescriptorCollection GetProperties(object component, Attri /// private static PropertyDescriptorCollection GetPropertiesImpl(object component, Attribute[] attributes, bool noCustomTypeDesc, bool noAttributes) { - if (component == null) + if (component is null) { Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here"); return new PropertyDescriptorCollection(null, true); @@ -1304,7 +1304,7 @@ private static PropertyDescriptorCollection GetPropertiesImpl(object component, if (noCustomTypeDesc) { ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component); - if (extDesc != null) + if (extDesc is not null) { ICollection extResults = noAttributes ? extDesc.GetProperties() : extDesc.GetProperties(attributes); results = PipelineMerge(PIPELINE_PROPERTIES, results, extResults, component, null); @@ -1322,7 +1322,7 @@ private static PropertyDescriptorCollection GetPropertiesImpl(object component, results = noAttributes ? typeDesc.GetProperties() : typeDesc.GetProperties(attributes); results = PipelineInitialize(PIPELINE_PROPERTIES, results, cache); ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component); - if (extDesc != null) + if (extDesc is not null) { ICollection extResults = noAttributes ? extDesc.GetProperties() : extDesc.GetProperties(attributes); results = PipelineMerge(PIPELINE_PROPERTIES, results, extResults, component, cache); @@ -1352,7 +1352,7 @@ private static PropertyDescriptorCollection GetPropertiesImpl(object component, [EditorBrowsable(EditorBrowsableState.Advanced)] public static TypeDescriptionProvider GetProvider(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -1370,7 +1370,7 @@ public static TypeDescriptionProvider GetProvider(Type type) [EditorBrowsable(EditorBrowsableState.Advanced)] public static TypeDescriptionProvider GetProvider(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -1396,7 +1396,7 @@ internal static TypeDescriptionProvider GetProviderRecursive(Type type) [EditorBrowsable(EditorBrowsableState.Advanced)] public static Type GetReflectionType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -1411,7 +1411,7 @@ public static Type GetReflectionType(Type type) [EditorBrowsable(EditorBrowsableState.Advanced)] public static Type GetReflectionType(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -1445,7 +1445,7 @@ public static Type GetReflectionType(object instance) /// private static TypeDescriptionNode NodeFor(Type type, bool createDelegator) { - Debug.Assert(type != null, "Caller should validate"); + Debug.Assert(type is not null, "Caller should validate"); CheckDefaultProvider(type); // First, check our provider type table to see if we have a matching @@ -1457,22 +1457,22 @@ private static TypeDescriptionNode NodeFor(Type type, bool createDelegator) TypeDescriptionNode node = null; Type searchType = type; - while (node == null) + while (node is null) { node = (TypeDescriptionNode)s_providerTypeTable[searchType] ?? (TypeDescriptionNode)s_providerTable[searchType]; - if (node == null) + if (node is null) { Type baseType = GetNodeForBaseType(searchType); - if (searchType == typeof(object) || baseType == null) + if (searchType == typeof(object) || baseType is null) { lock (s_providerTable) { node = (TypeDescriptionNode)s_providerTable[searchType]; - if (node == null) + if (node is null) { // The reflect type description provider is a default provider that // can provide type information for all objects. @@ -1531,10 +1531,10 @@ private static TypeDescriptionNode NodeFor(object instance, bool createDelegator // object it is wrapping. A GC'd object causes WeakReference to return // false for all .Equals, but it always returns a valid hash code. - Debug.Assert(instance != null, "Caller should validate"); + Debug.Assert(instance is not null, "Caller should validate"); TypeDescriptionNode node = (TypeDescriptionNode)s_providerTable[instance]; - if (node == null) + if (node is null) { Type type = instance.GetType(); @@ -1582,19 +1582,19 @@ private static void NodeRemove(object key, TypeDescriptionProvider provider) TypeDescriptionNode target = head; TypeDescriptionNode prev = null; - while (target != null && target.Provider != provider) + while (target is not null && target.Provider != provider) { prev = target; target = target.Next; } - if (target != null) + if (target is not null) { // We have our target node. There are three cases // to consider: the target is in the middle, the head, // or the end. - if (target.Next != null) + if (target.Next is not null) { // If there is a node after the target node, // steal the node's provider and store it @@ -1613,7 +1613,7 @@ private static void NodeRemove(object key, TypeDescriptionProvider provider) // always be at the end of the node list. if (target == head && target.Provider is DelegatingTypeDescriptionProvider) { - Debug.Assert(target.Next == null, "Delegating provider should always be the last provider in the chain."); + Debug.Assert(target.Next is null, "Delegating provider should always be the last provider in the chain."); s_providerTable.Remove(key); } } @@ -1656,7 +1656,7 @@ private static ICollection PipelineAttributeFilter(int pipelineType, ICollection IList list = members as ArrayList; - if (filter == null || filter.Length == 0) + if (filter is null || filter.Length == 0) { return members; } @@ -1666,7 +1666,7 @@ private static ICollection PipelineAttributeFilter(int pipelineType, ICollection // that means something higher in the pipeline has already changed // it so we must recompute anyway. // - if (cache != null && (list == null || list.IsReadOnly)) + if (cache is not null && (list is null || list.IsReadOnly)) { if (cache[s_pipelineAttributeFilterKeys[pipelineType]] is AttributeFilterCacheItem filterCache && filterCache.IsValid(filter)) { @@ -1676,17 +1676,17 @@ private static ICollection PipelineAttributeFilter(int pipelineType, ICollection // Our cache did not contain the correct state, so generate it. // - if (list == null || list.IsReadOnly) + if (list is null || list.IsReadOnly) { list = new ArrayList(members); } ArrayList filterResult = FilterMembers(list, filter); - if (filterResult != null) list = filterResult; + if (filterResult is not null) list = filterResult; // And, if we have a cache, store the updated state into it for future reference. // - if (cache != null) + if (cache is not null) { ICollection cacheValue; @@ -1731,7 +1731,7 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, ITypeDescriptorFilterService componentFilter = null; ISite site = component?.Site; - if (site != null) + if (site is not null) { componentFilter = site.GetService(typeof(ITypeDescriptorFilterService)) as ITypeDescriptorFilterService; } @@ -1740,9 +1740,9 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, // IList list = members as ArrayList; - if (componentFilter == null) + if (componentFilter is null) { - Debug.Assert(cache == null || list == null || !cache.Contains(s_pipelineFilterKeys[pipelineType]), "Earlier pipeline stage should have removed our cache"); + Debug.Assert(cache is null || list is null || !cache.Contains(s_pipelineFilterKeys[pipelineType]), "Earlier pipeline stage should have removed our cache"); return members; } @@ -1751,7 +1751,7 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, // that means something higher in the pipeline has already changed // it so we must recompute anyway. // - if (cache != null && (list == null || list.IsReadOnly)) + if (cache is not null && (list is null || list.IsReadOnly)) { if (cache[s_pipelineFilterKeys[pipelineType]] is FilterCacheItem cacheItem && cacheItem.IsValid(componentFilter)) { @@ -1800,8 +1800,8 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, // have to check. // string suffix = GetExtenderCollisionSuffix(desc); - Debug.Assert(suffix != null, "Name collision with non-extender property."); - if (suffix != null) + Debug.Assert(suffix is not null, "Name collision with non-extender property."); + if (suffix is not null) { filterTable[descName + suffix] = desc; } @@ -1810,7 +1810,7 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, // MemberDescriptor origDesc = (MemberDescriptor)filterTable[descName]; suffix = GetExtenderCollisionSuffix(origDesc); - if (suffix != null) + if (suffix is not null) { filterTable.Remove(descName); filterTable[origDesc.Name + suffix] = origDesc; @@ -1839,7 +1839,7 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, // See if we can re-use the IList that was passed. If we can, // it is more efficient to re-use its slots than to generate new ones. - if (list == null || list.IsReadOnly) + if (list is null || list.IsReadOnly) { list = new ArrayList(filterTable.Values); } @@ -1857,7 +1857,7 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, // so on successive invocations we can simply return. Note that // we always return the IList so that successive stages in the // pipeline can modify it. - if (cacheResults && cache != null) + if (cacheResults && cache is not null) { ICollection cacheValue; @@ -1922,7 +1922,7 @@ private static ICollection PipelineFilter(int pipelineType, ICollection members, /// private static ICollection PipelineInitialize(int pipelineType, ICollection members, IDictionary cache) { - if (cache != null) + if (cache is not null) { bool cacheValid = true; @@ -1963,7 +1963,7 @@ private static ICollection PipelineInitialize(int pipelineType, ICollection memb private static ICollection PipelineMerge(int pipelineType, ICollection primary, ICollection secondary, object instance, IDictionary cache) { // If there is no secondary collection, there is nothing to merge. - if (secondary == null || secondary.Count == 0) + if (secondary is null || secondary.Count == 0) { return primary; } @@ -2019,7 +2019,7 @@ private static ICollection PipelineMerge(int pipelineType, ICollection primary, list.Add(obj); } - if (cache != null) + if (cache is not null) { ICollection cacheValue; @@ -2082,7 +2082,7 @@ private static void RaiseRefresh(Type type) private static void Refresh(object component, bool refreshReflectionProvider) { - if (component == null) + if (component is null) { Debug.Fail("COMPAT: Returning, but you should not pass null here"); return; @@ -2110,16 +2110,16 @@ private static void Refresh(object component, bool refreshReflectionProvider) { DictionaryEntry de = e.Entry; Type nodeType = de.Key as Type; - if (nodeType != null && type.IsAssignableFrom(nodeType) || nodeType == typeof(object)) + if (nodeType is not null && type.IsAssignableFrom(nodeType) || nodeType == typeof(object)) { TypeDescriptionNode node = (TypeDescriptionNode)de.Value; - while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) + while (node is not null && !(node.Provider is ReflectTypeDescriptionProvider)) { found = true; node = node.Next; } - if (node != null) + if (node is not null) { ReflectTypeDescriptionProvider provider = (ReflectTypeDescriptionProvider)node.Provider; if (provider.IsPopulated(type)) @@ -2144,9 +2144,9 @@ private static void Refresh(object component, bool refreshReflectionProvider) // Now, clear any cached data for the instance. IDictionary cache = GetCache(component); - if (found || cache != null) + if (found || cache is not null) { - if (cache != null) + if (cache is not null) { for (int idx = 0; idx < s_pipelineFilterKeys.Length; idx++) { @@ -2169,7 +2169,7 @@ private static void Refresh(object component, bool refreshReflectionProvider) /// public static void Refresh(Type type) { - if (type == null) + if (type is null) { Debug.Fail("COMPAT: Returning, but you should not pass null here"); return; @@ -2194,16 +2194,16 @@ public static void Refresh(Type type) { DictionaryEntry de = e.Entry; Type nodeType = de.Key as Type; - if (nodeType != null && type.IsAssignableFrom(nodeType) || nodeType == typeof(object)) + if (nodeType is not null && type.IsAssignableFrom(nodeType) || nodeType == typeof(object)) { TypeDescriptionNode node = (TypeDescriptionNode)de.Value; - while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) + while (node is not null && !(node.Provider is ReflectTypeDescriptionProvider)) { found = true; node = node.Next; } - if (node != null) + if (node is not null) { ReflectTypeDescriptionProvider provider = (ReflectTypeDescriptionProvider)node.Provider; if (provider.IsPopulated(type)) @@ -2235,7 +2235,7 @@ public static void Refresh(Type type) /// public static void Refresh(Module module) { - if (module == null) + if (module is null) { Debug.Fail("COMPAT: Returning, but you should not pass null here"); return; @@ -2255,12 +2255,12 @@ public static void Refresh(Module module) { DictionaryEntry de = e.Entry; Type nodeType = de.Key as Type; - if (nodeType != null && nodeType.Module.Equals(module) || nodeType == typeof(object)) + if (nodeType is not null && nodeType.Module.Equals(module) || nodeType == typeof(object)) { TypeDescriptionNode node = (TypeDescriptionNode)de.Value; - while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) + while (node is not null && !(node.Provider is ReflectTypeDescriptionProvider)) { - if (refreshedTypes == null) + if (refreshedTypes is null) { refreshedTypes = new Hashtable(); } @@ -2268,7 +2268,7 @@ public static void Refresh(Module module) node = node.Next; } - if (node != null) + if (node is not null) { ReflectTypeDescriptionProvider provider = (ReflectTypeDescriptionProvider)node.Provider; Type[] populatedTypes = provider.GetPopulatedTypes(module); @@ -2276,7 +2276,7 @@ public static void Refresh(Module module) foreach (Type populatedType in populatedTypes) { provider.Refresh(populatedType); - if (refreshedTypes == null) + if (refreshedTypes is null) { refreshedTypes = new Hashtable(); } @@ -2288,7 +2288,7 @@ public static void Refresh(Module module) } // And raise the event if types were refresh and handlers are attached. - if (refreshedTypes != null && Refreshed != null) + if (refreshedTypes is not null && Refreshed is not null) { foreach (Type t in refreshedTypes.Keys) { @@ -2303,7 +2303,7 @@ public static void Refresh(Module module) /// public static void Refresh(Assembly assembly) { - if (assembly == null) + if (assembly is null) { Debug.Fail("COMPAT: Returning, but you should not pass null here"); return; @@ -2332,12 +2332,12 @@ public static IDesigner CreateDesigner(IComponent component, Type designerBaseTy if (attributes[i] is DesignerAttribute designerAttribute) { Type type2 = Type.GetType(designerAttribute.DesignerBaseTypeName); - if (type2 != null && type2 == designerBaseType) + if (type2 is not null && type2 == designerBaseType) { ISite site = component.Site; bool flag = false; ITypeResolutionService typeResolutionService = (ITypeResolutionService)site?.GetService(typeof(ITypeResolutionService)); - if (typeResolutionService != null) + if (typeResolutionService is not null) { flag = true; type = typeResolutionService.GetType(designerAttribute.DesignerTypeName); @@ -2346,14 +2346,14 @@ public static IDesigner CreateDesigner(IComponent component, Type designerBaseTy { type = Type.GetType(designerAttribute.DesignerTypeName); } - if (type != null) + if (type is not null) { break; } } } } - if (type != null) + if (type is not null) { result = (IDesigner)Activator.CreateInstance(type); } @@ -2372,17 +2372,17 @@ public static IComNativeDescriptorHandler ComNativeDescriptorHandler comNativeDescriptionProvider = (typeDescriptionNode.Provider as ComNativeDescriptionProvider); typeDescriptionNode = typeDescriptionNode.Next; } - while (typeDescriptionNode != null && comNativeDescriptionProvider == null); + while (typeDescriptionNode is not null && comNativeDescriptionProvider is null); return comNativeDescriptionProvider?.Handler; } set { TypeDescriptionNode typeDescriptionNode = NodeFor(ComObjectType); - while (typeDescriptionNode != null && !(typeDescriptionNode.Provider is ComNativeDescriptionProvider)) + while (typeDescriptionNode is not null && !(typeDescriptionNode.Provider is ComNativeDescriptionProvider)) { typeDescriptionNode = typeDescriptionNode.Next; } - if (typeDescriptionNode == null) + if (typeDescriptionNode is null) { AddProvider(new ComNativeDescriptionProvider(value), ComObjectType); return; @@ -2398,19 +2398,19 @@ public static IComNativeDescriptorHandler ComNativeDescriptorHandler [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RemoveAssociation(object primary, object secondary) { - if (primary == null) + if (primary is null) { throw new ArgumentNullException(nameof(primary)); } - if (secondary == null) + if (secondary is null) { throw new ArgumentNullException(nameof(secondary)); } Hashtable assocTable = AssociationTable; IList associations = (IList)assocTable?[primary]; - if (associations != null) + if (associations is not null) { lock (associations) { @@ -2420,7 +2420,7 @@ public static void RemoveAssociation(object primary, object secondary) // matches the given type. WeakReference weakRef = (WeakReference)associations[idx]; object secondaryItem = weakRef.Target; - if (secondaryItem == null || secondaryItem == secondary) + if (secondaryItem is null || secondaryItem == secondary) { associations.RemoveAt(idx); } @@ -2435,7 +2435,7 @@ public static void RemoveAssociation(object primary, object secondary) [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RemoveAssociations(object primary) { - if (primary == null) + if (primary is null) { throw new ArgumentNullException(nameof(primary)); } @@ -2453,12 +2453,12 @@ public static void RemoveAssociations(object primary) [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RemoveProvider(TypeDescriptionProvider provider, Type type) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -2477,12 +2477,12 @@ public static void RemoveProvider(TypeDescriptionProvider provider, Type type) [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RemoveProvider(TypeDescriptionProvider provider, object instance) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -2502,12 +2502,12 @@ public static void RemoveProvider(TypeDescriptionProvider provider, object insta [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RemoveProviderTransparent(TypeDescriptionProvider provider, Type type) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -2524,12 +2524,12 @@ public static void RemoveProviderTransparent(TypeDescriptionProvider provider, T [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RemoveProviderTransparent(TypeDescriptionProvider provider, object instance) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -2545,13 +2545,13 @@ public static void RemoveProviderTransparent(TypeDescriptionProvider provider, o /// private static bool ShouldHideMember(MemberDescriptor member, Attribute attribute) { - if (member == null || attribute == null) + if (member is null || attribute is null) { return true; } Attribute memberAttribute = member.Attributes[attribute.GetType()]; - if (memberAttribute == null) + if (memberAttribute is null) { return !attribute.IsDefaultAttribute(); } @@ -2566,7 +2566,7 @@ private static bool ShouldHideMember(MemberDescriptor member, Attribute attribut /// public static void SortDescriptorArray(IList infos) { - if (infos == null) + if (infos is null) { throw new ArgumentNullException(nameof(infos)); } @@ -2598,12 +2598,12 @@ internal ComNativeDescriptionProvider(IComNativeDescriptorHandler handler) /// public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } - if (instance == null) + if (instance is null) { return null; } @@ -2741,7 +2741,7 @@ public override AttributeCollection GetAttributes() for (int idx = 0; idx < newAttrs.Length; idx++) { - Debug.Assert(newAttrs[idx] != null, "_attributes contains a null member"); + Debug.Assert(newAttrs[idx] is not null, "_attributes contains a null member"); // We must see if this attribute is already in the existing // array. If it is, we replace it. @@ -2903,7 +2903,7 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() { AttributeCollection attrs = _primary.GetAttributes() ?? _secondary.GetAttributes(); - Debug.Assert(attrs != null, "Someone should have handled this"); + Debug.Assert(attrs is not null, "Someone should have handled this"); return attrs; } @@ -2914,7 +2914,7 @@ string ICustomTypeDescriptor.GetClassName() { string className = _primary.GetClassName() ?? _secondary.GetClassName(); - Debug.Assert(className != null, "Someone should have handled this"); + Debug.Assert(className is not null, "Someone should have handled this"); return className; } @@ -2933,7 +2933,7 @@ TypeConverter ICustomTypeDescriptor.GetConverter() { TypeConverter converter = _primary.GetConverter() ?? _secondary.GetConverter(); - Debug.Assert(converter != null, "Someone should have handled this"); + Debug.Assert(converter is not null, "Someone should have handled this"); return converter; } @@ -2958,7 +2958,7 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() /// object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { - if (editorBaseType == null) + if (editorBaseType is null) { throw new ArgumentNullException(nameof(editorBaseType)); } @@ -2975,7 +2975,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { EventDescriptorCollection events = _primary.GetEvents() ?? _secondary.GetEvents(); - Debug.Assert(events != null, "Someone should have handled this"); + Debug.Assert(events is not null, "Someone should have handled this"); return events; } @@ -2986,7 +2986,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes { EventDescriptorCollection events = _primary.GetEvents(attributes) ?? _secondary.GetEvents(attributes); - Debug.Assert(events != null, "Someone should have handled this"); + Debug.Assert(events is not null, "Someone should have handled this"); return events; } @@ -2997,7 +2997,7 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { PropertyDescriptorCollection properties = _primary.GetProperties() ?? _secondary.GetProperties(); - Debug.Assert(properties != null, "Someone should have handled this"); + Debug.Assert(properties is not null, "Someone should have handled this"); return properties; } @@ -3007,12 +3007,12 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection properties = _primary.GetProperties(attributes); - if (properties == null) + if (properties is null) { properties = _secondary.GetProperties(attributes); } - Debug.Assert(properties != null, "Someone should have handled this"); + Debug.Assert(properties is not null, "Someone should have handled this"); return properties; } @@ -3053,14 +3053,14 @@ internal TypeDescriptionNode(TypeDescriptionProvider provider) /// public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } - if (argTypes != null) + if (argTypes is not null) { - if (args == null) + if (args is null) { throw new ArgumentNullException(nameof(args)); } @@ -3080,7 +3080,7 @@ public override object CreateInstance(IServiceProvider provider, Type objectType /// public override IDictionary GetCache(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -3094,7 +3094,7 @@ public override IDictionary GetCache(object instance) /// public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -3104,7 +3104,7 @@ public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { - if (instance == null) + if (instance is null) { throw new ArgumentNullException(nameof(instance)); } @@ -3123,7 +3123,7 @@ protected internal override IExtenderProvider[] GetExtenderProviders(object inst /// public override string GetFullComponentName(object component) { - if (component == null) + if (component is null) { throw new ArgumentNullException(nameof(component)); } @@ -3137,7 +3137,7 @@ public override string GetFullComponentName(object component) /// public override Type GetReflectionType(Type objectType, object instance) { - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } @@ -3147,7 +3147,7 @@ public override Type GetReflectionType(Type objectType, object instance) public override Type GetRuntimeType(Type objectType) { - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } @@ -3161,12 +3161,12 @@ public override Type GetRuntimeType(Type objectType) /// public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { - if (objectType == null) + if (objectType is null) { throw new ArgumentNullException(nameof(objectType)); } - if (instance != null && !objectType.IsInstanceOfType(instance)) + if (instance is not null && !objectType.IsInstanceOfType(instance)) { throw new ArgumentException(nameof(instance)); } @@ -3176,7 +3176,7 @@ public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object public override bool IsSupportedType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -3217,9 +3217,9 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); AttributeCollection attrs = desc.GetAttributes(); - if (attrs == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetAttributes")); + if (attrs is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetAttributes")); return attrs; } @@ -3239,7 +3239,7 @@ string ICustomTypeDescriptor.GetClassName() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); string name = desc.GetClassName() ?? _instance.GetType().FullName; return name; } @@ -3260,7 +3260,7 @@ string ICustomTypeDescriptor.GetComponentName() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); return desc.GetComponentName(); } @@ -3280,9 +3280,9 @@ TypeConverter ICustomTypeDescriptor.GetConverter() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); TypeConverter converter = desc.GetConverter(); - if (converter == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetConverter")); + if (converter is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetConverter")); return converter; } @@ -3302,7 +3302,7 @@ EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); return desc.GetDefaultEvent(); } @@ -3321,7 +3321,7 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); return desc.GetDefaultProperty(); } @@ -3330,7 +3330,7 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() /// object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { - if (editorBaseType == null) + if (editorBaseType is null) { throw new ArgumentNullException(nameof(editorBaseType)); } @@ -3345,7 +3345,7 @@ object ICustomTypeDescriptor.GetEditor(Type editorBaseType) } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); return desc.GetEditor(editorBaseType); } @@ -3364,9 +3364,9 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); EventDescriptorCollection events = desc.GetEvents(); - if (events == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetEvents")); + if (events is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetEvents")); return events; } @@ -3390,9 +3390,9 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); EventDescriptorCollection evts = desc.GetEvents(attributes); - if (evts == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetEvents")); + if (evts is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetEvents")); return evts; } @@ -3411,9 +3411,9 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); PropertyDescriptorCollection properties = desc.GetProperties(); - if (properties == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetProperties")); + if (properties is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetProperties")); return properties; } @@ -3437,9 +3437,9 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] att } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); PropertyDescriptorCollection properties = desc.GetProperties(attributes); - if (properties == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetProperties")); + if (properties is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetProperties")); return properties; } @@ -3460,7 +3460,7 @@ object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); - if (desc == null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetExtendedTypeDescriptor")); object owner = desc.GetPropertyOwner(pd) ?? _instance; return owner; } @@ -3502,10 +3502,10 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); attrs = desc.GetAttributes(); - if (attrs == null) + if (attrs is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetAttributes")); } @@ -3529,7 +3529,7 @@ string ICustomTypeDescriptor.GetClassName() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); name = desc.GetClassName() ?? _objectType.FullName; } @@ -3554,7 +3554,7 @@ string ICustomTypeDescriptor.GetComponentName() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); name = desc.GetComponentName(); } @@ -3579,10 +3579,10 @@ TypeConverter ICustomTypeDescriptor.GetConverter() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); converter = desc.GetConverter(); - if (converter == null) + if (converter is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetConverter")); } @@ -3606,7 +3606,7 @@ EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); defaultEvent = desc.GetDefaultEvent(); } @@ -3631,7 +3631,7 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); defaultProperty = desc.GetDefaultProperty(); } @@ -3644,7 +3644,7 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() /// object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { - if (editorBaseType == null) + if (editorBaseType is null) { throw new ArgumentNullException(nameof(editorBaseType)); } @@ -3661,7 +3661,7 @@ object ICustomTypeDescriptor.GetEditor(Type editorBaseType) else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); editor = desc.GetEditor(editorBaseType); } @@ -3686,10 +3686,10 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); events = desc.GetEvents(); - if (events == null) + if (events is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetEvents")); } @@ -3713,10 +3713,10 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); events = desc.GetEvents(attributes); - if (events == null) + if (events is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetEvents")); } @@ -3740,10 +3740,10 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); properties = desc.GetProperties(); - if (properties == null) + if (properties is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetProperties")); } @@ -3767,10 +3767,10 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] att else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); properties = desc.GetProperties(attributes); - if (properties == null) + if (properties is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetProperties")); } @@ -3794,7 +3794,7 @@ object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) else { ICustomTypeDescriptor desc = p.GetTypeDescriptor(_objectType, _instance); - if (desc == null) + if (desc is null) throw new InvalidOperationException(SR.Format(SR.TypeDescriptorProviderError, _node.Provider.GetType().FullName, "GetTypeDescriptor")); owner = desc.GetPropertyOwner(pd) ?? _instance; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs index 492c6a6d223b40..ddd0c8d0607f34 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs @@ -66,14 +66,14 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { - if (value == null) + if (value is null) { return SR.none; } @@ -91,11 +91,11 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (_values == null) + if (_values is null) { object[] objTypes; - if (_types != null) + if (_types is not null) { objTypes = new object[_types.Length]; Array.Copy(_types, objTypes, _types.Length); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs index c1c5f6d14e3faf..9787e82e1d093c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs @@ -63,7 +63,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -73,7 +73,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ctor = typeof(Uri).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(UriKind) }, null); - Debug.Assert(ctor != null, "Couldn't find constructor"); + Debug.Assert(ctor is not null, "Couldn't find constructor"); return new InstanceDescriptor(ctor, new object[] { uri.OriginalString, GetUriKind(uri) }); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs index 32d567c5b3c052..d74ea6250e7bb7 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs @@ -64,7 +64,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -74,7 +74,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ctor = typeof(Version).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }, null); - Debug.Assert(ctor != null, "Couldn't find constructor"); + Debug.Assert(ctor is not null, "Couldn't find constructor"); return new InstanceDescriptor(ctor, new object[] { version.Major, version.Minor, version.Build, version.Revision }); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs index 56618993e49ada..f07540830a7469 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs @@ -79,7 +79,7 @@ private void ScavengeKeys() { if (o is WeakReference wr && !wr.IsAlive) { - if (cleanupList == null) + if (cleanupList is null) { cleanupList = new List(); } @@ -88,7 +88,7 @@ private void ScavengeKeys() } } - if (cleanupList != null) + if (cleanupList is not null) { foreach (object o in cleanupList) { @@ -105,11 +105,11 @@ private class WeakKeyComparer : IEqualityComparer { bool IEqualityComparer.Equals(object x, object y) { - if (x == null) + if (x is null) { - return y == null; + return y is null; } - if (y != null && x.GetHashCode() == y.GetHashCode()) + if (y is not null && x.GetHashCode() == y.GetHashCode()) { if (x is WeakReference wX) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs index 1dcd8567f22832..e0b5b5c607d950 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs @@ -47,7 +47,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -72,7 +72,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul return "'" + c.Name + "'"; } - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -128,8 +128,8 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul args = new object[] { c.R, c.G, c.B }; } - Debug.Assert(member != null, "Could not convert color to member. Did someone change method name / signature and not update ColorConverter?"); - if (member != null) + Debug.Assert(member is not null, "Could not convert color to member. Did someone change method name / signature and not update ColorConverter?"); + if (member is not null) { return new InstanceDescriptor(member, args); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs index e662f6f38b4bce..4cf835d221a004 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs @@ -33,7 +33,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Parse 2 integer values. - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -63,7 +63,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -72,7 +72,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (destinationType == typeof(string)) { - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -91,7 +91,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul else if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ctor = typeof(Point).GetConstructor(new Type[] { typeof(int), typeof(int) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { pt.X, pt.Y }); } @@ -103,7 +103,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - if (propertyValues == null) + if (propertyValues is null) { throw new ArgumentNullException(nameof(propertyValues)); } @@ -111,7 +111,7 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar object x = propertyValues["X"]; object y = propertyValues["Y"]; - if (x == null || y == null || !(x is int) || !(y is int)) + if (x is null || y is null || !(x is int) || !(y is int)) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs index 758f5bfa669e75..9f54a5154e58a9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs @@ -33,7 +33,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Parse 4 integer values. - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -61,7 +61,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -70,7 +70,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (destinationType == typeof(string)) { - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -93,7 +93,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul ConstructorInfo ctor = typeof(Rectangle).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int)}); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { rect.X, rect.Y, rect.Width, rect.Height}); @@ -106,7 +106,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - if (propertyValues == null) + if (propertyValues is null) { throw new ArgumentNullException(nameof(propertyValues)); } @@ -116,7 +116,7 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar object width = propertyValues["Width"]; object height = propertyValues["Height"]; - if (x == null || y == null || width == null || height == null || + if (x is null || y is null || width is null || height is null || !(x is int) || !(y is int) || !(width is int) || !(height is int)) { throw new ArgumentException(SR.PropertyValueInvalidEntry); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs index dc492bbac4bc88..15e5b047f85ed4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs @@ -33,7 +33,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Parse 2 integer values. - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -61,7 +61,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -70,7 +70,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (destinationType == typeof(string)) { - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -89,7 +89,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul else if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ctor = typeof(Size).GetConstructor(new Type[] { typeof(int), typeof(int) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { size.Width, size.Height }); } @@ -101,7 +101,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - if (propertyValues == null) + if (propertyValues is null) { throw new ArgumentNullException(nameof(propertyValues)); } @@ -109,7 +109,7 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar object width = propertyValues["Width"]; object height = propertyValues["Height"]; - if (width == null || height == null || !(width is int) || !(height is int)) + if (width is null || height is null || !(width is int) || !(height is int)) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs index 1dd5a976b87496..a64e22a6c96d53 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs @@ -33,7 +33,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } // Parse 2 integer values. - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -60,7 +60,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -69,7 +69,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (destinationType == typeof(string)) { - if (culture == null) + if (culture is null) { culture = CultureInfo.CurrentCulture; } @@ -86,7 +86,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul else if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ctor = typeof(SizeF).GetConstructor(new Type[] { typeof(float), typeof(float) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { size.Width, size.Height }); } @@ -98,7 +98,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - if (propertyValues == null) + if (propertyValues is null) { throw new ArgumentNullException(nameof(propertyValues)); } @@ -106,7 +106,7 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar object width = propertyValues["Width"]; object height = propertyValues["Height"]; - if (width == null || height == null || !(width is float) || !(height is float)) + if (width is null || height is null || !(width is float) || !(height is float)) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs index bb808042339b11..f4ee5222b0b723 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs @@ -75,7 +75,7 @@ public bool AutoReset else if (_autoReset != value) { _autoReset = value; - if (_timer != null) + if (_timer is not null) { UpdateTimer(); } @@ -107,7 +107,7 @@ public bool Enabled { if (!value) { - if (_timer != null) + if (_timer is not null) { _cookie = null; _timer.Dispose(); @@ -118,7 +118,7 @@ public bool Enabled else { _enabled = value; - if (_timer == null) + if (_timer is null) { if (_disposed) { @@ -160,7 +160,7 @@ public double Interval } _interval = value; - if (_timer != null) + if (_timer is not null) { UpdateTimer(); } @@ -205,11 +205,11 @@ public ISynchronizeInvoke SynchronizingObject { get { - if (_synchronizingObject == null && DesignMode) + if (_synchronizingObject is null && DesignMode) { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); object baseComponent = host?.RootComponent; - if (baseComponent != null && baseComponent is ISynchronizeInvoke) + if (baseComponent is not null && baseComponent is ISynchronizeInvoke) { _synchronizingObject = (ISynchronizeInvoke)baseComponent; } @@ -240,7 +240,7 @@ public void Close() _delayedEnable = false; _enabled = false; - if (_timer != null) + if (_timer is not null) { _timer.Dispose(); _timer = null; @@ -295,9 +295,9 @@ private void MyTimerCallback(object state) { // To avoid race between remove handler and raising the event ElapsedEventHandler intervalElapsed = _onIntervalElapsed; - if (intervalElapsed != null) + if (intervalElapsed is not null) { - if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) + if (SynchronizingObject is not null && SynchronizingObject.InvokeRequired) SynchronizingObject.BeginInvoke(intervalElapsed, new object[] { this, elapsedEventArgs }); else intervalElapsed(this, elapsedEventArgs); diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs index 738aa29a48d0be..dacfe8ec421bce 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs @@ -47,7 +47,7 @@ public PartConventionBuilder ForTypesDerivedFrom() /// A that must be used to specify the rule. public PartConventionBuilder ForTypesDerivedFrom(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -76,7 +76,7 @@ public PartConventionBuilder ForType() /// A that must be used to specify the rule. public PartConventionBuilder ForType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -95,7 +95,7 @@ public PartConventionBuilder ForType(Type type) /// A that must be used to specify the rule. public PartConventionBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter == null) + if (typeFilter is null) { throw new ArgumentNullException(nameof(typeFilter)); } @@ -113,7 +113,7 @@ public PartConventionBuilder ForTypesMatching(Predicate typeFilter) /// A that must be used to specify the rule. public PartConventionBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter == null) + if (typeFilter is null) { throw new ArgumentNullException(nameof(typeFilter)); } @@ -158,7 +158,7 @@ private IEnumerable>> EvaluateThisTypeInfoAgainstT /// The list of applied attributes. public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -166,7 +166,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, S // Now edit the attributes returned from the base type List cachedAttributes = null; var typeInfo = member as TypeInfo; - if (typeInfo != null) + if (typeInfo is not null) { var memberInfo = typeInfo as MemberInfo; _lock.EnterReadLock(); @@ -178,7 +178,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, S { _lock.ExitReadLock(); } - if (cachedAttributes == null) + if (cachedAttributes is null) { _lock.EnterWriteLock(); try @@ -190,12 +190,12 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, S foreach (Tuple> element in EvaluateThisTypeInfoAgainstTheConvention(typeInfo)) { attributeList = element.Item2; - if (attributeList != null) + if (attributeList is not null) { var mi = element.Item1 as MemberInfo; - if (mi != null) + if (mi is not null) { - if (mi != null && (mi is ConstructorInfo || mi is TypeInfo || mi is PropertyInfo || mi is MethodInfo)) + if (mi is not null && (mi is ConstructorInfo || mi is TypeInfo || mi is PropertyInfo || mi is MethodInfo)) { if (!_memberInfos.TryGetValue(mi, out List memberAttributes)) { @@ -206,7 +206,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, S else { var pi = element.Item1 as ParameterInfo; - if (pi == null) + if (pi is null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } @@ -241,7 +241,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, S else appliedAttributes = member.GetCustomAttributes(false); - return cachedAttributes == null ? appliedAttributes : appliedAttributes.Concat(cachedAttributes); + return cachedAttributes is null ? appliedAttributes : appliedAttributes.Concat(cachedAttributes); } private List ReadMemberCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) @@ -256,7 +256,7 @@ private List ReadMemberCustomAttributes(Type reflectedType, System.Re if (!_memberInfos.TryGetValue(member, out cachedAttributes)) { // If there is nothing for this member Cache any attributes for the DeclaringType - if (reflectedType != null + if (reflectedType is not null && !_memberInfos.TryGetValue(member.DeclaringType.GetTypeInfo() as MemberInfo, out cachedAttributes)) { // If there is nothing for this parameter look to see if the declaring Member has been cached yet? @@ -298,14 +298,14 @@ private List ReadMemberCustomAttributes(Type reflectedType, System.Re /// The list of applied attributes. public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { - if (parameter == null) + if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } IEnumerable attributes = parameter.GetCustomAttributes(false); List cachedAttributes = ReadParameterCustomAttributes(reflectedType, parameter); - return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes); + return cachedAttributes is null ? attributes : attributes.Concat(cachedAttributes); } private List ReadParameterCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) @@ -320,7 +320,7 @@ private List ReadParameterCustomAttributes(Type reflectedType, System if (!_parameters.TryGetValue(parameter, out cachedAttributes)) { // If there is nothing for this parameter Cache any attributes for the DeclaringType - if (reflectedType != null + if (reflectedType is not null && !_memberInfos.TryGetValue(reflectedType.GetTypeInfo() as MemberInfo, out cachedAttributes)) { // If there is nothing for this parameter look to see if the declaring Member has been cached yet? @@ -356,7 +356,7 @@ private List ReadParameterCustomAttributes(Type reflectedType, System private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseType) { - if (derivedType.BaseType == null) + if (derivedType.BaseType is null) return false; if (derivedType.BaseType == baseType.AsType()) @@ -374,7 +374,7 @@ private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseTyp private static bool IsDescendentOf(Type type, Type baseType) { - if (type == baseType || type == typeof(object) || type == null) + if (type == baseType || type == typeof(object) || type is null) { return false; } diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs index d460de83e2bfe0..e05e7fb197a7de 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs @@ -51,7 +51,7 @@ public ExportConventionBuilder AsContractType(Type type) /// An export builder allowing further configuration. public ExportConventionBuilder AsContractName(string contractName) { - if (contractName == null) + if (contractName is null) { throw new ArgumentNullException(nameof(contractName)); } @@ -82,7 +82,7 @@ public ExportConventionBuilder AsContractName(Func getContractName /// An export builder allowing further configuration. public ExportConventionBuilder AddMetadata(string name, object value) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -91,7 +91,7 @@ public ExportConventionBuilder AddMetadata(string name, object value) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataItems == null) + if (_metadataItems is null) { _metadataItems = new List>(); } @@ -107,7 +107,7 @@ public ExportConventionBuilder AddMetadata(string name, object value) /// An export builder allowing further configuration. public ExportConventionBuilder AddMetadata(string name, Func getValueFromPartType) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -116,12 +116,12 @@ public ExportConventionBuilder AddMetadata(string name, Func getVa throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (getValueFromPartType == null) + if (getValueFromPartType is null) { throw new ArgumentNullException(nameof(getValueFromPartType)); } - if (_metadataItemFuncs == null) + if (_metadataItemFuncs is null) { _metadataItemFuncs = new List>>(); } @@ -131,16 +131,16 @@ public ExportConventionBuilder AddMetadata(string name, Func getVa internal void BuildAttributes(Type type, ref List attributes) { - if (attributes == null) + if (attributes is null) { attributes = new List(); } - var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName; + var contractName = (_getContractNameFromPartType is not null) ? _getContractNameFromPartType(type) : _contractName; attributes.Add(new ExportAttribute(contractName, _contractType)); //Add metadata attributes from direct specification - if (_metadataItems != null) + if (_metadataItems is not null) { foreach (Tuple item in _metadataItems) { @@ -149,12 +149,12 @@ internal void BuildAttributes(Type type, ref List attributes) } //Add metadata attributes from func specification - if (_metadataItemFuncs != null) + if (_metadataItemFuncs is not null) { foreach (Tuple> item in _metadataItemFuncs) { var name = item.Item1; - var value = (item.Item2 != null) ? item.Item2(type) : null; + var value = (item.Item2 is not null) ? item.Item2(type) : null; attributes.Add(new ExportMetadataAttribute(name, value)); } } diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs index cbf0a1a54285e7..07bcd945dcb99d 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs @@ -30,7 +30,7 @@ internal ImportConventionBuilder() { } /// An import builder allowing further configuration. public ImportConventionBuilder AsContractName(string contractName) { - if (contractName == null) + if (contractName is null) { throw new ArgumentNullException(nameof(contractName)); } @@ -92,7 +92,7 @@ public ImportConventionBuilder AllowDefault() /// An import builder allowing further configuration. public ImportConventionBuilder AddMetadataConstraint(string name, object value) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -100,7 +100,7 @@ public ImportConventionBuilder AddMetadataConstraint(string name, object value) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataConstraintItems == null) + if (_metadataConstraintItems is null) { _metadataConstraintItems = new List>(); } @@ -116,7 +116,7 @@ public ImportConventionBuilder AddMetadataConstraint(string name, object value) /// An export builder allowing further configuration. public ImportConventionBuilder AddMetadataConstraint(string name, Func getConstraintValueFromPartType) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -125,12 +125,12 @@ public ImportConventionBuilder AddMetadataConstraint(string name, Func>>(); } @@ -142,7 +142,7 @@ internal void BuildAttributes(Type type, ref List attributes) { Attribute importAttribute; - var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName; + var contractName = (_getContractNameFromPartType is not null) ? _getContractNameFromPartType(type) : _contractName; // Infer from Type when not explicitly set. var asMany = _asMany ?? IsSupportedImportManyType(type.GetTypeInfo()); @@ -157,7 +157,7 @@ internal void BuildAttributes(Type type, ref List attributes) { importAttribute = new ImportManyAttribute(contractName); } - if (attributes == null) + if (attributes is null) { attributes = new List(); } @@ -165,7 +165,7 @@ internal void BuildAttributes(Type type, ref List attributes) //Add metadata attributes from direct specification - if (_metadataConstraintItems != null) + if (_metadataConstraintItems is not null) { foreach (Tuple item in _metadataConstraintItems) { @@ -174,12 +174,12 @@ internal void BuildAttributes(Type type, ref List attributes) } //Add metadata attributes from func specification - if (_metadataConstraintItemFuncs != null) + if (_metadataConstraintItemFuncs is not null) { foreach (Tuple> item in _metadataConstraintItemFuncs) { var name = item.Item1; - var value = (item.Item2 != null) ? item.Item2(type) : null; + var value = (item.Item2 is not null) ? item.Item2(type) : null; attributes.Add(new ImportMetadataConstraintAttribute(name, value)); } } diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs index 0ae9618a77ab59..875c0aad1a199d 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs @@ -67,7 +67,7 @@ public PartConventionBuilder Export() /// A part builder allowing further configuration of the part. public PartConventionBuilder Export(Action exportConfiguration) { - if (exportConfiguration == null) + if (exportConfiguration is null) { throw new ArgumentNullException(nameof(exportConfiguration)); } @@ -96,7 +96,7 @@ public PartConventionBuilder Export() /// A part builder allowing further configuration of the part. public PartConventionBuilder Export(Action exportConfiguration) { - if (exportConfiguration == null) + if (exportConfiguration is null) { throw new ArgumentNullException(nameof(exportConfiguration)); } @@ -139,7 +139,7 @@ public PartConventionBuilder SelectConstructor(Func /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter) { - if (interfaceFilter == null) + if (interfaceFilter is null) { throw new ArgumentNullException(nameof(interfaceFilter)); } @@ -165,12 +165,12 @@ public PartConventionBuilder ExportInterfaces() public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter, Action exportConfiguration) { - if (interfaceFilter == null) + if (interfaceFilter is null) { throw new ArgumentNullException(nameof(interfaceFilter)); } - if (exportConfiguration == null) + if (exportConfiguration is null) { throw new ArgumentNullException(nameof(exportConfiguration)); } @@ -192,7 +192,7 @@ private PartConventionBuilder ExportInterfacesImpl(Predicate interfaceFilt /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } @@ -209,12 +209,12 @@ public PartConventionBuilder ExportProperties(Predicate propertyFi public PartConventionBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } - if (exportConfiguration == null) + if (exportConfiguration is null) { throw new ArgumentNullException(nameof(exportConfiguration)); } @@ -237,7 +237,7 @@ private PartConventionBuilder ExportPropertiesImpl(Predicate prope /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } @@ -255,12 +255,12 @@ public PartConventionBuilder ExportProperties(Predicate propert public PartConventionBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } - if (exportConfiguration == null) + if (exportConfiguration is null) { throw new ArgumentNullException(nameof(exportConfiguration)); } @@ -282,7 +282,7 @@ private PartConventionBuilder ExportPropertiesImpl(Predicate pr /// A part builder allowing further configuration of the part. public PartConventionBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } @@ -299,12 +299,12 @@ public PartConventionBuilder ImportProperties(Predicate propertyFi public PartConventionBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } - if (importConfiguration == null) + if (importConfiguration is null) { throw new ArgumentNullException(nameof(importConfiguration)); } @@ -327,7 +327,7 @@ private PartConventionBuilder ImportPropertiesImpl(Predicate prope /// A part builder allowing further configuration of the part. public PartConventionBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } @@ -345,12 +345,12 @@ public PartConventionBuilder ImportProperties(Predicate propert public PartConventionBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter == null) + if (propertyFilter is null) { throw new ArgumentNullException(nameof(propertyFilter)); } - if (importConfiguration == null) + if (importConfiguration is null) { throw new ArgumentNullException(nameof(importConfiguration)); } @@ -361,7 +361,7 @@ public PartConventionBuilder ImportProperties(Predicate propert private PartConventionBuilder ImportPropertiesImpl(Predicate propertyFilter, Action importConfiguration) { - Predicate typedFilter = pi => pi.PropertyType.Equals(typeof(T)) && (propertyFilter == null || propertyFilter(pi)); + Predicate typedFilter = pi => pi.PropertyType.Equals(typeof(T)) && (propertyFilter is null || propertyFilter(pi)); _propertyImports.Add(Tuple.Create(typedFilter, importConfiguration)); return this; } @@ -392,7 +392,7 @@ public PartConventionBuilder Shared() /// A part builder allowing further configuration of the part. public PartConventionBuilder Shared(string sharingBoundary) { - if (sharingBoundary == null) + if (sharingBoundary is null) { throw new ArgumentNullException(nameof(sharingBoundary)); } @@ -420,7 +420,7 @@ private PartConventionBuilder SharedImpl(string sharingBoundary) /// A part builder allowing further configuration of the part. public PartConventionBuilder AddPartMetadata(string name, object value) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -429,7 +429,7 @@ public PartConventionBuilder AddPartMetadata(string name, object value) throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataItems == null) + if (_metadataItems is null) { _metadataItems = new List>(); } @@ -445,7 +445,7 @@ public PartConventionBuilder AddPartMetadata(string name, object value) /// A part builder allowing further configuration of the part. public PartConventionBuilder AddPartMetadata(string name, Func getValueFromPartType) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -454,12 +454,12 @@ public PartConventionBuilder AddPartMetadata(string name, Func get throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (getValueFromPartType == null) + if (getValueFromPartType is null) { throw new ArgumentNullException(nameof(getValueFromPartType)); } - if (_metadataItemFuncs == null) + if (_metadataItemFuncs is null) { _metadataItemFuncs = new List>>(); } @@ -492,9 +492,9 @@ internal IEnumerable BuildTypeAttributes(Type type) { var attributes = new List(); - if (_typeExportBuilders != null) + if (_typeExportBuilders is not null) { - bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() != null || MemberHasExportMetadata(type.GetTypeInfo()); + bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() is not null || MemberHasExportMetadata(type.GetTypeInfo()); if (isConfigured) { CompositionTrace.Registration_TypeExportConventionOverridden(type); @@ -512,23 +512,23 @@ internal IEnumerable BuildTypeAttributes(Type type) { // Check if there is already a SharedAttribute. If found Trace a warning and do not add this Shared // otherwise add new one - bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() != null; + bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_PartCreationConventionOverridden(type); } else { - attributes.Add(_sharingBoundary == null ? + attributes.Add(_sharingBoundary is null ? new SharedAttribute() : new SharedAttribute(_sharingBoundary)); } } //Add metadata attributes from direct specification - if (_metadataItems != null) + if (_metadataItems is not null) { - bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() != null; + bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_PartMetadataConventionOverridden(type); @@ -543,9 +543,9 @@ internal IEnumerable BuildTypeAttributes(Type type) } //Add metadata attributes from func specification - if (_metadataItemFuncs != null) + if (_metadataItemFuncs is not null) { - bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() != null; + bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_PartMetadataConventionOverridden(type); @@ -555,7 +555,7 @@ internal IEnumerable BuildTypeAttributes(Type type) foreach (Tuple> item in _metadataItemFuncs) { var name = item.Item1; - var value = (item.Item2 != null) ? item.Item2(type) : null; + var value = (item.Item2 is not null) ? item.Item2(type) : null; attributes.Add(new PartMetadataAttribute(name, value)); } } @@ -563,9 +563,9 @@ internal IEnumerable BuildTypeAttributes(Type type) if (_interfaceExports.Any()) { - if (_typeExportBuilders != null) + if (_typeExportBuilders is not null) { - bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() != null || MemberHasExportMetadata(type.GetTypeInfo()); + bool isConfigured = type.GetTypeInfo().GetCustomAttributes(false).FirstOrDefault() is not null || MemberHasExportMetadata(type.GetTypeInfo()); if (isConfigured) { CompositionTrace.Registration_TypeExportConventionOverridden(type); @@ -582,7 +582,7 @@ internal IEnumerable BuildTypeAttributes(Type type) // Run through the export specifications see if any match foreach (Tuple, Action> exportSpecification in _interfaceExports) { - if (exportSpecification.Item1 != null && exportSpecification.Item1(iface)) + if (exportSpecification.Item1 is not null && exportSpecification.Item1(iface)) { ExportConventionBuilder exportBuilder = new ExportConventionBuilder(); exportBuilder.AsContractType(iface); @@ -613,16 +613,16 @@ internal bool BuildConstructorAttributes(Type type, ref List>> configuredMembers, Action configureConstuctorImports) { - if (configuredMembers == null) + if (configuredMembers is null) { configuredMembers = new List>>(); } @@ -659,7 +659,7 @@ private static void ConfigureConstructorAttributes(ConstructorInfo constructorIn ParameterInfo[] parameterInfos = constructorInfo.GetParameters(); foreach (ParameterInfo pi in parameterInfos) { - bool isConfigured = pi.GetCustomAttributes(false).FirstOrDefault() != null || pi.GetCustomAttributes(false).FirstOrDefault() != null; + bool isConfigured = pi.GetCustomAttributes(false).FirstOrDefault() is not null || pi.GetCustomAttributes(false).FirstOrDefault() is not null; if (isConfigured) { CompositionTrace.Registration_ParameterImportConventionOverridden(pi, constructorInfo); @@ -682,7 +682,7 @@ private static void ConfigureConstructorAttributes(ConstructorInfo constructorIn internal void BuildOnImportsSatisfiedNotification(Type type, ref List>> configuredMembers) { //Add OnImportsSatisfiedAttribute where specified - if (_methodImportsSatisfiedNotifications != null) + if (_methodImportsSatisfiedNotifications is not null) { foreach (MethodInfo mi in type.GetRuntimeMethods()) { @@ -691,7 +691,7 @@ internal void BuildOnImportsSatisfiedNotification(Type type, ref List(false).FirstOrDefault() != null; + isConfigured = mi.GetCustomAttributes(false).FirstOrDefault() is not null; checkedIfConfigured = true; } @@ -715,7 +715,7 @@ internal void BuildOnImportsSatisfiedNotification(Type type, ref List { @@ -749,11 +749,11 @@ internal void BuildPropertyAttributes(Type type, ref List, Action> importSpecification in _propertyImports) { - if (underlyingPi == null) + if (underlyingPi is null) { underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name); } - if (importSpecification.Item1 != null && importSpecification.Item1(underlyingPi)) + if (importSpecification.Item1 is not null && importSpecification.Item1(underlyingPi)) { var importBuilder = new ImportConventionBuilder(); @@ -761,7 +761,7 @@ internal void BuildPropertyAttributes(Type type, ref List(false).FirstOrDefault() != null || pi.GetCustomAttributes(false).FirstOrDefault() != null; + isConfigured = pi.GetCustomAttributes(false).FirstOrDefault() is not null || pi.GetCustomAttributes(false).FirstOrDefault() is not null; checkedIfConfigured = true; } @@ -788,16 +788,16 @@ internal void BuildPropertyAttributes(Type type, ref List, Action, Type> exportSpecification in _propertyExports) { - if (underlyingPi == null) + if (underlyingPi is null) { underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name); } - if (exportSpecification.Item1 != null && exportSpecification.Item1(underlyingPi)) + if (exportSpecification.Item1 is not null && exportSpecification.Item1(underlyingPi)) { var exportBuilder = new ExportConventionBuilder(); - if (exportSpecification.Item3 != null) + if (exportSpecification.Item3 is not null) { exportBuilder.AsContractType(exportSpecification.Item3); } @@ -806,7 +806,7 @@ internal void BuildPropertyAttributes(Type type, ref List(false).FirstOrDefault() != null || MemberHasExportMetadata(pi); + isConfigured = pi.GetCustomAttributes(false).FirstOrDefault() is not null || MemberHasExportMetadata(pi); checkedIfConfigured = true; } @@ -822,9 +822,9 @@ internal void BuildPropertyAttributes(Type type, ref List>>(); } diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs index f1f021f9a3f7c6..2cdbced89d4a83 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs @@ -29,7 +29,7 @@ public bool VerifyMethodInfo(MethodInfo mi) private static MethodInfo SelectMethods(Expression> methodSelector) { - if (methodSelector == null) + if (methodSelector is null) { throw new ArgumentNullException(nameof(methodSelector)); } @@ -38,7 +38,7 @@ private static MethodInfo SelectMethods(Expression> methodSelector) if (expr.NodeType == ExpressionType.Call) { var memberInfo = ((MethodCallExpression)expr).Method as MethodInfo; - if (memberInfo != null) + if (memberInfo is not null) { return memberInfo; } @@ -100,7 +100,7 @@ public void ConfigureExport(PropertyInfo propertyInfo, ExportConventionBuilder e private static PropertyInfo SelectProperties(Expression> propertySelector) { - if (propertySelector == null) + if (propertySelector is null) { throw new ArgumentNullException(nameof(propertySelector)); } @@ -109,7 +109,7 @@ private static PropertyInfo SelectProperties(Expression> propert if (expr.NodeType == ExpressionType.MemberAccess) { var memberInfo = ((MemberExpression)expr).Member as PropertyInfo; - if (memberInfo != null) + if (memberInfo is not null) { return memberInfo; } @@ -146,7 +146,7 @@ public ConstructorInfo SelectConstructor(IEnumerable constructo public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConventionBuilder importBuilder) { - if (_importBuilders != null) + if (_importBuilders is not null) { if (_importBuilders.TryGetValue(parameterInfo, out Action parameterImportBuilder)) { @@ -159,7 +159,7 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConve private void ParseSelectConstructor(Expression> constructorSelector) { - if (constructorSelector == null) + if (constructorSelector is null) { throw new ArgumentNullException(nameof(constructorSelector)); } @@ -187,7 +187,7 @@ private void ParseSelectConstructor(Expression>(); } @@ -220,7 +220,7 @@ internal PartConventionBuilder(Predicate selectType) : base(selectType) /// A part builder allowing further configuration of the part. public PartConventionBuilder SelectConstructor(Expression> constructorSelector) { - if (constructorSelector == null) + if (constructorSelector is null) { throw new ArgumentNullException(nameof(constructorSelector)); } @@ -250,7 +250,7 @@ public PartConventionBuilder ExportProperty( Expression> propertySelector, Action exportConfiguration) { - if (propertySelector == null) + if (propertySelector is null) { throw new ArgumentNullException(nameof(propertySelector)); } @@ -283,7 +283,7 @@ public PartConventionBuilder ExportProperty( Expression> propertySelector, Action exportConfiguration) { - if (propertySelector == null) + if (propertySelector is null) { throw new ArgumentNullException(nameof(propertySelector)); } @@ -313,7 +313,7 @@ public PartConventionBuilder ImportProperty( Expression> propertySelector, Action importConfiguration) { - if (propertySelector == null) + if (propertySelector is null) { throw new ArgumentNullException(nameof(propertySelector)); } @@ -345,7 +345,7 @@ public PartConventionBuilder ImportProperty( Expression> propertySelector, Action importConfiguration) { - if (propertySelector == null) + if (propertySelector is null) { throw new ArgumentNullException(nameof(propertySelector)); } @@ -361,7 +361,7 @@ public PartConventionBuilder ImportProperty( /// A part builder allowing further configuration of the part. public PartConventionBuilder NotifyImportsSatisfied(Expression> methodSelector) { - if (methodSelector == null) + if (methodSelector is null) { throw new ArgumentNullException(nameof(methodSelector)); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs index b8b01750bdef2e..504dd123eea490 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs @@ -24,7 +24,7 @@ public sealed class CompositionHost : CompositionContext, IDisposable private CompositionHost(LifetimeContext rootLifetimeContext) { - Debug.Assert(rootLifetimeContext != null); + Debug.Assert(rootLifetimeContext is not null); _rootLifetimeContext = rootLifetimeContext; } @@ -43,7 +43,7 @@ public static CompositionHost CreateCompositionHost(params ExportDescriptorProvi /// The container as an . public static CompositionHost CreateCompositionHost(IEnumerable providers) { - if (providers == null) + if (providers is null) { throw new ArgumentNullException(nameof(providers)); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs index afb9a5b59f6f56..d7c5d330c5e856 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs @@ -39,17 +39,17 @@ public class CompositionDependency /// The contract required by the dependency. public static CompositionDependency Satisfied(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site) { - if (contract == null) + if (contract is null) { throw new ArgumentNullException(nameof(contract)); } - if (target == null) + if (target is null) { throw new ArgumentNullException(nameof(target)); } - if (site == null) + if (site is null) { throw new ArgumentNullException(nameof(site)); } @@ -66,12 +66,12 @@ public static CompositionDependency Satisfied(CompositionContract contract, Expo /// The contract required by the dependency. public static CompositionDependency Missing(CompositionContract contract, object site) { - if (contract == null) + if (contract is null) { throw new ArgumentNullException(nameof(contract)); } - if (site == null) + if (site is null) { throw new ArgumentNullException(nameof(site)); } @@ -89,17 +89,17 @@ public static CompositionDependency Missing(CompositionContract contract, object /// The contract required by the dependency. public static CompositionDependency Oversupplied(CompositionContract contract, IEnumerable targets, object site) { - if (contract == null) + if (contract is null) { throw new ArgumentNullException(nameof(contract)); } - if (targets == null) + if (targets is null) { throw new ArgumentNullException(nameof(targets)); } - if (site == null) + if (site is null) { throw new ArgumentNullException(nameof(site)); } @@ -164,13 +164,13 @@ public override string ToString() return SR.Format(SR.Dependency_ToStringFormat, Site, Target.Contract, Target.Origin); } - internal bool IsError { get { return _target == null; } } + internal bool IsError { get { return _target is null; } } internal void DescribeError(StringBuilder message) { Debug.Assert(IsError, "Should be in error state."); - if (_oversuppliedTargets != null) + if (_oversuppliedTargets is not null) { var list = Formatters.ReadableList(_oversuppliedTargets.Select(t => SR.Format(SR.Dependency_QuoteParameter, t.Origin))); message.AppendFormat(SR.Dependency_TooManyExports, Contract, list); diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs index 8feef63077f259..d2b039aa245315 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs @@ -30,12 +30,12 @@ private CompositionOperation() { } /// The composed object graph. public static object Run(LifetimeContext outermostLifetimeContext, CompositeActivator compositionRootActivator) { - if (outermostLifetimeContext == null) + if (outermostLifetimeContext is null) { throw new ArgumentNullException(nameof(outermostLifetimeContext)); } - if (compositionRootActivator == null) + if (compositionRootActivator is null) { throw new ArgumentNullException(nameof(compositionRootActivator)); } @@ -55,10 +55,10 @@ public static object Run(LifetimeContext outermostLifetimeContext, CompositeActi /// Action to run. public void AddNonPrerequisiteAction(Action action) { - if (action == null) + if (action is null) throw new ArgumentNullException(nameof(action)); - if (_nonPrerequisiteActions == null) + if (_nonPrerequisiteActions is null) _nonPrerequisiteActions = new List(); _nonPrerequisiteActions.Add(action); @@ -71,12 +71,12 @@ public void AddNonPrerequisiteAction(Action action) /// Action to run. public void AddPostCompositionAction(Action action) { - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } - if (_postCompositionActions == null) + if (_postCompositionActions is null) _postCompositionActions = new List(); _postCompositionActions.Add(action); @@ -84,9 +84,9 @@ public void AddPostCompositionAction(Action action) internal void EnterSharingLock(object sharingLock) { - Debug.Assert(sharingLock != null, "Expected a sharing lock to be passed."); + Debug.Assert(sharingLock is not null, "Expected a sharing lock to be passed."); - if (_sharingLock == null) + if (_sharingLock is null) { _sharingLock = sharingLock; Monitor.Enter(sharingLock); @@ -100,10 +100,10 @@ internal void EnterSharingLock(object sharingLock) private void Complete() { - while (_nonPrerequisiteActions != null) + while (_nonPrerequisiteActions is not null) RunAndClearActions(); - if (_postCompositionActions != null) + if (_postCompositionActions is not null) { foreach (var action in _postCompositionActions) action(); @@ -126,7 +126,7 @@ private void RunAndClearActions() /// public void Dispose() { - if (_sharingLock != null) + if (_sharingLock is not null) Monitor.Exit(_sharingLock); } } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs index d0d668712ddcc2..d8bcf9afc3e2a7 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs @@ -12,11 +12,11 @@ internal class DirectExportDescriptor : ExportDescriptor public DirectExportDescriptor(CompositeActivator activator, IDictionary metadata) { - if (activator == null) + if (activator is null) { throw new ArgumentNullException(nameof(activator)); } - if (metadata == null) + if (metadata is null) { throw new ArgumentNullException(nameof(metadata)); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorPromise.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorPromise.cs index c69e357b84e16e..97e52cddce6312 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorPromise.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorPromise.cs @@ -82,7 +82,7 @@ public ExportDescriptor GetDescriptor() try { ExportDescriptor relay = _descriptor.Value; - if (relay == null) + if (relay is null) { throw new ArgumentNullException("descriptor"); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs index 43112a62232a9f..c3b8a74a5c2b0d 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs @@ -114,7 +114,7 @@ private void CheckDependency(CompositionDependency dependency, HashSet dependencies) { var result = new StringBuilder(); - if (dependencies.FirstOrDefault() == null) + if (dependencies.FirstOrDefault() is null) { return result; } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/LifetimeContext.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/LifetimeContext.cs index f476054ac7aa22..870c1e8e44c6cf 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/LifetimeContext.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/LifetimeContext.cs @@ -74,11 +74,11 @@ internal LifetimeContext(LifetimeContext parent, string[] sharingBoundaries) /// Currently, the root cannot be a boundary. public LifetimeContext FindContextWithin(string sharingBoundary) { - if (sharingBoundary == null) + if (sharingBoundary is null) return _root; var toCheck = this; - while (toCheck != null) + while (toCheck is not null) { foreach (var implemented in toCheck._sharingBoundaries) { @@ -106,14 +106,14 @@ public void Dispose() IEnumerable toDispose = null; lock (_boundPartLock) { - if (_boundPartInstances != null) + if (_boundPartInstances is not null) { toDispose = _boundPartInstances; _boundPartInstances = null; } } - if (toDispose != null) + if (toDispose is not null) { foreach (var instance in toDispose) instance.Dispose(); @@ -129,7 +129,7 @@ public void AddBoundInstance(IDisposable instance) { lock (_boundPartLock) { - if (_boundPartInstances == null) + if (_boundPartInstances is null) throw new ObjectDisposedException(ToString()); _boundPartInstances.Add(instance); @@ -152,13 +152,13 @@ public void AddBoundInstance(IDisposable instance) public object GetOrCreate(int sharingId, CompositionOperation operation, CompositeActivator creator) { object result; - if (_sharedPartInstances != null && _sharedPartInstances.TryGetValue(sharingId, out result)) + if (_sharedPartInstances is not null && _sharedPartInstances.TryGetValue(sharingId, out result)) return result; // Remains locked for the rest of the operation. operation.EnterSharingLock(_sharingLock); - if (_sharedPartInstances == null) + if (_sharedPartInstances is null) { _sharedPartInstances = new SmallSparseInitonlyArray(); _instancesUndergoingInitialization = new SmallSparseInitonlyArray(); @@ -211,7 +211,7 @@ public override bool TryGetExport(CompositionContract contract, out object expor /// A string description. public override string ToString() { - if (_parent == null) + if (_parent is null) return "Root Lifetime Context"; if (_sharingBoundaries.Length == 0) diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/UpdateResult.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/UpdateResult.cs index d842fdb8a0d100..85c698f2967e5a 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/UpdateResult.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/UpdateResult.cs @@ -42,7 +42,7 @@ public void AddPromise(ExportDescriptorPromise promise) public ExportDescriptorPromise[] GetResults() { - if (_results == null) + if (_results is null) { if (_remainingProviders.Count != 0) { diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Providers/Metadata/MetadataViewProvider.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Providers/Metadata/MetadataViewProvider.cs index ff8f45abfe5c05..5cea911ccfb2cb 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Providers/Metadata/MetadataViewProvider.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Providers/Metadata/MetadataViewProvider.cs @@ -31,7 +31,7 @@ public static Func, TMetadata> GetMetadataViewProvid return ci.IsPublic && ps.Length == 1 && ps[0].ParameterType == typeof(IDictionary); }); - if (dictionaryConstructor != null) + if (dictionaryConstructor is not null) { var providerArg = Expression.Parameter(typeof(IDictionary), "metadata"); return Expression.Lambda, TMetadata>>( @@ -41,7 +41,7 @@ public static Func, TMetadata> GetMetadataViewProvid } var parameterlessConstructor = ti.DeclaredConstructors.SingleOrDefault(ci => ci.IsPublic && ci.GetParameters().Length == 0); - if (parameterlessConstructor != null) + if (parameterlessConstructor is not null) { var providerArg = Expression.Parameter(typeof(IDictionary), "metadata"); var resultVar = Expression.Variable(typeof(TMetadata), "result"); @@ -51,8 +51,8 @@ public static Func, TMetadata> GetMetadataViewProvid foreach (var prop in typeof(TMetadata).GetTypeInfo().DeclaredProperties .Where(prop => - prop.GetMethod != null && prop.GetMethod.IsPublic && !prop.GetMethod.IsStatic && - prop.SetMethod != null && prop.SetMethod.IsPublic && !prop.SetMethod.IsStatic)) + prop.GetMethod is not null && prop.GetMethod.IsPublic && !prop.GetMethod.IsStatic && + prop.SetMethod is not null && prop.SetMethod.IsPublic && !prop.SetMethod.IsStatic)) { var dva = Expression.Constant(prop.GetCustomAttribute(false), typeof(DefaultValueAttribute)); var name = Expression.Constant(prop.Name, typeof(string)); @@ -79,7 +79,7 @@ private static TValue GetMetadataValue(IDictionary metad if (metadata.TryGetValue(name, out result)) return (TValue)result; - if (defaultValue != null) + if (defaultValue is not null) return (TValue)defaultValue.Value; // This could be significantly improved by describing the target metadata property. diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs index a61eec7d61fc2c..4cd7032e7ef8a2 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs @@ -10,7 +10,7 @@ internal static class Formatters { public static string ReadableList(IEnumerable items) { - if (items == null) + if (items is null) { throw new ArgumentNullException(nameof(items)); } @@ -21,7 +21,7 @@ public static string ReadableList(IEnumerable items) public static string Format(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -35,7 +35,7 @@ public static string Format(Type type) private static string FormatClosedGeneric(Type closedGenericType) { - if (closedGenericType == null) + if (closedGenericType is null) { throw new ArgumentNullException(nameof(closedGenericType)); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs index 2b1abc61c8e44c..3828be61d20aad 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs @@ -19,14 +19,14 @@ private class Element { public int Index; public object Value; } public void Add(int index, object value) { - if (_elements == null) + if (_elements is null) _elements = new Element[ElementsCapacity]; var newElement = new Element { Index = index, Value = value }; var elementIndex = index & ElementIndexMask; var e = _elements[elementIndex]; - if (e == null) + if (e is null) { _elements[elementIndex] = newElement; return; @@ -41,7 +41,7 @@ public void Add(int index, object value) { var nextIndex = (index + offset) & ElementIndexMask; e = _elements[nextIndex]; - if (e == null) + if (e is null) { _elements[nextIndex] = newElement; return; @@ -53,7 +53,7 @@ public void Add(int index, object value) } } - if (_overflow == null) + if (_overflow is null) _overflow = new SmallSparseInitonlyArray(); _overflow.Add(index, value); @@ -61,7 +61,7 @@ public void Add(int index, object value) public bool TryGetValue(int index, out object value) { - if (_elements == null) + if (_elements is null) { value = null; return false; @@ -69,7 +69,7 @@ public bool TryGetValue(int index, out object value) var elementIndex = index & ElementIndexMask; var e = _elements[elementIndex]; - if (e != null && e.Index == index) + if (e is not null && e.Index == index) { value = e.Value; return true; @@ -78,7 +78,7 @@ public bool TryGetValue(int index, out object value) for (int offset = 1; offset <= LocalOffsetMax; ++offset) { e = _elements[(index + offset) & ElementIndexMask]; - if (e == null) + if (e is null) { value = null; return false; @@ -91,7 +91,7 @@ public bool TryGetValue(int index, out object value) } } - if (_overflow != null) + if (_overflow is not null) return _overflow.TryGetValue(index, out value); value = null; diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs index 6e8090ac45bddf..f20a6cc7795277 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs @@ -44,7 +44,7 @@ public CompositionContract(Type contractType, string contractName) /// Optionally, a non-empty collection of named constraints that apply to the contract. public CompositionContract(Type contractType, string contractName, IDictionary metadataConstraints) { - if (contractType == null) throw new ArgumentNullException(nameof(contractType)); + if (contractType is null) throw new ArgumentNullException(nameof(contractType)); if (metadataConstraints?.Count == 0) throw new ArgumentOutOfRangeException(nameof(metadataConstraints)); _contractType = contractType; @@ -76,9 +76,9 @@ public CompositionContract(Type contractType, string contractName, IDictionary string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value))))); @@ -124,7 +124,7 @@ public override string ToString() /// new contract type. public CompositionContract ChangeType(Type newContractType) { - if (newContractType == null) throw new ArgumentNullException(nameof(newContractType)); + if (newContractType is null) throw new ArgumentNullException(nameof(newContractType)); return new CompositionContract(newContractType, _contractName, _metadataConstraints); } @@ -140,12 +140,12 @@ public CompositionContract ChangeType(Type newContractType) /// True if the constraint is present and of the correct type, otherwise false. public bool TryUnwrapMetadataConstraint(string constraintName, out T constraintValue, out CompositionContract remainingContract) { - if (constraintName == null) throw new ArgumentNullException(nameof(constraintName)); + if (constraintName is null) throw new ArgumentNullException(nameof(constraintName)); constraintValue = default(T); remainingContract = null; - if (_metadataConstraints == null) + if (_metadataConstraints is null) return false; if (!_metadataConstraints.TryGetValue(constraintName, out object value)) @@ -174,7 +174,7 @@ internal static bool ConstraintEqual(IDictionary first, IDiction if (first == second) return true; - if (first == null || second == null) + if (first is null || second is null) return false; if (first.Count != second.Count) @@ -185,11 +185,11 @@ internal static bool ConstraintEqual(IDictionary first, IDiction if (!second.TryGetValue(firstItem.Key, out object secondValue)) return false; - if (firstItem.Value == null) + if (firstItem.Value is null) { - return secondValue == null; + return secondValue is null; } - else if (secondValue == null) + else if (secondValue is null) { return false; } @@ -198,7 +198,7 @@ internal static bool ConstraintEqual(IDictionary first, IDiction if (firstItem.Value is IEnumerable firstEnumerable && !(firstEnumerable is string)) { var secondEnumerable = secondValue as IEnumerable; - if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast(), secondEnumerable.Cast())) + if (secondEnumerable is null || !Enumerable.SequenceEqual(firstEnumerable.Cast(), secondEnumerable.Cast())) return false; } else if (!firstItem.Value.Equals(secondValue)) @@ -217,7 +217,7 @@ private static int ConstraintHashCode(IDictionary metadata) foreach (KeyValuePair kv in metadata) { result ^= kv.Key.GetHashCode(); - if (kv.Value != null) + if (kv.Value is not null) { if (kv.Value is string sval) { @@ -228,7 +228,7 @@ private static int ConstraintHashCode(IDictionary metadata) if (kv.Value is IEnumerable enumerableValue) { foreach (var ev in enumerableValue) - if (ev != null) + if (ev is not null) result ^= ev.GetHashCode(); } else diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs index 608aa72d73e0e2..0a3b57a9001c90 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs @@ -11,7 +11,7 @@ internal static class Formatters { public static string Format(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value is string) @@ -22,7 +22,7 @@ public static string Format(object value) public static string Format(Type type) { - if (type == null) throw new ArgumentNullException(nameof(type)); + if (type is null) throw new ArgumentNullException(nameof(type)); if (type.IsConstructedGenericType) return FormatClosedGeneric(type); @@ -32,7 +32,7 @@ public static string Format(Type type) private static string FormatClosedGeneric(Type closedGenericType) { - Debug.Assert(closedGenericType != null); + Debug.Assert(closedGenericType is not null); Debug.Assert(closedGenericType.IsConstructedGenericType); var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`')); IEnumerable args = closedGenericType.GenericTypeArguments.Select(t => Format(t)); diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs index 54736c2bbc350b..6d1d1b7578d013 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs @@ -44,9 +44,9 @@ public static void SatisfyImports(this CompositionContext compositionContext, ob private static void SatisfyImportsInternal(this CompositionContext exportProvider, object objectWithLooseImports, AttributedModelProvider conventions) { - if (exportProvider == null) throw new ArgumentNullException(nameof(exportProvider)); - if (objectWithLooseImports == null) throw new ArgumentNullException(nameof(objectWithLooseImports)); - if (conventions == null) throw new ArgumentNullException(nameof(conventions)); + if (exportProvider is null) throw new ArgumentNullException(nameof(exportProvider)); + if (objectWithLooseImports is null) throw new ArgumentNullException(nameof(objectWithLooseImports)); + if (conventions is null) throw new ArgumentNullException(nameof(conventions)); var objType = objectWithLooseImports.GetType(); diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/Debugging/ContainerConfigurationDebuggerProxy.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/Debugging/ContainerConfigurationDebuggerProxy.cs index 5e91bf571c0a78..75afb40a49a683 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/Debugging/ContainerConfigurationDebuggerProxy.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/Debugging/ContainerConfigurationDebuggerProxy.cs @@ -51,7 +51,7 @@ public Type[] IgnoredTypes private void InitDiscovery() { - if (_discoveredParts != null) + if (_discoveredParts is not null) return; var types = _configuration.DebugGetRegisteredTypes(); diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs index ac6433208b08e4..64e19c593fbc19 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs @@ -49,7 +49,7 @@ public CompositionHost CreateContainer() /// A configuration object allowing configuration to continue. public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider) { - if (exportDescriptorProvider == null) throw new ArgumentNullException(nameof(exportDescriptorProvider)); + if (exportDescriptorProvider is null) throw new ArgumentNullException(nameof(exportDescriptorProvider)); _addedSources.Add(exportDescriptorProvider); return this; } @@ -63,9 +63,9 @@ public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescri /// A configuration object allowing configuration to continue. public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions) { - if (conventions == null) throw new ArgumentNullException(nameof(conventions)); + if (conventions is null) throw new ArgumentNullException(nameof(conventions)); - if (_defaultAttributeContext != null) + if (_defaultAttributeContext is not null) throw new InvalidOperationException(SR.ContainerConfiguration_DefaultConventionSet); _defaultAttributeContext = conventions; @@ -92,7 +92,7 @@ public ContainerConfiguration WithPart(Type partType) /// A configuration object allowing configuration to continue. public ContainerConfiguration WithPart(Type partType, AttributedModelProvider conventions) { - if (partType == null) throw new ArgumentNullException(nameof(partType)); + if (partType is null) throw new ArgumentNullException(nameof(partType)); return WithParts(new[] { partType }, conventions); } @@ -150,7 +150,7 @@ public ContainerConfiguration WithParts(IEnumerable partTypes) /// A configuration object allowing configuration to continue. public ContainerConfiguration WithParts(IEnumerable partTypes, AttributedModelProvider conventions) { - if (partTypes == null) throw new ArgumentNullException(nameof(partTypes)); + if (partTypes is null) throw new ArgumentNullException(nameof(partTypes)); _types.Add(Tuple.Create(partTypes, conventions)); return this; } @@ -198,7 +198,7 @@ public ContainerConfiguration WithAssemblies(IEnumerable assemblies) /// A configuration object allowing configuration to continue. public ContainerConfiguration WithAssemblies(IEnumerable assemblies, AttributedModelProvider conventions) { - if (assemblies == null) throw new ArgumentNullException(nameof(assemblies)); + if (assemblies is null) throw new ArgumentNullException(nameof(assemblies)); return WithParts(assemblies.SelectMany(a => a.DefinedTypes.Select(dt => dt.AsType())), conventions); } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs index 8d06b69cdf25da..9c63bf750db304 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs @@ -21,7 +21,7 @@ internal class OnImportsSatisfiedFeature : ActivationFeature public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext) { - if (attributeContext == null) throw new ArgumentNullException(nameof(attributeContext)); + if (attributeContext is null) throw new ArgumentNullException(nameof(attributeContext)); _attributeContext = attributeContext; } @@ -35,7 +35,7 @@ public override CompositeActivator RewriteActivator( var partTypeAsType = partType.AsType(); var importsSatisfiedMethods = partTypeAsType.GetRuntimeMethods() - .Where(mi => _attributeContext.GetDeclaredAttribute(mi.DeclaringType, mi) != null); + .Where(mi => _attributeContext.GetDeclaredAttribute(mi.DeclaringType, mi) is not null); foreach (var m in importsSatisfiedMethods) { diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ContractHelpers.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ContractHelpers.cs index 3794657f438698..b917746497cac7 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ContractHelpers.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ContractHelpers.cs @@ -36,7 +36,7 @@ public static ImportInfo GetImportInfo(Type memberType, object[] attributes, obj foreach (var attr in attributes) { var ia = attr as ImportAttribute; - if (ia != null) + if (ia is not null) { importedContract = new CompositionContract(memberType, ia.ContractName); allowDefault = ia.AllowDefault; @@ -45,7 +45,7 @@ public static ImportInfo GetImportInfo(Type memberType, object[] attributes, obj else { var ima = attr as ImportManyAttribute; - if (ima != null) + if (ima is not null) { importMetadata = importMetadata ?? new Dictionary(); importMetadata.Add(ImportManyImportMetadataConstraintName, true); @@ -55,7 +55,7 @@ public static ImportInfo GetImportInfo(Type memberType, object[] attributes, obj else { var imca = attr as ImportMetadataConstraintAttribute; - if (imca != null) + if (imca is not null) { importMetadata = importMetadata ?? new Dictionary(); importMetadata.Add(imca.Name, imca.Value); @@ -65,7 +65,7 @@ public static ImportInfo GetImportInfo(Type memberType, object[] attributes, obj var attrType = attr.GetType(); // Note, we don't support ReflectionContext in this scenario - if (attrType.GetTypeInfo().GetCustomAttribute(true) != null) + if (attrType.GetTypeInfo().GetCustomAttribute(true) is not null) { // We don't coalesce to collections here the way export metadata does foreach (var prop in attrType @@ -84,7 +84,7 @@ public static ImportInfo GetImportInfo(Type memberType, object[] attributes, obj throw new CompositionFailedException(message); } - if (importMetadata != null) + if (importMetadata is not null) { importedContract = new CompositionContract(importedContract.ContractType, importedContract.ContractName, importMetadata); } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs index 84a14909a63c10..831a147d72600e 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs @@ -74,7 +74,7 @@ public CompositionDependency[] GetDependencies(DependencyAccessor definitionAcce return GetPartActivatorDependencies(definitionAccessor) .Concat(_activationFeatures .SelectMany(feature => feature.GetDependencies(_partType, definitionAccessor))) - .Where(a => a != null) + .Where(a => a is not null) .ToArray(); } @@ -82,13 +82,13 @@ private IEnumerable GetPartActivatorDependencies(Dependen { var partTypeAsType = _partType.AsType(); - if (_constructor == null) + if (_constructor is null) { foreach (var c in _partType.DeclaredConstructors.Where(ci => ci.IsPublic && !(ci.IsStatic))) { - if (_attributeContext.GetDeclaredAttribute(partTypeAsType, c) != null) + if (_attributeContext.GetDeclaredAttribute(partTypeAsType, c) is not null) { - if (_constructor != null) + if (_constructor is not null) { string message = SR.Format(SR.DiscoveredPart_MultipleImportingConstructorsFound, _partType); throw new CompositionFailedException(message); @@ -98,11 +98,11 @@ private IEnumerable GetPartActivatorDependencies(Dependen } } - if (_constructor == null) + if (_constructor is null) _constructor = _partType.DeclaredConstructors .FirstOrDefault(ci => ci.IsPublic && !(ci.IsStatic || ci.GetParameters().Any())); - if (_constructor == null) + if (_constructor is null) { string message = SR.Format(SR.DiscoveredPart_NoImportingConstructorsFound, _partType); throw new CompositionFailedException(message); @@ -132,7 +132,7 @@ private IEnumerable GetPartActivatorDependencies(Dependen public CompositeActivator GetActivator(DependencyAccessor definitionAccessor, IEnumerable dependencies) { - if (_partActivator != null) return _partActivator; + if (_partActivator is not null) return _partActivator; var contextParam = Expression.Parameter(typeof(LifetimeContext), "cc"); var operationParm = Expression.Parameter(typeof(CompositionOperation), "op"); @@ -247,7 +247,7 @@ public bool Equals(ParameterInfo x, ParameterInfo y) return true; } - if (x == null || y == null) + if (x is null || y is null) { return false; } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs index aeab2667cc1161..437994288eef45 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs @@ -28,7 +28,7 @@ public bool InspectTypeForPart(TypeInfo type, out DiscoveredPart part) { part = null; - if (type.IsAbstract || !type.IsClass || _attributeContext.GetDeclaredAttribute(type.AsType(), type) != null) + if (type.IsAbstract || !type.IsClass || _attributeContext.GetDeclaredAttribute(type.AsType(), type) is not null) return false; foreach (var export in DiscoverExports(type)) @@ -37,7 +37,7 @@ public bool InspectTypeForPart(TypeInfo type, out DiscoveredPart part) part.AddDiscoveredExport(export); } - return part != null; + return part is not null; } private IEnumerable DiscoverExports(TypeInfo partType) @@ -107,7 +107,7 @@ private void ReadLooseMetadata(object[] appliedAttributes, IDictionary metadata, string name, Type } var existingArray = existingValue as Array; - if (existingArray != null) + if (existingArray is not null) { var newArray = Array.CreateInstance(valueType, existingArray.Length + 1); Array.Copy(existingArray, newArray, existingArray.Length); @@ -150,7 +150,7 @@ private void ReadMetadataAttribute(Attribute attribute, IDictionary(true) == null) + if (attrType.GetTypeInfo().GetCustomAttribute(true) is null) return; foreach (var prop in attrType @@ -214,7 +214,7 @@ private static IEnumerable GetAssignableTypes(TypeInfo exportingMember yield return ifce.GetTypeInfo(); var b = exportingMemberType; - while (b != null) + while (b is not null) { yield return b; b = b.BaseType?.GetTypeInfo(); diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/TypedPartExportDescriptorProvider.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/TypedPartExportDescriptorProvider.cs index 68e4b2d6877915..83d3c2eeed97bb 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/TypedPartExportDescriptorProvider.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/TypedPartExportDescriptorProvider.cs @@ -76,7 +76,7 @@ public override IEnumerable GetExportDescriptors(Compos // If the contract has metadata constraints, look for exports with matching metadata. private void DiscoverConstrainedParts(CompositionContract contract) { - if (contract.MetadataConstraints != null) + if (contract.MetadataConstraints is not null) { var unconstrained = new CompositionContract(contract.ContractType, contract.ContractName); DiscoverGenericParts(unconstrained); diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs index 7e3e7670f96bbd..bf29bfd56ca496 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs @@ -11,8 +11,8 @@ internal class DirectAttributeContext : AttributedModelProvider { public override IEnumerable GetCustomAttributes(Type reflectedType, Reflection.MemberInfo member) { - if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType)); - if (member == null) throw new ArgumentNullException(nameof(member)); + if (reflectedType is null) throw new ArgumentNullException(nameof(reflectedType)); + if (member is null) throw new ArgumentNullException(nameof(member)); if (!(member is TypeInfo) && member.DeclaringType != reflectedType) return Array.Empty(); @@ -22,8 +22,8 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, R public override IEnumerable GetCustomAttributes(Type reflectedType, Reflection.ParameterInfo parameter) { - if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType)); - if (parameter == null) throw new ArgumentNullException(nameof(parameter)); + if (reflectedType is null) throw new ArgumentNullException(nameof(reflectedType)); + if (parameter is null) throw new ArgumentNullException(nameof(parameter)); return Attribute.GetCustomAttributes(parameter, false); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs index b232f721d46af5..8be9c71925aa76 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs @@ -30,12 +30,12 @@ public AppSettingsReader() /// public object GetValue(string key, Type type) { - if (key == null) throw new ArgumentNullException(nameof(key)); - if (type == null) throw new ArgumentNullException(nameof(type)); + if (key is null) throw new ArgumentNullException(nameof(key)); + if (type is null) throw new ArgumentNullException(nameof(type)); string val = _map[key]; - if (val == null) throw new InvalidOperationException(SR.Format(SR.AppSettingsReaderNoKey, key)); + if (val is null) throw new InvalidOperationException(SR.Format(SR.AppSettingsReaderNoKey, key)); if (type == s_stringType) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsSection.cs index 4da673bd7bf10d..ddae4c03848332 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsSection.cs @@ -41,7 +41,7 @@ public string File private static ConfigurationPropertyCollection EnsureStaticPropertyBag() { - if (s_properties != null) return s_properties; + if (s_properties is not null) return s_properties; ConfigurationProperty propAppSettings = new ConfigurationProperty( name: null, diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs index 2c5cd0efd1b1cf..40da46cc0e8876 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -57,24 +57,24 @@ protected ApplicationSettingsBase(string settingsKey) /// protected ApplicationSettingsBase(IComponent owner, string settingsKey) : this(settingsKey) { - if (owner == null) + if (owner is null) { throw new ArgumentNullException(nameof(owner)); } _owner = owner; - if (owner.Site != null) + if (owner.Site is not null) { ISettingsProviderService providerService = owner.Site.GetService(typeof(ISettingsProviderService)) as ISettingsProviderService; - if (providerService != null) + if (providerService is not null) { // The component's site has a settings provider service. We pass each SettingsProperty to it // to see if it wants to override the current provider. foreach (SettingsProperty property in Properties) { SettingsProvider provider = providerService.GetSettingsProvider(property); - if (provider != null) + if (provider is not null) { property.Provider = provider; } @@ -93,13 +93,13 @@ public override SettingsContext Context { get { - if (_context == null) + if (_context is null) { if (IsSynchronized) { lock (this) { - if (_context == null) + if (_context is null) { _context = new SettingsContext(); EnsureInitialized(); @@ -128,13 +128,13 @@ public override SettingsPropertyCollection Properties { get { - if (_settings == null) + if (_settings is null) { if (IsSynchronized) { lock (this) { - if (_settings == null) + if (_settings is null) { _settings = new SettingsPropertyCollection(); EnsureInitialized(); @@ -173,13 +173,13 @@ public override SettingsProviderCollection Providers { get { - if (_providers == null) + if (_providers is null) { if (IsSynchronized) { lock (this) { - if (_providers == null) + if (_providers is null) { _providers = new SettingsProviderCollection(); EnsureInitialized(); @@ -287,17 +287,17 @@ public object GetPreviousVersion(string propertyName) SettingsProperty sp = Properties[propertyName]; SettingsPropertyValue value = null; - if (sp == null) + if (sp is null) throw new SettingsPropertyNotFoundException(); IApplicationSettingsProvider clientProv = sp.Provider as IApplicationSettingsProvider; - if (clientProv != null) + if (clientProv is not null) { value = clientProv.GetPreviousVersion(Context, sp); } - if (value != null) + if (value is not null) { return value.PropertyValue; } @@ -342,7 +342,7 @@ protected virtual void OnSettingsSaving(object sender, CancelEventArgs e) /// public void Reload() { - if (PropertyValues != null) + if (PropertyValues is not null) { PropertyValues.Clear(); } @@ -360,12 +360,12 @@ public void Reload() /// public void Reset() { - if (Properties != null) + if (Properties is not null) { foreach (SettingsProvider provider in Providers) { IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider; - if (clientProv != null) + if (clientProv is not null) { clientProv.Reset(Context); } @@ -431,12 +431,12 @@ public override object this[string propertyName] /// public virtual void Upgrade() { - if (Properties != null) + if (Properties is not null) { foreach (SettingsProvider provider in Providers) { IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider; - if (clientProv != null) + if (clientProv is not null) { clientProv.Upgrade(Context, GetPropertiesForProvider(provider)); } @@ -465,7 +465,7 @@ private SettingsProperty CreateSetting(PropertyInfo propertyInfo) for (int i = 0; i < attributes.Length; i++) { Attribute attribute = attributes[i] as Attribute; - if (attribute == null) + if (attribute is null) continue; if (attribute is DefaultSettingValueAttribute) @@ -480,14 +480,14 @@ private SettingsProperty CreateSetting(PropertyInfo propertyInfo) { string providerTypeName = ((SettingsProviderAttribute)attribute).ProviderTypeName; Type providerType = Type.GetType(providerTypeName); - if (providerType == null) + if (providerType is null) { throw new ConfigurationErrorsException(SR.Format(SR.ProviderTypeLoadFailed, providerTypeName)); } SettingsProvider settingsProvider = TypeUtil.CreateInstance(providerType) as SettingsProvider; - if (settingsProvider == null) + if (settingsProvider is null) { throw new ConfigurationErrorsException(SR.Format(SR.ProviderInstantiationFailed, providerTypeName)); } @@ -498,7 +498,7 @@ private SettingsProperty CreateSetting(PropertyInfo propertyInfo) // See if we already have a provider of the same name in our collection. If so, // re-use the existing instance, since we cannot have multiple providers of the same name. SettingsProvider existing = _providers[settingsProvider.Name]; - if (existing != null) + if (existing is not null) { settingsProvider = existing; } @@ -558,7 +558,7 @@ private void EnsureInitialized() Type type = GetType(); - if (_context == null) + if (_context is null) { _context = new SettingsContext(); } @@ -569,12 +569,12 @@ private void EnsureInitialized() PropertyInfo[] properties = SettingsFilter(type.GetProperties(BindingFlags.Instance | BindingFlags.Public)); _classAttributes = type.GetCustomAttributes(false); - if (_settings == null) + if (_settings is null) { _settings = new SettingsPropertyCollection(); } - if (_providers == null) + if (_providers is null) { _providers = new SettingsProviderCollection(); } @@ -582,11 +582,11 @@ private void EnsureInitialized() for (int i = 0; i < properties.Length; i++) { SettingsProperty sp = CreateSetting(properties[i]); - if (sp != null) + if (sp is not null) { _settings.Add(sp); - if (sp.Provider != null && _providers[sp.Provider.Name] == null) + if (sp.Provider is not null && _providers[sp.Provider.Name] is null) { _providers.Add(sp.Provider); } @@ -607,7 +607,7 @@ private SettingsProperty Initializer get { - if (_init == null) + if (_init is null) { _init = new SettingsProperty(""); _init.DefaultValue = null; @@ -616,12 +616,12 @@ private SettingsProperty Initializer SettingsProvider provider = new LocalFileSettingsProvider(); - if (_classAttributes != null) + if (_classAttributes is not null) { for (int i = 0; i < _classAttributes.Length; i++) { Attribute attr = _classAttributes[i] as Attribute; - if (attr != null) + if (attr is not null) { if (attr is ReadOnlyAttribute) { @@ -629,7 +629,7 @@ private SettingsProperty Initializer } else if (attr is SettingsGroupNameAttribute) { - if (_context == null) + if (_context is null) { _context = new SettingsContext(); } @@ -639,10 +639,10 @@ private SettingsProperty Initializer { string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName; Type providerType = Type.GetType(providerTypeName); - if (providerType != null) + if (providerType is not null) { SettingsProvider spdr = TypeUtil.CreateInstance(providerType) as SettingsProvider; - if (spdr != null) + if (spdr is not null) { provider = spdr; } @@ -711,7 +711,7 @@ private SettingsPropertyCollection GetPropertiesForProvider(SettingsProvider pro /// private object GetPropertyValue(string propertyName) { - if (PropertyValues[propertyName] == null) + if (PropertyValues[propertyName] is null) { // If this is our first load and we are part of a Clickonce app, call Upgrade. @@ -729,9 +729,9 @@ private object GetPropertyValue(string propertyName) // on an infinite recursion when calling Properties[propertyName] as that calls this. _ = base[propertyName]; SettingsProperty setting = Properties[propertyName]; - SettingsProvider provider = setting != null ? setting.Provider : null; + SettingsProvider provider = setting is not null ? setting.Provider : null; - Debug.Assert(provider != null, "Could not determine provider from which settings were loaded"); + Debug.Assert(provider is not null, "Could not determine provider from which settings were loaded"); SettingsLoadedEventArgs e = new SettingsLoadedEventArgs(provider); OnSettingsLoaded(this, e); @@ -802,7 +802,7 @@ private void ResetProviders() foreach (SettingsProperty sp in Properties) { - if (Providers[sp.Provider.Name] == null) + if (Providers[sp.Provider.Name] is null) { Providers.Add(sp.Provider); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs index 1ca9090e874f40..3c0d230c5060eb 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs @@ -169,19 +169,19 @@ internal BaseConfigurationRecord() internal bool HasStream => ConfigStreamInfo.HasStream; - private bool IsInitDelayed => _initDelayedRoot != null; + private bool IsInitDelayed => _initDelayedRoot is not null; internal IInternalConfigHost Host => _configRoot.Host; internal BaseConfigurationRecord Parent => _parent; - internal bool IsRootConfig => _parent == null; + internal bool IsRootConfig => _parent is null; internal bool IsMachineConfig => _parent == _configRoot.RootConfigRecord; internal string LocationSubPath => _locationSubPath; - internal bool IsLocationConfig => _locationSubPath != null; + internal bool IsLocationConfig => _locationSubPath is not null; protected ConfigRecordStreamInfo ConfigStreamInfo => IsLocationConfig ? _parent._configStreamInfo : _configStreamInfo; @@ -197,14 +197,14 @@ private ProtectedConfigurationSection ProtectedConfig } } - private bool HasFactoryRecords => _factoryRecords != null; + private bool HasFactoryRecords => _factoryRecords is not null; // Return true if there is no unique configuration information in this record. - internal bool IsEmpty => (_parent != null) + internal bool IsEmpty => (_parent is not null) && !_initErrors.HasErrors(false) - && ((_sectionRecords == null) || (_sectionRecords.Count == 0)) - && ((_factoryRecords == null) || (_factoryRecords.Count == 0)) - && ((_locationSections == null) || (_locationSections.Count == 0)); + && ((_sectionRecords is null) || (_sectionRecords.Count == 0)) + && ((_factoryRecords is null) || (_factoryRecords.Count == 0)) + && ((_locationSections is null) || (_locationSections.Count == 0)); internal object ConfigContext { @@ -239,7 +239,7 @@ internal object ConfigContext internal FrameworkName TargetFramework => CurrentConfiguration?.TargetFramework; - internal Stack SectionsStack => CurrentConfiguration == null ? new Stack() : CurrentConfiguration.SectionsStack; + internal Stack SectionsStack => CurrentConfiguration is null ? new Stack() : CurrentConfiguration.SectionsStack; public string ConfigPath => _configPath; @@ -347,7 +347,7 @@ internal void Init( { // Treat location inputs from parent record // as though they were bonafide sections in this record. - if (IsLocationConfig && (_parent._locationSections != null)) + if (IsLocationConfig && (_parent._locationSections is not null)) { // Resolve paths and check for errors in location sections. _parent.ResolveLocationSections(); @@ -367,7 +367,7 @@ internal void Init( // remove the LocationSectionRecord from the list _parent._locationSections.RemoveAt(i); - if (locationSubPathInputs == null) locationSubPathInputs = new ArrayList(); + if (locationSubPathInputs is null) locationSubPathInputs = new ArrayList(); locationSubPathInputs.Add(locationSectionRecord); } @@ -385,7 +385,7 @@ internal void Init( // because a Configuration object will contain at most one location config record. while (!current.IsRootConfig) { - if (current._locationSections != null) + if (current._locationSections is not null) { current.ResolveLocationSections(); @@ -408,7 +408,7 @@ internal void Init( // First add all indirect inputs per configKey to a local list. // We will sort all lists after the while loop. - if (indirectLocationInputs == null) + if (indirectLocationInputs is null) indirectLocationInputs = new Dictionary>(1); string configKey = locationSectionRecord.SectionXmlInfo.ConfigKey; @@ -429,7 +429,7 @@ internal void Init( current = current._parent; } - if (indirectLocationInputs != null) + if (indirectLocationInputs is not null) { // Add indirect inputs per configKey foreach (KeyValuePair> keyValuePair in indirectLocationInputs) @@ -461,7 +461,7 @@ internal void Init( BaseConfigurationRecord current = _parent; while (!current.IsRootConfig) { - if (current._locationSections != null) + if (current._locationSections is not null) { current.ResolveLocationSections(); foreach (LocationSectionRecord locationSectionRecord in current._locationSections) @@ -496,7 +496,7 @@ internal void Init( else { // Add location sections for this record as bonafide sections. - if (locationSubPathInputs == null) return; + if (locationSubPathInputs is null) return; foreach (LocationSectionRecord locationSectionRecord in locationSubPathInputs) { // add the file input @@ -550,7 +550,7 @@ private void InitConfigFromFile() ConfigStreamInfo.StreamVersion = MonitorStream(null, null, ConfigStreamInfo.StreamName); using (Stream stream = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) { - if (stream == null) + if (stream is null) { // There is no stream to load from return; @@ -621,7 +621,7 @@ private void InitConfigFromFile() StreamInfo fileStreamInfo = (StreamInfo)streamInfos[ConfigStreamInfo.StreamName]; // add this file's streaminfo to the now empty list - if (fileStreamInfo != null) + if (fileStreamInfo is not null) { streamInfos.Remove(ConfigStreamInfo.StreamName); ConfigStreamInfo.StreamInfos.Add(ConfigStreamInfo.StreamName, fileStreamInfo); @@ -631,7 +631,7 @@ private void InitConfigFromFile() } // Stop monitoring streams outside the lock, to prevent deadlock. - if (streamInfos != null) + if (streamInfos is not null) { foreach (StreamInfo streamInfo in streamInfos.Values) if (streamInfo.IsMonitored) @@ -639,7 +639,7 @@ private void InitConfigFromFile() } // Remove file input - if (_sectionRecords != null) + if (_sectionRecords is not null) { List removes = null; foreach (SectionRecord sectionRecord in _sectionRecords.Values) @@ -655,13 +655,13 @@ private void InitConfigFromFile() else { // Remove the entire section record - if (removes == null) removes = new List(); + if (removes is null) removes = new List(); removes.Add(sectionRecord); } } - if (removes != null) + if (removes is not null) { foreach (SectionRecord sectionRecord in removes) _sectionRecords.Remove(sectionRecord.ConfigKey); @@ -696,7 +696,7 @@ private void RefreshFactoryRecord(string configKey) { using (Stream stream = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) { - if (stream != null) + if (stream is not null) { ConfigStreamInfo.HasStream = true; @@ -717,7 +717,7 @@ private void RefreshFactoryRecord(string configKey) } // Add implicit sections to the factory list - if (factoryList == null) + if (factoryList is null) { // But if factoryList isn't found in this config, we still try to // add implicit sections to an empty factoryList. @@ -740,7 +740,7 @@ private void RefreshFactoryRecord(string configKey) // Set/Add/Remove Record // Note that the _factoryRecords hashtable is protected by the hierarchy lock. - if ((factoryRecord != null) || HasFactoryRecords) EnsureFactories()[configKey] = factoryRecord; + if ((factoryRecord is not null) || HasFactoryRecords) EnsureFactories()[configKey] = factoryRecord; // Throw accumulated errors ThrowIfParseErrors(errors); @@ -790,7 +790,7 @@ private void GetSectionRecursive( // check for a cached result bool hasResult = false; SectionRecord sectionRecord = GetSectionRecord(configKey, getLkg); - if ((sectionRecord != null) && sectionRecord.HasResult) + if ((sectionRecord is not null) && sectionRecord.HasResult) { // Results should never be stored if the section has errors. Debug.Assert(!sectionRecord.HasErrors, "!sectionRecord.HasErrors"); @@ -824,7 +824,7 @@ private void GetSectionRecursive( // then merge it with our own input if we have any. if (!hasResult) { - bool hasInput = (sectionRecord != null) && sectionRecord.HasInput; + bool hasInput = (sectionRecord is not null) && sectionRecord.HasInput; // We want to cache results in a section record if: // - The request is made at this level, and so is likely to be @@ -894,7 +894,7 @@ private void GetSectionRecursive( // client user configuration files, which aren't needed by // most applications. if (IsInitDelayed - && ((factoryRecord == null) + && ((factoryRecord is null) || _initDelayedRoot.IsDefinitionAllowed(factoryRecord.AllowDefinition, factoryRecord.AllowExeDefinition))) @@ -927,7 +927,7 @@ private void GetSectionRecursive( // For compatibility with previous versions, // return null if the section is not found // or is a group. - if ((factoryRecord == null) || factoryRecord.IsGroup) return; + if ((factoryRecord is null) || factoryRecord.IsGroup) return; // Use the factory record's copy of the configKey, // so that we don't store more than one instance @@ -940,7 +940,7 @@ private void GetSectionRecursive( { // We'll need a factory to evaluate the input. factoryRecord = FindAndEnsureFactoryRecord(configKey, out isRootDeclaration); - Debug.Assert(factoryRecord != null, "factoryRecord != null"); + Debug.Assert(factoryRecord is not null, "factoryRecord is not null"); } else { @@ -949,18 +949,18 @@ private void GetSectionRecursive( // declared here. This is important to avoid a walk up the config // hierachy when there is no input in this record. factoryRecord = GetFactoryRecord(configKey, false); - if (factoryRecord == null) isRootDeclaration = false; + if (factoryRecord is null) isRootDeclaration = false; else { factoryRecord = FindAndEnsureFactoryRecord(configKey, out isRootDeclaration); - Debug.Assert(factoryRecord != null, "factoryRecord != null"); + Debug.Assert(factoryRecord is not null, "factoryRecord is not null"); } } } // We need a factory record to check permission. - Debug.Assert(!checkPermission || (factoryRecord != null), - "!checkPermission || factoryRecord != null"); + Debug.Assert(!checkPermission || (factoryRecord is not null), + "!checkPermission || factoryRecord is not null"); // If this is the root declaration, then we always want to cache // the result, in order to prevent the section default from being @@ -969,7 +969,7 @@ private void GetSectionRecursive( // We'll need a section record to cache results, // and maybe to use in creating the section default. - if ((sectionRecord == null) && cacheResults) sectionRecord = EnsureSectionRecord(configKey, true); + if ((sectionRecord is null) && cacheResults) sectionRecord = EnsureSectionRecord(configKey, true); // Retrieve the parent's runtime object if the runtimeObject // is requested, and we are not going to merge that input @@ -1027,7 +1027,7 @@ private void GetSectionRecursive( // to create a copy in the case of MgmtConfigurationRecord - // otherwise we could inadvertently return the parent to the user, // which could then be modified. - if (sectionRecord != null) + if (sectionRecord is not null) { tmpResult = UseParentResult(configKey, parentResult, sectionRecord); if (getRuntimeObject) @@ -1063,7 +1063,7 @@ private void GetSectionRecursive( // Cache the results. if (cacheResults) { - if (sectionRecord == null) sectionRecord = EnsureSectionRecord(configKey, true); + if (sectionRecord is null) sectionRecord = EnsureSectionRecord(configKey, true); sectionRecord.Result = tmpResult; if (getRuntimeObject) sectionRecord.ResultRuntimeObject = tmpResultRuntimeObject; @@ -1217,7 +1217,7 @@ private bool Evaluate( // Evaluate indirectLocationInputs. Used only in location config record. // See the comment for VSWhidbey 540184 in Init() for more details. - if (indirectLocationInputs != null) + if (indirectLocationInputs is not null) { Debug.Assert(IsLocationConfig, "indirectLocationInputs is non-null only in location config record"); @@ -1235,7 +1235,7 @@ private bool Evaluate( } // Evaluate location inputs - if (locationInputs != null) + if (locationInputs is not null) { foreach (SectionInput locationInput in locationInputs) { @@ -1251,7 +1251,7 @@ private bool Evaluate( } // Evaluate file input - if (fileInput != null) + if (fileInput is not null) { if (!fileInput.HasResult) { @@ -1272,8 +1272,8 @@ private bool Evaluate( // change to the section shouldn't go to the locationInput.Result. // // In runtime, UseParentResult does nothing. - Debug.Assert((locationInputs != null) || (indirectLocationInputs != null), - "locationInputs != null || indirectLocationInputs != null"); + Debug.Assert((locationInputs is not null) || (indirectLocationInputs is not null), + "locationInputs is not null || indirectLocationInputs is not null"); currentResult = UseParentResult(configKey, currentResult, sectionRecord); } @@ -1286,7 +1286,7 @@ private bool Evaluate( { // Catch the exception if LKG is requested and we have // location input to fall back on. - if (getLkg && (locationInputs != null)) savedException = e; + if (getLkg && (locationInputs is not null)) savedException = e; else throw; } @@ -1337,7 +1337,7 @@ private object EvaluateOne( try { ConfigXmlReader reader = GetSectionXmlReader(keys, input); - if (reader == null) + if (reader is null) { // If section is not found in a file, use the parent result result = UseParentResult(factoryRecord.ConfigKey, parentResult, sectionRecord); @@ -1368,18 +1368,18 @@ private ConfigXmlReader FindSection(string[] keys, SectionXmlInfo sectionXmlInfo { if (!_flags[SupportsRefresh] && - ((stream == null) || HasStreamChanged(sectionXmlInfo.Filename, sectionXmlInfo.StreamVersion))) + ((stream is null) || HasStreamChanged(sectionXmlInfo.Filename, sectionXmlInfo.StreamVersion))) { throw new ConfigurationErrorsException(SR.Config_file_has_changed, sectionXmlInfo.Filename, 0); } - if (stream == null) return null; + if (stream is null) return null; // CONSIDER: In refresh case, need to recheck validity of file - can't make assumptions using (XmlUtil xmlUtil = new XmlUtil(stream, sectionXmlInfo.Filename, true)) { - if (sectionXmlInfo.SubPath == null) + if (sectionXmlInfo.SubPath is null) section = FindSectionRecursive(keys, 0, xmlUtil, ref lineNumber); else { @@ -1409,7 +1409,7 @@ private ConfigXmlReader FindSection(string[] keys, SectionXmlInfo sectionXmlInfo locationSubPathAttribute)) { section = FindSectionRecursive(keys, 0, xmlUtil, ref lineNumber); - if (section != null) + if (section is not null) break; } } @@ -1442,7 +1442,7 @@ private ConfigXmlReader FindSectionRecursive(string[] keys, int iKey, XmlUtil xm { // We haven't reached the section yet, so keep evaluating section = FindSectionRecursive(keys, iKey + 1, xmlUtil, ref lineNumber); - if (section != null) break; + if (section is not null) break; continue; // don't call "Skip" -- FindSectionRecursive forwards the reader } @@ -1469,12 +1469,12 @@ private ConfigXmlReader FindSectionRecursive(string[] keys, int iKey, XmlUtil xm xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.NonSpecific); } - if (isValid && (locationSubPath == null)) + if (isValid && (locationSubPath is null)) { // Location sections that don't have a subpath are treated // as ordinary sections. section = FindSectionRecursive(keys, iKey, xmlUtil, ref lineNumber); - if (section != null) break; + if (section is not null) break; continue; // don't call "Skip" -- FindSectionRecursive forwards the reader } @@ -1492,7 +1492,7 @@ private ConfigXmlReader LoadConfigSource(string name, SectionXmlInfo sectionXmlI using (Stream stream = Host.OpenStreamForRead(configSourceStreamName)) { - if (stream == null) + if (stream is null) { throw new ConfigurationErrorsException( SR.Format(SR.Config_cannot_open_config_source, sectionXmlInfo.ConfigSource), @@ -1506,7 +1506,7 @@ private ConfigXmlReader LoadConfigSource(string name, SectionXmlInfo sectionXmlI // Check for protectionProvider string protectionProviderAttribute = xmlUtil.Reader.GetAttribute(ProtectionProviderAttibute); - if (protectionProviderAttribute != null) + if (protectionProviderAttribute is not null) { if (xmlUtil.Reader.AttributeCount != 1) { @@ -1547,7 +1547,7 @@ protected ConfigXmlReader GetSectionXmlReader(string[] keys, SectionInput input) { string name = keys[keys.Length - 1]; string rawXml = input.SectionXmlInfo.RawXml; - if (rawXml != null) + if (rawXml is not null) { // Use the stored raw xml to provide the content of the section. reader = new ConfigXmlReader(rawXml, input.SectionXmlInfo.Filename, input.SectionXmlInfo.LineNumber); @@ -1569,7 +1569,7 @@ protected ConfigXmlReader GetSectionXmlReader(string[] keys, SectionInput input) } } - if (reader != null) + if (reader is not null) { if (!input.IsProtectionProviderDetermined) { @@ -1577,7 +1577,7 @@ protected ConfigXmlReader GetSectionXmlReader(string[] keys, SectionInput input) GetProtectionProviderFromName(input.SectionXmlInfo.ProtectionProviderName, false); } - if (input.ProtectionProvider != null) + if (input.ProtectionProvider is not null) reader = DecryptConfigSection(reader, input.ProtectionProvider); } } @@ -1608,7 +1608,7 @@ internal void InitProtectedConfigurationSection() _protectedConfig = GetSection(ReservedSectionProtectedConfiguration, false, false) as ProtectedConfigurationSection; - Debug.Assert(_protectedConfig != null, + Debug.Assert(_protectedConfig is not null, " section should always be available because it's a built-in section"); _flags[ProtectedDataInitialized] = true; @@ -1624,7 +1624,7 @@ protected object CallCreateSection(bool inputIsTrusted, FactoryRecord factoryRec try { config = CreateSection(inputIsTrusted, factoryRecord, sectionRecord, parentConfig, reader); - if ((config == null) && (parentConfig != null)) + if ((config is null) && (parentConfig is not null)) throw new ConfigurationErrorsException(SR.Config_object_is_null, filename, line); } catch (ThreadAbortException) @@ -1651,7 +1651,7 @@ internal bool IsRootDeclaration(string configKey, bool implicitIsRooted) { if (!implicitIsRooted && IsImplicitSection(configKey)) return false; - return _parent.IsRootConfig || (_parent.FindFactoryRecord(configKey, true) == null); + return _parent.IsRootConfig || (_parent.FindFactoryRecord(configKey, true) is null); } // Search the config hierarchy for a FactoryRecord. @@ -1665,7 +1665,7 @@ internal FactoryRecord FindFactoryRecord(string configKey, bool permitErrors, while (!tConfigRecord.IsRootConfig) { FactoryRecord factoryRecord = tConfigRecord.GetFactoryRecord(configKey, permitErrors); - if (factoryRecord != null) + if (factoryRecord is not null) { #if DEBUG if (IsImplicitSection(configKey) && !factoryRecord.HasErrors) @@ -1701,7 +1701,7 @@ private FactoryRecord FindAndEnsureFactoryRecord(string configKey, out bool isRo BaseConfigurationRecord configRecord; FactoryRecord factoryRecord = FindFactoryRecord(configKey, false, out configRecord); - if ((factoryRecord == null) || factoryRecord.IsGroup) return factoryRecord; + if ((factoryRecord is null) || factoryRecord.IsGroup) return factoryRecord; // Find the root declaration FactoryRecord rootFactoryRecord = factoryRecord; @@ -1713,7 +1713,7 @@ private FactoryRecord FindAndEnsureFactoryRecord(string configKey, out bool isRo BaseConfigurationRecord tempConfigRecord; FactoryRecord tempFactoryRecord = currentConfigRecord.FindFactoryRecord(configKey, false, out tempConfigRecord); - if (tempFactoryRecord == null) + if (tempFactoryRecord is null) break; rootFactoryRecord = tempFactoryRecord; @@ -1726,7 +1726,7 @@ private FactoryRecord FindAndEnsureFactoryRecord(string configKey, out bool isRo // A child factory record must be equivalent to its parent, // so if the child has no errors, the parent must also have no errors. Debug.Assert(!rootFactoryRecord.HasErrors, "!rootFactoryRecord.HasErrors"); - if (rootFactoryRecord.Factory == null) + if (rootFactoryRecord.Factory is null) { try { @@ -1742,7 +1742,7 @@ private FactoryRecord FindAndEnsureFactoryRecord(string configKey, out bool isRo } } - if (factoryRecord.Factory == null) + if (factoryRecord.Factory is null) { factoryRecord.Factory = rootFactoryRecord.Factory; } @@ -1862,7 +1862,7 @@ private void ScanFactoriesRecursive(XmlUtil xmlUtil, string parentConfigKey, Has string configKey = CombineConfigKey(parentConfigKey, tagName); FactoryRecord factoryRecord = (FactoryRecord)factoryList[configKey]; - if (factoryRecord != null) + if (factoryRecord is not null) { // Error: duplicate declaration xmlUtil.SchemaErrors.AddError( @@ -1873,12 +1873,12 @@ private void ScanFactoriesRecursive(XmlUtil xmlUtil, string parentConfigKey, Has { // Look for a factory of the same name in the parent FactoryRecord parentFactoryRecord = _parent.FindFactoryRecord(configKey, true); - if (parentFactoryRecord != null) + if (parentFactoryRecord is not null) { configKey = parentFactoryRecord.ConfigKey; // make sure that an ancestor has not defined a
with the same name as the - if ((parentFactoryRecord != null) && + if ((parentFactoryRecord is not null) && (!parentFactoryRecord.IsGroup || !parentFactoryRecord.IsEquivalentSectionGroupFactory(Host, typeName))) { xmlUtil.SchemaErrors.AddError( @@ -1998,7 +1998,7 @@ private void ScanFactoriesRecursive(XmlUtil xmlUtil, string parentConfigKey, Has string configKey = CombineConfigKey(parentConfigKey, tagName); FactoryRecord factoryRecord = (FactoryRecord)factoryList[configKey]; - if (factoryRecord != null) + if (factoryRecord is not null) { // Error: duplicate section declaration xmlUtil.SchemaErrors.AddError( @@ -2010,7 +2010,7 @@ private void ScanFactoriesRecursive(XmlUtil xmlUtil, string parentConfigKey, Has else { FactoryRecord parentFactoryRecord = _parent.FindFactoryRecord(configKey, true); - if (parentFactoryRecord != null) + if (parentFactoryRecord is not null) { // We have a parent factory record with the same name configKey = parentFactoryRecord.ConfigKey; @@ -2219,7 +2219,7 @@ private OverrideMode ResolveOverrideModeFromParent(string configKey, out Overrid { SectionRecord sectionRecord = parent.GetSectionRecord(configKey, true); - if (sectionRecord != null) + if (sectionRecord is not null) { // Check for 1a if (IsLocationConfig && ReferenceEquals(immediateParent, parent)) @@ -2249,13 +2249,13 @@ private OverrideMode ResolveOverrideModeFromParent(string configKey, out Overrid // Case 2 if (mode == OverrideMode.Inherit) { - Debug.Assert(FindFactoryRecord(configKey, true) != null); + Debug.Assert(FindFactoryRecord(configKey, true) is not null); bool atDeclarationLevel; OverrideMode defaultMode = FindFactoryRecord(configKey, true).OverrideModeDefault.OverrideMode; - if (IsLocationConfig) atDeclarationLevel = Parent.GetFactoryRecord(configKey, true) != null; - else atDeclarationLevel = GetFactoryRecord(configKey, true) != null; + if (IsLocationConfig) atDeclarationLevel = Parent.GetFactoryRecord(configKey, true) is not null; + else atDeclarationLevel = GetFactoryRecord(configKey, true) is not null; if (!atDeclarationLevel) { @@ -2306,7 +2306,7 @@ protected OverrideMode GetSectionLockedMode(string configKey, out OverrideMode c // As long as nobody uses EnsureSectionRecordUnsafe this method will be returning the correct // lock value only by looking at the section record - if (sectionRecord != null) + if (sectionRecord is not null) { result = sectionRecord.Locked ? OverrideMode.Deny : OverrideMode.Allow; childLockMode = sectionRecord.LockChildren ? OverrideMode.Deny : OverrideMode.Allow; @@ -2382,7 +2382,7 @@ private void ScanSectionsRecursive( // Find the relevant factory record FactoryRecord factoryRecord = FindFactoryRecord(configKey, true); - if (factoryRecord == null) + if (factoryRecord is null) { // Unregistered configuration section, add DefaultSection factory for it. // @@ -2465,7 +2465,7 @@ private void ScanSectionsRecursive( OverrideMode sectionLockMode = OverrideMode.Inherit; OverrideMode sectionChildLockMode = OverrideMode.Inherit; bool positionedAtNextElement = false; - bool isFileInput = locationSubPath == null; + bool isFileInput = locationSubPath is null; if (!factoryRecord.HasErrors) { @@ -2483,7 +2483,7 @@ private void ScanSectionsRecursive( { // Verify that the section is unique SectionRecord sectionRecord = GetSectionRecord(configKey, true); - if ((sectionRecord != null) && sectionRecord.HasFileInput) + if ((sectionRecord is not null) && sectionRecord.HasFileInput) { if (!factoryRecord.IsIgnorable()) { @@ -2521,7 +2521,7 @@ private void ScanSectionsRecursive( // First do all the attributes reading without advancing the reader. string configSourceAttribute = xmlUtil.Reader.GetAttribute(ConfigSourceAttribute); - if (configSourceAttribute != null) + if (configSourceAttribute is not null) { try { @@ -2542,7 +2542,7 @@ private void ScanSectionsRecursive( } string protectionProviderAttribute = xmlUtil.Reader.GetAttribute(ProtectionProviderAttibute); - if (protectionProviderAttribute != null) + if (protectionProviderAttribute is not null) { try { @@ -2567,7 +2567,7 @@ private void ScanSectionsRecursive( // The 2nd part of the configSource check requires advancing the reader. // Please note that this part should be done only AFTER all other attributes // checking are done. - if (configSourceAttribute != null) + if (configSourceAttribute is not null) { if (!xmlUtil.Reader.IsEmptyElement) { @@ -2595,7 +2595,7 @@ private void ScanSectionsRecursive( } } - if (configSource != null) + if (configSource is not null) { try { @@ -2621,7 +2621,7 @@ private void ScanSectionsRecursive( // prefetch the raw xml if (!xmlUtil.SchemaErrors.HasLocalErrors) { - if ((configSource == null) && ShouldPrefetchRawXml(factoryRecord)) + if ((configSource is null) && ShouldPrefetchRawXml(factoryRecord)) { Debug.Assert(!positionedAtNextElement, "!positionedAtNextElement"); @@ -2667,7 +2667,7 @@ private void ScanSectionsRecursive( if (addInput) { - string targetConfigPath = locationSubPath == null ? _configPath : null; + string targetConfigPath = locationSubPath is null ? _configPath : null; SectionXmlInfo sectionXmlInfo = new SectionXmlInfo( configKey, _configPath, targetConfigPath, locationSubPath, @@ -2675,7 +2675,7 @@ private void ScanSectionsRecursive( configSource, configSourceStreamName, configSourceStreamVersion, protectionProviderName, overrideMode, skipInChildApps); - if (locationSubPath == null) + if (locationSubPath is null) { // Add this file input to the section record @@ -2777,7 +2777,7 @@ private void ScanLocationSection(XmlUtil xmlUtil) // Host.IsDefinitionAllowed. Instead of this we should invent a new method in // IInternalConfigHost to return whether a configPath can be part of an app or not. // But since it's Whidbey RC "Ask Mode" I chose not to do it due to bigger code churn. - if ((locationSubPath == null) && + if ((locationSubPath is null) && !inheritInChildApp && Host.IsDefinitionAllowed(_configPath, ConfigurationAllowDefinition.MachineToWebRoot, ConfigurationAllowExeDefinition.MachineOnly)) @@ -2801,7 +2801,7 @@ private void ScanLocationSection(XmlUtil xmlUtil) // Scan elements of the location section if the path is the current path. // We do not add to the _locationSections list. - if (locationSubPath == null) + if (locationSubPath is null) { ScanSectionsRecursive(xmlUtil, string.Empty, true, null, overrideMode, !inheritInChildApp); return; @@ -2816,14 +2816,14 @@ private void ScanLocationSection(XmlUtil xmlUtil) // Skip over location sections that don't apply to this (application) host for runtime records IInternalConfigHost host = Host; - if (this is RuntimeConfigurationRecord && (host != null) && (locationSubPath.Length != 0) && + if (this is RuntimeConfigurationRecord && (host is not null) && (locationSubPath.Length != 0) && (locationSubPath[0] != '.')) { // The application's config path is global to the AppDomain - if (s_appConfigPath == null) + if (s_appConfigPath is null) { object ctx = ConfigContext; - if (ctx != null) + if (ctx is not null) { string appConfigPath = ctx.ToString(); Interlocked.CompareExchange(ref s_appConfigPath, appConfigPath, null); @@ -2870,7 +2870,7 @@ private void ResolveLocationSections() { if (!_flags[IsLocationListResolved]) { - if (_locationSections != null) + if (_locationSections is not null) { // Create dictionary that maps configPaths to (dictionary that maps sectionNames to locationSectionRecords) HybridDictionary locationConfigPaths = new HybridDictionary(true); @@ -2884,7 +2884,7 @@ private void ResolveLocationSections() // Check uniqueness HybridDictionary locationSectionRecordDictionary = (HybridDictionary)locationConfigPaths[targetConfigPath]; - if (locationSectionRecordDictionary == null) + if (locationSectionRecordDictionary is null) { locationSectionRecordDictionary = new HybridDictionary(false); locationConfigPaths.Add(targetConfigPath, locationSectionRecordDictionary); @@ -2894,7 +2894,7 @@ private void ResolveLocationSections() (LocationSectionRecord) locationSectionRecordDictionary[locationSectionRecord.ConfigKey]; FactoryRecord factoryRecord = null; - if (duplicateRecord == null) + if (duplicateRecord is null) { locationSectionRecordDictionary.Add(locationSectionRecord.ConfigKey, locationSectionRecord); @@ -2902,7 +2902,7 @@ private void ResolveLocationSections() else { factoryRecord = FindFactoryRecord(locationSectionRecord.ConfigKey, true); - if ((factoryRecord == null) || !factoryRecord.IsIgnorable()) + if ((factoryRecord is null) || !factoryRecord.IsIgnorable()) { if (!duplicateRecord.HasErrors) { @@ -2920,7 +2920,7 @@ private void ResolveLocationSections() } // Check if the definition is allowed - if (factoryRecord == null) + if (factoryRecord is null) factoryRecord = FindFactoryRecord(locationSectionRecord.ConfigKey, true); if (factoryRecord.HasErrors) continue; @@ -2947,14 +2947,14 @@ private void ResolveLocationSections() // It is an error if a parent section with the same configKey is locked. SectionRecord sectionRecord = parent.GetSectionRecord(locationSectionRecord.ConfigKey, true); - if ((sectionRecord != null) && + if ((sectionRecord is not null) && (sectionRecord.LockChildren || sectionRecord.Locked)) locked = true; else { // It is an error if a parent configuration file locks a section for the // locationConfigPath or any sub-path of the locationConfigPath. - if (parent._locationSections != null) + if (parent._locationSections is not null) { string targetConfigPath = locationSectionRecord.SectionXmlInfo.TargetConfigPath; @@ -3114,10 +3114,10 @@ protected SectionRecord GetSectionRecord(string configKey, bool permitErrors) { SectionRecord sectionRecord; - if (_sectionRecords != null) sectionRecord = (SectionRecord)_sectionRecords[configKey]; + if (_sectionRecords is not null) sectionRecord = (SectionRecord)_sectionRecords[configKey]; else sectionRecord = null; - if ((sectionRecord != null) && !permitErrors) sectionRecord.ThrowOnErrors(); + if ((sectionRecord is not null) && !permitErrors) sectionRecord.ThrowOnErrors(); return sectionRecord; } @@ -3142,14 +3142,14 @@ protected SectionRecord EnsureSectionRecordUnsafe(string configKey, bool permitE private SectionRecord EnsureSectionRecordImpl(string configKey, bool permitErrors, bool setLockSettings) { SectionRecord sectionRecord = GetSectionRecord(configKey, permitErrors); - if (sectionRecord != null) return sectionRecord; + if (sectionRecord is not null) return sectionRecord; lock (this) { - if (_sectionRecords == null) _sectionRecords = new Hashtable(); + if (_sectionRecords is null) _sectionRecords = new Hashtable(); else sectionRecord = GetSectionRecord(configKey, permitErrors); - if (sectionRecord == null) + if (sectionRecord is null) { sectionRecord = new SectionRecord(configKey); @@ -3171,10 +3171,10 @@ private SectionRecord EnsureSectionRecordImpl(string configKey, bool permitError internal FactoryRecord GetFactoryRecord(string configKey, bool permitErrors) { - if (_factoryRecords == null) return null; + if (_factoryRecords is null) return null; FactoryRecord factoryRecord = (FactoryRecord)_factoryRecords[configKey]; - if ((factoryRecord != null) && !permitErrors) factoryRecord.ThrowOnErrors(); + if ((factoryRecord is not null) && !permitErrors) factoryRecord.ThrowOnErrors(); return factoryRecord; } @@ -3221,7 +3221,7 @@ protected object MonitorStream(string configKey, string configSource, string str if (_flags[Closed]) return null; StreamInfo streamInfo = (StreamInfo)ConfigStreamInfo.StreamInfos[streamname]; - if (streamInfo != null) + if (streamInfo is not null) { if (streamInfo.SectionName != configKey) { @@ -3255,7 +3255,7 @@ protected object MonitorStream(string configKey, string configSource, string str if (_flags[SupportsChangeNotifications]) { - if (ConfigStreamInfo.CallbackDelegate == null) + if (ConfigStreamInfo.CallbackDelegate is null) ConfigStreamInfo.CallbackDelegate = OnStreamChanged; callbackDelegate = ConfigStreamInfo.CallbackDelegate; @@ -3278,13 +3278,13 @@ private void OnStreamChanged(string streamname) return; StreamInfo streamInfo = (StreamInfo)ConfigStreamInfo.StreamInfos[streamname]; - if ((streamInfo == null) || !streamInfo.IsMonitored) + if ((streamInfo is null) || !streamInfo.IsMonitored) return; sectionName = streamInfo.SectionName; } - if (sectionName == null) notifyChanged = true; + if (sectionName is null) notifyChanged = true; else { FactoryRecord factoryRecord = FindFactoryRecord(sectionName, false); @@ -3312,7 +3312,7 @@ private void ValidateUniqueConfigSource( if (ConfigStreamInfo.HasStreamInfos) { StreamInfo streamInfo = (StreamInfo)ConfigStreamInfo.StreamInfos[configSourceStreamName]; - if ((streamInfo != null) && (streamInfo.SectionName != configKey)) + if ((streamInfo is not null) && (streamInfo.SectionName != configKey)) { throw new ConfigurationErrorsException( SR.Format(SR.Config_source_cannot_be_shared, configSourceArg), @@ -3338,7 +3338,7 @@ protected void ValidateUniqueChildConfigSource( { StreamInfo streamInfo = (StreamInfo)current.ConfigStreamInfo.StreamInfos[configSourceStreamName]; - if (streamInfo != null) + if (streamInfo is not null) { throw new ConfigurationErrorsException( SR.Format(SR.Config_source_parent_conflict, configSourceArg), @@ -3362,7 +3362,7 @@ internal void HlClearResultRecursive(string configKey, bool forceEvaluatation) // Clear any stored result in the section SectionRecord sectionRecord = GetSectionRecord(configKey, false); - if (sectionRecord != null) + if (sectionRecord is not null) { sectionRecord.ClearResult(); @@ -3378,7 +3378,7 @@ internal void HlClearResultRecursive(string configKey, bool forceEvaluatation) throw ExceptionUtil.UnexpectedError("BaseConfigurationRecord::hlClearResultRecursive"); FactoryRecord factoryRecord = FindFactoryRecord(configKey, false); - if ((factoryRecord != null) && !factoryRecord.IsGroup) + if ((factoryRecord is not null) && !factoryRecord.IsGroup) { configKey = factoryRecord.ConfigKey; sectionRecord = EnsureSectionRecord(configKey, false); @@ -3397,7 +3397,7 @@ internal void HlClearResultRecursive(string configKey, bool forceEvaluatation) } // Recurse - if (_children != null) + if (_children is not null) { IEnumerable children = _children.Values; foreach (BaseConfigurationRecord child in children) @@ -3416,7 +3416,7 @@ internal BaseConfigurationRecord HlGetChild(string configName) // Requires the hierarchy lock to be acquired (hl) internal void HlAddChild(string configName, BaseConfigurationRecord child) { - if (_children == null) _children = new Hashtable(StringComparer.OrdinalIgnoreCase); + if (_children is null) _children = new Hashtable(StringComparer.OrdinalIgnoreCase); _children.Add(configName, child); } @@ -3451,7 +3451,7 @@ internal bool HlNeedsChildFor(string configName) while (!configRecord.IsRootConfig) { - if (configRecord._locationSections != null) + if (configRecord._locationSections is not null) { configRecord.ResolveLocationSections(); foreach (LocationSectionRecord locationSectionRecord in configRecord._locationSections) @@ -3504,10 +3504,10 @@ internal void CloseRecursive() // no hierarchy lock is needed to access _children here, // as it has already been detached from the hierarchy tree - if (_children != null) + if (_children is not null) foreach (BaseConfigurationRecord child in _children.Values) child.CloseRecursive(); - if (streamInfos != null) + if (streamInfos is not null) { foreach (StreamInfo streamInfo in streamInfos.Values) if (streamInfo.IsMonitored) @@ -3543,9 +3543,9 @@ private bool HasStreamChanged(string streamname, object lastVersion) { object currentVersion = Host.GetStreamVersion(streamname); - if (lastVersion != null) return (currentVersion == null) || !lastVersion.Equals(currentVersion); + if (lastVersion is not null) return (currentVersion is null) || !lastVersion.Equals(currentVersion); - return currentVersion != null; + return currentVersion is not null; } protected virtual string CallHostDecryptSection(string encryptedXml, @@ -3657,12 +3657,12 @@ private void AddImplicitSections(Hashtable factoryList) // (e.g. if we're in machine.config) if (!_parent.IsRootConfig) return; - if (factoryList == null) factoryList = EnsureFactories(); + if (factoryList is null) factoryList = EnsureFactories(); // Look to see if we already have a factory for "configProtectedData" FactoryRecord factoryRecord = (FactoryRecord)factoryList[ReservedSectionProtectedConfiguration]; - if (factoryRecord != null) + if (factoryRecord is not null) { // If the user has mistakenly declared an implicit section, we should leave the factoryRecord // alone because it contains the error and the error will be thrown later. @@ -3719,7 +3719,7 @@ internal ConfigRecordStreamInfo() internal HybridDictionary StreamInfos => _streamInfos ?? (_streamInfos = new HybridDictionary(true)); - internal bool HasStreamInfos => _streamInfos != null; + internal bool HasStreamInfos => _streamInfos is not null; #if DEBUG internal string[] Keys diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs index e92c4f215aa63a..53e2f2a247e8a1 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs @@ -10,21 +10,21 @@ public sealed class CallbackValidator : ConfigurationValidatorBase public CallbackValidator(Type type, ValidatorCallback callback) : this(callback) { - if (type == null) throw new ArgumentNullException(nameof(type)); + if (type is null) throw new ArgumentNullException(nameof(type)); _type = type; } // Do not check for null type here to handle the callback attribute case internal CallbackValidator(ValidatorCallback callback) { - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback is null) throw new ArgumentNullException(nameof(callback)); _type = null; _callback = callback; } public override bool CanValidate(Type type) { - return (type == _type) || (_type == null); + return (type == _type) || (_type is null); } public override void Validate(object value) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidatorAttribute.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidatorAttribute.cs index 9c89dee73ec6e3..6790f61dc222b7 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidatorAttribute.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidatorAttribute.cs @@ -16,15 +16,15 @@ public override ConfigurationValidatorBase ValidatorInstance { get { - if (_callbackMethod == null) + if (_callbackMethod is null) { - if (_type == null) throw new ArgumentNullException(nameof(Type)); + if (_type is null) throw new ArgumentNullException(nameof(Type)); if (!string.IsNullOrEmpty(_callbackMethodName)) { MethodInfo methodInfo = _type.GetMethod(_callbackMethodName, BindingFlags.Public | BindingFlags.Static); - if (methodInfo != null) + if (methodInfo is not null) { ParameterInfo[] parameters = methodInfo.GetParameters(); if ((parameters.Length == 1) && (parameters[0].ParameterType == typeof(object))) @@ -35,7 +35,7 @@ public override ConfigurationValidatorBase ValidatorInstance } } - if (_callbackMethod == null) + if (_callbackMethod is null) throw new ArgumentException(SR.Format(SR.Validator_method_not_found, _callbackMethodName)); return new CallbackValidator(_callbackMethod); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs index 6c95205da167a0..9aa601c3247035 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs @@ -35,7 +35,7 @@ private ClientConfigPaths(string exePath, bool includeUserConfig) Assembly exeAssembly = null; bool isSingleFile = false; - if (exePath != null) + if (exePath is not null) { // Exe path was specified, use it ApplicationUri = Path.GetFullPath(exePath); @@ -56,7 +56,7 @@ private ClientConfigPaths(string exePath, bool includeUserConfig) HasEntryAssembly = true; } - if (exeAssembly != null && !isSingleFile) + if (exeAssembly is not null && !isSingleFile) { HasEntryAssembly = true; @@ -105,7 +105,7 @@ private ClientConfigPaths(string exePath, bool includeUserConfig) // In the case when exePath was explicitly supplied, we will not be able to // construct user.config paths, so quit here. - if (exePath != null) return; + if (exePath is not null) return; // Skip expensive initialization of user config file information if requested. if (!_includesUserConfig) return; @@ -163,13 +163,13 @@ private ClientConfigPaths(string exePath, bool includeUserConfig) internal string RoamingConfigDirectory { get; } - internal bool HasRoamingConfig => (RoamingConfigFilename != null) || !_includesUserConfig; + internal bool HasRoamingConfig => (RoamingConfigFilename is not null) || !_includesUserConfig; internal string LocalConfigFilename { get; } internal string LocalConfigDirectory { get; } - internal bool HasLocalConfig => (LocalConfigFilename != null) || !_includesUserConfig; + internal bool HasLocalConfig => (LocalConfigFilename is not null) || !_includesUserConfig; internal string ProductName { get; private set; } @@ -179,9 +179,9 @@ internal static ClientConfigPaths GetPaths(string exePath, bool includeUserConfi { ClientConfigPaths result; - if (exePath == null) + if (exePath is null) { - if ((s_current == null) || (includeUserConfig && !s_currentIncludesUserConfig)) + if ((s_current is null) || (includeUserConfig && !s_currentIncludesUserConfig)) { s_current = new ClientConfigPaths(null, includeUserConfig); s_currentIncludesUserConfig = includeUserConfig; @@ -203,7 +203,7 @@ internal static void RefreshCurrent() // Combines path2 with path1 if possible, else returns null. private static string CombineIfValid(string path1, string path2) { - if ((path1 == null) || (path2 == null)) return null; + if ((path1 is null) || (path2 is null)) return null; try { @@ -227,7 +227,7 @@ private static string GetTypeAndHashSuffix(string exePath, bool isSingleFile) string typeName = null; string hash = null; - if (assembly != null && !isSingleFile) + if (assembly is not null && !isSingleFile) { AssemblyName assemblyName = assembly.GetName(); Uri codeBase = new Uri(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assembly.ManifestModule.Name)); @@ -239,7 +239,7 @@ private static string GetTypeAndHashSuffix(string exePath, bool isSingleFile) } catch (PlatformNotSupportedException) { } - if (hash != null) + if (hash is not null) { typeName = StrongNameDesc; } @@ -276,16 +276,16 @@ private void SetNamesAndVersion(Assembly exeAssembly, bool isHttp) // Get CompanyName, ProductName, and ProductVersion // First try custom attributes on the assembly. - if (exeAssembly != null) + if (exeAssembly is not null) { object[] attrs = exeAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); - if ((attrs != null) && (attrs.Length > 0)) + if ((attrs is not null) && (attrs.Length > 0)) { _companyName = ((AssemblyCompanyAttribute)attrs[0]).Company?.Trim(); } attrs = exeAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); - if ((attrs != null) && (attrs.Length > 0)) + if ((attrs is not null) && (attrs.Length > 0)) { ProductName = ((AssemblyProductAttribute)attrs[0]).Product?.Trim(); } @@ -298,22 +298,22 @@ private void SetNamesAndVersion(Assembly exeAssembly, bool isHttp) (string.IsNullOrEmpty(_companyName) || string.IsNullOrEmpty(ProductName) || string.IsNullOrEmpty(ProductVersion))) { - if (exeAssembly != null) + if (exeAssembly is not null) { MethodInfo entryPoint = exeAssembly.EntryPoint; - if (entryPoint != null) + if (entryPoint is not null) { mainType = entryPoint.ReflectedType; } } string ns = null; - if (mainType != null) ns = mainType.Namespace; + if (mainType is not null) ns = mainType.Namespace; if (string.IsNullOrEmpty(ProductName)) { // Try the remainder of the namespace - if (ns != null) + if (ns is not null) { int lastDot = ns.LastIndexOf('.'); if ((lastDot != -1) && (lastDot < ns.Length - 1)) ProductName = ns.Substring(lastDot + 1); @@ -323,16 +323,16 @@ private void SetNamesAndVersion(Assembly exeAssembly, bool isHttp) } // Try the type of the entry assembly - if (string.IsNullOrEmpty(ProductName) && (mainType != null)) ProductName = mainType.Name.Trim(); + if (string.IsNullOrEmpty(ProductName) && (mainType is not null)) ProductName = mainType.Name.Trim(); // give up, return empty string - if (ProductName == null) ProductName = string.Empty; + if (ProductName is null) ProductName = string.Empty; } if (string.IsNullOrEmpty(_companyName)) { // Try the first part of the namespace - if (ns != null) + if (ns is not null) { int firstDot = ns.IndexOf('.'); _companyName = firstDot != -1 ? ns.Substring(0, firstDot) : ns; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs index c906306c539276..550676c9b05fe4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs @@ -43,7 +43,7 @@ internal static string MachineConfigFilePath { get { - if (s_machineConfigFilePath == null) + if (s_machineConfigFilePath is null) { string directory = AppDomain.CurrentDomain.BaseDirectory; s_machineConfigFilePath = Path.Combine(Path.Combine(directory, MachineConfigSubdirectory), @@ -58,7 +58,7 @@ public override bool HasRoamingConfig { get { - if (_fileMap != null) return !string.IsNullOrEmpty(_fileMap.RoamingUserConfigFilename); + if (_fileMap is not null) return !string.IsNullOrEmpty(_fileMap.RoamingUserConfigFilename); else return ConfigPaths.HasRoamingConfig; } } @@ -67,7 +67,7 @@ public override bool HasLocalConfig { get { - if (_fileMap != null) return !string.IsNullOrEmpty(_fileMap.LocalUserConfigFilename); + if (_fileMap is not null) return !string.IsNullOrEmpty(_fileMap.LocalUserConfigFilename); else return ConfigPaths.HasLocalConfig; } } @@ -114,7 +114,7 @@ string IInternalConfigClientHost.GetLocalUserConfigPath() public override void RefreshConfigPaths() { // Refresh current config paths. - if ((_configPaths != null) && !_configPaths.HasEntryAssembly && (_exePath == null)) + if ((_configPaths is not null) && !_configPaths.HasEntryAssembly && (_exePath is null)) { ClientConfigPaths.RefreshCurrent(); _configPaths = null; @@ -141,20 +141,20 @@ public override void Init(IInternalConfigRoot configRoot, params object[] hostIn // loading user.config files that may not be required. _initComplete = configRoot.IsDesignTime; - if ((fileMap != null) && !string.IsNullOrEmpty(_exePath)) + if ((fileMap is not null) && !string.IsNullOrEmpty(_exePath)) throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init"); if (string.IsNullOrEmpty(_exePath)) _exePath = null; // Initialize the fileMap, if provided. - if (fileMap != null) + if (fileMap is not null) { _fileMap = new ExeConfigurationFileMap(); if (!string.IsNullOrEmpty(fileMap.MachineConfigFilename)) _fileMap.MachineConfigFilename = Path.GetFullPath(fileMap.MachineConfigFilename); ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap; - if (exeFileMap != null) + if (exeFileMap is not null) { if (!string.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) _fileMap.ExeConfigFilename = Path.GetFullPath(exeFileMap.ExeConfigFilename); @@ -280,7 +280,7 @@ public override Stream OpenStreamForRead(string streamName) // the streamName can either be a file name, or a URI if (IsFile(streamName)) return Host.OpenStreamForRead(streamName); - if (streamName == null) return null; + if (streamName is null) return null; // scheme is http WebClient client = new WebClient(); @@ -299,7 +299,7 @@ public override Stream OpenStreamForRead(string streamName) } catch { } - if (fileData == null) return null; + if (fileData is null) return null; MemoryStream stream = new MemoryStream(fileData); return stream; @@ -436,13 +436,13 @@ internal static Configuration OpenExeConfiguration(ConfigurationFileMap fileMap, } // validate fileMap arguments - if (fileMap != null) + if (fileMap is not null) { if (string.IsNullOrEmpty(fileMap.MachineConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(fileMap.MachineConfigFilename)); ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap; - if (exeFileMap != null) + if (exeFileMap is not null) { switch (userLevel) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationSystem.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationSystem.cs index b57b402282606c..ea6b3a8fb0c37a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationSystem.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationSystem.cs @@ -198,7 +198,7 @@ private void PrepareClientConfigSystem(string sectionName) if (!_isUserConfigInited) EnsureInit(sectionName); // If an error occurred during initialzation, throw it. - if (_initError != null) throw _initError; + if (_initError is not null) throw _initError; } // If config has been removed because initialization was not complete, diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs index d342d6eb607cd1..b87b920ac07150 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs @@ -37,11 +37,11 @@ private ClientSettingsSection GetConfigSection(Configuration config, string sect string fullSectionName = UserSettingsGroupPrefix + sectionName; ClientSettingsSection section = null; - if (config != null) + if (config is not null) { section = config.GetSection(fullSectionName) as ClientSettingsSection; - if (section == null && declare) + if (section is null && declare) { // Looks like the section isn't declared - let's declare it and try again. DeclareSection(config, sectionName); @@ -58,7 +58,7 @@ private void DeclareSection(Configuration config, string sectionName) { ConfigurationSectionGroup settingsGroup = config.GetSectionGroup(UserSettingsGroupName); - if (settingsGroup == null) + if (settingsGroup is null) { //Declare settings group ConfigurationSectionGroup group = new UserSettingsGroup(); @@ -67,12 +67,12 @@ private void DeclareSection(Configuration config, string sectionName) settingsGroup = config.GetSectionGroup(UserSettingsGroupName); - Debug.Assert(settingsGroup != null, "Failed to declare settings group"); + Debug.Assert(settingsGroup is not null, "Failed to declare settings group"); - if (settingsGroup != null) + if (settingsGroup is not null) { ConfigurationSection section = settingsGroup.Sections[sectionName]; - if (section == null) + if (section is null) { section = new ClientSettingsSection(); section.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; @@ -95,7 +95,7 @@ internal IDictionary ReadSettings(string sectionName, bool isUserScoped) ConfigurationManager.RefreshSection(prefix + sectionName); ClientSettingsSection section = ConfigurationManager.GetSection(prefix + sectionName) as ClientSettingsSection; - if (section != null) + if (section is not null) { foreach (SettingElement setting in section.Settings) { @@ -135,7 +135,7 @@ internal static IDictionary ReadSettingsFromFile(string configFileName, string s Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel); ClientSettingsSection section = config.GetSection(prefix + sectionName) as ClientSettingsSection; - if (section != null) + if (section is not null) { foreach (SettingElement setting in section.Settings) { @@ -162,7 +162,7 @@ internal void RevertToParent(string sectionName, bool isRoaming) ClientSettingsSection section = GetConfigSection(config, sectionName, false); // If the section is null, there is nothing to revert. - if (section != null) + if (section is not null) { section.SectionInformation.RevertToParent(); config.Save(); @@ -179,14 +179,14 @@ internal void WriteSettings(string sectionName, bool isRoaming, IDictionary newS Configuration config = GetUserConfig(isRoaming); ClientSettingsSection section = GetConfigSection(config, sectionName, true); - if (section != null) + if (section is not null) { SettingElementCollection sec = section.Settings; foreach (DictionaryEntry entry in newSettings) { SettingElement se = sec.Get((string)entry.Key); - if (se == null) + if (se is null) { se = new SettingElement(); se.Name = (string)entry.Key; @@ -240,7 +240,7 @@ internal static IInternalConfigConfigurationFactory ConfigFactory { get { - if (s_configFactory == null) + if (s_configFactory is null) { s_configFactory = TypeUtil.CreateInstance(InternalConfigConfigurationFactoryTypeName); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigDefinitionUpdates.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigDefinitionUpdates.cs index 53039f2420a63f..6c4efeef7c21b7 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigDefinitionUpdates.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigDefinitionUpdates.cs @@ -33,7 +33,7 @@ internal DefinitionUpdate AddUpdate(OverrideModeSetting overrideMode, bool inher string updatedXml, SectionRecord sectionRecord) { LocationUpdates locationUpdates = FindLocationUpdates(overrideMode, inheritInChildApps); - if (locationUpdates == null) + if (locationUpdates is null) { locationUpdates = new LocationUpdates(overrideMode, inheritInChildApps); LocationUpdatesList.Add(locationUpdates); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlAttribute.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlAttribute.cs index 5fd15bcfd96b14..5cc7c1079e7269 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlAttribute.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlAttribute.cs @@ -27,7 +27,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlAttribute clone = cloneNode as ConfigXmlAttribute; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlCDataSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlCDataSection.cs index 300a04edcbfa71..7869f716e65e1a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlCDataSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlCDataSection.cs @@ -26,7 +26,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlCDataSection clone = cloneNode as ConfigXmlCDataSection; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlComment.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlComment.cs index 990fb31b5e831f..48e53a036be2b6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlComment.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlComment.cs @@ -26,7 +26,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlComment clone = cloneNode as ConfigXmlComment; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs index d90c3bb252585f..790f8351085aed 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs @@ -24,7 +24,7 @@ int IConfigErrorInfo.LineNumber { get { - if (_reader == null) + if (_reader is null) { return 0; } @@ -61,7 +61,7 @@ public override void Load(string filename) } finally { - if (_reader != null) + if (_reader is not null) { _reader.Close(); _reader = null; @@ -82,7 +82,7 @@ public void LoadSingleElement(string filename, XmlTextReader sourceReader) } finally { - if (_reader != null) + if (_reader is not null) { _reader.Close(); _reader = null; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlElement.cs index df1fd9980e0d0c..4196bb26486fdd 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlElement.cs @@ -27,7 +27,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlElement clone = cloneNode as ConfigXmlElement; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlSignificantWhitespace.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlSignificantWhitespace.cs index 451be5474f83ee..749c7bfb2a9e57 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlSignificantWhitespace.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlSignificantWhitespace.cs @@ -26,7 +26,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlSignificantWhitespace clone = cloneNode as ConfigXmlSignificantWhitespace; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlText.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlText.cs index 554a11d86854bc..e4cf51589e6428 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlText.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlText.cs @@ -26,7 +26,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlText clone = cloneNode as ConfigXmlText; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlWhitespace.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlWhitespace.cs index 7ffbac9d3b8bba..5a394853a5b315 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlWhitespace.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlWhitespace.cs @@ -26,7 +26,7 @@ public override XmlNode CloneNode(bool deep) { XmlNode cloneNode = base.CloneNode(deep); ConfigXmlWhitespace clone = cloneNode as ConfigXmlWhitespace; - if (clone != null) + if (clone is not null) { clone._line = _line; clone._filename = _filename; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Configuration.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Configuration.cs index c9ca2288d03480..cb01041a31b5a4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Configuration.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Configuration.cs @@ -93,7 +93,7 @@ public ConfigurationSectionGroup RootSectionGroup { get { - if (_rootSectionGroup == null) + if (_rootSectionGroup is null) { _rootSectionGroup = new ConfigurationSectionGroup(); _rootSectionGroup.RootAttachToConfigurationRecord(_configRecord); @@ -124,7 +124,7 @@ public Func TypeStringTransformer { if (_typeStringTransformer != value) { - TypeStringTransformerIsSet = value != null; + TypeStringTransformerIsSet = value is not null; _typeStringTransformer = value; } } @@ -137,7 +137,7 @@ public Func AssemblyStringTransformer { if (_assemblyStringTransformer != value) { - AssemblyStringTransformerIsSet = value != null; + AssemblyStringTransformerIsSet = value is not null; _assemblyStringTransformer = value; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationCollectionAttribute.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationCollectionAttribute.cs index 1e641ce84a88a0..7ddc5b27da8268 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationCollectionAttribute.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationCollectionAttribute.cs @@ -16,7 +16,7 @@ public sealed class ConfigurationCollectionAttribute : Attribute public ConfigurationCollectionAttribute(Type itemType) { - if (itemType == null) throw new ArgumentNullException(nameof(itemType)); + if (itemType is null) throw new ArgumentNullException(nameof(itemType)); ItemType = itemType; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs index 23cec43d17d629..824c8e677ccf4f 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs @@ -19,7 +19,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type) internal void ValidateType(object value, Type expected) { - if ((value != null) && (value.GetType() != expected)) + if ((value is not null) && (value.GetType() != expected)) throw new ArgumentException(SR.Format(SR.Converter_unsupported_value_type, expected.Name)); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs index d1f82070c295b9..bef8d044554dbe 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs @@ -71,7 +71,7 @@ protected ConfigurationElement() internal static bool IsNullOrNullProperty(object value) { - return value == null || value == s_nullPropertyValue; + return value is null || value == s_nullPropertyValue; } internal bool DataToWriteInternal { get; set; } @@ -120,14 +120,14 @@ protected internal object this[ConfigurationProperty prop] get { object o = Values[prop.Name]; - if (o == null) + if (o is null) { if (prop.IsConfigurationElementType) { lock (Values.SyncRoot) { o = Values[prop.Name]; - if (o == null) + if (o is null) { ConfigurationElement childElement = CreateElement(prop.Type); @@ -137,11 +137,11 @@ protected internal object this[ConfigurationProperty prop] { ConfigurationElementCollection childElementCollection = childElement as ConfigurationElementCollection; - if (prop.AddElementName != null) + if (prop.AddElementName is not null) childElementCollection.AddElementName = prop.AddElementName; - if (prop.RemoveElementName != null) + if (prop.RemoveElementName is not null) childElementCollection.RemoveElementName = prop.RemoveElementName; - if (prop.ClearElementName != null) + if (prop.ClearElementName is not null) childElementCollection.ClearElementName = prop.ClearElementName; } @@ -174,7 +174,7 @@ protected internal object this[string propertyName] get { ConfigurationProperty prop = Properties[propertyName]; - if (prop == null) + if (prop is null) { prop = Properties[DefaultCollectionPropertyName]; if (prop.ProvidedName != propertyName) return null; @@ -209,9 +209,9 @@ protected ContextInformation EvaluationContext { get { - if (_evalContext == null) + if (_evalContext is null) { - if (_configRecord == null) + if (_configRecord is null) { // This is not associated with a context, so throw failure throw new ConfigurationErrorsException(SR.Config_element_no_context); @@ -226,7 +226,7 @@ protected ContextInformation EvaluationContext protected internal virtual ConfigurationElementProperty ElementProperty => _elementProperty; - protected bool HasContext => _configRecord != null; + protected bool HasContext => _configRecord is not null; public Configuration CurrentConfiguration => _configRecord?.CurrentConfiguration; @@ -257,16 +257,16 @@ internal void CallInit() internal void MergeLocks(ConfigurationElement source) { - if (source == null) return; + if (source is null) return; _itemLockedFlag = (source._itemLockedFlag & ConfigurationValueFlags.Locked) != 0 ? ConfigurationValueFlags.Inherited | source._itemLockedFlag : _itemLockedFlag; - if (source._lockedAttributesList != null) + if (source._lockedAttributesList is not null) { // Mark entry as from the parent - read only - if (_lockedAttributesList == null) + if (_lockedAttributesList is null) { _lockedAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedAttributes); @@ -276,9 +276,9 @@ internal void MergeLocks(ConfigurationElement source) _lockedAttributesList.Add(key, ConfigurationValueFlags.Inherited); } - if (source._lockedAllExceptAttributesList != null) + if (source._lockedAllExceptAttributesList is not null) { - if (_lockedAllExceptAttributesList == null) + if (_lockedAllExceptAttributesList is null) { _lockedAllExceptAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedExceptionList, string.Empty, @@ -293,25 +293,25 @@ internal void MergeLocks(ConfigurationElement source) _lockedAllExceptAttributesList.Add(key, ConfigurationValueFlags.Default); } - if (source._lockedElementsList != null) + if (source._lockedElementsList is not null) { - if (_lockedElementsList == null) + if (_lockedElementsList is null) { _lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements); } ConfigurationElementCollection collection = null; - if (Properties.DefaultCollectionProperty != null) + if (Properties.DefaultCollectionProperty is not null) { // this is not a collection but it may contain a default collection collection = this[Properties.DefaultCollectionProperty] as ConfigurationElementCollection; - if (collection != null) + if (collection is not null) { // Default collections don't know their tag name collection.InternalElementTagName = source.ElementTagName; //point to the same instance of the collection from parent - if (collection._lockedElementsList == null) + if (collection._lockedElementsList is null) collection._lockedElementsList = _lockedElementsList; } } @@ -325,9 +325,9 @@ internal void MergeLocks(ConfigurationElement source) } } - if (source._lockedAllExceptElementsList != null) + if (source._lockedAllExceptElementsList is not null) { - if ((_lockedAllExceptElementsList == null) || (_lockedAllExceptElementsList.Count == 0)) + if ((_lockedAllExceptElementsList is null) || (_lockedAllExceptElementsList.Count == 0)) { _lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, source.ElementTagName, @@ -337,11 +337,11 @@ internal void MergeLocks(ConfigurationElement source) StringCollection intersectionCollection = IntersectLockCollections(_lockedAllExceptElementsList, source._lockedAllExceptElementsList); - if (Properties.DefaultCollectionProperty != null) + if (Properties.DefaultCollectionProperty is not null) { // this is not a collection but it may contain a default collection ConfigurationElementCollection collection = this[Properties.DefaultCollectionProperty] as ConfigurationElementCollection; - if ((collection != null) && (collection._lockedAllExceptElementsList == null)) + if ((collection is not null) && (collection._lockedAllExceptElementsList is null)) { // point default collection to the parent collection collection._lockedAllExceptElementsList = _lockedAllExceptElementsList; @@ -367,14 +367,14 @@ internal void MergeLocks(ConfigurationElement source) internal void HandleLockedAttributes(ConfigurationElement source) { // if there are locked attributes on this collection element - if (source == null || (source._lockedAttributesList == null && source._lockedAllExceptAttributesList == null)) return; + if (source is null || (source._lockedAttributesList is null && source._lockedAllExceptAttributesList is null)) return; // enumerate the possible locked properties foreach (PropertyInformation propInfo in source.ElementInformation.Properties) - if (((source._lockedAttributesList != null) && + if (((source._lockedAttributesList is not null) && (source._lockedAttributesList.Contains(propInfo.Name) || source._lockedAttributesList.Contains(LockAll))) || - ((source._lockedAllExceptAttributesList != null) && + ((source._lockedAllExceptAttributesList is not null) && !source._lockedAllExceptAttributesList.Contains(propInfo.Name)) ) { @@ -382,7 +382,7 @@ internal void HandleLockedAttributes(ConfigurationElement source) // if the attribute has been locked in the source then check to see // if the local config is trying to override it - if (ElementInformation.Properties[propInfo.Name] == null) + if (ElementInformation.Properties[propInfo.Name] is null) { // locked items are not defined @@ -426,10 +426,10 @@ internal virtual void AssociateContext(BaseConfigurationRecord configRecord) protected internal virtual bool IsModified() { if (_modified - || ((_lockedAttributesList != null) && _lockedAttributesList.IsModified) - || ((_lockedAllExceptAttributesList != null) && _lockedAllExceptAttributesList.IsModified) - || ((_lockedElementsList != null) && _lockedElementsList.IsModified) - || ((_lockedAllExceptElementsList != null) && _lockedAllExceptElementsList.IsModified) + || ((_lockedAttributesList is not null) && _lockedAttributesList.IsModified) + || ((_lockedAllExceptAttributesList is not null) && _lockedAllExceptAttributesList.IsModified) + || ((_lockedElementsList is not null) && _lockedElementsList.IsModified) + || ((_lockedAllExceptElementsList is not null) && _lockedAllExceptElementsList.IsModified) || ((_itemLockedFlag & ConfigurationValueFlags.Modified) != 0)) return true; @@ -468,12 +468,12 @@ internal void SetLocked() foreach (ConfigurationProperty prop in Properties) { ConfigurationElement elem = this[prop] as ConfigurationElement; - if (elem != null) + if (elem is not null) { if (elem.GetType() != GetType()) elem.SetLocked(); ConfigurationElementCollection collection = this[prop] as ConfigurationElementCollection; - if (collection != null) + if (collection is not null) { foreach (object obj in collection) { @@ -513,7 +513,7 @@ protected virtual void ListErrors(IList errorList) { elem.ListErrors(errorList); ConfigurationElementCollection collection = elem as ConfigurationElementCollection; - if (collection != null) foreach (ConfigurationElement item in collection) item.ListErrors(errorList); + if (collection is not null) foreach (ConfigurationElement item in collection) item.ListErrors(errorList); } } @@ -522,13 +522,13 @@ protected internal virtual void InitializeDefault() { } internal void CheckLockedElement(string elementName, XmlReader reader) { // have to check if clear was locked! - if (elementName != null) + if (elementName is not null) { - bool lockedInParent = (_lockedElementsList != null) && + bool lockedInParent = (_lockedElementsList is not null) && (_lockedElementsList.DefinedInParent(LockAll) || _lockedElementsList.DefinedInParent(elementName)); if (lockedInParent || - ((_lockedAllExceptElementsList != null) && (_lockedAllExceptElementsList.Count != 0) && + ((_lockedAllExceptElementsList is not null) && (_lockedAllExceptElementsList.Count != 0) && _lockedAllExceptElementsList.HasParentElements && !_lockedAllExceptElementsList.DefinedInParent(elementName)) || ((_itemLockedFlag & ConfigurationValueFlags.Inherited) != 0) @@ -555,13 +555,13 @@ internal void ResetLockLists(ConfigurationElement parentElement) _lockedElementsList = null; _lockedAllExceptElementsList = null; - if (parentElement == null) return; + if (parentElement is null) return; _itemLockedFlag = (parentElement._itemLockedFlag & ConfigurationValueFlags.Locked) != 0 ? ConfigurationValueFlags.Inherited | parentElement._itemLockedFlag : ConfigurationValueFlags.Default; - if (parentElement._lockedAttributesList != null) + if (parentElement._lockedAttributesList is not null) { // Mark entry as from the parent - read only _lockedAttributesList = new ConfigurationLockCollection(this, @@ -570,27 +570,27 @@ internal void ResetLockLists(ConfigurationElement parentElement) _lockedAttributesList.Add(key, ConfigurationValueFlags.Inherited); } - if (parentElement._lockedAllExceptAttributesList != null) + if (parentElement._lockedAllExceptAttributesList is not null) { _lockedAllExceptAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedExceptionList, string.Empty, parentElement._lockedAllExceptAttributesList); } - if (parentElement._lockedElementsList != null) + if (parentElement._lockedElementsList is not null) { _lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements); - if (Properties.DefaultCollectionProperty != null) + if (Properties.DefaultCollectionProperty is not null) { // this is not a collection but it may contain a default collection ConfigurationElementCollection collection = this[Properties.DefaultCollectionProperty] as ConfigurationElementCollection; - if (collection != null) + if (collection is not null) { collection.InternalElementTagName = parentElement.ElementTagName; // Default collections don't know there tag name - if (collection._lockedElementsList == null) + if (collection._lockedElementsList is null) collection._lockedElementsList = _lockedElementsList; } } @@ -600,17 +600,17 @@ internal void ResetLockLists(ConfigurationElement parentElement) _lockedElementsList.Add(key, ConfigurationValueFlags.Inherited); } - if (parentElement._lockedAllExceptElementsList != null) + if (parentElement._lockedAllExceptElementsList is not null) { _lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, parentElement.ElementTagName, parentElement._lockedAllExceptElementsList); - if (Properties.DefaultCollectionProperty != null) + if (Properties.DefaultCollectionProperty is not null) { // this is not a collection but it may contain a default collection ConfigurationElementCollection collection = this[Properties.DefaultCollectionProperty] as ConfigurationElementCollection; - if ((collection != null) && (collection._lockedAllExceptElementsList == null)) + if ((collection is not null) && (collection._lockedAllExceptElementsList is null)) collection._lockedAllExceptElementsList = _lockedAllExceptElementsList; } } @@ -622,7 +622,7 @@ protected internal virtual void Reset(ConfigurationElement parentElement) ResetLockLists(parentElement); ConfigurationPropertyCollection props = Properties; // Force the bag to be up to date ElementPresent = false; - if (parentElement == null) InitializeDefault(); + if (parentElement is null) InitializeDefault(); else { bool hasAnyChildElements = false; @@ -637,16 +637,16 @@ protected internal virtual void Reset(ConfigurationElement parentElement) PropertySourceInfo sourceInfo = configValue?.SourceInfo; ConfigurationProperty prop = parentElement.Properties[key]; - if ((prop == null) || ((collectionKeys != null) && !collectionKeys.Contains(prop.Name))) continue; + if ((prop is null) || ((collectionKeys is not null) && !collectionKeys.Contains(prop.Name))) continue; if (prop.IsConfigurationElementType) hasAnyChildElements = true; else { ConfigurationValueFlags flags = ConfigurationValueFlags.Inherited | - (((_lockedAttributesList != null) && + (((_lockedAttributesList is not null) && (_lockedAttributesList.Contains(key) || _lockedAttributesList.Contains(LockAll))) || - ((_lockedAllExceptAttributesList != null) && + ((_lockedAllExceptAttributesList is not null) && !_lockedAllExceptAttributesList.Contains(key)) ? ConfigurationValueFlags.Locked : ConfigurationValueFlags.Default); @@ -673,7 +673,7 @@ protected internal virtual void Reset(ConfigurationElement parentElement) object value = parentElement.Values[index]; ConfigurationProperty prop = parentElement.Properties[key]; - if ((prop != null) && prop.IsConfigurationElementType) + if ((prop is not null) && prop.IsConfigurationElementType) { //((ConfigurationElement)value).SerializeToXmlElement(writer, prop.Name); ConfigurationElement childElement = (ConfigurationElement)this[prop]; @@ -688,7 +688,7 @@ public override bool Equals(object compareTo) { ConfigurationElement otherElement = compareTo as ConfigurationElement; - if ((otherElement == null) || + if ((otherElement is null) || (compareTo.GetType() != GetType()) || (otherElement.Properties.Count != Properties.Count)) return false; @@ -716,7 +716,7 @@ public override int GetHashCode() foreach (ConfigurationProperty configProperty in Properties) { object o = this[configProperty]; - if (o != null) hHashCode ^= this[configProperty].GetHashCode(); + if (o is not null) hHashCode ^= this[configProperty].GetHashCode(); } return hHashCode; } @@ -725,12 +725,12 @@ private static bool PropertiesFromType(Type type, out ConfigurationPropertyColle { ConfigurationPropertyCollection properties = (ConfigurationPropertyCollection)s_propertyBags[type]; bool firstTimeInit = false; - if (properties == null) + if (properties is null) { lock (s_propertyBags.SyncRoot) { properties = (ConfigurationPropertyCollection)s_propertyBags[type]; - if (properties == null) + if (properties is null) { properties = CreatePropertyBagFromType(type); s_propertyBags[type] = properties; @@ -744,7 +744,7 @@ private static bool PropertiesFromType(Type type, out ConfigurationPropertyColle private static ConfigurationPropertyCollection CreatePropertyBagFromType(Type type) { - Debug.Assert(type != null, "type != null"); + Debug.Assert(type is not null, "type is not null"); // For ConfigurationElement derived classes - get the per-type validator if (typeof(ConfigurationElement).IsAssignableFrom(type)) @@ -753,11 +753,11 @@ private static ConfigurationPropertyCollection CreatePropertyBagFromType(Type ty Attribute.GetCustomAttribute(type, typeof(ConfigurationValidatorAttribute)) as ConfigurationValidatorAttribute; - if (validatorAttribute != null) + if (validatorAttribute is not null) { validatorAttribute.SetDeclaringType(type); ConfigurationValidatorBase validator = validatorAttribute.ValidatorInstance; - if (validator != null) CachePerTypeValidator(type, validator); + if (validator is not null) CachePerTypeValidator(type, validator); } } @@ -766,7 +766,7 @@ private static ConfigurationPropertyCollection CreatePropertyBagFromType(Type ty foreach (PropertyInfo propertyInformation in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { ConfigurationProperty property = CreateConfigurationPropertyFromAttributes(propertyInformation); - if (property != null) properties.Add(property); + if (property is not null) properties.Add(property); } return properties; @@ -774,7 +774,7 @@ private static ConfigurationPropertyCollection CreatePropertyBagFromType(Type ty private static ConfigurationProperty CreateConfigurationPropertyFromAttributes(PropertyInfo propertyInformation) { - Debug.Assert(propertyInformation != null, "propertyInformation != null"); + Debug.Assert(propertyInformation is not null, "propertyInformation is not null"); ConfigurationProperty result = null; @@ -783,11 +783,11 @@ private static ConfigurationProperty CreateConfigurationPropertyFromAttributes(P typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute; // If there is no ConfigurationPropertyAttribute - this is not considered a property - if (attribProperty != null) + if (attribProperty is not null) result = new ConfigurationProperty(propertyInformation); // Handle some special cases of property types - if ((result != null) && typeof(ConfigurationElement).IsAssignableFrom(result.Type)) + if ((result is not null) && typeof(ConfigurationElement).IsAssignableFrom(result.Type)) { ConfigurationPropertyCollection unused; PropertiesFromType(result.Type, out unused); @@ -798,7 +798,7 @@ private static ConfigurationProperty CreateConfigurationPropertyFromAttributes(P private static void CachePerTypeValidator(Type type, ConfigurationValidatorBase validator) { - Debug.Assert((type != null) && (validator != null)); + Debug.Assert((type is not null) && (validator is not null)); Debug.Assert(typeof(ConfigurationElement).IsAssignableFrom(type)); // Use the same lock as the property bag lock since in the current implementation @@ -806,7 +806,7 @@ private static void CachePerTypeValidator(Type type, ConfigurationValidatorBase // NOTE[ Thread Safety ]: Non-guarded access to static variable - since this code is called only from CreatePropertyBagFromType // which in turn is done onle once per type and is guarded by the s_propertyBag.SyncRoot then this call is thread safe as well - if (s_perTypeValidators == null) s_perTypeValidators = new Dictionary(); + if (s_perTypeValidators is null) s_perTypeValidators = new Dictionary(); // A type validator should be cached only once. If it isn't then attribute parsing is done more then once which should be avoided Debug.Assert(!s_perTypeValidators.ContainsKey(type)); @@ -823,7 +823,7 @@ private static void CachePerTypeValidator(Type type, ConfigurationValidatorBase private static void ApplyValidatorsRecursive(ConfigurationElement root) { - Debug.Assert(root != null); + Debug.Assert(root is not null); // Apply the validator on 'root' ApplyValidator(root); @@ -834,9 +834,9 @@ private static void ApplyValidatorsRecursive(ConfigurationElement root) private static void ApplyValidator(ConfigurationElement elem) { - Debug.Assert(elem != null); + Debug.Assert(elem is not null); - if ((s_perTypeValidators != null) && s_perTypeValidators.ContainsKey(elem.GetType())) + if ((s_perTypeValidators is not null) && s_perTypeValidators.ContainsKey(elem.GetType())) elem._elementProperty = new ConfigurationElementProperty(s_perTypeValidators[elem.GetType()]); } @@ -845,9 +845,9 @@ protected void SetPropertyValue(ConfigurationProperty prop, object value, bool i if (IsReadOnly()) throw new ConfigurationErrorsException(SR.Config_base_read_only); if ((ignoreLocks == false) && - (((_lockedAllExceptAttributesList != null) && _lockedAllExceptAttributesList.HasParentElements && + (((_lockedAllExceptAttributesList is not null) && _lockedAllExceptAttributesList.HasParentElements && !_lockedAllExceptAttributesList.DefinedInParent(prop.Name)) || - ((_lockedAttributesList != null) && + ((_lockedAttributesList is not null) && (_lockedAttributesList.DefinedInParent(prop.Name) || _lockedAttributesList.DefinedInParent(LockAll))) || (((_itemLockedFlag & ConfigurationValueFlags.Locked) != 0) && ((_itemLockedFlag & ConfigurationValueFlags.Inherited) != 0)))) @@ -856,7 +856,7 @@ protected void SetPropertyValue(ConfigurationProperty prop, object value, bool i _modified = true; // Run the new value through the validator to make sure its ok to store it - if (value != null) prop.Validate(value); + if (value is not null) prop.Validate(value); Values[prop.Name] = value ?? s_nullPropertyValue; } @@ -870,7 +870,7 @@ internal string PropertyFileName(string propertyName) { // Get the filename of the parent if prop is not there PropertySourceInfo p = PropertyInfoInternal(propertyName) ?? PropertyInfoInternal(string.Empty); - return p == null ? string.Empty : p.FileName; + return p is null ? string.Empty : p.FileName; } internal int PropertyLineNumber(string propertyName) @@ -891,7 +891,7 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode) { - if (sourceElement == null) return; + if (sourceElement is null) return; bool hasAnyChildElements = false; _lockedAllExceptAttributesList = sourceElement._lockedAllExceptAttributesList; @@ -901,24 +901,24 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, _lockedElementsList = sourceElement._lockedElementsList; AssociateContext(sourceElement._configRecord); - if (parentElement != null) + if (parentElement is not null) { - if (parentElement._lockedAttributesList != null) + if (parentElement._lockedAttributesList is not null) { _lockedAttributesList = UnMergeLockList(sourceElement._lockedAttributesList, parentElement._lockedAttributesList, saveMode); } - if (parentElement._lockedElementsList != null) + if (parentElement._lockedElementsList is not null) { _lockedElementsList = UnMergeLockList(sourceElement._lockedElementsList, parentElement._lockedElementsList, saveMode); } - if (parentElement._lockedAllExceptAttributesList != null) + if (parentElement._lockedAllExceptAttributesList is not null) { _lockedAllExceptAttributesList = UnMergeLockList(sourceElement._lockedAllExceptAttributesList, parentElement._lockedAllExceptAttributesList, saveMode); } - if (parentElement._lockedAllExceptElementsList != null) + if (parentElement._lockedAllExceptElementsList is not null) { _lockedAllExceptElementsList = UnMergeLockList(sourceElement._lockedAllExceptElementsList, parentElement._lockedAllExceptElementsList, saveMode); @@ -934,7 +934,7 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, string key = sourceElement.Values.GetKey(index); object value = sourceElement.Values[index]; ConfigurationProperty prop = sourceElement.Properties[key]; - if ((prop == null) || ((collectionKeys != null) && !collectionKeys.Contains(prop.Name))) + if ((prop is null) || ((collectionKeys is not null) && !collectionKeys.Contains(prop.Name))) continue; if (prop.IsConfigurationElementType) @@ -954,7 +954,7 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, foreach (ConfigurationProperty prop in Properties) { - if ((prop == null) || ((collectionKeys != null) && !collectionKeys.Contains(prop.Name))) continue; + if ((prop is null) || ((collectionKeys is not null) && !collectionKeys.Contains(prop.Name))) continue; if (prop.IsConfigurationElementType) hasAnyChildElements = true; else { @@ -968,7 +968,7 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, // Note: 'null' should be used as default for non-empty strings instead // of the current practice to use String.Epmty - if (prop.DefaultValue != null) + if (prop.DefaultValue is not null) value = prop.DefaultValue; // need to make sure required properties are persisted } @@ -992,7 +992,7 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, // Also update properties that ARE inherited when we are resetting the object // as long as the property is not the same as the default value for the property if (prop.IsRequired || modified || !inherited || - ((parentElement == null) && inherited && !Equals(value, value2))) + ((parentElement is null) && inherited && !Equals(value, value2))) Values[prop.Name] = value; break; case ConfigurationSaveMode.Full: @@ -1013,7 +1013,7 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, ConfigurationElement pElem = (ConfigurationElement)parentElement?[prop]; ConfigurationElement childElement = (ConfigurationElement)this[prop]; - if ((ConfigurationElement)sourceElement[prop] != null) + if ((ConfigurationElement)sourceElement[prop] is not null) { childElement.Unmerge((ConfigurationElement)sourceElement[prop], pElem, saveMode); @@ -1024,12 +1024,12 @@ protected internal virtual void Unmerge(ConfigurationElement sourceElement, protected internal virtual bool SerializeToXmlElement(XmlWriter writer, string elementName) { - if ((_configRecord != null) && (_configRecord.TargetFramework != null)) + if ((_configRecord is not null) && (_configRecord.TargetFramework is not null)) { ConfigurationSection section = null; if (_configRecord.SectionsStack.Count > 0) section = _configRecord.SectionsStack.Peek() as ConfigurationSection; - if ((section != null) && + if ((section is not null) && !section.ShouldSerializeElementInTargetVersion(this, elementName, _configRecord.TargetFramework)) return false; } @@ -1037,8 +1037,8 @@ protected internal virtual bool SerializeToXmlElement(XmlWriter writer, string e bool dataToWrite = DataToWriteInternal; // Don't write elements that are locked in the parent - if (((_lockedElementsList != null) && _lockedElementsList.DefinedInParent(elementName)) || - ((_lockedAllExceptElementsList != null) && _lockedAllExceptElementsList.HasParentElements && + if (((_lockedElementsList is not null) && _lockedElementsList.DefinedInParent(elementName)) || + ((_lockedAllExceptElementsList is not null) && _lockedAllExceptElementsList.HasParentElements && !_lockedAllExceptElementsList.DefinedInParent(elementName))) return dataToWrite; @@ -1067,15 +1067,15 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ object value = Values[index]; ConfigurationProperty prop = props[key]; - if ((prop == null) || ((collectionKeys != null) && !collectionKeys.Contains(prop.Name))) continue; + if ((prop is null) || ((collectionKeys is not null) && !collectionKeys.Contains(prop.Name))) continue; - if (prop.IsVersionCheckRequired && (_configRecord != null) && (_configRecord.TargetFramework != null)) + if (prop.IsVersionCheckRequired && (_configRecord is not null) && (_configRecord.TargetFramework is not null)) { ConfigurationSection section = null; if (_configRecord.SectionsStack.Count > 0) section = _configRecord.SectionsStack.Peek() as ConfigurationSection; - if ((section != null) && + if ((section is not null) && !section.ShouldSerializePropertyInTargetVersion(prop, prop.Name, _configRecord.TargetFramework, this)) continue; @@ -1088,9 +1088,9 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ } else { - if (((_lockedAllExceptAttributesList != null) && _lockedAllExceptAttributesList.HasParentElements && + if (((_lockedAllExceptAttributesList is not null) && _lockedAllExceptAttributesList.HasParentElements && !_lockedAllExceptAttributesList.DefinedInParent(prop.Name)) || - ((_lockedAttributesList != null) && _lockedAttributesList.DefinedInParent(prop.Name))) + ((_lockedAttributesList is not null) && _lockedAttributesList.DefinedInParent(prop.Name))) { if (prop.IsRequired) { @@ -1112,7 +1112,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ xmlValue = prop.ConvertToString(value); } - if ((xmlValue != null) && (writer != null)) + if ((xmlValue is not null) && (writer is not null)) { if (prop.IsTypeStringTransformationRequired) xmlValue = GetTransformedTypeString(xmlValue); @@ -1122,7 +1122,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ writer.WriteAttributeString(prop.Name, xmlValue); } - dataToWrite = dataToWrite || (xmlValue != null); + dataToWrite = dataToWrite || (xmlValue is not null); } } @@ -1154,8 +1154,8 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ if ((serializeCollectionKey && !prop.IsKey) || !(value is ConfigurationElement)) continue; - if (((_lockedElementsList != null) && _lockedElementsList.DefinedInParent(key)) || - ((_lockedAllExceptElementsList != null) && + if (((_lockedElementsList is not null) && _lockedElementsList.DefinedInParent(key)) || + ((_lockedAllExceptElementsList is not null) && _lockedAllExceptElementsList.HasParentElements && !_lockedAllExceptElementsList.DefinedInParent(key))) continue; @@ -1197,7 +1197,7 @@ private bool SerializeLockList(ConfigurationLockCollection list, string elementK { StringBuilder sb = new StringBuilder(); - if (list != null) + if (list is not null) { foreach (string key in list) if (!list.DefinedInParent(key)) @@ -1208,7 +1208,7 @@ private bool SerializeLockList(ConfigurationLockCollection list, string elementK } } - if ((writer != null) && (sb.Length != 0)) + if ((writer is not null) && (sb.Length != 0)) writer.WriteAttributeString(elementKey, sb.ToString()); return sb.Length != 0; } @@ -1269,14 +1269,14 @@ internal void ReportInvalidLock(string attribToLockTrim, ConfigurationLockCollec if ((lockedType == ConfigurationLockCollectionType.LockedElements) || (lockedType == ConfigurationLockCollectionType.LockedElementsExceptionList)) { - format = value != null ? SR.Config_base_invalid_element_to_lock : SR.Config_base_invalid_element_to_lock_by_add; + format = value is not null ? SR.Config_base_invalid_element_to_lock : SR.Config_base_invalid_element_to_lock_by_add; } else { - format = value != null ? SR.Config_base_invalid_attribute_to_lock : SR.Config_base_invalid_attribute_to_lock_by_add; + format = value is not null ? SR.Config_base_invalid_attribute_to_lock : SR.Config_base_invalid_attribute_to_lock_by_add; } - if (value != null) + if (value is not null) { throw new ConfigurationErrorsException( SR.Format(format, attribToLockTrim, sb), @@ -1328,7 +1328,7 @@ private ConfigurationLockCollection ParseLockedAttributes(ConfigurationValue val { ConfigurationProperty propToLock = Properties[attribToLockTrim]; - if ((propToLock == null) || // if the prop does not exist + if ((propToLock is null) || // if the prop does not exist (attribToLockTrim == LockAttributesKey) || // or it is the lockattributes keyword (attribToLockTrim == LockAllAttributesExceptKey) || // or it is the lockattributes keyword (attribToLockTrim == LockElementsKey) || // or it is the lockelements keyword @@ -1345,13 +1345,13 @@ private ConfigurationLockCollection ParseLockedAttributes(ConfigurationValue val // check to see if this is a collection and we are locking a collection element ConfigurationElementCollection collection = this as ConfigurationElementCollection; - if ((collection == null) && (Properties.DefaultCollectionProperty != null)) + if ((collection is null) && (Properties.DefaultCollectionProperty is not null)) // this is not a collection but it may contain a default collection { collection = this[Properties.DefaultCollectionProperty] as ConfigurationElementCollection; } - if ((collection == null) || + if ((collection is null) || (lockType == ConfigurationLockCollectionType.LockedAttributes) || // If the collection type is not element then the lock is bogus (lockType == ConfigurationLockCollectionType.LockedExceptionList)) @@ -1363,7 +1363,7 @@ private ConfigurationLockCollection ParseLockedAttributes(ConfigurationValue val } } - if ((propToLock != null) && propToLock.IsRequired) + if ((propToLock is not null) && propToLock.IsRequired) { throw new ConfigurationErrorsException( SR.Format(SR.Config_base_required_attribute_lock_attempt, propToLock.Name)); @@ -1409,7 +1409,7 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial ConfigurationElement defaultCollection = null; ConfigurationProperty defaultCollectionProperty = props?.DefaultCollectionProperty; - if (defaultCollectionProperty != null) + if (defaultCollectionProperty is not null) defaultCollection = (ConfigurationElement)this[defaultCollectionProperty]; // Process attributes @@ -1419,9 +1419,9 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial Values.SetValue(DefaultCollectionPropertyName, defaultCollection, ConfigurationValueFlags.Modified, rootInfo); - if (((_lockedElementsList != null) && (_lockedElementsList.Contains(reader.Name) || + if (((_lockedElementsList is not null) && (_lockedElementsList.Contains(reader.Name) || (_lockedElementsList.Contains(LockAll) && (reader.Name != ElementTagName)))) || - ((_lockedAllExceptElementsList != null) && (_lockedAllExceptElementsList.Count != 0) && + ((_lockedAllExceptElementsList is not null) && (_lockedAllExceptElementsList.Count != 0) && !_lockedAllExceptElementsList.Contains(reader.Name)) || (((_itemLockedFlag & ConfigurationValueFlags.Locked) != 0) && ((_itemLockedFlag & ConfigurationValueFlags.Inherited) != 0)) @@ -1434,9 +1434,9 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial while (reader.MoveToNextAttribute()) { string propertyName = reader.Name; - if (((_lockedAttributesList != null) && + if (((_lockedAttributesList is not null) && (_lockedAttributesList.Contains(propertyName) || _lockedAttributesList.Contains(LockAll))) || - ((_lockedAllExceptAttributesList != null) && + ((_lockedAllExceptAttributesList is not null) && !_lockedAllExceptAttributesList.Contains(propertyName)) ) { @@ -1448,7 +1448,7 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial } ConfigurationProperty prop = props?[propertyName]; - if (prop != null) + if (prop is not null) { if (serializeCollectionKey && !prop.IsKey) { @@ -1523,7 +1523,7 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial CheckLockedElement(propertyName, null); ConfigurationProperty prop = props?[propertyName]; - if (prop != null) + if (prop is not null) { if (prop.IsConfigurationElementType) { @@ -1555,7 +1555,7 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial if (!OnDeserializeUnrecognizedElement(propertyName, reader)) { // Let the default collection, if there is one, handle this node. - if ((defaultCollection == null) || + if ((defaultCollection is null) || !defaultCollection.OnDeserializeUnrecognizedElement(propertyName, reader)) { throw new ConfigurationErrorsException( @@ -1584,7 +1584,7 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial catch (ConfigurationException e) { // Catch the generic message from deserialization and include line info if necessary - if ((e.Filename == null) || (e.Filename.Length == 0)) + if ((e.Filename is null) || (e.Filename.Length == 0)) throw new ConfigurationErrorsException(e.Message, reader); // give it some info throw; @@ -1596,9 +1596,9 @@ protected internal virtual void DeserializeElement(XmlReader reader, bool serial _itemLockedFlag = ConfigurationValueFlags.Locked; } - if (lockedAttributesList != null) + if (lockedAttributesList is not null) { - if (_lockedAttributesList == null) + if (_lockedAttributesList is null) { _lockedAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedAttributes); @@ -1615,11 +1615,11 @@ string key in } } - if (lockedAllExceptList != null) + if (lockedAllExceptList is not null) { ConfigurationLockCollection newCollection = ParseLockedAttributes(lockedAllExceptList, ConfigurationLockCollectionType.LockedExceptionList); - if (_lockedAllExceptAttributesList == null) + if (_lockedAllExceptAttributesList is null) { // Prevent the list from thinking this was set by a parent. _lockedAllExceptAttributesList = new ConfigurationLockCollection(this, @@ -1635,9 +1635,9 @@ string key in _lockedAllExceptAttributesList.Add(key, ConfigurationValueFlags.Default); } - if (lockedElementList != null) + if (lockedElementList is not null) { - if (_lockedElementsList == null) + if (_lockedElementsList is null) { _lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements); @@ -1646,11 +1646,11 @@ string key in ConfigurationLockCollection localLockedElementList = ParseLockedAttributes(lockedElementList, ConfigurationLockCollectionType.LockedElements); - if (props.DefaultCollectionProperty != null) + if (props.DefaultCollectionProperty is not null) // this is not a collection but it may contain a default collection { ConfigurationElementCollection collection = this[props.DefaultCollectionProperty] as ConfigurationElementCollection; - if ((collection != null) && (collection._lockedElementsList == null)) + if ((collection is not null) && (collection._lockedElementsList is null)) collection._lockedElementsList = _lockedElementsList; } @@ -1660,7 +1660,7 @@ string key in _lockedElementsList.Add(key, ConfigurationValueFlags.Default); // add the local copy ConfigurationProperty propToLock = Properties[key]; - if ((propToLock != null) && typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type)) + if ((propToLock is not null) && typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type)) ((ConfigurationElement)this[key]).SetLocked(); if (key == LockAll) { @@ -1672,11 +1672,11 @@ string key in } } - if (lockedAllElementsExceptList != null) + if (lockedAllElementsExceptList is not null) { ConfigurationLockCollection newCollection = ParseLockedAttributes(lockedAllElementsExceptList, ConfigurationLockCollectionType.LockedElementsExceptionList); - if (_lockedAllExceptElementsList == null) + if (_lockedAllExceptElementsList is null) { _lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, ElementTagName, newCollection); @@ -1686,11 +1686,11 @@ string key in StringCollection intersectionCollection = IntersectLockCollections(_lockedAllExceptElementsList, newCollection); - if (props.DefaultCollectionProperty != null) + if (props.DefaultCollectionProperty is not null) { // this is not a collection but it may contain a default collection ConfigurationElementCollection collection = this[props.DefaultCollectionProperty] as ConfigurationElementCollection; - if ((collection != null) && (collection._lockedAllExceptElementsList == null)) + if ((collection is not null) && (collection._lockedAllExceptElementsList is null)) collection._lockedAllExceptElementsList = _lockedAllExceptElementsList; } @@ -1706,16 +1706,16 @@ string key in } // Make sure default collections use the same lock element lists - if (defaultCollectionProperty != null) + if (defaultCollectionProperty is not null) { defaultCollection = (ConfigurationElement)this[defaultCollectionProperty]; - if (_lockedElementsList == null) + if (_lockedElementsList is null) { _lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements); } defaultCollection._lockedElementsList = _lockedElementsList; - if (_lockedAllExceptElementsList == null) + if (_lockedAllExceptElementsList is null) { _lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, reader.Name); @@ -1730,8 +1730,8 @@ string key in private object DeserializePropertyValue(ConfigurationProperty prop, XmlReader reader) { - Debug.Assert(prop != null, "prop != null"); - Debug.Assert(reader != null, "reader != null"); + Debug.Assert(prop is not null, "prop is not null"); + Debug.Assert(reader is not null, "reader is not null"); // By default we try to load (i.e. parse/validate ) all properties // If a property value is invalid ( cannot be parsed or is not valid ) we will keep the value @@ -1775,14 +1775,14 @@ internal static void ValidateElement(ConfigurationElement elem, ConfigurationVal ConfigurationValidatorBase validator = propValidator; - if ((validator == null) && // Not a property - use the per-type validator - (elem.ElementProperty != null)) + if ((validator is null) && // Not a property - use the per-type validator + (elem.ElementProperty is not null)) { validator = elem.ElementProperty.Validator; // Since ElementProperty can be overriden by derived classes we need to make sure that // the validator supports the type of elem every time - if ((validator != null) && !validator.CanValidate(elem.GetType())) + if ((validator is not null) && !validator.CanValidate(elem.GetType())) { throw new ConfigurationErrorsException(SR.Format(SR.Validator_does_not_support_elem_type, elem.GetType().Name)); @@ -1822,7 +1822,7 @@ internal static void ValidateElement(ConfigurationElement elem, ConfigurationVal { ConfigurationElement value = elem.Values[index] as ConfigurationElement; - if (value != null) + if (value is not null) { // Run the per-type validator on the child element and proceed with validation in subelements // Note we dont run the per-property validator here since we run those when the property value is set @@ -1837,7 +1837,7 @@ private void EnsureRequiredProperties(bool ensureKeysOnly) ConfigurationPropertyCollection props = Properties; // Make sure all required properties are here - if (props != null) + if (props is not null) { foreach (ConfigurationProperty prop in props) if (prop.IsRequired && !Values.Contains(prop.Name)) @@ -1880,7 +1880,7 @@ protected virtual bool OnDeserializeUnrecognizedElement(string elementName, XmlR protected virtual string GetTransformedTypeString(string typeName) { - if ((typeName == null) || (_configRecord == null) || !_configRecord.TypeStringTransformerIsSet) + if ((typeName is null) || (_configRecord is null) || !_configRecord.TypeStringTransformerIsSet) return typeName; return _configRecord.TypeStringTransformer(typeName); @@ -1888,7 +1888,7 @@ protected virtual string GetTransformedTypeString(string typeName) protected virtual string GetTransformedAssemblyString(string assemblyName) { - if ((assemblyName == null) || (_configRecord == null) || !_configRecord.AssemblyStringTransformerIsSet) + if ((assemblyName is null) || (_configRecord is null) || !_configRecord.AssemblyStringTransformerIsSet) return assemblyName; return _configRecord.AssemblyStringTransformer(assemblyName); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs index 735cc787566718..8b4e733e160adc 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs @@ -31,7 +31,7 @@ protected ConfigurationElementCollection() { } protected ConfigurationElementCollection(IComparer comparer) { - if (comparer == null) throw new ArgumentNullException(nameof(comparer)); + if (comparer is null) throw new ArgumentNullException(nameof(comparer)); _comparer = comparer; } @@ -205,7 +205,7 @@ internal IEnumerator GetElementsEnumerator() public override bool Equals(object compareTo) { - if (compareTo == null || compareTo.GetType() != GetType()) + if (compareTo is null || compareTo.GetType() != GetType()) return false; ConfigurationElementCollection compareToElem = (ConfigurationElementCollection)compareTo; @@ -248,7 +248,7 @@ protected internal override void Unmerge(ConfigurationElement sourceElement, ConfigurationSaveMode saveMode) { base.Unmerge(sourceElement, parentElement, saveMode); - if (sourceElement == null) return; + if (sourceElement is null) return; ConfigurationElementCollection parentCollection = parentElement as ConfigurationElementCollection; ConfigurationElementCollection sourceCollection = sourceElement as ConfigurationElementCollection; @@ -261,24 +261,24 @@ protected internal override void Unmerge(ConfigurationElement sourceElement, AssociateContext(sourceElement._configRecord); - if (parentElement != null) + if (parentElement is not null) { - if (parentElement._lockedAttributesList != null) + if (parentElement._lockedAttributesList is not null) { _lockedAttributesList = UnMergeLockList(sourceElement._lockedAttributesList, parentElement._lockedAttributesList, saveMode); } - if (parentElement._lockedElementsList != null) + if (parentElement._lockedElementsList is not null) { _lockedElementsList = UnMergeLockList(sourceElement._lockedElementsList, parentElement._lockedElementsList, saveMode); } - if (parentElement._lockedAllExceptAttributesList != null) + if (parentElement._lockedAllExceptAttributesList is not null) { _lockedAllExceptAttributesList = UnMergeLockList(sourceElement._lockedAllExceptAttributesList, parentElement._lockedAllExceptAttributesList, saveMode); } - if (parentElement._lockedAllExceptElementsList != null) + if (parentElement._lockedAllExceptElementsList is not null) { _lockedAllExceptElementsList = UnMergeLockList(sourceElement._lockedAllExceptElementsList, parentElement._lockedAllExceptElementsList, saveMode); @@ -293,7 +293,7 @@ protected internal override void Unmerge(ConfigurationElement sourceElement, EmitClear = ((saveMode == ConfigurationSaveMode.Full) && (_clearElement.Length != 0)) || ((saveMode == ConfigurationSaveMode.Modified) && _collectionCleared) || sourceCollection.EmitClear; - if ((parentCollection != null) && (EmitClear != true)) + if ((parentCollection is not null) && (EmitClear != true)) { foreach (Entry entry in parentCollection.Items) if (entry.EntryType != EntryType.Removed) @@ -349,7 +349,7 @@ protected internal override void Unmerge(ConfigurationElement sourceElement, } } - if ((parentCollection != null) && (EmitClear != true)) + if ((parentCollection is not null) && (EmitClear != true)) { foreach (Entry entry in parentCollection.Items) { @@ -397,7 +397,7 @@ protected internal override void Unmerge(ConfigurationElement sourceElement, if ((entry.EntryType != EntryType.Added) && (entry.EntryType != EntryType.Replaced)) continue; bool inParent = false; - if (parentCollection != null) + if (parentCollection is not null) { foreach (Entry parentEntry in parentCollection.Items) { @@ -455,7 +455,7 @@ protected internal override void Reset(ConfigurationElement parentElement) ConfigurationElementCollection parentCollection = parentElement as ConfigurationElementCollection; ResetLockLists(parentElement); - if (parentCollection != null) + if (parentCollection is not null) { foreach (Entry entry in parentCollection.Items) { @@ -513,7 +513,7 @@ private void BaseAdd(ConfigurationElement element, bool throwIfExists, bool igno Entry entry = (Entry)Items[index]; if (!CompareKeys(key, entry.GetKey(this))) continue; - if ((entry.Value != null) && entry.Value.LockItem && (ignoreLocks == false)) + if ((entry.Value is not null) && entry.Value.LockItem && (ignoreLocks == false)) throw new ConfigurationErrorsException(SR.Config_base_collection_item_locked); if ((entry.EntryType != EntryType.Removed) && throwIfExists) @@ -734,7 +734,7 @@ private void BaseRemove(object key, bool throwIfMissing) { if (CompareKeys(key, entry.GetKey(this))) { - if (entry.Value == null) // A phoney delete is already present + if (entry.Value is null) // A phoney delete is already present { if (throwIfMissing) { @@ -860,7 +860,7 @@ protected internal ConfigurationElement BaseGet(int index) if (entryfound.EntryType != EntryType.Removed) virtualIndex++; } - if (entry != null) + if (entry is not null) return entry.Value; throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index)); @@ -897,7 +897,7 @@ protected internal object BaseGetKey(int index) } // Entry entry = (Entry)_items[index]; - if (entry == null) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index)); + if (entry is null) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index)); return entry.GetKey(this); } @@ -934,7 +934,7 @@ protected internal void BaseClear() for (int checkIndex = 0; checkIndex < Items.Count; checkIndex++) { Entry entry = (Entry)Items[checkIndex]; - if ((entry.Value != null) && entry.Value.LockItem) + if ((entry.Value is not null) && entry.Value.LockItem) throw new ConfigurationErrorsException(SR.Config_base_collection_item_locked_cannot_clear); } @@ -972,7 +972,7 @@ protected internal void BaseRemoveAt(int index) if (entryfound.EntryType != EntryType.Removed) virtualIndex++; } - if (entry == null) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index)); + if (entry is null) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index)); if (entry.Value.LockItem) { throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked, @@ -1038,7 +1038,7 @@ protected internal override bool SerializeElement(XmlWriter writer, bool seriali // no real elements if (_emitClearTag && (_clearElement.Length != 0)) { - if (writer != null) + if (writer is not null) { writer.WriteStartElement(_clearElement); writer.WriteEndElement(); @@ -1071,7 +1071,7 @@ protected internal override bool SerializeElement(XmlWriter writer, bool seriali case ConfigurationElementCollectionType.AddRemoveClearMapAlternate: if (((entry.EntryType == EntryType.Removed) || (entry.EntryType == EntryType.Replaced)) && - (entry.Value != null)) + (entry.Value is not null)) { writer?.WriteStartElement(_removeElement); entry.Value.SerializeElement(writer, true); @@ -1186,7 +1186,7 @@ protected virtual ConfigurationElement CreateNewElement(string elementName) internal object GetElementKeyInternal(ConfigurationElement element) { object key = GetElementKey(element); - if (key == null) + if (key is null) throw new ConfigurationErrorsException(SR.Config_base_invalid_element_key); return key; } @@ -1198,7 +1198,7 @@ protected virtual bool IsElementRemovable(ConfigurationElement element) private bool CompareKeys(object key1, object key2) { - if (_comparer != null) return _comparer.Compare(key1, key2) == 0; + if (_comparer is not null) return _comparer.Compare(key1, key2) == 0; return key1.Equals(key2); } @@ -1253,7 +1253,7 @@ internal Entry(EntryType type, object key, ConfigurationElement value) internal object GetKey(ConfigurationElementCollection thisCollection) { // For items that have been really inserted... - return Value != null ? thisCollection.GetElementKeyInternal(Value) : _key; + return Value is not null ? thisCollection.GetElementKeyInternal(Value) : _key; } } @@ -1275,7 +1275,7 @@ bool IEnumerator.MoveNext() { Entry entry = (Entry)_itemsEnumerator.Current; if (entry.EntryType == EntryType.Removed) continue; - _current.Key = entry.GetKey(_thisCollection) != null ? entry.GetKey(_thisCollection) : "key"; + _current.Key = entry.GetKey(_thisCollection) is not null ? entry.GetKey(_thisCollection) : "key"; _current.Value = entry.Value; return true; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs index cee27df385a207..6de05197be0b06 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs @@ -11,7 +11,7 @@ public sealed class ConfigurationElementProperty { public ConfigurationElementProperty(ConfigurationValidatorBase validator) { - if (validator == null) throw new ArgumentNullException(nameof(validator)); + if (validator is null) throw new ArgumentNullException(nameof(validator)); Validator = validator; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationErrorsException.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationErrorsException.cs index 5cc2b89c8aaf90..7f66a018c136c9 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationErrorsException.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationErrorsException.cs @@ -161,7 +161,7 @@ public ICollection Errors { get { - if (_errors != null) return _errors; + if (_errors is not null) return _errors; ConfigurationErrorsException e = new ConfigurationErrorsException(BareMessage, InnerException, _firstFilename, _firstLine); @@ -203,7 +203,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont // (since first error duplicates this error, only worry if // there is more than one) int subErrors = 0; - if ((_errors != null) && (_errors.Length > 1)) + if ((_errors is not null) && (_errors.Length > 1)) { subErrors = _errors.Length; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationLockCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationLockCollection.cs index f2f9b647546a00..7b9c2c9e4bf294 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationLockCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationLockCollection.cs @@ -42,7 +42,7 @@ internal ConfigurationLockCollection(ConfigurationElement thisElement, Configura (LockType == ConfigurationLockCollectionType.LockedElementsExceptionList); _ignoreName = ignoreName; - if (parentCollection == null) return; + if (parentCollection is null) return; foreach (string key in parentCollection) // seed the new collection { @@ -132,10 +132,10 @@ public void Add(string name) string attribToLockTrim = name.Trim(); ConfigurationProperty propToLock = _thisElement.Properties[attribToLockTrim]; - if ((propToLock == null) && (attribToLockTrim != LockAll)) + if ((propToLock is null) && (attribToLockTrim != LockAll)) { ConfigurationElementCollection collection = _thisElement as ConfigurationElementCollection; - if ((collection == null) && (_thisElement.Properties.DefaultCollectionProperty != null)) + if ((collection is null) && (_thisElement.Properties.DefaultCollectionProperty is not null)) { // this is not a collection but it may contain a default collection collection = @@ -143,7 +143,7 @@ _thisElement[_thisElement.Properties.DefaultCollectionProperty] as ConfigurationElementCollection; } - if ((collection == null) || + if ((collection is null) || (LockType == ConfigurationLockCollectionType.LockedAttributes) || // If the collection type is not element then the lock is bogus (LockType == ConfigurationLockCollectionType.LockedExceptionList)) @@ -157,7 +157,7 @@ _thisElement[_thisElement.Properties.DefaultCollectionProperty] as else { // the lock is in the property bag but is it the correct type? - if ((propToLock != null) && propToLock.IsRequired) + if ((propToLock is not null) && propToLock.IsRequired) { throw new ConfigurationErrorsException(SR.Format(SR.Config_base_required_attribute_lock_attempt, propToLock.Name)); @@ -209,7 +209,7 @@ internal void Add(string name, ConfigurationValueFlags flags) internal bool DefinedInParent(string name) { - if (name == null) + if (name is null) return false; if (!ExceptionList) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs index ae5f976f1de937..aaa31eea88fa4d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs @@ -53,7 +53,7 @@ public static ConnectionStringSettingsCollection ConnectionStrings object section = GetSection("connectionStrings"); // Verify type, and return the collection - if ((section == null) || (section.GetType() != typeof(ConnectionStringsSection))) + if ((section is null) || (section.GetType() != typeof(ConnectionStringsSection))) { // If config is null or not the type we expect, the declaration was changed. // Treat it as a configuration error. @@ -140,7 +140,7 @@ private static void PrepareConfigSystem() if (s_initState < InitState.Usable) EnsureConfigurationSystem(); // If there was an initialization error, throw it. - if (s_initError != null) throw s_initError; + if (s_initError is not null) throw s_initError; } public static object GetSection(string sectionName) @@ -203,10 +203,10 @@ private static Configuration OpenExeConfigurationImpl(ConfigurationFileMap fileM { // exePath must be specified if not running inside ClientConfigurationSystem if (!isMachine && - (((fileMap == null) && (exePath == null)) || - ((fileMap != null) && (((ExeConfigurationFileMap)fileMap).ExeConfigFilename == null)))) + (((fileMap is null) && (exePath is null)) || + ((fileMap is not null) && (((ExeConfigurationFileMap)fileMap).ExeConfigFilename is null)))) { - if ((s_configSystem != null) && + if ((s_configSystem is not null) && (s_configSystem.GetType() != typeof(ClientConfigurationSystem))) throw new ArgumentException(SR.Config_configmanager_open_noexe); } @@ -221,7 +221,7 @@ private static Configuration OpenExeConfigurationImpl(ConfigurationFileMap fileM /// private static void PreloadConfiguration(Configuration configuration) { - if (null == configuration) return; + if (configuration is null) return; // Preload root-level sections. foreach (ConfigurationSection section in configuration.Sections) { } @@ -233,7 +233,7 @@ private static void PreloadConfiguration(Configuration configuration) private static void PreloadConfigurationSectionGroup(ConfigurationSectionGroup sectionGroup) { - if (null == sectionGroup) return; + if (sectionGroup is null) return; // Preload sections just by iterating. foreach (ConfigurationSection section in sectionGroup.Sections) { } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs index b6b1cf4b7975b3..c21c0fc5c4c4fc 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs @@ -13,7 +13,7 @@ internal static IConfigurationManagerInternal Instance { get { - if (s_instance == null) + if (s_instance is null) { s_instance = new ConfigurationManagerInternal(); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs index 7602d12216380b..a18a3022e96a5e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs @@ -67,7 +67,7 @@ public ConfigurationProperty(string name, internal ConfigurationProperty(PropertyInfo info) { - Debug.Assert(info != null, "info != null"); + Debug.Assert(info is not null, "info is not null"); ConfigurationPropertyAttribute propertyAttribute = null; DescriptionAttribute descriptionAttribute = null; @@ -92,7 +92,7 @@ internal ConfigurationProperty(PropertyInfo info) } else if (attribute is ConfigurationValidatorAttribute) { - if (validator != null) + if (validator is not null) { // We only allow one validator to be specified on a property. // @@ -131,7 +131,7 @@ internal ConfigurationProperty(PropertyInfo info) Attribute.GetCustomAttribute(propertyType, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; - if (collectionAttribute != null) + if (collectionAttribute is not null) { if (collectionAttribute.AddItemName.IndexOf(',') == -1) AddElementName = collectionAttribute.AddItemName; // string.Contains(char) is .NetCore2.1+ specific RemoveElementName = collectionAttribute.RemoveItemName; @@ -140,7 +140,7 @@ internal ConfigurationProperty(PropertyInfo info) } // This constructor shouldn't be invoked if the reflection info is not for an actual config property - Debug.Assert(propertyAttribute != null, "attribProperty != null"); + Debug.Assert(propertyAttribute is not null, "attribProperty is not null"); ConstructorInit(propertyAttribute.Name, info.PropertyType, @@ -241,7 +241,7 @@ private void ConstructorInit( _converter = converter; // Use the default validator if none was supplied - if (Validator == null) + if (Validator is null) { Validator = s_defaultValidatorInstance; } @@ -373,7 +373,7 @@ internal void Validate(object value) private void CreateConverter() { - if (_converter != null) return; + if (_converter is not null) return; if (Type.IsEnum) { @@ -390,7 +390,7 @@ private void CreateConverter() { _converter = TypeDescriptor.GetConverter(Type); - if ((_converter == null) || + if ((_converter is null) || !_converter.CanConvertFrom(typeof(string)) || !_converter.CanConvertTo(typeof(string))) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSection.cs index 5fefeb4bfc7199..29a05492c4f7bd 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSection.cs @@ -45,8 +45,8 @@ protected internal virtual void DeserializeSection(XmlReader reader) protected internal virtual string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode) { - if ((CurrentConfiguration != null) && - (CurrentConfiguration.TargetFramework != null) && + if ((CurrentConfiguration is not null) && + (CurrentConfiguration.TargetFramework is not null) && !ShouldSerializeSectionInTargetVersion(CurrentConfiguration.TargetFramework)) return string.Empty; @@ -65,12 +65,12 @@ protected internal virtual string SerializeSection(ConfigurationElement parentEl tempElement.DataToWriteInternal = saveMode != ConfigurationSaveMode.Minimal; - if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null)) + if ((CurrentConfiguration is not null) && (CurrentConfiguration.TargetFramework is not null)) _configRecord.SectionsStack.Push(this); tempElement.SerializeToXmlElement(writer, name); - if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null)) + if ((CurrentConfiguration is not null) && (CurrentConfiguration.TargetFramework is not null)) _configRecord.SectionsStack.Pop(); writer.Flush(); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs index d00befe43ef2c4..d403193fc48eef 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs @@ -46,7 +46,7 @@ internal void DetachFromConfigurationRecord() private void VerifyIsAttachedToConfigRecord() { - if (_configRecord == null) + if (_configRecord is null) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsectiongroup_when_not_attached); } @@ -70,7 +70,7 @@ public void Clear() public void CopyTo(ConfigurationSection[] array, int index) { - if (array == null) throw new ArgumentNullException(nameof(array)); + if (array is null) throw new ArgumentNullException(nameof(array)); int c = Count; if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroup.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroup.cs index bd6750c97e5625..fc1ce46b89b247 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroup.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroup.cs @@ -12,7 +12,7 @@ public class ConfigurationSectionGroup private ConfigurationSectionCollection _configSections; private string _typeName; - internal bool Attached => _configRecord != null; + internal bool Attached => _configRecord is not null; public bool IsDeclared { get; private set; } @@ -37,7 +37,7 @@ public string Type string typeName = value; if (string.IsNullOrEmpty(typeName)) typeName = null; - if (_configRecord != null) + if (_configRecord is not null) { if (_configRecord.IsLocationConfig) { @@ -47,10 +47,10 @@ public string Type // allow type to be different from current type, // so long as it doesn't conflict with a type already defined - if (typeName != null) + if (typeName is not null) { FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && !factoryRecord.IsEquivalentType(_configRecord.Host, typeName)) + if ((factoryRecord is not null) && !factoryRecord.IsEquivalentType(_configRecord.Host, typeName)) { throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, SectionGroupName)); @@ -66,7 +66,7 @@ public ConfigurationSectionCollection Sections { get { - if (_configSections == null) + if (_configSections is null) { VerifyIsAttachedToConfigRecord(); _configSections = new ConfigurationSectionCollection(_configRecord, this); @@ -80,7 +80,7 @@ public ConfigurationSectionGroupCollection SectionGroups { get { - if (_configSectionGroups == null) + if (_configSectionGroups is null) { VerifyIsAttachedToConfigRecord(); _configSectionGroups = new ConfigurationSectionGroupCollection(_configRecord, this); @@ -99,14 +99,14 @@ internal void AttachToConfigurationRecord(MgmtConfigurationRecord configRecord, Name = factoryRecord.Name; _typeName = factoryRecord.FactoryTypeName; - if (_typeName != null) + if (_typeName is not null) { FactoryRecord parentFactoryRecord = null; if (!configRecord.Parent.IsRootConfig) parentFactoryRecord = configRecord.Parent.FindFactoryRecord(factoryRecord.ConfigKey, true); - IsDeclarationRequired = parentFactoryRecord?.FactoryTypeName == null; - IsDeclared = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, true) != null; + IsDeclarationRequired = parentFactoryRecord?.FactoryTypeName is null; + IsDeclared = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, true) is not null; } } @@ -128,7 +128,7 @@ private FactoryRecord FindParentFactoryRecord(bool permitErrors) { FactoryRecord factoryRecord = null; - if ((_configRecord != null) && !_configRecord.Parent.IsRootConfig) + if ((_configRecord is not null) && !_configRecord.Parent.IsRootConfig) factoryRecord = _configRecord.Parent.FindFactoryRecord(SectionGroupName, permitErrors); return factoryRecord; @@ -136,7 +136,7 @@ private FactoryRecord FindParentFactoryRecord(bool permitErrors) private void VerifyIsAttachedToConfigRecord() { - if (_configRecord == null) + if (_configRecord is null) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsectiongroup_when_not_attached); } @@ -152,7 +152,7 @@ public void ForceDeclaration(bool force) if (IsRoot) throw new InvalidOperationException(SR.Config_root_section_group_cannot_be_edited); - if ((_configRecord != null) && _configRecord.IsLocationConfig) + if ((_configRecord is not null) && _configRecord.IsLocationConfig) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsectiongroup_in_location_config); if (!force && IsDeclarationRequired) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs index 408ca76170bbe4..4b9ba9cfda7f31 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs @@ -42,7 +42,7 @@ internal void DetachFromConfigurationRecord() private void VerifyIsAttachedToConfigRecord() { - if (_configRecord == null) + if (_configRecord is null) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsectiongroup_when_not_attached); } @@ -67,7 +67,7 @@ public void Clear() public void CopyTo(ConfigurationSectionGroup[] array, int index) { - if (array == null) throw new ArgumentNullException(nameof(array)); + if (array is null) throw new ArgumentNullException(nameof(array)); int c = Count; if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValidatorAttribute.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValidatorAttribute.cs index 5c93f7549e4fff..223c5adc1543f7 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValidatorAttribute.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValidatorAttribute.cs @@ -14,7 +14,7 @@ protected ConfigurationValidatorAttribute() { } public ConfigurationValidatorAttribute(Type validator) { - if (validator == null) throw new ArgumentNullException(nameof(validator)); + if (validator is null) throw new ArgumentNullException(nameof(validator)); if (!typeof(ConfigurationValidatorBase).IsAssignableFrom(validator)) { @@ -38,13 +38,13 @@ public virtual ConfigurationValidatorBase ValidatorInstance // security constraints than its base type. internal void SetDeclaringType(Type declaringType) { - if (declaringType == null) + if (declaringType is null) { Debug.Fail("Declaring type must not be null."); return; // don't throw in an in-place update } - if (_declaringType == null) + if (_declaringType is null) { // First call to this method - allow any type to be set _declaringType = declaringType; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs index 4bdda6f749aef8..d56ca07061df16 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs @@ -56,7 +56,7 @@ internal void AssociateContext(BaseConfigurationRecord configRecord) internal bool Contains(string key) { - return BaseGet(key) != null; + return BaseGet(key) is not null; } internal string GetKey(int index) @@ -83,13 +83,13 @@ internal PropertySourceInfo GetSourceInfo(string key) internal void ChangeSourceInfo(string key, PropertySourceInfo sourceInfo) { ConfigurationValue configurationValue = GetConfigValue(key); - if (configurationValue != null) configurationValue.SourceInfo = sourceInfo; + if (configurationValue is not null) configurationValue.SourceInfo = sourceInfo; } private ConfigurationValue CreateConfigValue(object value, ConfigurationValueFlags valueFlags, PropertySourceInfo sourceInfo) { - if (value != null) + if (value is not null) { if (value is ConfigurationElement) { @@ -127,7 +127,7 @@ internal ConfigurationValueFlags RetrieveFlags(string key) internal bool IsModified(string key) { ConfigurationValue configurationValue = (ConfigurationValue)BaseGet(key); - if (configurationValue != null) + if (configurationValue is not null) return (configurationValue.ValueFlags & ConfigurationValueFlags.Modified) != 0; return false; } @@ -135,7 +135,7 @@ internal bool IsModified(string key) internal bool IsInherited(string key) { ConfigurationValue configurationValue = (ConfigurationValue)BaseGet(key); - if (configurationValue != null) + if (configurationValue is not null) return (configurationValue.ValueFlags & ConfigurationValueFlags.Inherited) != 0; return false; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs index dbfd2dd05754de..a7da3fc914ff37 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs @@ -19,7 +19,7 @@ public ConnectionStringSettings this[int index] get { return (ConnectionStringSettings)BaseGet(index); } set { - if (BaseGet(index) != null) BaseRemoveAt(index); + if (BaseGet(index) is not null) BaseRemoveAt(index); BaseAdd(index, value); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ContextInformation.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ContextInformation.cs index ac9c07a22c66d5..3709c1d90f312b 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ContextInformation.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ContextInformation.cs @@ -13,7 +13,7 @@ public sealed class ContextInformation internal ContextInformation(BaseConfigurationRecord configRecord) { - Debug.Assert(configRecord != null, "configRecord != null"); + Debug.Assert(configRecord is not null, "configRecord is not null"); _hostingContextEvaluated = false; _hostingContext = null; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DateTimeConfigurationCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DateTimeConfigurationCollection.cs index dffa2d2ba87ebd..e9f116088039cd 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DateTimeConfigurationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DateTimeConfigurationCollection.cs @@ -15,7 +15,7 @@ public DateTime this[int index] get { return ((DateTimeConfigurationElement)BaseGet(index)).Value; } set { - if (BaseGet(index) != null) BaseRemoveAt(index); + if (BaseGet(index) is not null) BaseRemoveAt(index); BaseAdd(index, new DateTimeConfigurationElement(value)); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DefaultSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DefaultSection.cs index d0c6aac10ddfc4..dbc778dd95b3d8 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DefaultSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DefaultSection.cs @@ -21,7 +21,7 @@ public DefaultSection() private static ConfigurationPropertyCollection EnsureStaticPropertyBag() { - if (s_properties == null) + if (s_properties is null) { ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); s_properties = properties; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs index b2ff1b7b89a76c..d7a7b518f5a727 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs @@ -28,7 +28,7 @@ public virtual object Create(object parent, object context, XmlNode section) // start res off as a shallow clone of the parent - if (parent == null) + if (parent is null) res = new Hashtable(StringComparer.OrdinalIgnoreCase); else res = (Hashtable)((Hashtable)parent).Clone(); @@ -56,7 +56,7 @@ public virtual object Create(object parent, object context, XmlNode section) value = HandlerBase.RemoveAttribute(child, ValueAttributeName); HandlerBase.CheckForUnrecognizedAttributes(child); - if (value == null) + if (value is null) value = ""; res[key] = value; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DpapiProtectedConfigurationProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DpapiProtectedConfigurationProvider.cs index db546c8010316c..1879d4acce62dd 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DpapiProtectedConfigurationProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DpapiProtectedConfigurationProvider.cs @@ -24,15 +24,15 @@ public override XmlNode Decrypt(XmlNode encryptedNode) } XmlNode cipherNode = TraverseToChild(encryptedNode, "CipherData", false); - if (cipherNode == null) + if (cipherNode is null) throw new ConfigurationErrorsException(SR.DPAPI_bad_data); XmlNode cipherValue = TraverseToChild(cipherNode, "CipherValue", true); - if (cipherValue == null) + if (cipherValue is null) throw new ConfigurationErrorsException(SR.DPAPI_bad_data); string encText = cipherValue.InnerText; - if (encText == null) + if (encText is null) throw new ConfigurationErrorsException(SR.DPAPI_bad_data); string decText = DecryptText(encText); @@ -58,7 +58,7 @@ public override XmlNode Encrypt(XmlNode node) private string EncryptText(string clearText) { - if (clearText == null || clearText.Length < 1) + if (clearText is null || clearText.Length < 1) return clearText; byte[] inputData = PrepareDataBlob(clearText); @@ -74,7 +74,7 @@ private string EncryptText(string clearText) private string DecryptText(string encText) { - if (encText == null || encText.Length < 1) + if (encText is null || encText.Length < 1) return encText; byte[] inputData = Convert.FromBase64String(encText); @@ -117,13 +117,13 @@ private static XmlNode TraverseToChild(XmlNode node, string name, bool onlyChild private static byte[] PrepareDataBlob(string s) { - return (s != null) ? Encoding.Unicode.GetBytes(s) : Array.Empty(); + return (s is not null) ? Encoding.Unicode.GetBytes(s) : Array.Empty(); } private static bool GetBooleanValue(NameValueCollection configurationValues, string valueName, bool defaultValue) { string s = configurationValues[valueName]; - if (s == null) + if (s is null) return defaultValue; configurationValues.Remove(valueName); if (s == "true") diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ElementInformation.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ElementInformation.cs index 80cd52628e6df9..080c799cb5f06a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ElementInformation.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ElementInformation.cs @@ -29,7 +29,7 @@ public bool IsCollection get { ConfigurationElementCollection collection = _thisElement as ConfigurationElementCollection; - if ((collection == null) && (_thisElement.Properties.DefaultCollectionProperty != null)) + if ((collection is null) && (_thisElement.Properties.DefaultCollectionProperty is not null)) { // this is not a collection but it may contain a default collection collection = @@ -37,7 +37,7 @@ _thisElement[_thisElement.Properties.DefaultCollectionProperty] as ConfigurationElementCollection; } - return collection != null; + return collection is not null; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs index 5e18a49a8a4ea8..a1292cacd96871 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs @@ -25,7 +25,7 @@ int IConfigErrorInfo.LineNumber { get { - if (_reader == null) return 0; + if (_reader is null) return 0; if (_lineOffset > 0) return _reader.LineNumber + _lineOffset - 1; @@ -45,7 +45,7 @@ public override void Load(string filename) } finally { - if (_reader != null) + if (_reader is not null) { _reader.Close(); _reader = null; @@ -66,7 +66,7 @@ private void LoadFromConfigXmlReader(ConfigXmlReader reader) } finally { - if (_reader != null) + if (_reader is not null) { _reader.Close(); _reader = null; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs index 2ca9406ec964f9..c7dbf7db5399d6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs @@ -20,13 +20,13 @@ internal static bool GetHasErrors(List errors) internal static void AddError(ref List errors, ConfigurationException e) { - Debug.Assert(e != null, "e != null"); + Debug.Assert(e is not null, "e is not null"); // Create on demand - if (errors == null) errors = new List(); + if (errors is null) errors = new List(); ConfigurationErrorsException ce = e as ConfigurationErrorsException; - if (ce == null) errors.Add(e); + if (ce is null) errors.Add(e); else { ICollection col = ce.ErrorsGeneric; @@ -37,7 +37,7 @@ internal static void AddError(ref List errors, Configura internal static void AddErrors(ref List errors, ICollection coll) { - if ((coll == null) || (coll.Count == 0)) + if ((coll is null) || (coll.Count == 0)) { // Nothing to do here, bail return; @@ -48,7 +48,7 @@ internal static void AddErrors(ref List errors, ICollect internal static ConfigurationErrorsException GetErrorsException(List errors) { - if (errors == null) return null; + if (errors is null) return null; Debug.Assert(errors.Count != 0, "errors.Count != 0"); return new ConfigurationErrorsException(errors); @@ -57,7 +57,7 @@ internal static ConfigurationErrorsException GetErrorsException(List errors) { ConfigurationErrorsException e = GetErrorsException(errors); - if (e != null) throw e; + if (e is not null) throw e; } } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ExceptionUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ExceptionUtil.cs index 96fb33160d0a0a..f1d3f86d74d2da 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ExceptionUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ExceptionUtil.cs @@ -38,7 +38,7 @@ internal static InvalidOperationException UnexpectedError(string methodName) internal static ConfigurationErrorsException WrapAsConfigException(string outerMessage, Exception e, IConfigErrorInfo errorInfo) { - return errorInfo != null + return errorInfo is not null ? WrapAsConfigException(outerMessage, e, errorInfo.Filename, errorInfo.LineNumber) : WrapAsConfigException(outerMessage, e, null, 0); } @@ -48,11 +48,11 @@ internal static ConfigurationErrorsException WrapAsConfigException(string outerM { // Preserve ConfigurationErrorsException ConfigurationErrorsException ce = e as ConfigurationErrorsException; - if (ce != null) return ce; + if (ce is not null) return ce; // Promote deprecated ConfigurationException to ConfigurationErrorsException ConfigurationException deprecatedException = e as ConfigurationException; - if (deprecatedException != null) + if (deprecatedException is not null) return new ConfigurationErrorsException( deprecatedException.BareMessage, deprecatedException.InnerException, @@ -61,7 +61,7 @@ internal static ConfigurationErrorsException WrapAsConfigException(string outerM // For XML exceptions, preserve the text of the exception in the outer message. XmlException xe = e as XmlException; - if (xe != null) + if (xe is not null) { if (xe.LineNumber != 0) line = xe.LineNumber; @@ -69,7 +69,7 @@ internal static ConfigurationErrorsException WrapAsConfigException(string outerM } // Wrap other exceptions in an inner exception, and give as much info as possible - if (e != null) + if (e is not null) { return new ConfigurationErrorsException( SR.Format(SR.Wrapped_exception_message, outerMessage, e.Message), diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/FactoryRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/FactoryRecord.cs index d30062e8b3621f..85d64a096e3496 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/FactoryRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/FactoryRecord.cs @@ -183,7 +183,7 @@ internal FactoryRecord CloneSection(string filename, int lineNumber) // by cloning we contain a single copy of the strings referred to in the factory and section records internal FactoryRecord CloneSectionGroup(string factoryTypeName, string filename, int lineNumber) { - if (FactoryTypeName != null) factoryTypeName = FactoryTypeName; + if (FactoryTypeName is not null) factoryTypeName = FactoryTypeName; return new FactoryRecord(ConfigKey, Group, @@ -208,7 +208,7 @@ internal bool IsEquivalentType(IInternalConfigHost host, string typeName) Type t1, t2; - if (host != null) + if (host is not null) { t1 = TypeUtil.GetType(host, typeName, false); t2 = TypeUtil.GetType(host, FactoryTypeName, false); @@ -219,7 +219,7 @@ internal bool IsEquivalentType(IInternalConfigHost host, string typeName) t2 = TypeUtil.GetType(FactoryTypeName, false); } - return (t1 != null) && (t1 == t2); + return (t1 is not null) && (t1 == t2); } catch { } @@ -228,7 +228,7 @@ internal bool IsEquivalentType(IInternalConfigHost host, string typeName) internal bool IsEquivalentSectionGroupFactory(IInternalConfigHost host, string typeName) { - if ((typeName == null) || (FactoryTypeName == null)) + if ((typeName is null) || (FactoryTypeName is null)) return true; return IsEquivalentType(host, typeName); @@ -265,10 +265,10 @@ internal void ThrowOnErrors() internal bool IsIgnorable() { - if (Factory != null) + if (Factory is not null) return Factory is IgnoreSectionHandler; - return (FactoryTypeName != null) && FactoryTypeName.Contains("System.Configuration.IgnoreSection"); + return (FactoryTypeName is not null) && FactoryTypeName.Contains("System.Configuration.IgnoreSection"); } } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/GenericEnumConverter.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/GenericEnumConverter.cs index 2d74dc3a0f81b4..cd4480269c4398 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/GenericEnumConverter.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/GenericEnumConverter.cs @@ -13,7 +13,7 @@ public sealed class GenericEnumConverter : ConfigurationConverterBase public GenericEnumConverter(Type typeEnum) { - if (typeEnum == null) + if (typeEnum is null) throw new ArgumentNullException(nameof(typeEnum)); _enumType = typeEnum; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/HandlerBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/HandlerBase.cs index d1601ee198c25d..7d91b5d0fcb41d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/HandlerBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/HandlerBase.cs @@ -17,7 +17,7 @@ private static XmlNode GetAndRemoveAttribute(XmlNode node, string attrib, bool f XmlNode a = node.Attributes.RemoveNamedItem(attrib); // If the attribute is required and was not present, throw - if (fRequired && a == null) + if (fRequired && a is null) { throw new ConfigurationErrorsException( SR.Format(SR.Config_missing_required_attribute, attrib, node.Name), @@ -30,7 +30,7 @@ private static XmlNode GetAndRemoveAttribute(XmlNode node, string attrib, bool f private static XmlNode GetAndRemoveStringAttributeInternal(XmlNode node, string attrib, bool fRequired, ref string val) { XmlNode a = GetAndRemoveAttribute(node, attrib, fRequired); - if (a != null) + if (a is not null) val = a.Value; return a; @@ -45,7 +45,7 @@ internal static XmlNode GetAndRemoveStringAttribute(XmlNode node, string attrib, private static XmlNode GetAndRemoveBooleanAttributeInternal(XmlNode node, string attrib, bool fRequired, ref bool val) { XmlNode a = GetAndRemoveAttribute(node, attrib, fRequired); - if (a != null) + if (a is not null) { try { @@ -71,7 +71,7 @@ internal static XmlNode GetAndRemoveBooleanAttribute(XmlNode node, string attrib private static XmlNode GetAndRemoveIntegerAttributeInternal(XmlNode node, string attrib, bool fRequired, ref int val) { XmlNode a = GetAndRemoveAttribute(node, attrib, fRequired); - if (a != null) + if (a is not null) { if (a.Value.Trim() != a.Value) { @@ -115,7 +115,7 @@ internal static string RemoveAttribute(XmlNode node, string name) XmlNode attribute = node.Attributes.RemoveNamedItem(name); - if (attribute != null) + if (attribute is not null) { return attribute.Value; } @@ -133,7 +133,7 @@ internal static string RemoveRequiredAttribute(XmlNode node, string name, bool a { XmlNode attribute = node.Attributes.RemoveNamedItem(name); - if (attribute == null) + if (attribute is null) { throw new ConfigurationErrorsException( SR.Format(SR.Config_base_required_attribute_missing, name), diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IgnoreSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IgnoreSection.cs index ca46677b8c0c91..c87f06b608ee32 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IgnoreSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IgnoreSection.cs @@ -21,7 +21,7 @@ public IgnoreSection() private static ConfigurationPropertyCollection EnsureStaticPropertyBag() { - if (s_properties == null) + if (s_properties is null) { ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); s_properties = properties; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ImplicitMachineConfigHost.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ImplicitMachineConfigHost.cs index f762d328e584a1..af9d7a45c312f6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ImplicitMachineConfigHost.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ImplicitMachineConfigHost.cs @@ -38,7 +38,7 @@ private void GetFileMap(object[] parameters) foreach (object parameter in parameters) { _fileMap = parameter as ConfigurationFileMap; - if (_fileMap != null) + if (_fileMap is not null) return; } } @@ -62,7 +62,7 @@ public override Stream OpenStreamForRead(string streamName) { Stream stream = base.OpenStreamForRead(streamName); - if (stream == null && streamName == _machineStreamName) + if (stream is null && streamName == _machineStreamName) { // We only want to inject if we aren't able to load stream = new MemoryStream(Encoding.UTF8.GetBytes(ImplicitMachineConfig)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/FileVersion.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/FileVersion.cs index a572a5246f6be0..f787a341c95344 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/FileVersion.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/FileVersion.cs @@ -22,7 +22,7 @@ public override bool Equals(object obj) { FileVersion other = obj as FileVersion; return - (other != null) + (other is not null) && (_exists == other._exists) && (_fileSize == other._fileSize) && (_utcCreationTime == other._utcCreationTime) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/InternalConfigRoot.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/InternalConfigRoot.cs index 99cd96209a88dd..fcd7a98c9ae0b0 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/InternalConfigRoot.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/InternalConfigRoot.cs @@ -221,7 +221,7 @@ private void HlFindConfigRecord(string[] parts, out int nextIndex, out BaseConfi for (; nextIndex < parts.Length; nextIndex++) { BaseConfigurationRecord childRecord = currentRecord.HlGetChild(parts[nextIndex]); - if (childRecord == null) + if (childRecord is null) break; currentRecord = childRecord; @@ -246,7 +246,7 @@ private void RemoveConfigImpl(string configPath, BaseConfigurationRecord configR HlFindConfigRecord(parts, out index, out currentRecord); // Return if not found, or does not match the one we are trying to remove. - if ((index != parts.Length) || ((configRecord != null) && !ReferenceEquals(configRecord, currentRecord))) + if ((index != parts.Length) || ((configRecord is not null) && !ReferenceEquals(configRecord, currentRecord))) return; // Remove it from the hierarchy. diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs index 8033ead725fa23..c720ef55ca0360 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs @@ -72,7 +72,7 @@ internal void Complete(string filename, bool success) } else { - if (_templateFilename != null) + if (_templateFilename is not null) { // Copy Acl from template file DuplicateTemplateAttributes(_templateFilename, TempNewFilename); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/KeyValueConfigurationCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/KeyValueConfigurationCollection.cs index aba83eecca4478..b9443a728015f3 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/KeyValueConfigurationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/KeyValueConfigurationCollection.cs @@ -30,7 +30,7 @@ public void Add(KeyValueConfigurationElement keyValue) // the appsettings add works more like a namevalue collection add in that it appends values // when add is called and teh key already exists. KeyValueConfigurationElement oldValue = (KeyValueConfigurationElement)BaseGet(keyValue.Key); - if (oldValue == null) + if (oldValue is null) { BaseAdd(keyValue); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs index b7b3e46664876a..2faee26286fbc6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs @@ -40,7 +40,7 @@ private XmlEscaper Escaper { get { - if (_escaper == null) + if (_escaper is null) { _escaper = new XmlEscaper(); } @@ -56,7 +56,7 @@ private ClientSettingsStore Store { get { - if (_store == null) + if (_store is null) { _store = new ClientSettingsStore(); } @@ -99,16 +99,16 @@ public override SettingsPropertyValueCollection GetPropertyValues(SettingsContex // First look for and handle "special" settings SpecialSettingAttribute attr = setting.Attributes[typeof(SpecialSettingAttribute)] as SpecialSettingAttribute; - bool isConnString = (attr != null) ? (attr.SpecialSetting == SpecialSetting.ConnectionString) : false; + bool isConnString = (attr is not null) ? (attr.SpecialSetting == SpecialSetting.ConnectionString) : false; if (isConnString) { string connStringName = sectionName + "." + settingName; - if (connStrings != null && connStrings[connStringName] != null) + if (connStrings is not null && connStrings[connStringName] is not null) { value.PropertyValue = connStrings[connStringName].ConnectionString; } - else if (setting.DefaultValue != null && setting.DefaultValue is string) + else if (setting.DefaultValue is not null && setting.DefaultValue is string) { value.PropertyValue = setting.DefaultValue; } @@ -148,7 +148,7 @@ public override SettingsPropertyValueCollection GetPropertyValues(SettingsContex value.SerializedValue = valueString; } - else if (setting.DefaultValue != null) + else if (setting.DefaultValue is not null) { value.SerializedValue = setting.DefaultValue; } @@ -331,7 +331,7 @@ private string GetPreviousConfigFileName(bool isRoaming) if (Version.TryParse(directory.Name, out tempVersion) && tempVersion < currentVersion) { - if (previousVersion == null) + if (previousVersion is null) { previousVersion = tempVersion; previousDirectory = directory; @@ -344,7 +344,7 @@ private string GetPreviousConfigFileName(bool isRoaming) } } - if (previousDirectory != null) + if (previousDirectory is not null) { file = Path.Combine(previousDirectory.FullName, ConfigurationManagerInternalFactory.Instance.UserConfigFilename); } @@ -377,7 +377,7 @@ private string GetSectionName(SettingsContext context) string groupName = (string)context["GroupName"]; string key = (string)context["SettingsKey"]; - Debug.Assert(groupName != null, "SettingsContext did not have a GroupName!"); + Debug.Assert(groupName is not null, "SettingsContext did not have a GroupName!"); string sectionName = groupName; @@ -430,7 +430,7 @@ private SettingsPropertyValueCollection GetSettingValuesFromFile(string configFi private static bool IsRoamingSetting(SettingsProperty setting) { SettingsManageabilityAttribute manageAttr = setting.Attributes[typeof(SettingsManageabilityAttribute)] as SettingsManageabilityAttribute; - return manageAttr != null && ((manageAttr.Manageability & SettingsManageability.Roaming) == SettingsManageability.Roaming); + return manageAttr is not null && ((manageAttr.Manageability & SettingsManageability.Roaming) == SettingsManageability.Roaming); } /// @@ -462,20 +462,20 @@ private XmlNode SerializeToXmlElement(SettingsProperty setting, SettingsProperty string serializedValue = value.SerializedValue as string; - if (serializedValue == null && setting.SerializeAs == SettingsSerializeAs.Binary) + if (serializedValue is null && setting.SerializeAs == SettingsSerializeAs.Binary) { // SettingsPropertyValue returns a byte[] in the binary serialization case. We need to // encode this - we use base64 since SettingsPropertyValue understands it and we won't have // to special case while deserializing. byte[] buffer = value.SerializedValue as byte[]; - if (buffer != null) + if (buffer is not null) { serializedValue = Convert.ToBase64String(buffer); } } - if (serializedValue == null) + if (serializedValue is null) { serializedValue = string.Empty; } @@ -498,7 +498,7 @@ private XmlNode SerializeToXmlElement(SettingsProperty setting, SettingsProperty break; } } - if (unwanted != null) + if (unwanted is not null) { valueXml.RemoveChild(unwanted); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs index 90b743d3956987..04a5741ef43654 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs @@ -55,10 +55,10 @@ internal Hashtable SectionGroupFactories internal string ConfigurationFilePath => UpdateConfigHost.GetNewStreamname(ConfigStreamInfo.StreamName) ?? string.Empty; - private bool HasRemovedSectionsOrGroups => ((_removedSections != null) && (_removedSections.Count > 0)) - || ((_removedSectionGroups != null) && (_removedSectionGroups.Count > 0)); + private bool HasRemovedSectionsOrGroups => ((_removedSections is not null) && (_removedSections.Count > 0)) + || ((_removedSectionGroups is not null) && (_removedSectionGroups.Count > 0)); - private bool HasRemovedSections => (_removedSections != null) && (_removedSections.Count > 0); + private bool HasRemovedSections => (_removedSections is not null) && (_removedSections.Count > 0); internal bool NamespacePresent { @@ -100,7 +100,7 @@ private void Init( base.Init(configRoot, (BaseConfigurationRecord)parent, configPath, locationSubPath); if (IsLocationConfig && - ((MgmtParent._locationTags == null) || !MgmtParent._locationTags.Contains(_locationSubPath))) + ((MgmtParent._locationTags is null) || !MgmtParent._locationTags.Contains(_locationSubPath))) { // By instantiating a "new" LocationSubPath class, we have implicitly // asked for one to be created @@ -154,7 +154,7 @@ protected override object CreateSection(bool inputIsTrusted, FactoryRecord facto // Initialize the ConfigurationSection with XML or just its parent. ConfigurationSection parentConfigSection = (ConfigurationSection)parentConfig; configSection.Reset(parentConfigSection); - if (reader != null) configSection.DeserializeSection(reader); + if (reader is not null) configSection.DeserializeSection(reader); // Clear the modified bit. configSection.ResetModified(); @@ -177,7 +177,7 @@ private ConstructorInfo CreateSectionGroupFactory(FactoryRecord factoryRecord) private ConstructorInfo EnsureSectionGroupFactory(FactoryRecord factoryRecord) { ConstructorInfo factory = (ConstructorInfo)factoryRecord.Factory; - if (factory == null) + if (factory is null) { factory = CreateSectionGroupFactory(factoryRecord); factoryRecord.Factory = factory; @@ -194,7 +194,7 @@ private ConstructorInfo EnsureSectionGroupFactory(FactoryRecord factoryRecord) protected override object UseParentResult(string configKey, object parentResult, SectionRecord sectionRecord) { FactoryRecord factoryRecord = FindFactoryRecord(configKey, false); - if (factoryRecord == null) + if (factoryRecord is null) { throw new ConfigurationErrorsException(SR.Format(SR.Config_unrecognized_configuration_section, configKey)); @@ -215,7 +215,7 @@ protected override object GetRuntimeObject(object result) private ConfigurationSection GetConfigSection(string configKey) { SectionRecord sectionRecord = GetSectionRecord(configKey, false); - if ((sectionRecord != null) && sectionRecord.HasResult) return (ConfigurationSection)sectionRecord.Result; + if ((sectionRecord is not null) && sectionRecord.HasResult) return (ConfigurationSection)sectionRecord.Result; return null; } @@ -223,7 +223,7 @@ private ConfigurationSection GetConfigSection(string configKey) internal ConfigurationSectionGroup LookupSectionGroup(string configKey) { ConfigurationSectionGroup configSectionGroup = null; - if (_sectionGroups != null) configSectionGroup = (ConfigurationSectionGroup)_sectionGroups[configKey]; + if (_sectionGroups is not null) configSectionGroup = (ConfigurationSectionGroup)_sectionGroups[configKey]; return configSectionGroup; } @@ -235,15 +235,15 @@ internal ConfigurationSectionGroup LookupSectionGroup(string configKey) internal ConfigurationSectionGroup GetSectionGroup(string configKey) { ConfigurationSectionGroup configSectionGroup = LookupSectionGroup(configKey); - if (configSectionGroup != null) return configSectionGroup; + if (configSectionGroup is not null) return configSectionGroup; BaseConfigurationRecord configRecord; FactoryRecord factoryRecord = FindFactoryRecord(configKey, false, out configRecord); - if (factoryRecord == null) return null; + if (factoryRecord is null) return null; if (!factoryRecord.IsGroup) throw ExceptionUtil.ParameterInvalid("sectionGroupName"); - if (factoryRecord.FactoryTypeName == null) + if (factoryRecord.FactoryTypeName is null) { // If no type is defined for the section group, return a base ConfigurationSectionGroup. // For example: @@ -288,7 +288,7 @@ internal ConfigurationLocationCollection GetLocationCollection(Configuration con ArrayList locations = new ArrayList(); // Now add the other empty location sections we recorded - if (_locationTags != null) + if (_locationTags is not null) { foreach (string subPath in _locationTags.Values) locations.Add(new ConfigurationLocation(config, subPath)); @@ -300,7 +300,7 @@ internal ConfigurationLocationCollection GetLocationCollection(Configuration con // Record all location tags in the config file, even if they are empty. protected override void AddLocation(string locationSubPath) { - if (_locationTags == null) _locationTags = new Hashtable(StringComparer.OrdinalIgnoreCase); + if (_locationTags is null) _locationTags = new Hashtable(StringComparer.OrdinalIgnoreCase); _locationTags[locationSubPath] = locationSubPath; } @@ -313,7 +313,7 @@ private Hashtable GetAllFactories(bool isGroup) MgmtConfigurationRecord configRecord = this; do { - if (configRecord._factoryRecords != null) + if (configRecord._factoryRecords is not null) { foreach (FactoryRecord factoryRecord in configRecord._factoryRecords.Values) if (factoryRecord.IsGroup == isGroup) @@ -348,7 +348,7 @@ internal ConfigurationSection FindImmediateParentSection(ConfigurationSection se { Debug.Assert(IsLocationConfig, "Indirect location inputs exist only in location config record"); SectionInput input = sectionRecord.LastIndirectLocationInput; - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(input.HasResult, "input.HasResult"); result = (ConfigurationSection)input.Result; } @@ -370,7 +370,7 @@ internal ConfigurationSection FindImmediateParentSection(ConfigurationSection se while (!current.IsRootConfig) { sectionRecord = current.GetSectionRecord(configKey, false); - if ((sectionRecord != null) && sectionRecord.HasResult) + if ((sectionRecord is not null) && sectionRecord.HasResult) { result = (ConfigurationSection)sectionRecord.Result; break; @@ -430,7 +430,7 @@ internal string GetRawXml(string configKey) { // Get the section record created during Init SectionRecord sectionRecord = GetSectionRecord(configKey, false); - if ((sectionRecord == null) || !sectionRecord.HasFileInput) return null; + if ((sectionRecord is null) || !sectionRecord.HasFileInput) return null; // The section exists, so find and return its RawXml. string[] keys = configKey.Split(s_configPathSeparatorParams); @@ -507,7 +507,7 @@ private bool IsStreamUsed(string oldStreamName) current = MgmtParent; // Check whether a file section is using the configsource directive. - if (current._sectionRecords != null) + if (current._sectionRecords is not null) { foreach (SectionRecord sectionRecord in current._sectionRecords.Values) if (sectionRecord.HasFileInput && @@ -518,7 +518,7 @@ private bool IsStreamUsed(string oldStreamName) } // Check whether a location is using the configsource directive. - if (current._locationSections == null) return false; + if (current._locationSections is null) return false; foreach (LocationSectionRecord locationSectionRecord in current._locationSections) if (StringUtil.EqualsIgnoreCase(locationSectionRecord.SectionXmlInfo.ConfigSourceStreamName, @@ -547,21 +547,21 @@ internal void ChangeConfigSource( throw new ConfigurationErrorsException(SR.Config_source_requires_file); string newConfigSourceStreamName = null; - if (newConfigSource != null) + if (newConfigSource is not null) { newConfigSourceStreamName = Host.GetStreamNameForConfigSource(ConfigStreamInfo.StreamName, newConfigSource); } // Add the stream to the updates - if (newConfigSourceStreamName != null) + if (newConfigSourceStreamName is not null) { // Ensure that no parent is using the same config source stream ValidateUniqueChildConfigSource(sectionInformation.ConfigKey, newConfigSourceStreamName, newConfigSource, null); StreamInfo streamInfo = (StreamInfo)_streamInfoUpdates[newConfigSourceStreamName]; - if (streamInfo != null) + if (streamInfo is not null) { // Detect if another section in this file is using the same configSource // with has a different section name. @@ -580,7 +580,7 @@ internal void ChangeConfigSource( } // remove old streamname if no longer referenced - if ((oldConfigSourceStreamName != null) && !IsStreamUsed(oldConfigSourceStreamName)) + if ((oldConfigSourceStreamName is not null) && !IsStreamUsed(oldConfigSourceStreamName)) _streamInfoUpdates.Remove(oldConfigSourceStreamName); // update the configSourceStreamName @@ -660,7 +660,7 @@ internal void AddConfigurationSection(string group, string name, ConfigurationSe VerifySectionName(name, null, false); - if (configSection == null) throw new ArgumentNullException(nameof(configSection)); + if (configSection is null) throw new ArgumentNullException(nameof(configSection)); // Ensure the section is not already part of the configuration hierarchy. if (configSection.SectionInformation.Attached) @@ -670,7 +670,7 @@ internal void AddConfigurationSection(string group, string name, ConfigurationSe // Ensure the section is not already declared. FactoryRecord factoryRecord = FindFactoryRecord(configKey, true); - if (factoryRecord != null) + if (factoryRecord is not null) throw new ArgumentException(SR.Config_add_configurationsection_already_exists); // Add the configSource if needed. @@ -751,7 +751,7 @@ internal void RemoveConfigurationSection(string group, string name) if (RemovedSections.Contains(configKey)) return; // If it's not a registered section, there's nothing to do. - if (FindFactoryRecord(configKey, true) == null) return; + if (FindFactoryRecord(configKey, true) is null) return; // Detach from this record ConfigurationSection configSection = GetConfigSection(configKey); @@ -759,24 +759,24 @@ internal void RemoveConfigurationSection(string group, string name) // Remove from list of all sections if this is the root declaration. bool isRootDeclaration = IsRootDeclaration(configKey, false); - if ((_sectionFactories != null) && isRootDeclaration) _sectionFactories.Remove(configKey); + if ((_sectionFactories is not null) && isRootDeclaration) _sectionFactories.Remove(configKey); // Remove from collection of factory records. - if (!IsLocationConfig && (_factoryRecords != null) && _factoryRecords.Contains(configKey)) + if (!IsLocationConfig && (_factoryRecords is not null) && _factoryRecords.Contains(configKey)) { sectionIsUsed = true; _factoryRecords.Remove(configKey); } // Remove from collection of section records. - if ((_sectionRecords != null) && _sectionRecords.Contains(configKey)) + if ((_sectionRecords is not null) && _sectionRecords.Contains(configKey)) { sectionIsUsed = true; _sectionRecords.Remove(configKey); } // Remove all location section records for this section in this file. - if (_locationSections != null) + if (_locationSections is not null) { int i = 0; while (i < _locationSections.Count) @@ -822,7 +822,7 @@ internal void AddConfigurationSectionGroup(string group, string name, VerifySectionName(name, null, false); // Validate configSectionGroup argument. - if (configSectionGroup == null) throw ExceptionUtil.ParameterInvalid(nameof(name)); + if (configSectionGroup is null) throw ExceptionUtil.ParameterInvalid(nameof(name)); // A section group can only belong to one section group collection. if (configSectionGroup.Attached) @@ -831,7 +831,7 @@ internal void AddConfigurationSectionGroup(string group, string name, // Do not add if the section group already exists, even if it is of a different type. FactoryRecord factoryRecord = FindFactoryRecord(configKey, true); - if (factoryRecord != null) + if (factoryRecord is not null) throw new ArgumentException(SR.Config_add_configurationsectiongroup_already_exists); // Add to list of all section groups. @@ -907,7 +907,7 @@ internal void RemoveConfigurationSectionGroup(string group, string name) string configKey = CombineConfigKey(group, name); // If it's not a registered section, there's nothing to do. - if (FindFactoryRecord(configKey, true) == null) return; + if (FindFactoryRecord(configKey, true) is null) return; // Remove all descendent sections. ArrayList sections = GetDescendentSectionFactories(configKey); @@ -931,7 +931,7 @@ internal void RemoveConfigurationSectionGroup(string group, string name) // Remove from list of all section group factories if this is the root declaration. bool isRootDeclaration = IsRootDeclaration(descendent.ConfigKey, false); - if ((_sectionGroupFactories != null) && isRootDeclaration) + if ((_sectionGroupFactories is not null) && isRootDeclaration) _sectionGroupFactories.Remove(descendent.ConfigKey); // Remove from list of factory records. @@ -957,11 +957,11 @@ internal void SaveAs(string filename, ConfigurationSaveMode saveMode, bool force ConfigDefinitionUpdates definitionUpdates; ArrayList configSourceUpdates; bool checkedConfigForUpdates = false; - bool requireUpdates = filename != null; + bool requireUpdates = filename is not null; GetConfigDefinitionUpdates(requireUpdates, saveMode, forceUpdateAll, out definitionUpdates, out configSourceUpdates); - if (filename != null) + if (filename is not null) { Debug.Assert(filename.Length > 0, "The caller should make sure that filename is not empty"); @@ -1007,7 +1007,7 @@ internal void SaveAs(string filename, ConfigurationSaveMode saveMode, bool force requireUpdates = RecordItselfRequiresUpdates; } - if ((declarationUpdates != null) || (definitionUpdates != null) || requireUpdates) + if ((declarationUpdates is not null) || (definitionUpdates is not null) || requireUpdates) { // Copy the input stream before opening the output stream. byte[] readBuffer = null; @@ -1016,7 +1016,7 @@ internal void SaveAs(string filename, ConfigurationSaveMode saveMode, bool force { using (Stream streamRead = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) { - if (streamRead == null) + if (streamRead is null) { throw new ConfigurationErrorsException(SR.Config_file_has_changed, ConfigStreamInfo.StreamName, 0); @@ -1046,7 +1046,7 @@ internal void SaveAs(string filename, ConfigurationSaveMode saveMode, bool force } string changedStreamName = FindChangedConfigurationStream(); - if (changedStreamName != null) + if (changedStreamName is not null) throw new ConfigurationErrorsException(SR.Config_file_has_changed, changedStreamName, 0); checkedConfigForUpdates = true; @@ -1065,7 +1065,7 @@ internal void SaveAs(string filename, ConfigurationSaveMode saveMode, bool force // Use the default StreamWriter constructor if encoding is null, // otherwise specify the encoding. using ( - StreamWriter streamWriter = encoding == null + StreamWriter streamWriter = encoding is null ? new StreamWriter(streamWrite) : new StreamWriter(streamWrite, encoding)) { @@ -1106,13 +1106,13 @@ internal void SaveAs(string filename, ConfigurationSaveMode saveMode, bool force ConfigStreamInfo.StreamVersion = MonitorStream(null, null, ConfigStreamInfo.StreamName); } - if (configSourceUpdates != null) + if (configSourceUpdates is not null) { // If we haven't checked before, check now if (!checkedConfigForUpdates) { string changedStreamName = FindChangedConfigurationStream(); - if (changedStreamName != null) + if (changedStreamName is not null) { throw new ConfigurationErrorsException(SR.Config_file_has_changed, changedStreamName, 0); @@ -1268,7 +1268,7 @@ private string ExeDefinitionToString(ConfigurationAllowExeDefinition allowDefini private string GetUpdatedSectionGroupDeclarationXml(FactoryRecord factoryRecord, ConfigurationSectionGroup configSectionGroup) { - if ((TargetFramework != null) && + if ((TargetFramework is not null) && !configSectionGroup.ShouldSerializeSectionGroupInTargetVersion(TargetFramework)) return null; @@ -1298,7 +1298,7 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod bool hasChanged = HasRemovedSectionsOrGroups; SectionUpdates sectionUpdates = new SectionUpdates(string.Empty); - if (_factoryRecords != null) + if (_factoryRecords is not null) { foreach (FactoryRecord factoryRecord in _factoryRecords.Values) if (!factoryRecord.IsGroup) @@ -1312,7 +1312,7 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod // and has a result. In another word, only sections that have been accessed. ConfigurationSection configSection = GetConfigSection(factoryRecord.ConfigKey); - if (configSection != null) + if (configSection is not null) { // We should skip this section declaration only if all below hold true: // 1. The section should not be declared at this level. Reasons: @@ -1323,13 +1323,13 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod // 4. It's not valid in the current Target Framework version if (!configSection.SectionInformation.IsDeclared && !MgmtParent.IsRootConfig - && (MgmtParent.FindFactoryRecord(factoryRecord.ConfigKey, false) != null)) + && (MgmtParent.FindFactoryRecord(factoryRecord.ConfigKey, false) is not null)) { if (factoryRecord.HasFile) hasChanged = true; continue; } - if ((TargetFramework != null) && + if ((TargetFramework is not null) && !configSection.ShouldSerializeSectionInTargetVersion(TargetFramework)) continue; @@ -1359,14 +1359,14 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod } else { - if ((configSectionGroup != null) && configSectionGroup.IsDeclarationRequired) + if ((configSectionGroup is not null) && configSectionGroup.IsDeclarationRequired) { // The section group is declared in this config file addGroupUpdate = true; } else { - if ((factoryRecord.FactoryTypeName != null) || (configSectionGroup != null)) + if ((factoryRecord.FactoryTypeName is not null) || (configSectionGroup is not null)) { FactoryRecord parentFactoryRecord = null; if (!MgmtParent.IsRootConfig) @@ -1377,7 +1377,7 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod // Add it if declaration is required. Please note this check is identical to the check // for _declarationRequired in ConfigurationSectionGroup.AttachToConfigurationRecord. - addGroupUpdate = parentFactoryRecord?.FactoryTypeName == null; + addGroupUpdate = parentFactoryRecord?.FactoryTypeName is null; } } } @@ -1388,7 +1388,7 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod if (!factoryRecord.HasFile || - ((configSectionGroup != null) && + ((configSectionGroup is not null) && (configSectionGroup.Type != factoryRecord.FactoryTypeName))) { updatedXml = GetUpdatedSectionGroupDeclarationXml(factoryRecord, configSectionGroup); @@ -1406,11 +1406,11 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod } } - if (_sectionRecords != null) + if (_sectionRecords is not null) { foreach (SectionRecord sectionRecord in _sectionRecords.Values) { - if ((GetFactoryRecord(sectionRecord.ConfigKey, false) != null) || !sectionRecord.HasResult) + if ((GetFactoryRecord(sectionRecord.ConfigKey, false) is not null) || !sectionRecord.HasResult) { // Skip because this factory is defined locally ( in // which case we handled above), or it was not used @@ -1439,16 +1439,16 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod } } - if (_sectionGroups != null) + if (_sectionGroups is not null) { foreach (ConfigurationSectionGroup configSectionGroup in _sectionGroups.Values) { - if (GetFactoryRecord(configSectionGroup.SectionGroupName, false) != null) continue; + if (GetFactoryRecord(configSectionGroup.SectionGroupName, false) is not null) continue; FactoryRecord factoryRecord = MgmtParent.FindFactoryRecord(configSectionGroup.SectionGroupName, false); if (configSectionGroup.IsDeclared || - ((factoryRecord != null) && (configSectionGroup.Type != factoryRecord.FactoryTypeName))) + ((factoryRecord is not null) && (configSectionGroup.Type != factoryRecord.FactoryTypeName))) { string updatedXml = GetUpdatedSectionGroupDeclarationXml(factoryRecord, configSectionGroup); if (!string.IsNullOrEmpty(updatedXml)) @@ -1530,7 +1530,7 @@ private void GetConfigDefinitionUpdates( bool hasChanged = HasRemovedSections; // Loop through all the section records. - if (_sectionRecords != null) + if (_sectionRecords is not null) { InitProtectedConfigurationSection(); // Make sure we have the initialized the protected config section, otherwise the foreach loop may blow up @@ -1563,7 +1563,7 @@ private void GetConfigDefinitionUpdates( { ConfigurationSection configSection = (ConfigurationSection)sectionRecord.Result; - if ((TargetFramework != null) && + if ((TargetFramework is not null) && !configSection.ShouldSerializeSectionInTargetVersion(TargetFramework)) continue; @@ -1588,7 +1588,7 @@ private void GetConfigDefinitionUpdates( bool sectionAttributesModified = AreSectionAttributesModified(sectionRecord, configSection); bool sectionContentModified = isModified || - (configSection.SectionInformation.RawXml != null); + (configSection.SectionInformation.RawXml is not null); // Get the updated XML if the section has been modified. if (sectionContentModified || sectionAttributesModified) @@ -1607,7 +1607,7 @@ private void GetConfigDefinitionUpdates( } if (isModified || - (configSection.SectionInformation.RawXml == null) || + (configSection.SectionInformation.RawXml is null) || (saveMode == ConfigurationSaveMode.Full)) { // Note: we won't use RawXml if saveMode == Full because Full means we want to @@ -1627,7 +1627,7 @@ private void GetConfigDefinitionUpdates( // * The section is encrypted. if (!string.IsNullOrEmpty(configSection.SectionInformation.ConfigSource) || !configSection.SectionInformation.LocationAttributesAreDefault || - (configSection.SectionInformation.ProtectionProvider != null)) + (configSection.SectionInformation.ProtectionProvider is not null)) updatedXml = WriteEmptyElement(configSection.SectionInformation.Name); } @@ -1655,7 +1655,7 @@ private void GetConfigDefinitionUpdates( hasChanged = true; // Encrypt if required. - if (configSection.SectionInformation.ProtectionProvider != null) + if (configSection.SectionInformation.ProtectionProvider is not null) { ProtectedConfigurationSection protectedConfig = GetSection(ReservedSectionProtectedConfiguration) as @@ -1712,7 +1712,7 @@ private void GetConfigDefinitionUpdates( if (addToConfigSourceUpdates) { - if (configSourceUpdates == null) configSourceUpdates = new ArrayList(); + if (configSourceUpdates is null) configSourceUpdates = new ArrayList(); configSourceUpdates.Add(definitionUpdate); } } @@ -1753,7 +1753,7 @@ private string WriteEmptyElement(string elementName) // to reflect changes that were made in the config file. private void UpdateRecords() { - if (_factoryRecords != null) + if (_factoryRecords is not null) { foreach (FactoryRecord factoryRecord in _factoryRecords.Values) { @@ -1764,9 +1764,9 @@ private void UpdateRecords() factoryRecord.LineNumber = 0; ConfigurationSection configSection = GetConfigSection(factoryRecord.ConfigKey); - if (configSection == null) continue; + if (configSection is null) continue; - if (configSection.SectionInformation.Type != null) + if (configSection.SectionInformation.Type is not null) factoryRecord.FactoryTypeName = configSection.SectionInformation.Type; factoryRecord.AllowLocation = configSection.SectionInformation.AllowLocation; @@ -1778,7 +1778,7 @@ private void UpdateRecords() } } - if (_sectionRecords != null) + if (_sectionRecords is not null) { string definitionConfigPath = IsLocationConfig ? _parent.ConfigPath : ConfigPath; foreach (SectionRecord sectionRecord in _sectionRecords.Values) @@ -1850,7 +1850,7 @@ private void UpdateRecords() if (addUpdate) { SectionInput fileInput = sectionRecord.FileInput; - if (fileInput == null) + if (fileInput is null) { SectionXmlInfo sectionXmlInfo = new SectionXmlInfo( sectionRecord.ConfigKey, definitionConfigPath, _configPath, _locationSubPath, @@ -1919,7 +1919,7 @@ private void UpdateRecords() _flags[SuggestLocationRemoval] = false; // Handle removed location sections - if (!IsLocationConfig && (_locationSections != null) && (_removedSections != null) && + if (!IsLocationConfig && (_locationSections is not null) && (_removedSections is not null) && (_removedSections.Count > 0)) { int i = 0; @@ -1958,7 +1958,7 @@ private void CreateNewConfig( const int LineIndent = DefaultIndent + 1; - if (declarationUpdates != null) + if (declarationUpdates is not null) WriteNewConfigDeclarations(declarationUpdates, utilWriter, LineIndent, DefaultIndent, false); WriteNewConfigDefinitions(definitionUpdates, utilWriter, LineIndent, DefaultIndent); @@ -1990,7 +1990,7 @@ private void WriteUnwrittenConfigDeclarationsRecursive(SectionUpdates declaratio XmlUtilWriter utilWriter, int linePosition, int indent, bool skipFirstIndent) { string[] unretrievedSectionNames = declarationUpdates.GetUnretrievedSectionNames(); - if (unretrievedSectionNames != null) + if (unretrievedSectionNames is not null) { foreach (string configKey in unretrievedSectionNames) { @@ -2008,14 +2008,14 @@ private void WriteUnwrittenConfigDeclarationsRecursive(SectionUpdates declaratio } string[] unretrievedGroupNames = declarationUpdates.GetUnretrievedGroupNames(); - if (unretrievedGroupNames == null) return; + if (unretrievedGroupNames is null) return; foreach (string group in unretrievedGroupNames) { - if (TargetFramework != null) + if (TargetFramework is not null) { ConfigurationSectionGroup g = GetSectionGroup(group); - if ((g != null) && !g.ShouldSerializeSectionGroupInTargetVersion(TargetFramework)) + if ((g is not null) && !g.ShouldSerializeSectionGroupInTargetVersion(TargetFramework)) { declarationUpdates.MarkGroupAsRetrieved(group); continue; @@ -2026,7 +2026,7 @@ private void WriteUnwrittenConfigDeclarationsRecursive(SectionUpdates declaratio SectionUpdates declarationUpdatesChild = declarationUpdates.GetSectionUpdatesForGroup(group); DeclarationUpdate groupUpdate = declarationUpdatesChild.GetSectionGroupUpdate(); - if (groupUpdate == null) utilWriter.Write(""); + if (groupUpdate is null) utilWriter.Write(""); else utilWriter.Write(groupUpdate.UpdatedXml); utilWriter.AppendNewLine(); @@ -2040,7 +2040,7 @@ private void WriteUnwrittenConfigDeclarationsRecursive(SectionUpdates declaratio private void WriteNewConfigDefinitions(ConfigDefinitionUpdates configDefinitionUpdates, XmlUtilWriter utilWriter, int linePosition, int indent) { - if (configDefinitionUpdates == null) + if (configDefinitionUpdates is null) return; foreach (LocationUpdates locationUpdates in configDefinitionUpdates.LocationUpdatesList) @@ -2050,7 +2050,7 @@ private void WriteNewConfigDefinitions(ConfigDefinitionUpdates configDefinitionU continue; configDefinitionUpdates.FlagLocationWritten(); - bool writeLocationTag = (_locationSubPath != null) || !locationUpdates.IsDefault; + bool writeLocationTag = (_locationSubPath is not null) || !locationUpdates.IsDefault; int recurseLinePosition = linePosition; utilWriter.AppendSpacesToLinePosition(linePosition); @@ -2058,7 +2058,7 @@ private void WriteNewConfigDefinitions(ConfigDefinitionUpdates configDefinitionU if (writeLocationTag) { // write the start tag - if (_locationSubPath == null) + if (_locationSubPath is null) { utilWriter.Write(string.Format(CultureInfo.InvariantCulture, FormatLocationNoPath, locationUpdates.OverrideMode.LocationTagXmlString, @@ -2112,7 +2112,7 @@ private bool WriteNewConfigDefinitionsRecursive(XmlUtilWriter utilWriter, Sectio bool wroteASection = false; string[] movedSectionNames = sectionUpdates.GetMovedSectionNames(); - if (movedSectionNames != null) + if (movedSectionNames is not null) { wroteASection = true; foreach (string configKey in movedSectionNames) @@ -2125,14 +2125,14 @@ private bool WriteNewConfigDefinitionsRecursive(XmlUtilWriter utilWriter, Sectio } string[] newGroupNames = sectionUpdates.GetNewGroupNames(); - if (newGroupNames != null) + if (newGroupNames is not null) { foreach (string group in newGroupNames) { - if (TargetFramework != null) + if (TargetFramework is not null) { ConfigurationSectionGroup g = GetSectionGroup(group); - if ((g != null) && !g.ShouldSerializeSectionGroupInTargetVersion(TargetFramework)) + if ((g is not null) && !g.ShouldSerializeSectionGroupInTargetVersion(TargetFramework)) { sectionUpdates.MarkGroupAsRetrieved(group); continue; @@ -2242,7 +2242,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat : null; } - bool needsChildren = (declarationUpdates != null) || (definitionUpdates != null); + bool needsChildren = (declarationUpdates is not null) || (definitionUpdates is not null); string configurationEndElement = xmlUtil.UpdateStartElement(utilWriter, configurationStartElement, needsChildren, configurationElementLinePosition, indent); @@ -2263,7 +2263,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat bool isEmptyConfigSectionsElement = reader.IsEmptyElement; // if no updates, copy the entire element - if (declarationUpdates == null) xmlUtil.CopyOuterXmlToNextElement(utilWriter, true); + if (declarationUpdates is null) xmlUtil.CopyOuterXmlToNextElement(utilWriter, true); else { // copy , and open it if it is an empty element @@ -2291,7 +2291,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat { // determine the line position of the end element int endElementLinePosition = 0; - if (configSectionsEndElement == null) + if (configSectionsEndElement is null) endElementLinePosition = xmlUtil.TrueLinePosition; // indent a new line @@ -2301,12 +2301,12 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat configSectionsElementLinePosition + indent, indent, false); // restore spaces to end element - if (configSectionsEndElement == null) + if (configSectionsEndElement is null) utilWriter.AppendSpacesToLinePosition(endElementLinePosition); } // Copy the element - if (configSectionsEndElement == null) xmlUtil.CopyXmlNode(utilWriter); + if (configSectionsEndElement is null) xmlUtil.CopyXmlNode(utilWriter); else { // note that configSectionsEndElement already contains the proper indenting @@ -2320,7 +2320,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat } // Write new declarations - if (!foundConfigSectionsElement && (declarationUpdates != null)) + if (!foundConfigSectionsElement && (declarationUpdates is not null)) { bool skipFirstIndent = (reader.Depth > 0) && (reader.NodeType == XmlNodeType.Element); int newConfigSectionsLinePosition; @@ -2331,7 +2331,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat skipFirstIndent); } - if (definitionUpdates != null) + if (definitionUpdates is not null) { // Copy sections recursively. In the file we copy we start out at // location path="." allowOverride="true" inheritInChildApps="true" @@ -2343,7 +2343,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat locationPathApplies = true; locationUpdates = definitionUpdates.FindLocationUpdates( OverrideModeSetting.s_locationDefault, true); - if (locationUpdates != null) sectionUpdates = locationUpdates.SectionUpdates; + if (locationUpdates is not null) sectionUpdates = locationUpdates.SectionUpdates; } CopyConfigDefinitionsRecursive(definitionUpdates, xmlUtil, utilWriter, locationPathApplies, @@ -2356,9 +2356,9 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat #if DEBUG Debug.Assert( - (configurationEndElement != null) || + (configurationEndElement is not null) || ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == ConfigurationTag)), - "configurationEndElement != null || (reader.NodeType == XmlNodeType.EndElement && reader.Name == KEYWORD_CONFIGURATION)"); + "configurationEndElement is not null || (reader.NodeType == XmlNodeType.EndElement && reader.Name == KEYWORD_CONFIGURATION)"); foreach (LocationUpdates l in definitionUpdates.LocationUpdatesList) Debug.Assert(!l.SectionUpdates.HasUnretrievedSections(), "!l.SectionUpdates.HasUnretrievedSections()"); @@ -2366,7 +2366,7 @@ private void CopyConfig(SectionUpdates declarationUpdates, ConfigDefinitionUpdat } - if (configurationEndElement != null) + if (configurationEndElement is not null) { // If we have to add closing config tag, then do it now // before copying extra whitespace/comments @@ -2413,7 +2413,7 @@ private bool CopyConfigDeclarationsRecursive( // Write any new section declarations that apply to this group string[] movedSectionNames = declarationUpdates?.GetMovedSectionNames(); - if (movedSectionNames != null) + if (movedSectionNames is not null) { if (!utilWriter.IsLastLineBlank) utilWriter.AppendNewLine(); @@ -2462,7 +2462,7 @@ private bool CopyConfigDeclarationsRecursive( { // it's a group - get the updates for children declarationUpdatesChild = declarationUpdates.GetSectionUpdatesForGroup(name); - if (declarationUpdatesChild != null) + if (declarationUpdatesChild is not null) { // get the group update groupUpdate = declarationUpdatesChild.GetSectionGroupUpdate(); @@ -2483,7 +2483,7 @@ private bool CopyConfigDeclarationsRecursive( sectionUpdate = declarationUpdates.GetDeclarationUpdate(configKey); } - bool writeGroupUpdate = groupUpdate?.UpdatedXml != null; + bool writeGroupUpdate = groupUpdate?.UpdatedXml is not null; if (recurse) { // create a checkpoint that we can revert to if no children are written @@ -2501,7 +2501,7 @@ private bool CopyConfigDeclarationsRecursive( } else closingElement = xmlUtil.UpdateStartElement(utilWriter, null, true, linePosition, indent); - if (closingElement == null) + if (closingElement is null) { // Only if there is a closing element should // we move to it @@ -2512,7 +2512,7 @@ private bool CopyConfigDeclarationsRecursive( bool recurseWroteASection = CopyConfigDeclarationsRecursive( recurseDeclarationUpdates, xmlUtil, utilWriter, recurseGroup, linePosition, indent); - if (closingElement != null) + if (closingElement is not null) { utilWriter.AppendSpacesToLinePosition(linePosition); utilWriter.Write(closingElement); @@ -2541,7 +2541,7 @@ private bool CopyConfigDeclarationsRecursive( { bool skip; bool skipChildElements = false; - if (sectionUpdate == null) + if (sectionUpdate is null) { skip = true; if (writeGroupUpdate) @@ -2557,11 +2557,11 @@ private bool CopyConfigDeclarationsRecursive( } else { - if (groupUpdate != null) + if (groupUpdate is not null) { // If groupUpdate exists, that means we've decided in GetConfigDeclarationUpdates // that the section group should stay in the file. - Debug.Assert(groupUpdate.UpdatedXml == null, "groupUpdate.UpdatedXml == null"); + Debug.Assert(groupUpdate.UpdatedXml is null, "groupUpdate.UpdatedXml is null"); Debug.Assert(!declarationUpdatesChild.HasUnretrievedSections(), "If the group has any unretrieved section, we should have chosen the recursive code path above."); @@ -2577,7 +2577,7 @@ private bool CopyConfigDeclarationsRecursive( else { wroteASection = true; - if (sectionUpdate.UpdatedXml == null) skip = false; + if (sectionUpdate.UpdatedXml is null) skip = false; else { skip = true; @@ -2643,14 +2643,14 @@ private bool CopyConfigDefinitionsRecursive( } // Write any new sections that apply to this group - if ((sectionUpdates != null) && addNewSections) + if ((sectionUpdates is not null) && addNewSections) { // Remove newness, so we won't write again sectionUpdates.IsNew = false; Debug.Assert(locationPathApplies, nameof(locationPathApplies)); string[] movedSectionNames = sectionUpdates.GetMovedSectionNames(); - if (movedSectionNames != null) + if (movedSectionNames is not null) { if (!utilWriter.IsLastLineBlank) utilWriter.AppendNewLine(); @@ -2708,7 +2708,7 @@ private bool CopyConfigDefinitionsRecursive( { // For location config we will compare config paths instead of location strings // so that we dont end up comparing "1" with "Default Web Site" and ending up with the wrong result - if (locationSubPathAttribute == null) elementLocationPathApplies = false; + if (locationSubPathAttribute is null) elementLocationPathApplies = false; else { elementLocationPathApplies = StringUtil.EqualsIgnoreCase(ConfigPath, @@ -2717,37 +2717,37 @@ private bool CopyConfigDefinitionsRecursive( } else { - Debug.Assert(LocationSubPath == null); + Debug.Assert(LocationSubPath is null); // This is the same as doing StringUtil.EqualsIgnoreCase(_locationSubPath, locationSubPathAttribute) // but remember the first one is null. Also remember locationSubPathAttribute is already normalized - elementLocationPathApplies = locationSubPathAttribute == null; + elementLocationPathApplies = locationSubPathAttribute is null; } if (elementLocationPathApplies) { // Retrieve overrideMode and InheritInChildApps string allowOverrideAttribute = reader.GetAttribute(LocationAllowOverrideAttribute); - if (allowOverrideAttribute != null) + if (allowOverrideAttribute is not null) { overrideMode = OverrideModeSetting.CreateFromXmlReadValue(bool.Parse(allowOverrideAttribute)); } string overrideModeAttribute = reader.GetAttribute(LocationOverrideModeAttribute); - if (overrideModeAttribute != null) + if (overrideModeAttribute is not null) { overrideMode = OverrideModeSetting.CreateFromXmlReadValue( OverrideModeSetting.ParseOverrideModeXmlValue(overrideModeAttribute, null)); - Debug.Assert(allowOverrideAttribute == null, + Debug.Assert(allowOverrideAttribute is null, "allowOverride and overrideMode both detected in a tag"); } string inheritInChildAppsAttribute = reader.GetAttribute(LocationInheritInChildApplicationsAttribute); - if (inheritInChildAppsAttribute != null) + if (inheritInChildAppsAttribute is not null) inheritInChildApps = bool.Parse(inheritInChildAppsAttribute); // Flag that we already have one of these locations @@ -2758,7 +2758,7 @@ private bool CopyConfigDefinitionsRecursive( { if (elementLocationPathApplies && (configDefinitionUpdates.FindLocationUpdates(overrideMode, - inheritInChildApps) != null)) + inheritInChildApps) is not null)) { // If we are going to make updates here, then // delete the one that is here (so we can update later) @@ -2775,18 +2775,18 @@ private bool CopyConfigDefinitionsRecursive( // recurse if this location applies to us if (elementLocationPathApplies) { - if (configDefinitionUpdates != null) + if (configDefinitionUpdates is not null) { recurseLocationUpdates = configDefinitionUpdates.FindLocationUpdates(overrideMode, inheritInChildApps); - if (recurseLocationUpdates != null) + if (recurseLocationUpdates is not null) { recurse = true; recurseSectionUpdates = recurseLocationUpdates.SectionUpdates; // If this is , we don't want to add moved sections // to it. - if ((_locationSubPath == null) && recurseLocationUpdates.IsDefault) + if ((_locationSubPath is null) && recurseLocationUpdates.IsDefault) recurseAddNewSections = false; } } @@ -2808,7 +2808,7 @@ private bool CopyConfigDefinitionsRecursive( { string configKey = CombineConfigKey(group, elementName); FactoryRecord factoryRecord = FindFactoryRecord(configKey, false); - if (factoryRecord == null) + if (factoryRecord is null) { // The factory was deleted, so regardless of whether this is a // section or sectionGroup, it can be skipped. @@ -2825,11 +2825,11 @@ private bool CopyConfigDefinitionsRecursive( else { // if the location path applies, recurse if there are updates - if (sectionUpdates != null) + if (sectionUpdates is not null) { SectionUpdates sectionUpdatesChild = sectionUpdates.GetSectionUpdatesForGroup(elementName); - if (sectionUpdatesChild != null) + if (sectionUpdatesChild is not null) { recurse = true; recurseGroup = configKey; @@ -2840,7 +2840,7 @@ private bool CopyConfigDefinitionsRecursive( { if (!elementLocationPathApplies && !IsLocationConfig) { - if ((_removedSectionGroups != null) && + if ((_removedSectionGroups is not null) && _removedSectionGroups.Contains(configKey)) removedSectionOrGroup = true; else @@ -2858,12 +2858,12 @@ private bool CopyConfigDefinitionsRecursive( else { // it is a section - get the update - if (sectionUpdates != null) update = sectionUpdates.GetDefinitionUpdate(configKey); + if (sectionUpdates is not null) update = sectionUpdates.GetDefinitionUpdate(configKey); else { if (!elementLocationPathApplies && !IsLocationConfig) { - if ((_removedSections != null) && _removedSections.Contains(configKey)) + if ((_removedSections is not null) && _removedSections.Contains(configKey)) removedSectionOrGroup = true; } } @@ -2902,7 +2902,7 @@ private bool CopyConfigDefinitionsRecursive( else { bool skip; - if (update == null) + if (update is null) { // remove the section from the file if we're in the correct location, // or if the section or group should be removed from all locations @@ -2913,7 +2913,7 @@ private bool CopyConfigDefinitionsRecursive( // replace the section if the xml for it has been updated // if it is a configSource, don't write it unless the configSource parameters have changed skip = false; - if (update.UpdatedXml != null) + if (update.UpdatedXml is not null) { ConfigurationSection configSection = (ConfigurationSection)update.SectionRecord.Result; if (string.IsNullOrEmpty(configSection.SectionInformation.ConfigSource) || @@ -2943,7 +2943,7 @@ private bool CopyConfigDefinitionsRecursive( } // Write new section groups - if ((sectionUpdates != null) && addNewSections && sectionUpdates.HasNewSectionGroups()) + if ((sectionUpdates is not null) && addNewSections && sectionUpdates.HasNewSectionGroups()) { // Add whitespace to align us with the other elements in this group linePosition = parentLinePosition + indent; @@ -3002,7 +3002,7 @@ private void SaveConfigSource(DefinitionUpdate update) byte[] readBuffer = null; using (Stream streamRead = Host.OpenStreamForRead(configSourceStreamName)) { - if (streamRead != null) + if (streamRead is not null) { readBuffer = new byte[streamRead.Length]; int count = streamRead.Read(readBuffer, 0, (int)streamRead.Length); @@ -3011,7 +3011,7 @@ private void SaveConfigSource(DefinitionUpdate update) } // Write the changes to the output stream. - bool hasFile = readBuffer != null; + bool hasFile = readBuffer is not null; object writeContext = null; bool streamOpened = false; @@ -3032,7 +3032,7 @@ private void SaveConfigSource(DefinitionUpdate update) ref writeContext)) { streamOpened = true; - if (update.UpdatedXml == null) + if (update.UpdatedXml is null) { Debug.Assert(hasFile, "hasFile"); if (hasFile) streamWrite.Write(readBuffer, 0, readBuffer.Length); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueConfigurationCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueConfigurationCollection.cs index 27e9651f060382..3295b4b9b15532 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueConfigurationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueConfigurationCollection.cs @@ -17,7 +17,7 @@ public sealed class NameValueConfigurationCollection : ConfigurationElementColle { int index = -1; // append by default NameValueConfigurationElement tempElement = (NameValueConfigurationElement)BaseGet(name); - if (tempElement != null) + if (tempElement is not null) { index = BaseIndexOf(tempElement); BaseRemoveAt(index); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs index d434bd577a2e7d..6d83e89459420b 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs @@ -26,12 +26,12 @@ public object Create(object parent, object configContext, XmlNode section) result = NameValueSectionHandler.CreateStatic(result, section); - if (fileAttribute != null && fileAttribute.Value.Length != 0) + if (fileAttribute is not null && fileAttribute.Value.Length != 0) { string filename = null; filename = fileAttribute.Value; IConfigErrorInfo configXmlNode = fileAttribute as IConfigErrorInfo; - if (configXmlNode == null) + if (configXmlNode is null) { return null; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueSectionHandler.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueSectionHandler.cs index 099b1d7ec84f2f..a12e4bf1ae1d3d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueSectionHandler.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueSectionHandler.cs @@ -29,7 +29,7 @@ internal static object CreateStatic(object parent, XmlNode section, string keyAt // start result off as a shallow clone of the parent - if (parent == null) + if (parent is null) result = new ReadOnlyNameValueCollection(StringComparer.OrdinalIgnoreCase); else { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs index 7a6ceb3caf06ba..d0e4d4758df272 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs @@ -12,7 +12,7 @@ public override bool CanValidate(Type type) public override void Validate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if ((TimeSpan)value <= TimeSpan.Zero) throw new ArgumentException(SR.Validator_timespan_value_must_be_positive); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformation.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformation.cs index b94c886e53f088..c329edfdb637d1 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformation.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformation.cs @@ -39,21 +39,21 @@ public PropertyValueOrigin ValueOrigin { get { - if (_thisElement.Values[Name] == null) return PropertyValueOrigin.Default; + if (_thisElement.Values[Name] is null) return PropertyValueOrigin.Default; return _thisElement.Values.IsInherited(Name) ? PropertyValueOrigin.Inherited : PropertyValueOrigin.SetHere; } } - public bool IsModified => _thisElement.Values[Name] != null && _thisElement.Values.IsModified(Name); + public bool IsModified => _thisElement.Values[Name] is not null && _thisElement.Values.IsModified(Name); public bool IsKey => Prop.IsKey; public bool IsRequired => Prop.IsRequired; public bool IsLocked => - ((_thisElement.LockedAllExceptAttributesList != null) && + ((_thisElement.LockedAllExceptAttributesList is not null) && !_thisElement.LockedAllExceptAttributesList.DefinedInParent(Name)) || - ((_thisElement.LockedAttributesList != null) && + ((_thisElement.LockedAttributesList is not null) && (_thisElement.LockedAttributesList.DefinedInParent(Name) || _thisElement.LockedAttributesList.DefinedInParent(LockAll))) || (((_thisElement.ItemLocked & ConfigurationValueFlags.Locked) != 0) && @@ -66,7 +66,7 @@ public string Source { PropertySourceInfo psi = _thisElement.Values.GetSourceInfo(Name) ?? _thisElement.Values.GetSourceInfo(string.Empty); - return psi == null ? string.Empty : psi.FileName; + return psi is null ? string.Empty : psi.FileName; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs index 9023f6be23ed6b..12f0e418076af2 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs @@ -25,12 +25,12 @@ public PropertyInformation this[string propertyName] PropertyInformation result = (PropertyInformation)BaseGet(propertyName); // check for default collection name - if (result == null) + if (result is null) { PropertyInformation defaultColl = (PropertyInformation)BaseGet(ConfigurationProperty.DefaultCollectionPropertyName); - if ((defaultColl != null) && (defaultColl.ProvidedName == propertyName)) result = defaultColl; + if ((defaultColl is not null) && (defaultColl.ProvidedName == propertyName)) result = defaultColl; } return result; } @@ -41,7 +41,7 @@ public PropertyInformation this[string propertyName] public void CopyTo(PropertyInformation[] array, int index) { - if (array == null) throw new ArgumentNullException(nameof(array)); + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Length < Count + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs index 1a3fe6399a99e9..2d2204b11c4110 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs @@ -22,7 +22,7 @@ private string GetFilename(XmlReader reader) { IConfigErrorInfo err = reader as IConfigErrorInfo; - return err != null ? err.Filename : ""; + return err is not null ? err.Filename : ""; } private int GetLineNumber(XmlReader reader) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfiguration.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfiguration.cs index 983f09acacfc1e..e74691afd4a475 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfiguration.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfiguration.cs @@ -13,7 +13,7 @@ public static ProtectedConfigurationProviderCollection Providers PrivilegedConfigurationManager.GetSection( BaseConfigurationRecord.ReservedSectionProtectedConfiguration) as ProtectedConfigurationSection; - return config == null ? new ProtectedConfigurationProviderCollection() : config.GetAllProviders(); + return config is null ? new ProtectedConfigurationProviderCollection() : config.GetAllProviders(); } } @@ -29,7 +29,7 @@ public static string DefaultProvider PrivilegedConfigurationManager.GetSection( BaseConfigurationRecord.ReservedSectionProtectedConfiguration) as ProtectedConfigurationSection; - return config != null ? config.DefaultProvider : ""; + return config is not null ? config.DefaultProvider : ""; } } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs index 4c111c86800e51..53c33b1d8c79de 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs @@ -11,7 +11,7 @@ public class ProtectedConfigurationProviderCollection : ProviderCollection public override void Add(ProviderBase provider) { - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); if (!(provider is ProtectedConfigurationProvider)) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs index 1b2d903c0d8efd..41a6c6c68338d0 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs @@ -47,7 +47,7 @@ internal ProtectedConfigurationProvider GetProviderFromName(string providerName) { ProviderSettings ps = Providers[providerName]; - if (ps == null) + if (ps is null) throw new ArgumentException(SR.Format(SR.ProtectedConfigurationProvider_not_found, providerName), nameof(providerName)); return InstantiateProvider(ps); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderBase.cs index f4f9242fc05e22..693361a84ded5b 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderBase.cs @@ -25,13 +25,13 @@ public virtual void Initialize(string name, NameValueCollection config) _initialized = true; } - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Config_provider_name_null_or_empty, nameof(name)); _name = name; - if (config != null) + if (config is not null) { _description = config["description"]; config.Remove("description"); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderCollection.cs index 88a3b7feeeb67a..13a4e6ef44a655 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Provider/ProviderCollection.cs @@ -38,10 +38,10 @@ public virtual void Add(ProviderBase provider) if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); - if ((provider.Name == null) || (provider.Name.Length < 1)) + if ((provider.Name is null) || (provider.Name.Length < 1)) throw new ArgumentException(SR.Config_provider_name_null_or_empty); _hashtable.Add(provider.Name, provider); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs index 74b7449ec1469c..3388b057ad495d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs @@ -62,7 +62,7 @@ public NameValueCollection Parameters { get { - if (_propertyNameCollection != null) return _propertyNameCollection; + if (_propertyNameCollection is not null) return _propertyNameCollection; lock (this) { @@ -106,14 +106,14 @@ internal bool UpdatePropertyCollection() bool bIsModified = false; ArrayList removeList = null; - if (_propertyNameCollection != null) + if (_propertyNameCollection is not null) { // remove any data that has been delete from the collection foreach (ConfigurationProperty prop in _properties) if ((prop.Name != "name") && (prop.Name != "type")) { - if (_propertyNameCollection.Get(prop.Name) != null) continue; - if (removeList == null) + if (_propertyNameCollection.Get(prop.Name) is not null) continue; + if (removeList is null) removeList = new ArrayList(); if ((Values.GetConfigValue(prop.Name).ValueFlags & ConfigurationValueFlags.Locked) != 0) @@ -122,7 +122,7 @@ internal bool UpdatePropertyCollection() bIsModified = true; } - if (removeList != null) + if (removeList is not null) { foreach (string propName in removeList) _properties.Remove(propName); @@ -134,7 +134,7 @@ internal bool UpdatePropertyCollection() string valueInCollection = _propertyNameCollection[key]; string valueInBag = GetProperty(key); - if ((valueInBag == null) || (valueInCollection != valueInBag)) // add new property + if ((valueInBag is null) || (valueInCollection != valueInBag)) // add new property { SetProperty(key, valueInCollection); bIsModified = true; @@ -156,7 +156,7 @@ private string GetProperty(string propName) if (_properties.Contains(propName)) { ConfigurationProperty prop = _properties[propName]; - if (prop != null) + if (prop is not null) return (string)base[prop]; } return null; @@ -173,7 +173,7 @@ private void SetProperty(string propName, string value) _properties.Add(setPropName); } - if (setPropName == null) return; + if (setPropName is null) return; base[setPropName] = value; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettingsCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettingsCollection.cs index 8782e2bd07d0b3..0aa884f177e21d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettingsCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettingsCollection.cs @@ -21,7 +21,7 @@ public ProviderSettings this[int index] get { return (ProviderSettings)BaseGet(index); } set { - if (BaseGet(index) != null) + if (BaseGet(index) is not null) BaseRemoveAt(index); BaseAdd(index, value); @@ -30,7 +30,7 @@ public ProviderSettings this[int index] public void Add(ProviderSettings provider) { - if (provider != null) + if (provider is not null) { provider.UpdatePropertyCollection(); BaseAdd(provider); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RegexStringValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RegexStringValidator.cs index e5bf2a2d427c7f..0578582ad9223a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RegexStringValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RegexStringValidator.cs @@ -27,7 +27,7 @@ public override void Validate(object value) { ValidatorUtils.HelperParamValidation(value, typeof(string)); - if (value == null) return; + if (value is null) return; Match match = _regex.Match((string)value); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RsaProtectedConfigurationProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RsaProtectedConfigurationProvider.cs index 23577c74383f1d..bc9ac808acde3f 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RsaProtectedConfigurationProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RsaProtectedConfigurationProvider.cs @@ -182,7 +182,7 @@ public override void Initialize(string name, NameValueCollection configurationVa _keyName = "Rsa Key"; _keyContainerName = configurationValues["keyContainerName"]; configurationValues.Remove("keyContainerName"); - if (_keyContainerName == null || _keyContainerName.Length < 1) + if (_keyContainerName is null || _keyContainerName.Length < 1) _keyContainerName = DefaultRsaKeyContainerName; _cspProviderName = configurationValues["cspProviderName"]; @@ -205,7 +205,7 @@ private RSACryptoServiceProvider GetCryptoServiceProvider(bool exportable, bool csp.KeyNumber = 1; csp.ProviderType = 1; // Dev10 Bug #548719: Explicitly require "RSA Full (Signature and Key Exchange)" - if (CspProviderName != null && CspProviderName.Length > 0) + if (CspProviderName is not null && CspProviderName.Length > 0) csp.ProviderName = CspProviderName; if (UseMachineContainer) @@ -236,7 +236,7 @@ private byte[] GetRandomKey() private static bool GetBooleanValue(NameValueCollection configurationValues, string valueName, bool defaultValue) { string s = configurationValues[valueName]; - if (s == null) + if (s is null) return defaultValue; configurationValues.Remove(valueName); if (s == "true") diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs index 4df65174e3d6a5..0b50cd3d994518 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs @@ -59,7 +59,7 @@ protected override object GetRuntimeObject(object result) { object runtimeObject; ConfigurationSection section = result as ConfigurationSection; - if (section == null) runtimeObject = result; + if (section is null) runtimeObject = result; else { // Call into config section while impersonating process or UNC identity @@ -121,7 +121,7 @@ private void Init(RuntimeConfigurationRecord configRecord, FactoryRecord factory private static void CheckForLockAttributes(string sectionName, XmlNode xmlNode) { XmlAttributeCollection attributes = xmlNode.Attributes; - if (attributes != null) + if (attributes is not null) { foreach (XmlAttribute attribute in attributes) if (ConfigurationElement.IsLockAttributeName(attribute.Name)) @@ -140,7 +140,7 @@ internal object CreateSection(bool inputIsTrusted, RuntimeConfigurationRecord co { object config; - if (_sectionCtor != null) + if (_sectionCtor is not null) { ConfigurationSection configSection = (ConfigurationSection)_sectionCtor.Invoke(null); @@ -153,11 +153,11 @@ internal object CreateSection(bool inputIsTrusted, RuntimeConfigurationRecord co ConfigurationSection parentSection = (ConfigurationSection)parentConfig; configSection.Reset(parentSection); - if (reader != null) configSection.DeserializeSection(reader); + if (reader is not null) configSection.DeserializeSection(reader); // throw if there are any cached errors ConfigurationErrorsException errors = configSection.GetErrors(); - if (errors != null) throw errors; + if (errors is not null) throw errors; // don't allow changes to sections at runtime configSection.SetReadOnly(); @@ -169,7 +169,7 @@ internal object CreateSection(bool inputIsTrusted, RuntimeConfigurationRecord co } else { - if (reader != null) + if (reader is not null) { XmlNode xmlNode = ErrorInfoXmlDocument.CreateSectionXmlNode(reader); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SchemeSettingInternal.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SchemeSettingInternal.cs index 8dd6b30357ffc5..d6743e622105f9 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SchemeSettingInternal.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SchemeSettingInternal.cs @@ -12,7 +12,7 @@ internal sealed class SchemeSettingInternal public SchemeSettingInternal(string name, GenericUriParserOptions options) { - Debug.Assert(name != null, "'name' must not be null."); + Debug.Assert(name is not null, "'name' must not be null."); this.name = name.ToLowerInvariant(); this.options = options; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionInformation.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionInformation.cs index 4916e4188fcb11..137c979317ad12 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionInformation.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionInformation.cs @@ -65,7 +65,7 @@ internal SectionInformation(ConfigurationSection associatedConfigurationSection) } private bool IsRuntime => _flags[FlagAttached] && - (_configRecord == null); + (_configRecord is null); internal bool Attached => _flags[FlagAttached]; @@ -92,7 +92,7 @@ public ConfigurationAllowDefinition AllowDefinition // allow AllowDefinition to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && (factoryRecord.AllowDefinition != value)) + if ((factoryRecord is not null) && (factoryRecord.AllowDefinition != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _allowDefinition = value; @@ -113,7 +113,7 @@ public ConfigurationAllowExeDefinition AllowExeDefinition // allow AllowDefinition to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && (factoryRecord.AllowExeDefinition != value)) + if ((factoryRecord is not null) && (factoryRecord.AllowExeDefinition != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _allowExeDefinition = value; @@ -134,7 +134,7 @@ public OverrideMode OverrideModeDefault // allow OverrideModeDefault to be different from current value, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && (factoryRecord.OverrideModeDefault.OverrideMode != value)) + if ((factoryRecord is not null) && (factoryRecord.OverrideModeDefault.OverrideMode != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); // Threat "Inherit" as "Allow" as "Inherit" does not make sense as a default @@ -160,7 +160,7 @@ public bool AllowLocation // allow AllowLocation to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && (factoryRecord.AllowLocation != value)) + if ((factoryRecord is not null) && (factoryRecord.AllowLocation != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _flags[FlagAllowLocation] = value; @@ -290,18 +290,18 @@ public bool IsDeclarationRequired // on the Definition that is allowed, and what context we are // writing the file private bool IsDefinitionAllowed - => (_configRecord == null) || _configRecord.IsDefinitionAllowed(_allowDefinition, _allowExeDefinition); + => (_configRecord is null) || _configRecord.IsDefinitionAllowed(_allowDefinition, _allowExeDefinition); public bool IsLocked => _flags[FlagLocationLocked] || !IsDefinitionAllowed || _configurationSection.ElementInformation.IsLocked; - public bool IsProtected => ProtectionProvider != null; + public bool IsProtected => ProtectionProvider is not null; public ProtectedConfigurationProvider ProtectionProvider { get { - if (!_flags[FlagProtectionProviderDetermined] && (_configRecord != null)) + if (!_flags[FlagProtectionProviderDetermined] && (_configRecord is not null)) { _protectionProvider = _configRecord.GetProtectionProviderFromName(ProtectionProviderName, false); _flags[FlagProtectionProviderDetermined] = true; @@ -324,7 +324,7 @@ public bool RestartOnExternalChanges // allow RestartOnExternalChanges to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && (factoryRecord.RestartOnExternalChanges != value)) + if ((factoryRecord is not null) && (factoryRecord.RestartOnExternalChanges != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _flags[FlagRestartOnExternalChanges] = value; @@ -345,7 +345,7 @@ public bool RequirePermission // allow RequirePermission to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if ((factoryRecord != null) && (factoryRecord.RequirePermission != value)) + if ((factoryRecord is not null) && (factoryRecord.RequirePermission != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _flags[FlagRequirePermission] = value; @@ -369,10 +369,10 @@ public string Type // allow type to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); - if (factoryRecord != null) + if (factoryRecord is not null) { IInternalConfigHost host = null; - if (_configRecord != null) host = _configRecord.Host; + if (_configRecord is not null) host = _configRecord.Host; if (!factoryRecord.IsEquivalentType(host, value)) { @@ -443,7 +443,7 @@ internal void SetRuntimeConfigurationInformation(BaseConfigurationRecord configR else { _flags[FlagIsUndeclared] = false; - _flags[FlagDeclared] = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, false) != null; + _flags[FlagDeclared] = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, false) is not null; _flags[FlagDeclarationRequired] = configRecord.IsRootDeclaration(factoryRecord.ConfigKey, false); } @@ -491,7 +491,7 @@ private void VerifyDesigntime() private void VerifyIsAttachedToConfigRecord() { - if (_configRecord == null) + if (_configRecord is null) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_not_attached); } @@ -515,7 +515,7 @@ internal void VerifyIsEditable() throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_parentsection); if (!_flags[FlagAllowLocation] && - (_configRecord != null) && + (_configRecord is not null) && _configRecord.IsLocationConfig) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_location_locked); } @@ -530,14 +530,14 @@ private void VerifyNotParentSection() // in machine.config, or in any place for the web config system private void VerifySupportsLocation() { - if ((_configRecord != null) && + if ((_configRecord is not null) && !_configRecord.RecordSupportsLocation) throw new InvalidOperationException(SR.Config_cannot_edit_locationattriubtes); } internal void VerifyIsEditableFactory() { - if ((_configRecord != null) && _configRecord.IsLocationConfig) + if ((_configRecord is not null) && _configRecord.IsLocationConfig) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_in_location_config); // Can't edit factory if the section is built-in @@ -553,7 +553,7 @@ private FactoryRecord FindParentFactoryRecord(bool permitErrors) { FactoryRecord factoryRecord = null; - if ((_configRecord != null) && !_configRecord.Parent.IsRootConfig) + if ((_configRecord is not null) && !_configRecord.Parent.IsRootConfig) factoryRecord = _configRecord.Parent.FindFactoryRecord(ConfigKey, permitErrors); return factoryRecord; @@ -608,7 +608,7 @@ public void ProtectSection(string protectionProvider) if (!AllowLocation || (ConfigKey == BaseConfigurationRecord.ReservedSectionProtectedConfiguration)) throw new InvalidOperationException(SR.Config_not_allowed_to_encrypt_this_section); - if (_configRecord != null) + if (_configRecord is not null) { if (string.IsNullOrEmpty(protectionProvider)) protectionProvider = _configRecord.DefaultProviderName; @@ -643,10 +643,10 @@ public ConfigurationSection GetParentSection() // if a users create a configsection with : sectionType sec = new sectionType(); // the config record will be null. Return null for the parent in this case. ConfigurationSection ancestor = null; - if (_configRecord != null) + if (_configRecord is not null) { ancestor = _configRecord.FindAndCloneImmediateParentSection(_configurationSection); - if (ancestor != null) + if (ancestor is not null) { ancestor.SectionInformation._flags[FlagIsParentSection] = true; ancestor.SetReadOnly(); @@ -668,7 +668,7 @@ public void SetRawXml(string rawXml) { VerifyIsEditable(); - if (_configRecord != null) _configRecord.SetRawXml(_configurationSection, rawXml); + if (_configRecord is not null) _configRecord.SetRawXml(_configurationSection, rawXml); else RawXml = string.IsNullOrEmpty(rawXml) ? null : rawXml; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionRecord.cs index 744028a98b9dae..81d9ba4b2534c6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionRecord.cs @@ -103,18 +103,18 @@ internal bool AddUpdate set { _flags[FlagAddUpdate] = value; } } - internal bool HasLocationInputs => (LocationInputs != null) && (LocationInputs.Count > 0); + internal bool HasLocationInputs => (LocationInputs is not null) && (LocationInputs.Count > 0); internal List LocationInputs { get; private set; } internal SectionInput LastLocationInput => HasLocationInputs ? LocationInputs[LocationInputs.Count - 1] : null; - internal bool HasFileInput => FileInput != null; + internal bool HasFileInput => FileInput is not null; internal SectionInput FileInput { get; private set; } internal bool HasIndirectLocationInputs - => (IndirectLocationInputs != null) && (IndirectLocationInputs.Count > 0); + => (IndirectLocationInputs is not null) && (IndirectLocationInputs.Count > 0); internal List IndirectLocationInputs { get; private set; } @@ -165,7 +165,7 @@ internal void ChangeLockSettings(OverrideMode forSelf, OverrideMode forChildren) // AddFileInput internal void AddFileInput(SectionInput sectionInput) { - Debug.Assert(sectionInput != null); + Debug.Assert(sectionInput is not null); FileInput = sectionInput; @@ -188,7 +188,7 @@ internal void AddFileInput(SectionInput sectionInput) internal void RemoveFileInput() { - if (FileInput != null) + if (FileInput is not null) { FileInput = null; @@ -215,7 +215,7 @@ private void ? FlagIndirectLocationInputLockApplied : FlagLocationInputLockApplied; - if (inputs == null) + if (inputs is null) { inputs = new List(1); @@ -265,7 +265,7 @@ internal void ClearResult() { FileInput?.ClearResult(); - if (LocationInputs != null) foreach (SectionInput input in LocationInputs) input.ClearResult(); + if (LocationInputs is not null) foreach (SectionInput input in LocationInputs) input.ClearResult(); Result = s_unevaluated; ResultRuntimeObject = s_unevaluated; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs index 7dde1e555e2ff3..a206433e0c0b9c 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs @@ -43,7 +43,7 @@ private SectionUpdates FindSectionUpdates(string configKey, bool isGroup) foreach (string groupPart in groups) { SectionUpdates sectionUpdatesChild = (SectionUpdates)sectionUpdates._groups[groupPart]; - if (sectionUpdatesChild == null) + if (sectionUpdatesChild is null) { sectionUpdatesChild = new SectionUpdates(groupPart); sectionUpdates._groups[groupPart] = sectionUpdatesChild; @@ -91,7 +91,7 @@ internal void AddSectionGroup(Update update) private Update GetUpdate(string configKey) { Update update = (Update)_sections[configKey]; - if (update != null) + if (update is not null) { if (update.Retrieved) update = null; else @@ -107,7 +107,7 @@ private Update GetUpdate(string configKey) internal DeclarationUpdate GetSectionGroupUpdate() { - if ((_sectionGroupUpdate != null) && !_sectionGroupUpdate.Retrieved) + if ((_sectionGroupUpdate is not null) && !_sectionGroupUpdate.Retrieved) { _sectionGroupUpdate.Retrieved = true; return (DeclarationUpdate)_sectionGroupUpdate; @@ -134,7 +134,7 @@ internal SectionUpdates GetSectionUpdatesForGroup(string group) // Return true if this section group or any of its children have unretrieved sections. internal bool HasUnretrievedSections() { - if ((_cUnretrieved > 0) || ((_sectionGroupUpdate != null) && !_sectionGroupUpdate.Retrieved)) return true; + if ((_cUnretrieved > 0) || ((_sectionGroupUpdate is not null) && !_sectionGroupUpdate.Retrieved)) return true; foreach (SectionUpdates sectionUpdates in _groups.Values) if (sectionUpdates.HasUnretrievedSections()) return true; @@ -146,7 +146,7 @@ internal void MarkAsRetrieved() { _cUnretrieved = 0; foreach (SectionUpdates sectionUpdates in _groups.Values) sectionUpdates.MarkAsRetrieved(); - if (_sectionGroupUpdate != null) _sectionGroupUpdate.Retrieved = true; + if (_sectionGroupUpdate is not null) _sectionGroupUpdate.Retrieved = true; } internal void MarkGroupAsRetrieved(string groupName) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingElement.cs index d3f3f30bc79a0b..5199ec91f86c89 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingElement.cs @@ -45,7 +45,7 @@ internal string Key public override bool Equals(object settings) { SettingElement element = settings as SettingElement; - return (element != null && base.Equals(settings) && Equals(element.Value, Value)); + return (element is not null && base.Equals(settings) && Equals(element.Value, Value)); } public override int GetHashCode() diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs index 2042139f754127..52b5947699e9c3 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs @@ -17,7 +17,7 @@ protected internal override ConfigurationPropertyCollection Properties { get { - if (_properties == null) + if (_properties is null) { _properties = new ConfigurationPropertyCollection(); } @@ -47,7 +47,7 @@ protected internal override void DeserializeElement(XmlReader reader, bool seria public override bool Equals(object settingValue) { SettingValueElement u = settingValue as SettingValueElement; - return (u != null && Equals(u.ValueXml, ValueXml)); + return (u is not null && Equals(u.ValueXml, ValueXml)); } public override int GetHashCode() @@ -67,9 +67,9 @@ protected internal override void ResetModified() protected internal override bool SerializeToXmlElement(XmlWriter writer, string elementName) { - if (ValueXml != null) + if (ValueXml is not null) { - if (writer != null) + if (writer is not null) { ValueXml?.WriteTo(writer); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsBase.cs index 34d7f257e5aaf5..3d2e7701e16ded 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsBase.cs @@ -52,17 +52,17 @@ public virtual object this[string propertyName] private object GetPropertyValueByName(string propertyName) { - if (Properties == null || _propertyValues == null || Properties.Count == 0) + if (Properties is null || _propertyValues is null || Properties.Count == 0) throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName)); SettingsProperty pp = Properties[propertyName]; - if (pp == null) + if (pp is null) throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName)); SettingsPropertyValue p = _propertyValues[propertyName]; - if (p == null) + if (p is null) { GetPropertiesFromProvider(pp.Provider); p = _propertyValues[propertyName]; - if (p == null) + if (p is null) throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName)); } return p.PropertyValue; @@ -70,25 +70,25 @@ private object GetPropertyValueByName(string propertyName) private void SetPropertyValueByName(string propertyName, object propertyValue) { - if (Properties == null || _propertyValues == null || Properties.Count == 0) + if (Properties is null || _propertyValues is null || Properties.Count == 0) throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName)); SettingsProperty pp = Properties[propertyName]; - if (pp == null) + if (pp is null) throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName)); if (pp.IsReadOnly) throw new SettingsPropertyIsReadOnlyException(SR.Format(SR.SettingsPropertyReadOnly, propertyName)); - if (propertyValue != null && !pp.PropertyType.IsInstanceOfType(propertyValue)) + if (propertyValue is not null && !pp.PropertyType.IsInstanceOfType(propertyValue)) throw new SettingsPropertyWrongTypeException(SR.Format(SR.SettingsPropertyWrongType, propertyName)); SettingsPropertyValue p = _propertyValues[propertyName]; - if (p == null) + if (p is null) { GetPropertiesFromProvider(pp.Provider); p = _propertyValues[propertyName]; - if (p == null) + if (p is null) throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName)); } @@ -122,7 +122,7 @@ public virtual void Save() private void SaveCore() { - if (Properties == null || _propertyValues == null || Properties.Count == 0) + if (Properties is null || _propertyValues is null || Properties.Count == 0) return; foreach (SettingsProvider prov in Providers) @@ -165,7 +165,7 @@ private void GetPropertiesFromProvider(SettingsProvider provider) SettingsPropertyValueCollection ppcv = provider.GetPropertyValues(Context, ppc); foreach (SettingsPropertyValue p in ppcv) { - if (_propertyValues[p.Name] == null) + if (_propertyValues[p.Name] is null) _propertyValues.Add(p); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyCollection.cs index e662c9646536c7..06dc1222b8d734 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyCollection.cs @@ -38,7 +38,7 @@ public void Remove(string name) if (_readOnly) throw new NotSupportedException(); SettingsProperty toRemove = (SettingsProperty)_hashtable[name]; - if (toRemove == null) + if (toRemove is null) return; OnRemove(toRemove); _hashtable.Remove(name); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs index 12849c5e9258fe..bc02e7565c66d8 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs @@ -38,7 +38,7 @@ public object PropertyValue Deserialized = true; } - if (_value != null && !Property.PropertyType.IsPrimitive && !(_value is string) && !(_value is DateTime)) + if (_value is not null && !Property.PropertyType.IsPrimitive && !(_value is string) && !(_value is DateTime)) { UsingDefaultValue = false; _changedSinceLastSerialized = true; @@ -78,7 +78,7 @@ public object SerializedValue private bool IsHostedInAspnet() { // See System.Web.Hosting.ApplicationManager::PopulateDomainBindings - return AppDomain.CurrentDomain.GetData(".appDomain") != null; + return AppDomain.CurrentDomain.GetData(".appDomain") is not null; } private object Deserialize() @@ -86,7 +86,7 @@ private object Deserialize() object value = null; // Attempt 1: Try creating from SerializedValue - if (SerializedValue != null) + if (SerializedValue is not null) { try { @@ -124,15 +124,15 @@ private object Deserialize() } } - if (value != null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type + if (value is not null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type value = null; } // Attempt 2: Try creating from default value - if (value == null) + if (value is null) { UsingDefaultValue = true; - if (Property.DefaultValue == null || Property.DefaultValue.ToString() == "[null]") + if (Property.DefaultValue is null || Property.DefaultValue.ToString() == "[null]") { if (Property.PropertyType.IsValueType) return TypeUtil.CreateInstance(Property.PropertyType); @@ -155,12 +155,12 @@ private object Deserialize() } } - if (value != null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type + if (value is not null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type throw new ArgumentException(SR.Format(SR.Could_not_create_from_default_value_2, Property.Name)); } // Attempt 3: Create via the parameterless constructor - if (value == null) + if (value is null) { if (Property.PropertyType == typeof(string)) { @@ -182,11 +182,11 @@ private object Deserialize() private static object GetObjectFromString(Type type, SettingsSerializeAs serializeAs, string serializedValue) { // Deal with string types - if (type == typeof(string) && (serializedValue == null || serializedValue.Length < 1 || serializeAs == SettingsSerializeAs.String)) + if (type == typeof(string) && (serializedValue is null || serializedValue.Length < 1 || serializeAs == SettingsSerializeAs.String)) return serializedValue; // Return null if there is nothing to convert - if (serializedValue == null || serializedValue.Length < 1) + if (serializedValue is null || serializedValue.Length < 1) return null; // Convert based on the serialized type @@ -205,7 +205,7 @@ private static object GetObjectFromString(Type type, SettingsSerializeAs seriali return xs.Deserialize(sr); case SettingsSerializeAs.String: TypeConverter converter = TypeDescriptor.GetConverter(type); - if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) + if (converter is not null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) return converter.ConvertFromInvariantString(serializedValue); throw new ArgumentException(SR.Format(SR.Unable_to_convert_type_from_string, type), nameof(type)); default: @@ -215,7 +215,7 @@ private static object GetObjectFromString(Type type, SettingsSerializeAs seriali private object SerializePropertyValue() { - if (_value == null) + if (_value is null) return null; if (Property.SerializeAs != SettingsSerializeAs.Binary) @@ -246,7 +246,7 @@ private static string ConvertObjectToString(object propertyValue, Type type, Set { case SettingsSerializeAs.String: TypeConverter converter = TypeDescriptor.GetConverter(type); - if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) + if (converter is not null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) return converter.ConvertToInvariantString(propertyValue); throw new ArgumentException(SR.Format(SR.Unable_to_convert_type_to_string, type), nameof(type)); case SettingsSerializeAs.Xml: diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs index 3563b1628c17ed..34c373bbcb2350 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs @@ -42,7 +42,7 @@ public void Remove(string name) object pos = _indices[name]; - if (pos == null || !(pos is int)) + if (pos is null || !(pos is int)) return; int ipos = (int)pos; @@ -69,7 +69,7 @@ public SettingsPropertyValue this[string name] { object pos = _indices[name]; - if (pos == null || !(pos is int)) + if (pos is null || !(pos is int)) return null; int ipos = (int)pos; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderAttribute.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderAttribute.cs index 146949f5bb40fc..af8a745958fc56 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderAttribute.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderAttribute.cs @@ -24,7 +24,7 @@ public SettingsProviderAttribute(string providerTypeName) /// public SettingsProviderAttribute(Type providerType) { - if (providerType != null) + if (providerType is not null) { _providerTypeName = providerType.AssemblyQualifiedName; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs index 23fb407e92fb0f..9cdf0d00fce722 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs @@ -9,7 +9,7 @@ public class SettingsProviderCollection : ProviderCollection { public override void Add(ProviderBase provider) { - if (provider == null) + if (provider is null) { throw new ArgumentNullException(nameof(provider)); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SingleTagSectionHandler.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SingleTagSectionHandler.cs index e5148260ec50fc..349e00c06ab62c 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SingleTagSectionHandler.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SingleTagSectionHandler.cs @@ -26,7 +26,7 @@ public virtual object Create(object parent, object context, XmlNode section) // start result off as a shallow clone of the parent - if (parent == null) + if (parent is null) result = new Hashtable(); else result = new Hashtable((IDictionary)parent); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringAttributeCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringAttributeCollection.cs index b91713cc7ad18f..2cee158c0415ab 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringAttributeCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringAttributeCollection.cs @@ -37,7 +37,7 @@ public CommaDelimitedStringCollection() internal void FromString(string list) { char[] delimiters = { ',' }; - if (list != null) + if (list is not null) { string[] items = list.Split(delimiters); foreach (string item in items) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringUtil.cs index 5bb89677b6c3be..299f0cb66ebc9d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/StringUtil.cs @@ -17,13 +17,13 @@ internal static bool EqualsIgnoreCase(string s1, string s2) internal static bool StartsWithOrdinal(string s1, string s2) { - if (s2 == null) return false; + if (s2 is null) return false; return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.Ordinal); } internal static bool StartsWithOrdinalIgnoreCase(string s1, string s2) { - if (s2 == null) return false; + if (s2 is null) return false; return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs index 6fcde53396b382..a466d566ba581c 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs @@ -10,7 +10,7 @@ public sealed class SubclassTypeValidator : ConfigurationValidatorBase public SubclassTypeValidator(Type baseClass) { - if (baseClass == null) + if (baseClass is null) throw new ArgumentNullException(nameof(baseClass)); _base = baseClass; @@ -23,7 +23,7 @@ public override bool CanValidate(Type type) public override void Validate(object value) { - if (value == null) return; + if (value is null) return; // Make a check here since value.GetType() returns RuntimeType rather then Type if (!(value is Type)) ValidatorUtils.HelperParamValidation(value, typeof(Type)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs index d9576ba0ef3573..0a12aded2897e5 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs @@ -15,7 +15,7 @@ public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, obj string result = null; - if (value != null) result = ((Type)value).AssemblyQualifiedName; + if (value is not null) result = ((Type)value).AssemblyQualifiedName; return result; } @@ -24,7 +24,7 @@ public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, o { Type result = TypeUtil.GetType((string)data, false); - if (result == null) throw new ArgumentException(SR.Format(SR.Type_cannot_be_resolved, (string)data)); + if (result is null) throw new ArgumentException(SR.Format(SR.Type_cannot_be_resolved, (string)data)); return result; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs index 91a6ce26e950d4..f173b419d89899 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs @@ -61,7 +61,7 @@ private static Type GetImplicitType(string typeString) { Assembly configurationAssembly = typeof(ConfigurationException).Assembly; Type type = configurationAssembly.GetType(typeString, false); - if (type != null) + if (type is not null) return type; } catch { } @@ -71,7 +71,7 @@ private static Type GetImplicitType(string typeString) try { Type type = Type.GetType($"{typeString}, {assembly}"); - if (type != null) + if (type is not null) return type; } catch { } @@ -94,13 +94,13 @@ internal static Type GetType(string typeString, bool throwOnError) catch { type = GetImplicitType(typeString); - if (type == null) + if (type is null) { throw; } } - if (type == null) + if (type is null) { type = GetImplicitType(typeString); } @@ -121,13 +121,13 @@ internal static Type GetType(IInternalConfigHost host, string typeString, bool t catch { type = GetImplicitType(typeString); - if (type == null) + if (type is null) { throw; } } - if (type == null) + if (type is null) { type = GetImplicitType(typeString); } @@ -150,14 +150,14 @@ internal static object CreateInstance(Type type) internal static ConstructorInfo GetConstructor(Type type, Type baseType, bool throwOnError) { type = VerifyAssignableType(baseType, type, throwOnError); - if (type == null) + if (type is null) return null; const BindingFlags BindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; ConstructorInfo ctor = type.GetConstructor(BindingFlags, null, CallingConventions.HasThis, Type.EmptyTypes, null); - if ((ctor == null) && throwOnError) + if ((ctor is null) && throwOnError) throw new TypeLoadException(SR.Format(SR.TypeNotPublic, type.AssemblyQualifiedName)); return ctor; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs index 6655e464999a61..e3aebe00b928c2 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs @@ -36,7 +36,7 @@ internal void AddStreamname(string oldStreamname, string newStreamname, bool alw if (!alwaysIntercept && StringUtil.EqualsIgnoreCase(oldStreamname, newStreamname)) return; - if (_streams == null) _streams = new HybridDictionary(true); + if (_streams is null) _streams = new HybridDictionary(true); _streams[oldStreamname] = new StreamUpdate(newStreamname); } @@ -46,7 +46,7 @@ internal void AddStreamname(string oldStreamname, string newStreamname, bool alw internal string GetNewStreamname(string oldStreamname) { StreamUpdate streamUpdate = GetStreamUpdate(oldStreamname, false); - return streamUpdate != null ? streamUpdate.NewStreamname : oldStreamname; + return streamUpdate is not null ? streamUpdate.NewStreamname : oldStreamname; } // Get the StreamUpdate for a stream. @@ -56,11 +56,11 @@ internal string GetNewStreamname(string oldStreamname) // if the new stream has been successfully written to. private StreamUpdate GetStreamUpdate(string oldStreamname, bool alwaysIntercept) { - if (_streams == null) + if (_streams is null) return null; StreamUpdate streamUpdate = (StreamUpdate)_streams[oldStreamname]; - if ((streamUpdate != null) && !alwaysIntercept && !streamUpdate.WriteCompleted) streamUpdate = null; + if ((streamUpdate is not null) && !alwaysIntercept && !streamUpdate.WriteCompleted) streamUpdate = null; return streamUpdate; } @@ -68,7 +68,7 @@ private StreamUpdate GetStreamUpdate(string oldStreamname, bool alwaysIntercept) public override object GetStreamVersion(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); - return streamUpdate != null + return streamUpdate is not null ? InternalConfigHost.StaticGetStreamVersion(streamUpdate.NewStreamname) : Host.GetStreamVersion(streamName); } @@ -76,7 +76,7 @@ public override object GetStreamVersion(string streamName) public override Stream OpenStreamForRead(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); - return streamUpdate != null + return streamUpdate is not null ? InternalConfigHost.StaticOpenStreamForRead(streamUpdate.NewStreamname) : Host.OpenStreamForRead(streamName); } @@ -85,7 +85,7 @@ public override Stream OpenStreamForWrite(string streamName, string templateStre { // Always attempt to write to the new stream name if it exists. StreamUpdate streamUpdate = GetStreamUpdate(streamName, true); - if (streamUpdate != null) + if (streamUpdate is not null) { return InternalConfigHost.StaticOpenStreamForWrite( streamUpdate.NewStreamname, templateStreamName, ref writeContext); @@ -96,7 +96,7 @@ public override Stream OpenStreamForWrite(string streamName, string templateStre public override void WriteCompleted(string streamName, bool success, object writeContext) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, true); - if (streamUpdate != null) + if (streamUpdate is not null) { InternalConfigHost.StaticWriteCompleted(streamUpdate.NewStreamname, success, writeContext); @@ -118,14 +118,14 @@ public override bool IsConfigRecordRequired(string configPath) public override void DeleteStream(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); - if (streamUpdate != null) InternalConfigHost.StaticDeleteStream(streamUpdate.NewStreamname); + if (streamUpdate is not null) InternalConfigHost.StaticDeleteStream(streamUpdate.NewStreamname); else Host.DeleteStream(streamName); } public override bool IsFile(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); - return streamUpdate != null + return streamUpdate is not null ? InternalConfigHost.StaticIsFile(streamUpdate.NewStreamname) : Host.IsFile(streamName); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UrlPath.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UrlPath.cs index 7fe4fc2d359777..3644d562dd1ff6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UrlPath.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UrlPath.cs @@ -98,7 +98,7 @@ private static bool IsDirectorySeparatorChar(char ch) private static bool IsAbsoluteLocalPhysicalPath(string path) { - if ((path == null) || (path.Length < 3)) + if ((path is null) || (path.Length < 3)) return false; // e.g c:\foo @@ -107,7 +107,7 @@ private static bool IsAbsoluteLocalPhysicalPath(string path) private static bool IsAbsoluteUncPhysicalPath(string path) { - if ((path == null) || (path.Length < 3)) + if ((path is null) || (path.Length < 3)) return false; // e.g \\server\share\foo or //server/share/foo diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ValidatorUtils.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ValidatorUtils.cs index 3c9ea058b5c945..74bde36d317904 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ValidatorUtils.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ValidatorUtils.cs @@ -10,7 +10,7 @@ internal static class ValidatorUtils { public static void HelperParamValidation(object value, Type allowedType) { - if (value == null) return; + if (value is null) return; if (value.GetType() != allowedType) throw new ArgumentException(SR.Validator_value_type_invalid, string.Empty); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/WhiteSpaceTrimStringConverter.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/WhiteSpaceTrimStringConverter.cs index d48b3116473d2d..e8e397bb5ada5a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/WhiteSpaceTrimStringConverter.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/WhiteSpaceTrimStringConverter.cs @@ -12,7 +12,7 @@ public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, obj { ValidateType(value, typeof(string)); - return value == null ? string.Empty : ((string)value).Trim(); + return value is null ? string.Empty : ((string)value).Trim(); } public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs index 2e083fc15685bb..0101096d3fe67a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs @@ -131,7 +131,7 @@ private static int GetPositionOffset(XmlNodeType nodeType) private void ReleaseResources() { - if (Reader != null) + if (Reader is not null) { // closing _reader will also close underlying _stream Reader.Close(); @@ -142,7 +142,7 @@ private void ReleaseResources() _stream = null; - if (_cachedStringWriter != null) + if (_cachedStringWriter is not null) { _cachedStringWriter.Close(); _cachedStringWriter = null; @@ -256,7 +256,7 @@ internal void VerifyNoUnrecognizedAttributes(ExceptionAction action) /// internal bool VerifyRequiredAttribute(object requiredAttribute, string attrName, ExceptionAction action) { - if (requiredAttribute == null) + if (requiredAttribute is null) { AddErrorRequiredAttribute(attrName, action); return false; @@ -792,7 +792,7 @@ internal bool CopyXmlNode(XmlUtilWriter utilWriter) nodeType = Reader.NodeType; // Close the node we are copying. - if (close != null) + if (close is not null) { // Find the position of the close string, for example: // @@ -873,12 +873,12 @@ internal string UpdateStartElement(XmlUtilWriter utilWriter, string updatedStart // If the element is empty, determine if a new end element is needed. if (Reader.IsEmptyElement) { - if ((updatedStartElement == null) && needsChildren) updatedStartElement = RetrieveFullOpenElementTag(); + if ((updatedStartElement is null) && needsChildren) updatedStartElement = RetrieveFullOpenElementTag(); - needsEndElement = updatedStartElement != null; + needsEndElement = updatedStartElement is not null; } - if (updatedStartElement == null) + if (updatedStartElement is null) { // If no changes to the start element are required, just copy it. CopyXmlNode(utilWriter); @@ -920,7 +920,7 @@ internal string UpdateStartElement(XmlUtilWriter utilWriter, string updatedStart // otherwise reuse the existing buffer. private void ResetCachedStringWriter() { - if (_cachedStringWriter == null) + if (_cachedStringWriter is null) _cachedStringWriter = new StringWriter(new StringBuilder(64), CultureInfo.InvariantCulture); else _cachedStringWriter.GetStringBuilder().Length = 0; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs index 161e6336a2d997..e35ba6d849bd9d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs @@ -158,7 +158,7 @@ internal int AppendEscapeXmlString(string s, bool inAttribute, char quoteChar) if (appendCharEntity) charactersWritten += AppendCharEntity(ch); else { - if (entityRef != null) charactersWritten += AppendEntityRef(entityRef); + if (entityRef is not null) charactersWritten += AppendEntityRef(entityRef); else charactersWritten += Write(ch); } } diff --git a/src/libraries/System.Console/src/System/Console.cs b/src/libraries/System.Console/src/System/Console.cs index 642c48b468784d..586301647bd48b 100644 --- a/src/libraries/System.Console/src/System/Console.cs +++ b/src/libraries/System.Console/src/System/Console.cs @@ -47,7 +47,7 @@ static TextReader EnsureInitialized() lock (s_syncObject) // Ensures In and InputEncoding are synchronized. { - if (s_in == null) + if (s_in is null) { Volatile.Write(ref s_in, ConsolePal.GetOrCreateReader()); } @@ -63,11 +63,11 @@ public static Encoding InputEncoding get { Encoding? encoding = Volatile.Read(ref s_inputEncoding); - if (encoding == null) + if (encoding is null) { lock (s_syncObject) { - if (s_inputEncoding == null) + if (s_inputEncoding is null) { Volatile.Write(ref s_inputEncoding, ConsolePal.InputEncoding); } @@ -100,11 +100,11 @@ public static Encoding OutputEncoding get { Encoding? encoding = Volatile.Read(ref s_outputEncoding); - if (encoding == null) + if (encoding is null) { lock (s_syncObject) { - if (s_outputEncoding == null) + if (s_outputEncoding is null) { Volatile.Write(ref s_outputEncoding, ConsolePal.OutputEncoding); } @@ -125,12 +125,12 @@ public static Encoding OutputEncoding // Before changing the code page we need to flush the data // if Out hasn't been redirected. Also, have the next call to // s_out reinitialize the console code page. - if (s_out != null && !s_isOutTextWriterRedirected) + if (s_out is not null && !s_isOutTextWriterRedirected) { s_out.Flush(); Volatile.Write(ref s_out, null!); } - if (s_error != null && !s_isErrorTextWriterRedirected) + if (s_error is not null && !s_isErrorTextWriterRedirected) { s_error.Flush(); Volatile.Write(ref s_error, null!); @@ -185,7 +185,7 @@ static TextWriter EnsureInitialized() { lock (s_syncObject) // Ensures Out and OutputEncoding are synchronized. { - if (s_out == null) + if (s_out is null) { Volatile.Write(ref s_out, CreateOutputWriter(OpenStandardOutput())); } @@ -205,7 +205,7 @@ static TextWriter EnsureInitialized() { lock (s_syncObject) // Ensures Error and OutputEncoding are synchronized. { - if (s_error == null) + if (s_error is null) { Volatile.Write(ref s_error, CreateOutputWriter(OpenStandardError())); } @@ -494,7 +494,7 @@ public static event ConsoleCancelEventHandler? CancelKeyPress s_cancelCallbacks += value; // If we haven't registered our control-C handler, do it. - if (s_registrar == null) + if (s_registrar is null) { s_registrar = new ConsolePal.ControlCHandlerRegistrar(); s_registrar.Register(); @@ -506,7 +506,7 @@ public static event ConsoleCancelEventHandler? CancelKeyPress lock (s_syncObject) { s_cancelCallbacks -= value; - if (s_registrar != null && s_cancelCallbacks == null) + if (s_registrar is not null && s_cancelCallbacks is null) { s_registrar.Unregister(); s_registrar = null; @@ -604,7 +604,7 @@ public static void SetError(TextWriter newError) private static void CheckNonNull(object obj, string paramName) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(paramName); } @@ -736,7 +736,7 @@ public static void WriteLine(string format, object? arg0, object? arg1, object? [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(string format, params object?[]? arg) { - if (arg == null) // avoid ArgumentNullException from String.Format + if (arg is null) // avoid ArgumentNullException from String.Format Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg); else Out.WriteLine(format, arg); @@ -763,7 +763,7 @@ public static void Write(string format, object? arg0, object? arg1, object? arg2 [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(string format, params object?[]? arg) { - if (arg == null) // avoid ArgumentNullException from String.Format + if (arg is null) // avoid ArgumentNullException from String.Format Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg); else Out.Write(format, arg); @@ -852,7 +852,7 @@ public static void Write(string? value) internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey) { ConsoleCancelEventHandler? handler = s_cancelCallbacks; - if (handler == null) + if (handler is null) { return false; } diff --git a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs index fd011d10beaed3..4e118276d60e8f 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs @@ -268,7 +268,7 @@ private static void SetCachedCursorPosition(int left, int top, int? version = nu { Debug.Assert(left >= 0); - bool setPosition = version == null || version == s_cursorVersion; + bool setPosition = version is null || version == s_cursorVersion; if (setPosition) { @@ -725,7 +725,7 @@ public static bool IsErrorRedirectedCore() private static Encoding GetConsoleEncoding() { Encoding? enc = EncodingHelper.GetEncodingFromCharset(); - return enc != null ? + return enc is not null ? enc.RemovePreamble() : new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); } @@ -789,7 +789,7 @@ private static void WriteSetColorString(bool foreground, ConsoleColor color) int fgbgIndex = foreground ? 0 : 1; int ccValue = (int)color; string evaluatedString = s_fgbgAndColorStrings[fgbgIndex, ccValue]; // benign race - if (evaluatedString != null) + if (evaluatedString is not null) { WriteStdoutAnsiString(evaluatedString); return; @@ -947,7 +947,7 @@ private static void EnsureInitializedCore() if (!Console.IsOutputRedirected) { string? keypadXmit = TerminalFormatStrings.Instance.KeypadXmit; - if (keypadXmit != null) + if (keypadXmit is not null) { Interop.Sys.SetKeypadXmit(keypadXmit); } @@ -1034,7 +1034,7 @@ internal class TerminalFormatStrings public TerminalFormatStrings(TermInfo.Database? db) { - if (db == null) + if (db is null) return; KeypadXmit = db.GetString(TermInfo.WellKnownStrings.KeypadXmit); @@ -1147,13 +1147,13 @@ private static string GetTitle(TermInfo.Database db) // Try to get the format string from tsl/fsl and use it if they're available string? tsl = db.GetString(TermInfo.WellKnownStrings.ToStatusLine); string? fsl = db.GetString(TermInfo.WellKnownStrings.FromStatusLine); - if (tsl != null && fsl != null) + if (tsl is not null && fsl is not null) { return tsl + "%p1%s" + fsl; } string term = db.Term; - if (term == null) + if (term is null) { return string.Empty; } @@ -1410,7 +1410,7 @@ private sealed class UnixConsoleStream : ConsoleStream internal UnixConsoleStream(SafeFileHandle handle, FileAccess access, bool useReadLine = false) : base(access) { - Debug.Assert(handle != null, "Expected non-null console handle"); + Debug.Assert(handle is not null, "Expected non-null console handle"); Debug.Assert(!handle.IsInvalid, "Expected valid console handle"); _handle = handle; _useReadLine = useReadLine; @@ -1489,7 +1489,7 @@ private static void OnBreakEvent(Interop.Sys.CtrlCode ctrlCode) private static void HandleBreakEvent(object? state) { - Debug.Assert(state != null); + Debug.Assert(state is not null); var ctrlCode = (Interop.Sys.CtrlCode)state; ConsoleSpecialKey controlKey = (ctrlCode == Interop.Sys.CtrlCode.Break ? ConsoleSpecialKey.ControlBreak : ConsoleSpecialKey.ControlC); bool cancel = Console.HandleBreakEvent(controlKey); diff --git a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs index 513e281eac7529..e4a944227c990e 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs @@ -1146,7 +1146,7 @@ private static unsafe int ReadFileNative(IntPtr hFile, byte[] bytes, int offset, { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); - Debug.Assert(bytes != null, "bytes != null"); + Debug.Assert(bytes is not null, "bytes is not null"); // Don't corrupt memory when multiple threads are erroneously writing // to this stream simultaneously. if (bytes.Length - offset < count) @@ -1190,7 +1190,7 @@ private static unsafe int WriteFileNative(IntPtr hFile, byte[] bytes, int offset { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); - Debug.Assert(bytes != null, "bytes != null"); + Debug.Assert(bytes is not null, "bytes is not null"); Debug.Assert(bytes.Length >= offset + count, "bytes.Length >= offset + count"); // You can't use the fixed statement on an array of length 0. diff --git a/src/libraries/System.Console/src/System/IO/ConsoleStream.cs b/src/libraries/System.Console/src/System/IO/ConsoleStream.cs index 7b82be220b1d51..adcd89845de681 100644 --- a/src/libraries/System.Console/src/System/IO/ConsoleStream.cs +++ b/src/libraries/System.Console/src/System/IO/ConsoleStream.cs @@ -71,7 +71,7 @@ public sealed override long Seek(long offset, SeekOrigin origin) protected void ValidateRead(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(offset < 0 ? nameof(offset) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -83,7 +83,7 @@ protected void ValidateRead(byte[] buffer, int offset, int count) protected void ValidateWrite(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(offset < 0 ? nameof(offset) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Console/src/System/IO/StdInReader.cs b/src/libraries/System.Console/src/System/IO/StdInReader.cs index 8b0cd2021ecfe9..dbc69df6614617 100644 --- a/src/libraries/System.Console/src/System/IO/StdInReader.cs +++ b/src/libraries/System.Console/src/System/IO/StdInReader.cs @@ -187,7 +187,7 @@ private bool ReadLineCore(bool consumeKeys) if (ConsolePal.TryGetCursorPosition(out int left, out int top, reinitializeForRead: true) && left == 0 && top > 0) { - if (s_clearToEol == null) + if (s_clearToEol is null) { s_clearToEol = ConsolePal.TerminalFormatStrings.Instance.ClrEol ?? string.Empty; } @@ -199,7 +199,7 @@ private bool ReadLineCore(bool consumeKeys) } else { - if (s_moveLeftString == null) + if (s_moveLeftString is null) { string? moveLeft = ConsolePal.TerminalFormatStrings.Instance.CursorLeft; s_moveLeftString = !string.IsNullOrEmpty(moveLeft) ? moveLeft + " " + moveLeft : string.Empty; diff --git a/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs b/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs index 9e68d74c1b0023..b5bf72bb72bd4f 100644 --- a/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs +++ b/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs @@ -15,7 +15,7 @@ internal StdInReader Inner get { var inner = _in as StdInReader; - Debug.Assert(inner != null); + Debug.Assert(inner is not null); return inner; } } diff --git a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs index 7a2661691e6247..606d85eafe57ea 100644 --- a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs +++ b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs @@ -16,7 +16,7 @@ internal sealed partial class SyncTextReader : TextReader public static SyncTextReader GetSynchronizedTextReader(TextReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); return reader as SyncTextReader ?? new SyncTextReader(reader); } @@ -102,7 +102,7 @@ public override Task ReadToEndAsync() public override Task ReadBlockAsync(char[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -114,7 +114,7 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) public override Task ReadAsync(char[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Console/src/System/TermInfo.cs b/src/libraries/System.Console/src/System/TermInfo.cs index 1b0b41de98ece1..0caf2ecdc0f30d 100644 --- a/src/libraries/System.Console/src/System/TermInfo.cs +++ b/src/libraries/System.Console/src/System/TermInfo.cs @@ -190,14 +190,14 @@ private Database(string term, byte[] data) // First try a location specified in the TERMINFO environment variable. string? terminfo = Environment.GetEnvironmentVariable("TERMINFO"); - if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null) + if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) is not null) { return db; } // Then try in the user's home directory. string? home = PersistedFiles.GetHomeDirectory(); - if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null) + if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) is not null) { return db; } @@ -205,7 +205,7 @@ private Database(string term, byte[] data) // Then try a set of well-known locations. foreach (string terminfoLocation in _terminfoLocations) { - if ((db = ReadDatabase(term, terminfoLocation)) != null) + if ((db = ReadDatabase(term, terminfoLocation)) is not null) { return db; } @@ -323,7 +323,7 @@ private static bool TryOpen(string filePath, [NotNullWhen(true)] out SafeFileHan /// The string if it's in the database; otherwise, null. public string? GetExtendedString(string name) { - Debug.Assert(name != null); + Debug.Assert(name is not null); string? value; return _extendedStrings.TryGetValue(name, out value) ? @@ -529,7 +529,7 @@ internal static class ParameterizedStrings public static string Evaluate(string format, FormatParam arg) { FormatParam[]? args = t_cachedOneElementArgsArray; - if (args == null) + if (args is null) { t_cachedOneElementArgsArray = args = new FormatParam[1]; } @@ -547,7 +547,7 @@ public static string Evaluate(string format, FormatParam arg) public static string Evaluate(string format, FormatParam arg1, FormatParam arg2) { FormatParam[]? args = t_cachedTwoElementArgsArray; - if (args == null) + if (args is null) { t_cachedTwoElementArgsArray = args = new FormatParam[2]; } @@ -564,18 +564,18 @@ public static string Evaluate(string format, FormatParam arg1, FormatParam arg2) /// The formatted string. public static string Evaluate(string format, params FormatParam[] args) { - if (format == null) + if (format is null) { throw new ArgumentNullException(nameof(format)); } - if (args == null) + if (args is null) { throw new ArgumentNullException(nameof(args)); } // Initialize the stack to use for processing. Stack? stack = t_cachedStack; - if (stack == null) + if (stack is null) { t_cachedStack = stack = new Stack(); } @@ -873,7 +873,7 @@ private static unsafe string FormatPrintF(string format, object arg) // Determine how much space is needed to store the formatted string. string? stringArg = arg as string; - int neededLength = stringArg != null ? + int neededLength = stringArg is not null ? Interop.Sys.SNPrintF(null, 0, format, stringArg) : Interop.Sys.SNPrintF(null, 0, format, (int)arg); if (neededLength == 0) @@ -889,7 +889,7 @@ private static unsafe string FormatPrintF(string format, object arg) byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator fixed (byte* ptr = &bytes[0]) { - int length = stringArg != null ? + int length = stringArg is not null ? Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) : Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg); if (length != neededLength) diff --git a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs index 60c883d88fe842..6a4d9a9e110fb1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs @@ -67,17 +67,17 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// public override object? ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object? value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { - return value != null ? value.ToString() : string.Empty; + return value is not null ? value.ToString() : string.Empty; } - if (value != null && destinationType == typeof(InstanceDescriptor)) + if (value is not null && destinationType == typeof(InstanceDescriptor)) { object newValue = value; if (value is string) @@ -94,7 +94,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati if (value is Type || value is string) { MethodInfo method = typeof(Type).GetMethod("GetType", new Type[] { typeof(string) })!; - if (method != null) + if (method is not null) { return new InstanceDescriptor(method, new object[] { ((Type)newValue).AssemblyQualifiedName! }); } @@ -110,7 +110,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value != null && value.GetType() == typeof(string)) + if (value is not null && value.GetType() == typeof(string)) { for (int i = 0; i < s_types.Length; i++) { @@ -131,11 +131,11 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (_values == null) + if (_values is null) { object[]? objTypes; - if (s_types != null) + if (s_types is not null) { objTypes = new object[s_types.Length]; Array.Copy(s_types, objTypes, s_types.Length); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs b/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs index 619b5baa871a56..46405d71c8a0f6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs @@ -27,8 +27,8 @@ internal static partial class ADP // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it static partial void TraceException(string trace, Exception e) { - Debug.Assert(e != null, "TraceException: null Exception"); - if (e != null) + Debug.Assert(e is not null, "TraceException: null Exception"); + if (e is not null) { DataCommonEventSource.Log.Trace(trace, e); } @@ -788,7 +788,7 @@ internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray) for (int i = columnNameArray.Length - 1; 0 <= i; --i) { string columnName = columnNameArray[i]; - if ((null != columnName) && (0 < columnName.Length)) + if ((columnName is not null) && (0 < columnName.Length)) { columnName = columnName.ToLowerInvariant(); int index; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs index fdff3ed6ab990c..fc76d239fc85eb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs @@ -41,7 +41,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -95,7 +95,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ConvertToBigInteger(value, FormatProvider); } @@ -125,7 +125,7 @@ public override object Get(int record) public override void Set(int record, object value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = BigInteger.Zero; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs index 99e6ce414dab34..2d64d9ac422956 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs @@ -92,7 +92,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -115,7 +115,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToBoolean(FormatProvider); } @@ -145,7 +145,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs index 1fd8b9dbc76677..af9afd2bf44b25 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs @@ -164,7 +164,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -187,7 +187,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToByte(FormatProvider); } @@ -217,7 +217,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs index 72027fea73c3ae..db91234f4517a1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs @@ -91,7 +91,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -114,7 +114,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToChar(FormatProvider); } @@ -144,7 +144,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs index dfc46cfcb2185b..a53058d31fb829 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs @@ -57,7 +57,7 @@ internal ParameterNames(DbCommandBuilder dbCommandBuilder, DbSchemaRow?[] schema for (int i = 0; i < schemaRows.Length; i++) { var schemaRow = schemaRows[i]; - if (null == schemaRow) + if (schemaRow is null) { continue; } @@ -189,7 +189,7 @@ private void EliminateConflictingNames() for (int i = 0; i < _count - 1; i++) { string? name = _baseParameterNames[i]; - if (null != name) + if (name is not null) { for (int j = i + 1; j < _count; j++) { @@ -223,7 +223,7 @@ internal void GenerateMissingNames(DbSchemaRow?[] schemaRows) for (int i = 0; i < _baseParameterNames.Length; i++) { name = _baseParameterNames[i]; - if (null == name) + if (name is null) { _baseParameterNames[i] = GetNextGenericParameterName(); _originalParameterNames[i] = GetNextGenericParameterName(); @@ -390,7 +390,7 @@ public virtual string CatalogSeparator get { string? catalogSeparator = _catalogSeparator; - return (((null != catalogSeparator) && (0 < catalogSeparator.Length)) ? catalogSeparator : NameSeparator); + return (((catalogSeparator is not null) && (0 < catalogSeparator.Length)) ? catalogSeparator : NameSeparator); } set { @@ -422,7 +422,7 @@ public DbDataAdapter? DataAdapter SetRowUpdatingHandler(_dataAdapter); _dataAdapter = null; } - if (null != value) + if (value is not null) { // derived should add event handler to new adapter SetRowUpdatingHandler(value); @@ -478,7 +478,7 @@ public virtual string QuoteSuffix get { string? quoteSuffix = _quoteSuffix; - return ((null != quoteSuffix) ? quoteSuffix : string.Empty); + return ((quoteSuffix is not null) ? quoteSuffix : string.Empty); } set { @@ -498,7 +498,7 @@ public virtual string SchemaSeparator get { string? schemaSeparator = _schemaSeparator; - return (((null != schemaSeparator) && (0 < schemaSeparator.Length)) ? schemaSeparator : NameSeparator); + return (((schemaSeparator is not null) && (0 < schemaSeparator.Length)) ? schemaSeparator : NameSeparator); } set { @@ -571,7 +571,7 @@ private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsF DbCommand srcCommand = GetSelectCommand(); DbConnection? connection = srcCommand.Connection; - if (null == connection) + if (connection is null) { throw ADP.MissingSourceCommandConnection(); } @@ -620,7 +620,7 @@ private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsF } } - if (null == schemaTable) + if (schemaTable is null) { throw ADP.DynamicSQLNoTableInfo(); } @@ -657,7 +657,7 @@ private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsF private void BuildInformation(DataTable schemaTable) { DbSchemaRow?[]? rows = DbSchemaRow.GetSortedSchemaRows(schemaTable, false); - if ((null == rows) || (0 == rows.Length)) + if ((rows is null) || (0 == rows.Length)) { throw ADP.DynamicSQLNoTableInfo(); } @@ -671,7 +671,7 @@ private void BuildInformation(DataTable schemaTable) { DbSchemaRow row = rows[i]!; string tableName = row.BaseTableName; - if ((null == tableName) || (0 == tableName.Length)) + if ((tableName is null) || (0 == tableName.Length)) { rows[i] = null; continue; @@ -680,19 +680,19 @@ private void BuildInformation(DataTable schemaTable) string serverName = row.BaseServerName; string catalogName = row.BaseCatalogName; string schemaName = row.BaseSchemaName; - if (null == serverName) + if (serverName is null) { serverName = string.Empty; } - if (null == catalogName) + if (catalogName is null) { catalogName = string.Empty; } - if (null == schemaName) + if (schemaName is null) { schemaName = string.Empty; } - if (null == baseTableName) + if (baseTableName is null) { baseServerName = serverName; baseCatalogName = catalogName; @@ -722,7 +722,7 @@ private void BuildInformation(DataTable schemaTable) baseCatalogName = null; baseSchemaName = null; } - if ((null == baseTableName) || (0 == baseTableName.Length)) + if ((baseTableName is null) || (0 == baseTableName.Length)) { throw ADP.DynamicSQLNoTableInfo(); } @@ -746,18 +746,18 @@ private void BuildInformation(DataTable schemaTable) System.Text.StringBuilder builder = new System.Text.StringBuilder(); if (CatalogLocation.Start == location) { - if (null != baseServerName) + if (baseServerName is not null) { builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseServerName)); builder.Append(catalogSeparator); } - if (null != baseCatalogName) + if (baseCatalogName is not null) { builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseCatalogName)); builder.Append(catalogSeparator); } } - if (null != baseSchemaName) + if (baseSchemaName is not null) { builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseSchemaName)); builder.Append(schemaSeparator); @@ -766,12 +766,12 @@ private void BuildInformation(DataTable schemaTable) if (CatalogLocation.End == location) { - if (null != baseServerName) + if (baseServerName is not null) { builder.Append(catalogSeparator); builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseServerName)); } - if (null != baseCatalogName) + if (baseCatalogName is not null) { builder.Append(catalogSeparator); builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseCatalogName)); @@ -782,7 +782,7 @@ private void BuildInformation(DataTable schemaTable) _hasPartialPrimaryKey = false; foreach (DbSchemaRow? row in rows) { - if ((null != row) && (row.IsKey || row.IsUnique) && !row.IsLong && !row.IsRowVersion && row.IsHidden) + if ((row is not null) && (row.IsKey || row.IsUnique) && !row.IsLong && !row.IsRowVersion && row.IsHidden) { _hasPartialPrimaryKey = true; break; @@ -831,7 +831,7 @@ private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRo { DbSchemaRow row = schemaRows[i]; - if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInInsertValues(row)) + if ((row is null) || (0 == row.BaseColumnName.Length) || !IncludeInInsertValues(row)) continue; object? currentValue = null; @@ -840,11 +840,11 @@ private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRo // If we're building a statement for a specific row, then check the // values to see whether the column should be included in the insert // statement or not - if ((null != mappings) && (null != dataRow)) + if ((mappings is not null) && (null != dataRow)) { DataColumn? dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); - if (null == dataColumn) + if (dataColumn is null) continue; // Don't bother inserting if the column is readonly in both the data @@ -857,7 +857,7 @@ private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRo // If the value is null, and the column doesn't support nulls, then // the user is requesting the server-specified default value, so don't // include it in the set-list. - if (!row.AllowDBNull && (null == currentValue || Convert.IsDBNull(currentValue))) + if (!row.AllowDBNull && (currentValue is null || Convert.IsDBNull(currentValue))) continue; } @@ -920,7 +920,7 @@ private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRo { DbSchemaRow row = schemaRows[i]; - if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInUpdateSet(row)) + if ((row is null) || (0 == row.BaseColumnName.Length) || !IncludeInUpdateSet(row)) continue; object? currentValue = null; @@ -929,11 +929,11 @@ private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRo // If we're building a statement for a specific row, then check the // values to see whether the column should be included in the update // statement or not - if ((null != mappings) && (null != dataRow)) + if ((mappings is not null) && (null != dataRow)) { DataColumn? dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); - if (null == dataColumn) + if (dataColumn is null) continue; // Don't bother updating if the column is readonly in both the data @@ -951,7 +951,7 @@ private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRo object originalValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Original); if ((originalValue == currentValue) - || ((null != originalValue) && originalValue.Equals(currentValue))) + || ((originalValue is not null) && originalValue.Equals(currentValue))) { continue; } @@ -1009,7 +1009,7 @@ bool isUpdate { DbSchemaRow row = schemaRows[i]; - if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInWhereClause(row, isUpdate)) + if ((row is null) || (0 == row.BaseColumnName.Length) || !IncludeInWhereClause(row, isUpdate)) { continue; } @@ -1020,7 +1020,7 @@ bool isUpdate string sourceColumn = _sourceColumnNames![i]; string baseColumnName = QuotedColumn(row.BaseColumnName); - if ((null != mappings) && (null != dataRow)) + if ((mappings is not null) && (null != dataRow)) value = GetColumnValue(dataRow, sourceColumn, mappings, DataRowVersion.Original); if (!row.AllowDBNull) @@ -1134,7 +1134,7 @@ bool whereClause DbParameter p = GetNextParameter(command, parameterCount); Debug.Assert(!string.IsNullOrEmpty(sourceColumn), "empty source column"); - if (null == parameterName) + if (parameterName is null) { p.ParameterName = GetParameterName(1 + parameterCount); } @@ -1159,7 +1159,7 @@ bool whereClause command.Parameters.Add(p); } - if (null == parameterName) + if (parameterName is null) { return GetParameterPlaceholder(1 + parameterCount); } @@ -1186,7 +1186,7 @@ bool whereClause { DbParameter p = GetNextParameter(command, parameterCount); - if (null == parameterName) + if (parameterName is null) { p.ParameterName = GetParameterName(1 + parameterCount); } @@ -1208,7 +1208,7 @@ bool whereClause command.Parameters.Add(p); } - if (null == parameterName) + if (parameterName is null) { return GetParameterPlaceholder(1 + parameterCount); } @@ -1236,13 +1236,13 @@ protected override void Dispose(bool disposing) private DataTableMapping? GetTableMapping(DataRow? dataRow) { DataTableMapping? tableMapping = null; - if (null != dataRow) + if (dataRow is not null) { DataTable dataTable = dataRow.Table; - if (null != dataTable) + if (dataTable is not null) { DbDataAdapter? adapter = DataAdapter; - if (null != adapter) + if (adapter is not null) { tableMapping = adapter.GetTableMapping(dataTable); } @@ -1294,7 +1294,7 @@ private DbCommand GetSelectCommand() { DbCommand? select = null; DbDataAdapter? adapter = DataAdapter; - if (null != adapter) + if (adapter is not null) { if (0 == _missingMappingAction) { @@ -1302,7 +1302,7 @@ private DbCommand GetSelectCommand() } select = adapter.SelectCommand; } - if (null == select) + if (select is null) { throw ADP.MissingSourceCommand(); } @@ -1364,7 +1364,7 @@ internal DbCommand GetDeleteCommand(DataRow? dataRow, bool useColumnsForParamete private object? GetColumnValue(DataRow row, DataColumn? column, DataRowVersion version) { object? value = null; - if (null != column) + if (column is not null) { value = row[column, version]; } @@ -1391,11 +1391,11 @@ private static DbParameter GetNextParameter(DbCommand command, int pcount) else { p = command.CreateParameter(); - /*if (null == p) { + /*if (p is null) { // CONSIDER: throw exception }*/ } - Debug.Assert(null != p, "null CreateParameter"); + Debug.Assert(p is not null, "null CreateParameter"); return p; } @@ -1449,11 +1449,11 @@ private bool IncrementWhereCount(DbSchemaRow row) protected virtual DbCommand InitializeCommand(DbCommand? command) { - if (null == command) + if (command is null) { DbCommand select = GetSelectCommand(); command = select.Connection!.CreateCommand(); - /*if (null == command) { + /*if (command is null) { // CONSIDER: throw exception }*/ @@ -1486,7 +1486,7 @@ public virtual void RefreshSchema() _quotedBaseTableName = null; DbDataAdapter? adapter = DataAdapter; - if (null != adapter) + if (adapter is not null) { if (InsertCommand == adapter.InsertCommand) { @@ -1529,7 +1529,7 @@ private static void RemoveExtraParameters(DbCommand command, int usedParameterCo protected void RowUpdatingHandler(RowUpdatingEventArgs rowUpdatingEvent) { - if (null == rowUpdatingEvent) + if (rowUpdatingEvent is null) { throw ADP.ArgumentNull(nameof(rowUpdatingEvent)); } @@ -1540,7 +1540,7 @@ protected void RowUpdatingHandler(RowUpdatingEventArgs rowUpdatingEvent) StatementType stmtType = rowUpdatingEvent.StatementType; DbCommand? command = (DbCommand?)rowUpdatingEvent.Command; - if (null != command) + if (command is not null) { switch (stmtType) { @@ -1563,11 +1563,11 @@ protected void RowUpdatingHandler(RowUpdatingEventArgs rowUpdatingEvent) if (command != rowUpdatingEvent.Command) { command = (DbCommand?)rowUpdatingEvent.Command; - if ((null != command) && (null == command.Connection)) + if ((command is not null) && (command.Connection is null)) { DbDataAdapter? adapter = DataAdapter; - DbCommand? select = ((null != adapter) ? adapter.SelectCommand : null); - if (null != select) + DbCommand? select = ((adapter is not null) ? adapter.SelectCommand : null); + if (select is not null) { command.Connection = select.Connection; } @@ -1576,7 +1576,7 @@ protected void RowUpdatingHandler(RowUpdatingEventArgs rowUpdatingEvent) } else command = null; } - if (null == command) + if (command is null) { RowUpdatingHandlerBuilder(rowUpdatingEvent); } @@ -1616,9 +1616,9 @@ private void RowUpdatingHandlerBuilder(RowUpdatingEventArgs rowUpdatingEvent) default: throw ADP.InvalidStatementType(rowUpdatingEvent.StatementType); } - if (null == command) + if (command is null) { - if (null != datarow) + if (datarow is not null) { datarow.AcceptChanges(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs index 438433e3b4a9ee..f1a4014578a044 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs @@ -15,7 +15,7 @@ internal sealed class DbSchemaRow internal static DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool returnProviderSpecificTypes) { DataColumn? sortindex = dataTable.Columns[SchemaMappingUnsortedIndex]; - if (null == sortindex) + if (sortindex is null) { sortindex = new DataColumn(SchemaMappingUnsortedIndex, typeof(int)); dataTable.Columns.Add(sortindex); @@ -29,7 +29,7 @@ internal static DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool retu const DataViewRowState rowStates = DataViewRowState.Unchanged | DataViewRowState.Added | DataViewRowState.ModifiedCurrent; DataRow[] dataRows = dataTable.Select(null, "ColumnOrdinal ASC", rowStates); - Debug.Assert(null != dataRows, "GetSchemaRows: unexpected null dataRows"); + Debug.Assert(dataRows is not null, "GetSchemaRows: unexpected null dataRows"); DbSchemaRow[] schemaRows = new DbSchemaRow[dataRows.Length]; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs index cbe77258b18e87..c7afaca4982694 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs @@ -106,7 +106,7 @@ internal DataColumn? DataType private DataColumn? CachedDataColumn(ColumnEnum column, ColumnEnum column2) { DataColumn? dataColumn = _columnCache[(int)column]; - if (null == dataColumn) + if (dataColumn is null) { int index = _columns.IndexOf(s_DBCOLUMN_NAME[(int)column]); if ((-1 == index) && (column != column2)) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs index 48e44921c91f50..e64edc5f7caf91 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs @@ -167,10 +167,10 @@ public DataTableMappingCollection TableMappings get { DataTableMappingCollection? mappings = _tableMappings; - if (null == mappings) + if (mappings is null) { mappings = CreateTableMappings(); - if (null == mappings) + if (mappings is null) { mappings = new DataTableMappingCollection(); } @@ -218,7 +218,7 @@ private void CloneFrom(DataAdapter from) _missingMappingAction = from._missingMappingAction; _missingSchemaAction = from._missingSchemaAction; - if ((null != from._tableMappings) && (0 < from.TableMappings.Count)) + if ((from._tableMappings is not null) && (0 < from.TableMappings.Count)) { DataTableMappingCollection parameters = TableMappings; foreach (object parameter in from.TableMappings) @@ -256,7 +256,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, schemaType={1}, srcTable, dataReader", ObjectID, schemaType); try { - if (null == dataSet) + if (dataSet is null) { throw ADP.ArgumentNull(nameof(dataSet)); } @@ -268,7 +268,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, { throw ADP.FillSchemaRequiresSourceTableName(nameof(srcTable)); } - if ((null == dataReader) || dataReader.IsClosed) + if ((dataReader is null) || dataReader.IsClosed) { throw ADP.FillRequires(nameof(dataReader)); } @@ -288,7 +288,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTable, schemaType, dataReader", ObjectID); try { - if (null == dataTable) + if (dataTable is null) { throw ADP.ArgumentNull(nameof(dataTable)); } @@ -296,7 +296,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, { throw ADP.InvalidSchemaType(schemaType); } - if ((null == dataReader) || dataReader.IsClosed) + if ((dataReader is null) || dataReader.IsClosed) { throw ADP.FillRequires(nameof(dataReader)); } @@ -325,7 +325,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, continue; } string? tmp = null; - if (null != dataset) + if (dataset is not null) { tmp = DataAdapter.GetSourceTableName(srcTable!, schemaCount); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) @@ -333,14 +333,14 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, SchemaMapping mapping = new SchemaMapping(this, dataset, datatable, readerHandler, true, schemaType, tmp, false, null, null); - if (null != datatable) + if (datatable is not null) { // do not read remaining results in single DataTable case return mapping.DataTable; } - else if (null != mapping.DataTable) + else if (mapping.DataTable is not null) { - if (null == dataTables) + if (dataTables is null) { dataTables = new DataTable[1] { mapping.DataTable }; } @@ -352,7 +352,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, } while (dataReader.NextResult()); // FillSchema does not capture errors for FillError event object? value = dataTables; - if ((null == value) && (null == datatable)) + if ((value is null) && (null == datatable)) { value = Array.Empty(); } @@ -369,7 +369,7 @@ protected virtual int Fill(DataSet dataSet, string srcTable, IDataReader dataRea long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, srcTable, dataReader, startRecord, maxRecords", ObjectID); try { - if (null == dataSet) + if (dataSet is null) { throw ADP.FillRequires(nameof(dataSet)); } @@ -377,7 +377,7 @@ protected virtual int Fill(DataSet dataSet, string srcTable, IDataReader dataRea { throw ADP.FillRequiresSourceTableName(nameof(srcTable)); } - if (null == dataReader) + if (dataReader is null) { throw ADP.FillRequires(nameof(dataReader)); } @@ -415,11 +415,11 @@ protected virtual int Fill(DataTable[] dataTables, IDataReader dataReader, int s try { ADP.CheckArgumentLength(dataTables, nameof(dataTables)); - if ((null == dataTables) || (0 == dataTables.Length) || (null == dataTables[0])) + if ((dataTables is null) || (0 == dataTables.Length) || (null == dataTables[0])) { throw ADP.FillRequires("dataTable"); } - if (null == dataReader) + if (dataReader is null) { throw ADP.FillRequires(nameof(dataReader)); } @@ -433,14 +433,14 @@ protected virtual int Fill(DataTable[] dataTables, IDataReader dataReader, int s DataSet? commonDataSet = dataTables[0].DataSet; try { - if (null != commonDataSet) + if (commonDataSet is not null) { enforceContraints = commonDataSet.EnforceConstraints; commonDataSet.EnforceConstraints = false; } for (int i = 0; i < dataTables.Length; ++i) { - Debug.Assert(null != dataTables[i], "null DataTable Fill"); + Debug.Assert(dataTables[i] is not null, "null DataTable Fill"); if (dataReader.IsClosed) { @@ -516,15 +516,15 @@ internal int FillFromReader(DataSet? dataset, DataTable? datatable, string? srcT SchemaMapping? mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) - if (null == mapping) + if (mapping is null) { continue; // loop to next result } - if (null == mapping.DataValues) + if (mapping.DataValues is null) { continue; // loop to next result } - if (null == mapping.DataTable) + if (mapping.DataTable is null) { continue; // loop to next result } @@ -552,7 +552,7 @@ internal int FillFromReader(DataSet? dataset, DataTable? datatable, string? srcT { mapping.DataTable.EndLoadData(); } - if (null != datatable) + if (datatable is not null) { break; // do not read remaining results in single DataTable case } @@ -646,7 +646,7 @@ private SchemaMapping FillMappingInternal(DataSet? dataset, DataTable? datatable { bool withKeyInfo = (Data.MissingSchemaAction.AddWithKey == MissingSchemaAction); string? tmp = null; - if (null != dataset) + if (dataset is not null) { tmp = DataAdapter.GetSourceTableName(srcTable!, schemaCount); } @@ -731,7 +731,7 @@ private void OnFillErrorHandler(Exception e, DataTable? dataTable, object?[]? da if (!fillErrorEvent.Continue) { - if (null != fillErrorEvent.Errors) + if (fillErrorEvent.Errors is not null) { throw fillErrorEvent.Errors; } @@ -766,7 +766,7 @@ private static DataTable[] AddDataTableToArray(DataTable[] tables, DataTable new // dynamically generate source table names private static string GetSourceTableName(string srcTable, int index) { - //if ((null != srcTable) && (0 <= index) && (index < srcTable.Length)) { + //if ((srcTable is not null) && (0 <= index) && (index < srcTable.Length)) { if (0 == index) { return srcTable; //[index]; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs index 7f53c995836c4f..c4b36324e43942 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs @@ -54,7 +54,7 @@ public string SourceColumn get { return _sourceColumnName ?? string.Empty; } set { - if ((null != Parent) && (0 != ADP.SrcCompare(_sourceColumnName, value))) + if ((Parent is not null) && (0 != ADP.SrcCompare(_sourceColumnName, value))) { Parent.ValidateSourceColumn(-1, value); } @@ -79,7 +79,7 @@ object ICloneable.Clone() [EditorBrowsable(EditorBrowsableState.Advanced)] public static DataColumn? GetDataColumnBySchemaAction(string? sourceColumn, string? dataSetColumn, DataTable dataTable, Type? dataType, MissingSchemaAction schemaAction) { - if (null == dataTable) + if (dataTable is null) { throw ADP.ArgumentNull(nameof(dataTable)); } @@ -88,20 +88,20 @@ object ICloneable.Clone() return null; } DataColumnCollection columns = dataTable.Columns; - Debug.Assert(null != columns, "GetDataColumnBySchemaAction: unexpected null DataColumnCollection"); + Debug.Assert(columns is not null, "GetDataColumnBySchemaAction: unexpected null DataColumnCollection"); int index = columns.IndexOf(dataSetColumn); if ((0 <= index) && (index < columns.Count)) { DataColumn dataColumn = columns[index]; - Debug.Assert(null != dataColumn, "GetDataColumnBySchemaAction: unexpected null dataColumn"); + Debug.Assert(dataColumn is not null, "GetDataColumnBySchemaAction: unexpected null dataColumn"); if (!string.IsNullOrEmpty(dataColumn.Expression)) { throw ADP.ColumnSchemaExpression(sourceColumn, dataSetColumn); } - if ((null == dataType) || (dataType.IsArray == dataColumn.DataType.IsArray)) + if ((dataType is null) || (dataType.IsArray == dataColumn.DataType.IsArray)) { return dataColumn; } @@ -114,7 +114,7 @@ object ICloneable.Clone() internal static DataColumn? CreateDataColumnBySchemaAction(string? sourceColumn, string? dataSetColumn, DataTable dataTable, Type? dataType, MissingSchemaAction schemaAction) { - Debug.Assert(dataTable != null, "Should not call with a null DataTable"); + Debug.Assert(dataTable is not null, "Should not call with a null DataTable"); if (string.IsNullOrEmpty(dataSetColumn)) { return null; @@ -158,7 +158,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (null == destinationType) + if (destinationType is null) { throw ADP.ArgumentNull(nameof(destinationType)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs index 7c6776d35db686..b6002b52f9c8fe 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs @@ -153,7 +153,7 @@ public void AddCloneOfRange(IEnumerable values) { private void AddEnumerableRange(IEnumerable values, bool doClone) { - if (null == values) + if (values is null) { throw ADP.ArgumentNull(nameof(values)); } @@ -252,7 +252,7 @@ public IEnumerator GetEnumerator() public int IndexOf(object? value) { - if (null != value) + if (value is not null) { ValidateType(value); for (int i = 0; i < Count; ++i) @@ -306,7 +306,7 @@ public void Insert(int index, object? value) public void Insert(int index, DataColumnMapping value) { - if (null == value) + if (value is null) { throw ADP.ColumnsAddNullAttempt(nameof(value)); } @@ -360,7 +360,7 @@ public void Remove(object? value) public void Remove(DataColumnMapping value) { - if (null == value) + if (value is null) { throw ADP.ColumnsAddNullAttempt(nameof(value)); } @@ -387,7 +387,7 @@ private void Replace(int index, DataColumnMapping newValue) private void ValidateType([NotNull] object? value) { - if (null == value) + if (value is null) { throw ADP.ColumnsAddNullAttempt(nameof(value)); } @@ -399,11 +399,11 @@ private void ValidateType([NotNull] object? value) private void Validate(int index, [NotNull] DataColumnMapping? value) { - if (null == value) + if (value is null) { throw ADP.ColumnsAddNullAttempt(nameof(value)); } - if (null != value.Parent) + if (value.Parent is not null) { if (this != value.Parent) { @@ -444,7 +444,7 @@ internal void ValidateSourceColumn(int index, string? value) [EditorBrowsable(EditorBrowsableState.Advanced)] public static DataColumn? GetDataColumn(DataColumnMappingCollection? columnMappings, string sourceColumn, Type? dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) { - if (null != columnMappings) + if (columnMappings is not null) { int index = columnMappings.IndexOf(sourceColumn); if (-1 != index) @@ -473,7 +473,7 @@ internal void ValidateSourceColumn(int index, string? value) [EditorBrowsable(EditorBrowsableState.Advanced)] public static DataColumnMapping? GetColumnMappingBySchemaAction(DataColumnMappingCollection? columnMappings, string sourceColumn, MissingMappingAction mappingAction) { - if (null != columnMappings) + if (columnMappings is not null) { int index = columnMappings.IndexOf(sourceColumn); if (-1 != index) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs index 7c0989201be808..2b5fcd46c1b9ba 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs @@ -17,8 +17,8 @@ internal sealed class DataRecordInternal : DbDataRecord, ICustomTypeDescriptor // copy all runtime data information internal DataRecordInternal(SchemaInfo[] schemaInfo, object[] values, PropertyDescriptorCollection descriptors, FieldNameLookup fieldNameLookup) { - Debug.Assert(null != schemaInfo, "invalid attempt to instantiate DataRecordInternal with null schema information"); - Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]"); + Debug.Assert(schemaInfo is not null, "invalid attempt to instantiate DataRecordInternal with null schema information"); + Debug.Assert(values is not null, "invalid attempt to instantiate DataRecordInternal with null value[]"); _schemaInfo = schemaInfo; _values = values; _propertyDescriptors = descriptors; @@ -35,7 +35,7 @@ public override int FieldCount public override int GetValues(object[] values) { - if (null == values) + if (values is null) { throw ADP.ArgumentNull(nameof(values)); } @@ -120,7 +120,7 @@ public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIn ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have - if (null == buffer) + if (buffer is null) return cbytes; try @@ -191,7 +191,7 @@ public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIn // if no buffer is passed in, return the number of characters we have - if (null == buffer) + if (buffer is null) { return cchars; } @@ -293,7 +293,7 @@ public override DateTime GetDateTime(int i) public override bool IsDBNull(int i) { object o = _values[i]; - return (null == o || Convert.IsDBNull(o)); + return (o is null || Convert.IsDBNull(o)); } // @@ -356,7 +356,7 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { - if (_propertyDescriptors == null) + if (_propertyDescriptors is null) { _propertyDescriptors = new PropertyDescriptorCollection(null); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs index 55cec5acc9737a..abc6d578f8d411 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs @@ -284,7 +284,7 @@ public virtual void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRoo public static DataStorage CreateStorage(DataColumn column, Type dataType, StorageType typeCode) { Debug.Assert(typeCode == GetStorageType(dataType), "Incorrect storage type specified"); - if ((StorageType.Empty == typeCode) && (null != dataType)) + if ((StorageType.Empty == typeCode) && (dataType is not null)) { if (typeof(INullable).IsAssignableFrom(dataType)) { // Udt, OracleTypes @@ -499,7 +499,7 @@ internal static void ImplementsInterfaces( private static Tuple InspectTypeForInterfaces(Type dataType) { - Debug.Assert(dataType != null, "Type should not be null"); + Debug.Assert(dataType is not null, "Type should not be null"); return new Tuple( typeof(INullable).IsAssignableFrom(dataType), @@ -516,13 +516,13 @@ internal static bool ImplementsINullableValue(StorageType typeCode, Type dataTyp public static bool IsObjectNull(object value) { - return ((null == value) || (DBNull.Value == value) || IsObjectSqlNull(value)); + return ((value is null) || (DBNull.Value == value) || IsObjectSqlNull(value)); } public static bool IsObjectSqlNull(object value) { INullable? inullable = (value as INullable); - return ((null != inullable) && inullable.IsNull); + return ((inullable is not null) && inullable.IsNull); } internal object GetEmptyStorageInternal(int recordCount) @@ -560,7 +560,7 @@ protected void SetNullStorage(BitArray nullbits) internal static Type GetType(string value) { Type? dataType = Type.GetType(value); // throwOnError=false, ignoreCase=fase - if (null == dataType) + if (dataType is null) { if ("System.Numerics.BigInteger" == value) { @@ -580,7 +580,7 @@ internal static Type GetType(string value) /// when type implements IDynamicMetaObjectProvider and not IXmlSerializable internal static string GetQualifiedName(Type type) { - Debug.Assert(null != type, "null type"); + Debug.Assert(type is not null, "null type"); ObjectStorage.VerifyIDynamicMetaObjectProvider(type); return type.AssemblyQualifiedName!; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs index cbf3743a207f5f..ae3911dba55e0f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs @@ -32,7 +32,7 @@ public DataTableMapping(string? sourceTable, string? dataSetTable, DataColumnMap { SourceTable = sourceTable; DataSetTable = dataSetTable; - if ((null != columnMappings) && (0 < columnMappings.Length)) + if ((columnMappings is not null) && (0 < columnMappings.Length)) { ColumnMappings.AddRange(columnMappings); } @@ -50,7 +50,7 @@ public DataColumnMappingCollection ColumnMappings get { DataColumnMappingCollection? columnMappings = _columnMappings; - if (null == columnMappings) + if (columnMappings is null) { columnMappings = new DataColumnMappingCollection(); _columnMappings = columnMappings; @@ -86,7 +86,7 @@ public string SourceTable get { return _sourceTableName ?? string.Empty; } set { - if ((null != Parent) && (0 != ADP.SrcCompare(_sourceTableName, value))) + if ((Parent is not null) && (0 != ADP.SrcCompare(_sourceTableName, value))) { Parent.ValidateSourceTable(-1, value); } @@ -126,7 +126,7 @@ object ICloneable.Clone() [EditorBrowsable(EditorBrowsableState.Advanced)] public DataTable? GetDataTableBySchemaAction(DataSet dataSet, MissingSchemaAction schemaAction) { - if (null == dataSet) + if (dataSet is null) { throw ADP.ArgumentNull(nameof(dataSet)); } @@ -180,7 +180,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (null == destinationType) + if (destinationType is null) { throw ADP.ArgumentNull(nameof(destinationType)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs index 46e2fbbc518804..a4e7c84cbbc099 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs @@ -107,7 +107,7 @@ private DataTableMapping Add(DataTableMapping value) private void AddEnumerableRange(IEnumerable values, bool doClone) { - if (null == values) + if (values is null) { throw ADP.ArgumentNull(nameof(values)); } @@ -189,7 +189,7 @@ public DataTableMapping GetByDataSetTable(string dataSetTable) public int IndexOf(object? value) { - if (null != value) + if (value is not null) { ValidateType(value); for (int i = 0; i < Count; ++i) @@ -210,7 +210,7 @@ public int IndexOf(string? sourceTable) for (int i = 0; i < Count; ++i) { string value = _items![i].SourceTable; - if ((null != value) && (0 == ADP.SrcCompare(sourceTable, value))) + if ((value is not null) && (0 == ADP.SrcCompare(sourceTable, value))) { return i; } @@ -226,7 +226,7 @@ public int IndexOfDataSetTable(string? dataSetTable) for (int i = 0; i < Count; ++i) { string value = _items![i].DataSetTable; - if ((null != value) && (0 == ADP.DstCompare(dataSetTable, value))) + if ((value is not null) && (0 == ADP.DstCompare(dataSetTable, value))) { return i; } @@ -243,7 +243,7 @@ public void Insert(int index, object? value) public void Insert(int index, DataTableMapping value) { - if (null == value) + if (value is null) { throw ADP.TablesAddNullAttempt(nameof(value)); } @@ -297,7 +297,7 @@ public void Remove(object? value) public void Remove(DataTableMapping value) { - if (null == value) + if (value is null) { throw ADP.TablesAddNullAttempt(nameof(value)); } @@ -323,7 +323,7 @@ private void Replace(int index, DataTableMapping newValue) private void ValidateType([NotNull] object? value) { - if (null == value) + if (value is null) { throw ADP.TablesAddNullAttempt(nameof(value)); } @@ -335,11 +335,11 @@ private void ValidateType([NotNull] object? value) private void Validate(int index, [NotNull] DataTableMapping? value) { - if (null == value) + if (value is null) { throw ADP.TablesAddNullAttempt(nameof(value)); } - if (null != value.Parent) + if (value.Parent is not null) { if (this != value.Parent) { @@ -380,7 +380,7 @@ internal void ValidateSourceTable(int index, string? value) [EditorBrowsable(EditorBrowsableState.Advanced)] public static DataTableMapping? GetTableMappingBySchemaAction(DataTableMappingCollection? tableMappings, string sourceTable, string dataSetTable, MissingMappingAction mappingAction) { - if (null != tableMappings) + if (tableMappings is not null) { int index = tableMappings.IndexOf(sourceTable); if (-1 != index) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs index aca975ea779e82..12b8cdc6dfbba6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs @@ -103,7 +103,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -122,7 +122,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((DateTimeOffset)value); } @@ -152,7 +152,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = s_defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs index 30337abccad753..a46f037595130c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs @@ -103,7 +103,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -122,7 +122,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToDateTime(FormatProvider); } @@ -152,7 +152,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = s_defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs index 08e2c6e02efd53..0eca91012c0561 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs @@ -37,7 +37,7 @@ public DbConnectionOptions(string? connectionString, Dictionary? { _useOdbcRules = useOdbcRules; _parsetable = new Dictionary(); - _usersConnectionString = ((null != connectionString) ? connectionString : ""); + _usersConnectionString = ((connectionString is not null) ? connectionString : ""); // first pass on parsing, initial syntax check if (0 < _usersConnectionString.Length) @@ -57,11 +57,11 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); - if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) + if ((keyName is null) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) { throw ADP.InvalidKeyname(keyName); } - if ((null != keyValue) && !IsValueValidInternal(keyValue)) + if ((keyValue is not null) && !IsValueValidInternal(keyValue)) { throw ADP.InvalidValue(keyName); } @@ -81,7 +81,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key } builder.Append('='); - if (null != keyValue) + if (keyValue is not null) { // else =; if (useOdbcRules) @@ -137,7 +137,7 @@ internal string ExpandKeyword(string keyword, string replacementValue) int copyPosition = 0; var builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair? current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; current is not null; current = current.Next) { if ((current.Name == keyword) && (current.Value == this[keyword])) { @@ -167,11 +167,11 @@ static partial void DebugTraceKeyValuePair(string keyname, string? keyvalue, Dic { Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower"); - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + string realkeyname = ((synonyms is not null) ? (string)synonyms[keyname] : keyname); if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! - if (null != keyvalue) + if (keyvalue is not null) { DataCommonEventSource.Log.Trace(" KeyName='{0}', KeyValue='{1}'", keyname, keyvalue); } @@ -184,11 +184,11 @@ static partial void DebugTraceKeyValuePair(string keyname, string? keyvalue, Dic internal static void ValidateKeyValuePair(string keyword, string value) { - if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) + if ((keyword is null) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) { throw ADP.InvalidKeyname(keyword); } - if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value)) + if ((value is not null) && !s_connectionStringValidValueRegex.IsMatch(value)) { throw ADP.InvalidValue(keyword); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs index 533e6ed5ab841e..2f8510cc34cd8d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs @@ -50,7 +50,7 @@ private Dictionary CurrentValues get { Dictionary? values = _currentValues; - if (null == values) + if (values is null) { values = new Dictionary(StringComparer.OrdinalIgnoreCase); _currentValues = values; @@ -85,7 +85,7 @@ public virtual object this[string keyword] { ADP.CheckArgumentNull(keyword, nameof(keyword)); bool flag = false; - if (null != value) + if (value is not null) { string keyvalue = DbConnectionStringBuilderUtil.ConvertToString(value); DbConnectionOptions.ValidateKeyValuePair(keyword, keyvalue); @@ -132,12 +132,12 @@ public string ConnectionString { DataCommonEventSource.Log.Trace(" {0}", ObjectID); string? connectionString = _connectionString; - if (null == connectionString) + if (connectionString is null) { StringBuilder builder = new StringBuilder(); foreach (string keyword in Keys) { - Debug.Assert(keyword != null); + Debug.Assert(keyword is not null); object? value; if (ShouldSerialize(keyword) && TryGetValue(keyword, out value)) { @@ -158,9 +158,9 @@ public string ConnectionString Clear(); try { - for (NameValuePair? pair = constr._keyChain; null != pair; pair = pair.Next) + for (NameValuePair? pair = constr._keyChain; pair is not null; pair = pair.Next) { - if (null != pair.Value) + if (pair.Value is not null) { this[pair.Name] = pair.Value; } @@ -241,7 +241,7 @@ public virtual ICollection Values { keylist.MoveNext(); values[i] = this[keylist.Current]; - Debug.Assert(null != values[i], "null value " + keylist.Current); + Debug.Assert(values[i] is not null, "null value " + keylist.Current); } return new ReadOnlyCollection(values); } @@ -249,7 +249,7 @@ public virtual ICollection Values internal virtual string? ConvertValueToString(object? value) { - return (value == null) ? null : Convert.ToString(value, CultureInfo.InvariantCulture); + return (value is null) ? null : Convert.ToString(value, CultureInfo.InvariantCulture); } void IDictionary.Add(object keyword, object? value) @@ -390,7 +390,7 @@ internal Attribute[] GetAttributesFromCollection(AttributeCollection collection) private PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection? propertyDescriptors = _propertyDescriptors; - if (null == propertyDescriptors) + if (propertyDescriptors is null) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try @@ -422,7 +422,7 @@ protected virtual void GetProperties(Hashtable propertyDescriptors) Attribute[]? attributes; foreach (PropertyDescriptor reflected in TypeDescriptor.GetProperties(this, true)) { - Debug.Assert(reflected != null); + Debug.Assert(reflected is not null); if (ADP.ConnectionString != reflected.Name) { string displayName = reflected.DisplayName; @@ -451,13 +451,13 @@ protected virtual void GetProperties(Hashtable propertyDescriptors) attributes = null; foreach (string keyword in Keys) { - Debug.Assert(keyword != null); + Debug.Assert(keyword is not null); if (!propertyDescriptors.ContainsKey(keyword)) { object value = this[keyword]; Type vtype; - if (null != value) + if (value is not null) { vtype = value.GetType(); if (typeof(string) == vtype) @@ -492,7 +492,7 @@ protected virtual void GetProperties(Hashtable propertyDescriptors) RefreshPropertiesAttribute.All, }; } - else if (null == attributes) + else if (attributes is null) { attributes = new Attribute[] { BrowsableAttribute.Yes, @@ -517,7 +517,7 @@ protected virtual void GetProperties(Hashtable propertyDescriptors) private PropertyDescriptorCollection GetProperties(Attribute[]? attributes) { PropertyDescriptorCollection propertyDescriptors = GetProperties(); - if ((null == attributes) || (0 == attributes.Length)) + if ((attributes is null) || (0 == attributes.Length)) { // Basic case has no filtering return propertyDescriptors; @@ -532,14 +532,14 @@ private PropertyDescriptorCollection GetProperties(Attribute[]? attributes) // Iterate over each property foreach (PropertyDescriptor property in propertyDescriptors) { - Debug.Assert(property != null); + Debug.Assert(property is not null); // Identify if this property's attributes match the specification bool match = true; foreach (Attribute attribute in attributes) { Attribute attr = property.Attributes[attribute.GetType()]; - if ((attr == null && !attribute.IsDefaultAttribute()) || attr?.Match(attribute) == false) + if ((attr is null && !attribute.IsDefaultAttribute()) || attr?.Match(attribute) == false) { match = false; break; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs index 16e792bcdfacc4..6f08823a7c0eeb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs @@ -22,13 +22,13 @@ internal DbConnectionStringBuilderDescriptor(string propertyName, Type component public override bool CanResetValue(object component) { DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); - return ((null != builder) && builder.ShouldSerialize(DisplayName)); + return ((builder is not null) && builder.ShouldSerialize(DisplayName)); } public override object? GetValue(object component) { DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); - if (null != builder) + if (builder is not null) { object? value; if (builder.TryGetValue(DisplayName, out value)) @@ -42,7 +42,7 @@ public override bool CanResetValue(object component) public override void ResetValue(object component) { DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); - if (null != builder) + if (builder is not null) { builder.Remove(DisplayName); @@ -56,7 +56,7 @@ public override void ResetValue(object component) public override void SetValue(object component, object? value) { DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); - if (null != builder) + if (builder is not null) { // via the editor, empty string does a defacto Reset if ((typeof(string) == PropertyType) && string.Empty.Equals(value)) @@ -75,7 +75,7 @@ public override void SetValue(object component, object? value) public override bool ShouldSerializeValue(object component) { DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); - return ((null != builder) && builder.ShouldSerialize(DisplayName)); + return ((builder is not null) && builder.ShouldSerialize(DisplayName)); } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs index b1e417ec7d14c2..369aebbf6a4bc2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs @@ -309,7 +309,7 @@ public override DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType) try { IDbCommand? command = _IDbDataAdapter.SelectCommand; - if (DesignMode && ((null == command) || (null == command.Connection) || string.IsNullOrEmpty(command.CommandText))) + if (DesignMode && ((command is null) || (null == command.Connection) || string.IsNullOrEmpty(command.CommandText))) { return Array.Empty(); // design-time support } @@ -342,7 +342,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, schemaType, command, srcTable, behavior={1}", ObjectID, behavior); try { - if (null == dataSet) + if (dataSet is null) { throw ADP.ArgumentNull(nameof(dataSet)); } @@ -354,7 +354,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, { throw ADP.FillSchemaRequiresSourceTableName(nameof(srcTable)); } - if (null == command) + if (command is null) { throw ADP.MissingSelectCommand(ADP.FillSchema); } @@ -372,7 +372,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTable, schemaType, command, behavior={1}", ObjectID, behavior); try { - if (null == dataTable) + if (dataTable is null) { throw ADP.ArgumentNull(nameof(dataTable)); } @@ -380,7 +380,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, { throw ADP.InvalidSchemaType(schemaType); } - if (null == command) + if (command is null) { throw ADP.MissingSelectCommand(ADP.FillSchema); } @@ -401,7 +401,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, private object? FillSchemaInternal(DataSet? dataset, DataTable? datatable, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior) { object? dataTables = null; - bool restoreNullConnection = (null == command.Connection); + bool restoreNullConnection = (command.Connection is null); try { IDbConnection activeConnection = DbDataAdapter.GetConnection3(this, command, ADP.FillSchema); @@ -412,7 +412,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, QuietOpen(activeConnection, out originalState); using (IDataReader dataReader = command.ExecuteReader(behavior | CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo)) { - if (null != datatable) + if (datatable is not null) { // delegate to next set of protected FillSchema methods dataTables = FillSchema(datatable, schemaType, dataReader); } @@ -491,7 +491,7 @@ protected virtual int Fill(DataSet dataSet, int startRecord, int maxRecords, str long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, startRecord, maxRecords, srcTable, command, behavior={1}", ObjectID, behavior); try { - if (null == dataSet) + if (dataSet is null) { throw ADP.FillRequires(nameof(dataSet)); } @@ -507,7 +507,7 @@ protected virtual int Fill(DataSet dataSet, int startRecord, int maxRecords, str { throw ADP.FillRequiresSourceTableName(nameof(srcTable)); } - if (null == command) + if (command is null) { throw ADP.MissingSelectCommand(ADP.Fill); } @@ -572,7 +572,7 @@ protected virtual int Fill(DataTable[] dataTables, int startRecord, int maxRecor long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTables[], startRecord, maxRecords, command, behavior={1}", ObjectID, behavior); try { - if ((null == dataTables) || (0 == dataTables.Length) || (null == dataTables[0])) + if ((dataTables is null) || (0 == dataTables.Length) || (null == dataTables[0])) { throw ADP.FillRequires("dataTable"); } @@ -588,7 +588,7 @@ protected virtual int Fill(DataTable[] dataTables, int startRecord, int maxRecor { throw ADP.OnlyOneTableForStartRecordOrMaxRecords(); } - if (null == command) + if (command is null) { throw ADP.MissingSelectCommand(ADP.Fill); } @@ -607,7 +607,7 @@ protected virtual int Fill(DataTable[] dataTables, int startRecord, int maxRecor private int FillInternal(DataSet? dataset, DataTable[]? datatables, int startRecord, int maxRecords, string? srcTable, IDbCommand command, CommandBehavior behavior) { int rowsAddedToDataSet = 0; - bool restoreNullConnection = (null == command.Connection); + bool restoreNullConnection = (command.Connection is null); try { IDbConnection activeConnection = DbDataAdapter.GetConnection3(this, command, ADP.Fill); @@ -630,7 +630,7 @@ private int FillInternal(DataSet? dataset, DataTable[]? datatables, int startRec { dataReader = command.ExecuteReader(behavior); - if (null != datatables) + if (datatables is not null) { // delegate to next set of protected Fill methods rowsAddedToDataSet = Fill(datatables, dataReader, startRecord, maxRecords); } @@ -641,7 +641,7 @@ private int FillInternal(DataSet? dataset, DataTable[]? datatables, int startRec } finally { - if (null != dataReader) + if (dataReader is not null) { dataReader.Dispose(); } @@ -692,16 +692,16 @@ public override IDataParameter[] GetFillParameters() { IDataParameter[]? value = null; IDbCommand? select = _IDbDataAdapter.SelectCommand; - if (null != select) + if (select is not null) { IDataParameterCollection parameters = select.Parameters; - if (null != parameters) + if (parameters is not null) { value = new IDataParameter[parameters.Count]; parameters.CopyTo(value, 0); } } - if (null == value) + if (value is null) { value = Array.Empty(); } @@ -716,7 +716,7 @@ internal DataTableMapping GetTableMapping(DataTable dataTable) { tableMapping = TableMappings[index]; } - if (null == tableMapping) + if (tableMapping is null) { if (System.Data.MissingMappingAction.Error == MissingMappingAction) { @@ -750,13 +750,13 @@ private void ParameterInput(IDataParameterCollection parameters, StatementType t foreach (IDataParameter parameter in parameters) { - if ((null != parameter) && (0 != (ParameterDirection.Input & parameter.Direction))) + if ((parameter is not null) && (0 != (ParameterDirection.Input & parameter.Direction))) { string columnName = parameter.SourceColumn; if (!string.IsNullOrEmpty(columnName)) { DataColumn? dataColumn = mappings.GetDataColumn(columnName, null, row.Table, missingMapping, missingSchema); - if (null != dataColumn) + if (dataColumn is not null) { DataRowVersion version = DbDataAdapter.GetParameterSourceVersion(typeIndex, parameter); parameter.Value = row[dataColumn, version]; @@ -767,7 +767,7 @@ private void ParameterInput(IDataParameterCollection parameters, StatementType t } DbParameter? dbparameter = (parameter as DbParameter); - if ((null != dbparameter) && dbparameter.SourceColumnNullMapping) + if ((dbparameter is not null) && dbparameter.SourceColumnNullMapping) { Debug.Assert(DbType.Int32 == parameter.DbType, "unexpected DbType"); parameter.Value = ADP.IsNull(parameter.Value) ? s_parameterValueNullValue : s_parameterValueNonNullValue; @@ -782,14 +782,14 @@ private void ParameterOutput(IDataParameter parameter, DataRow row, DataTableMap if (0 != (ParameterDirection.Output & parameter.Direction)) { object? value = parameter.Value; - if (null != value) + if (value is not null) { // null means default, meaning we leave the current DataRow value alone string columnName = parameter.SourceColumn; if (!string.IsNullOrEmpty(columnName)) { DataColumn? dataColumn = mappings.GetDataColumn(columnName, null, row.Table, missingMapping, missingSchema); - if (null != dataColumn) + if (dataColumn is not null) { if (dataColumn.ReadOnly) { @@ -820,7 +820,7 @@ private void ParameterOutput(IDataParameterCollection parameters, DataRow row, D foreach (IDataParameter parameter in parameters) { - if (null != parameter) + if (parameter is not null) { ParameterOutput(parameter, row, mappings, missingMapping, missingSchema); } @@ -846,7 +846,7 @@ public int Update(DataRow[] dataRows) try { int rowsAffected = 0; - if (null == dataRows) + if (dataRows is null) { throw ADP.ArgumentNull(nameof(dataRows)); } @@ -855,16 +855,16 @@ public int Update(DataRow[] dataRows) DataTable? dataTable = null; for (int i = 0; i < dataRows.Length; ++i) { - if ((null != dataRows[i]) && (dataTable != dataRows[i].Table)) + if ((dataRows[i] is not null) && (dataTable != dataRows[i].Table)) { - if (null != dataTable) + if (dataTable is not null) { throw ADP.UpdateMismatchRowTable(i); } dataTable = dataRows[i].Table; } } - if (null != dataTable) + if (dataTable is not null) { DataTableMapping tableMapping = GetTableMapping(dataTable); rowsAffected = Update(dataRows, tableMapping); @@ -883,7 +883,7 @@ public int Update(DataTable dataTable) long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTable", ObjectID); try { - if (null == dataTable) + if (dataTable is null) { throw ADP.UpdateRequiresDataTable(nameof(dataTable)); } @@ -894,7 +894,7 @@ public int Update(DataTable dataTable) { tableMapping = TableMappings[index]; } - if (null == tableMapping) + if (tableMapping is null) { if (System.Data.MissingMappingAction.Error == MissingMappingAction) { @@ -915,7 +915,7 @@ public int Update(DataSet dataSet, string srcTable) long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, srcTable='{1}'", ObjectID, srcTable); try { - if (null == dataSet) + if (dataSet is null) { throw ADP.UpdateRequiresNonNullDataSet(nameof(dataSet)); } @@ -927,13 +927,13 @@ public int Update(DataSet dataSet, string srcTable) int rowsAffected = 0; DataTableMapping? tableMapping = GetTableMappingBySchemaAction(srcTable, srcTable, UpdateMappingAction); - Debug.Assert(null != tableMapping, "null TableMapping when MissingMappingAction.Error"); + Debug.Assert(tableMapping is not null, "null TableMapping when MissingMappingAction.Error"); // the ad-hoc scenario of no dataTable just returns // ad-hoc scenario is defined as MissingSchemaAction.Add or MissingSchemaAction.Ignore System.Data.MissingSchemaAction schemaAction = UpdateSchemaAction; DataTable? dataTable = tableMapping.GetDataTableBySchemaAction(dataSet, schemaAction); - if (null != dataTable) + if (dataTable is not null) { rowsAffected = UpdateFromDataTable(dataTable, tableMapping); } @@ -955,8 +955,8 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataRows[], tableMapping", ObjectID); try { - Debug.Assert((null != dataRows) && (0 < dataRows.Length), "Update: bad dataRows"); - Debug.Assert(null != tableMapping, "Update: bad DataTableMapping"); + Debug.Assert((dataRows is not null) && (0 < dataRows.Length), "Update: bad dataRows"); + Debug.Assert(tableMapping is not null, "Update: bad DataTableMapping"); // If records were affected, increment row count by one - that is number of rows affected in dataset. int cumulativeDataRowsAffected = 0; @@ -966,10 +966,10 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) bool useSelectConnectionState = false; IDbCommand? tmpcmd = _IDbDataAdapter.SelectCommand; - if (null != tmpcmd) + if (tmpcmd is not null) { connections[0] = tmpcmd.Connection; - if (null != connections[0]) + if (connections[0] is not null) { connectionStates[0] = connections[0]!.State; useSelectConnectionState = true; @@ -1002,7 +1002,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) // for each row which is either insert, update, or delete foreach (DataRow dataRow in dataRows) { - if (null == dataRow) + if (dataRow is null) { continue; // foreach DataRow } @@ -1041,7 +1041,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) try { dataRow.RowError = null; - if (null != dataCommand) + if (dataCommand is not null) { // prepare the parameters for the user who then can modify them during OnRowUpdating ParameterInput(dataCommand.Parameters, statementType, dataRow, tableMapping); @@ -1098,7 +1098,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) if (1 == maxBatchCommands) { - if (null != dataCommand) + if (dataCommand is not null) { batchCommands[0]._commandIdentifier = 0; batchCommands[0]._parameterCount = dataCommand.Parameters.Count; @@ -1115,7 +1115,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) try { - if (null != dataCommand) + if (dataCommand is not null) { if (0 == (UpdateRowSource.FirstReturnedRecord & dataCommand.UpdatedRowSource)) { @@ -1156,7 +1156,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) errors = e; } - if (null != errors) + if (errors is not null) { // TODO: See above comment on dataCommand being null rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand, StatementType.Batch, tableMapping); @@ -1205,7 +1205,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; } } - else if (null != dataCommand) + else if (dataCommand is not null) { IDbConnection connection = DbDataAdapter.GetConnection4(this, dataCommand, statementType, isCommandFromRowUpdating); ConnectionState state = UpdateConnectionOpen(connection, statementType, connections, connectionStates, useSelectConnectionState); @@ -1355,7 +1355,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCount, RowUpdatedEventArgs rowUpdatedEvent) { - Debug.Assert(rowUpdatedEvent.Rows != null); + Debug.Assert(rowUpdatedEvent.Rows is not null); try { // the batch execution may succeed, partially succeed and throw an exception (or not), or totally fail @@ -1393,7 +1393,7 @@ private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCou batchCommands[bc]._recordsAffected = rowAffected; } - if ((null == batchCommands[bc]._errors) && batchCommands[bc]._recordsAffected.HasValue) + if ((batchCommands[bc]._errors is null) && batchCommands[bc]._recordsAffected.HasValue) { // determine possible concurrency violations per datarow if ((StatementType.Update == statementType) || (StatementType.Delete == statementType)) @@ -1401,7 +1401,7 @@ private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCou checkRecordsAffected++; if (0 == rowAffected) { - if (null == rows) + if (rows is null) { rows = new List(); } @@ -1431,7 +1431,7 @@ private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCou } } - if (null == rowUpdatedEvent.Errors) + if (rowUpdatedEvent.Errors is null) { // Only error if RecordsAffect == 0, not -1. A value of -1 means no count was received from server, // do not error in that situation (means 'set nocount on' was executed on server). @@ -1440,8 +1440,8 @@ private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCou if ((0 < checkRecordsAffected) && ((0 == rowUpdatedEvent.RecordsAffected) || hasConcurrencyViolation)) { // bug50526, an exception if no records affected and attempted an Update/Delete - Debug.Assert(null == rowUpdatedEvent.Errors, "Continue - but contains an exception"); - DataRow[] rowsInError = (null != rows) ? rows.ToArray() : rowUpdatedEvent.Rows!; + Debug.Assert(rowUpdatedEvent.Errors is null, "Continue - but contains an exception"); + DataRow[] rowsInError = (rows is not null) ? rows.ToArray() : rowUpdatedEvent.Rows!; rowUpdatedEvent.Errors = ADP.UpdateConcurrencyViolation(StatementType.Batch, commandCount - rowsInError.Length, commandCount, rowsInError); rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; } @@ -1451,7 +1451,7 @@ private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCou private ConnectionState UpdateConnectionOpen(IDbConnection connection, StatementType statementType, IDbConnection?[] connections, ConnectionState[] connectionStates, bool useSelectConnectionState) { - Debug.Assert(null != connection, "unexpected null connection"); + Debug.Assert(connection is not null, "unexpected null connection"); int index = (int)statementType; if (connection != connections[index]) { @@ -1475,7 +1475,7 @@ private int UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMappi { int rowsAffected = 0; DataRow[] dataRows = ADP.SelectAdapterRows(dataTable, false); - if ((null != dataRows) && (0 < dataRows.Length)) + if ((dataRows is not null) && (0 < dataRows.Length)) { rowsAffected = Update(dataRows, tableMapping); } @@ -1484,8 +1484,8 @@ private int UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMappi private void UpdateRowExecute(RowUpdatedEventArgs rowUpdatedEvent, IDbCommand dataCommand, StatementType cmdIndex) { - Debug.Assert(null != rowUpdatedEvent, "null rowUpdatedEvent"); - Debug.Assert(null != dataCommand, "null dataCommand"); + Debug.Assert(rowUpdatedEvent is not null, "null rowUpdatedEvent"); + Debug.Assert(dataCommand is not null, "null dataCommand"); Debug.Assert(rowUpdatedEvent.Command == dataCommand, "dataCommand differs from rowUpdatedEvent"); bool insertAcceptChanges = true; @@ -1519,7 +1519,7 @@ private void UpdateRowExecute(RowUpdatedEventArgs rowUpdatedEvent, IDbCommand da { SchemaMapping mapping = new SchemaMapping(this, null, rowUpdatedEvent.Row.Table, readerHandler, false, SchemaType.Mapped, rowUpdatedEvent.TableMapping.SourceTable, true, null, null); - if ((null != mapping.DataTable) && (null != mapping.DataValues)) + if ((mapping.DataTable is not null) && (mapping.DataValues is not null)) { if (dataReader.Read()) { @@ -1572,7 +1572,7 @@ private void UpdateRowExecute(RowUpdatedEventArgs rowUpdatedEvent, IDbCommand da case StatementType.Delete: if (0 == rowUpdatedEvent.RecordsAffected) { - Debug.Assert(null == rowUpdatedEvent.Errors, "Continue - but contains an exception"); + Debug.Assert(rowUpdatedEvent.Errors is null, "Continue - but contains an exception"); rowUpdatedEvent.Errors = ADP.UpdateConcurrencyViolation(cmdIndex, rowUpdatedEvent.RecordsAffected, 1, new DataRow[] { rowUpdatedEvent.Row }); rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; } @@ -1584,7 +1584,7 @@ private void UpdateRowExecute(RowUpdatedEventArgs rowUpdatedEvent, IDbCommand da private int UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, int commandCount) { - Debug.Assert(null != rowUpdatedEvent, "null rowUpdatedEvent"); + Debug.Assert(rowUpdatedEvent is not null, "null rowUpdatedEvent"); int cumulativeDataRowsAffected = 0; switch (rowUpdatedEvent.Status) { @@ -1606,7 +1606,7 @@ private int UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandIn private int UpdatedRowStatusContinue(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, int commandCount) { - Debug.Assert(null != batchCommands, "null batchCommands?"); + Debug.Assert(batchCommands is not null, "null batchCommands?"); int cumulativeDataRowsAffected = 0; // 1. We delay accepting the changes until after we fire RowUpdatedEvent // so the user has a chance to call RejectChanges for any given reason @@ -1623,9 +1623,9 @@ private int UpdatedRowStatusContinue(RowUpdatedEventArgs rowUpdatedEvent, BatchC { var batchCommand = batchCommands[i]; DataRow row = batchCommand._row; - if ((null == batchCommand._errors) && batchCommand._recordsAffected != null && (0 != batchCommand._recordsAffected.Value)) + if ((batchCommand._errors is null) && batchCommand._recordsAffected is not null && (0 != batchCommand._recordsAffected.Value)) { - Debug.Assert(null != row, "null dataRow?"); + Debug.Assert(row is not null, "null dataRow?"); if (acdu) { if (0 != ((DataRowState.Added | DataRowState.Deleted | DataRowState.Modified) & row.RowState)) @@ -1641,9 +1641,9 @@ private int UpdatedRowStatusContinue(RowUpdatedEventArgs rowUpdatedEvent, BatchC private int UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, int commandCount) { - Debug.Assert(null != batchCommands, "null batchCommands?"); + Debug.Assert(batchCommands is not null, "null batchCommands?"); Exception? errors = rowUpdatedEvent.Errors; - if (null == errors) + if (errors is null) { // user changed status to ErrorsOccurred without supplying an exception message errors = ADP.RowUpdatedErrors(); @@ -1657,7 +1657,7 @@ private int UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCom for (int i = 0; i < commandCount; i++) { DataRow row = batchCommands[i]._row; - Debug.Assert(null != row, "null dataRow?"); + Debug.Assert(row is not null, "null dataRow?"); if (batchCommands[i]._errors is Exception commandErrors) { // will exist if 0 == RecordsAffected @@ -1693,14 +1693,14 @@ private int UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCom private int UpdatedRowStatusSkip(BatchCommandInfo[] batchCommands, int commandCount) { - Debug.Assert(null != batchCommands, "null batchCommands?"); + Debug.Assert(batchCommands is not null, "null batchCommands?"); int cumulativeDataRowsAffected = 0; for (int i = 0; i < commandCount; i++) { DataRow row = batchCommands[i]._row; - Debug.Assert(null != row, "null dataRow?"); + Debug.Assert(row is not null, "null dataRow?"); if (0 != ((DataRowState.Detached | DataRowState.Unchanged) & row.RowState)) { cumulativeDataRowsAffected++; @@ -1711,10 +1711,10 @@ private int UpdatedRowStatusSkip(BatchCommandInfo[] batchCommands, int commandCo private void UpdatingRowStatusErrors(RowUpdatingEventArgs rowUpdatedEvent, DataRow dataRow) { - Debug.Assert(null != dataRow, "null dataRow"); + Debug.Assert(dataRow is not null, "null dataRow"); Exception? errors = rowUpdatedEvent.Errors; - if (null == errors) + if (errors is null) { // user changed status to ErrorsOccurred without supplying an exception message errors = ADP.RowUpdatingErrors(); @@ -1732,24 +1732,24 @@ private void UpdatingRowStatusErrors(RowUpdatingEventArgs rowUpdatedEvent, DataR private static IDbConnection GetConnection1(DbDataAdapter adapter) { IDbCommand? command = adapter._IDbDataAdapter.SelectCommand; - if (null == command) + if (command is null) { command = adapter._IDbDataAdapter.InsertCommand; - if (null == command) + if (command is null) { command = adapter._IDbDataAdapter.UpdateCommand; - if (null == command) + if (command is null) { command = adapter._IDbDataAdapter.DeleteCommand; } } } IDbConnection? connection = null; - if (null != command) + if (command is not null) { connection = command.Connection; } - if (null == connection) + if (connection is null) { throw ADP.UpdateConnectionRequired(StatementType.Batch, false); } @@ -1758,10 +1758,10 @@ private static IDbConnection GetConnection1(DbDataAdapter adapter) private static IDbConnection GetConnection3(DbDataAdapter adapter, IDbCommand command, string method) { - Debug.Assert(null != command, "GetConnection3: null command"); + Debug.Assert(command is not null, "GetConnection3: null command"); Debug.Assert(!string.IsNullOrEmpty(method), "missing method name"); IDbConnection? connection = command.Connection; - if (null == connection) + if (connection is null) { throw ADP.ConnectionRequired_Res(method); } @@ -1770,9 +1770,9 @@ private static IDbConnection GetConnection3(DbDataAdapter adapter, IDbCommand co private static IDbConnection GetConnection4(DbDataAdapter adapter, IDbCommand command, StatementType statementType, bool isCommandFromRowUpdating) { - Debug.Assert(null != command, "GetConnection4: null command"); + Debug.Assert(command is not null, "GetConnection4: null command"); IDbConnection? connection = command.Connection; - if (null == connection) + if (connection is null) { throw ADP.UpdateConnectionRequired(statementType, isCommandFromRowUpdating); } @@ -1798,7 +1798,7 @@ private static void QuietClose(IDbConnection? connection, ConnectionState origin // close the connection if: // * it was closed on first use and adapter has opened it, AND // * provider's implementation did not ask to keep this connection open - if ((null != connection) && (ConnectionState.Closed == originalState)) + if ((connection is not null) && (ConnectionState.Closed == originalState)) { // we don't have to check the current connection state because // it is supposed to be safe to call Close multiple times @@ -1811,7 +1811,7 @@ private static void QuietClose(IDbConnection? connection, ConnectionState origin // where we would Open the connection and not close it private static void QuietOpen(IDbConnection connection, out ConnectionState originalState) { - Debug.Assert(null != connection, "QuietOpen: null connection"); + Debug.Assert(connection is not null, "QuietOpen: null connection"); originalState = connection.State; if (ConnectionState.Closed == originalState) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs index 2140301f49ca86..984e79f7562572 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs @@ -74,12 +74,12 @@ private static ReadOnlyCollection GetColumnSchemaCompatibility(DbDataR { var columnSchema = new List(); DataTable? schemaTable = reader.GetSchemaTable(); - if (schemaTable != null) + if (schemaTable is not null) { DataColumnCollection schemaTableColumns = schemaTable.Columns; foreach (DataRow row in schemaTable.Rows) { - Debug.Assert(row != null); + Debug.Assert(row is not null); columnSchema.Add(new DataRowDbColumn(row, schemaTableColumns)); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs index 35a5ae9099751a..6542aee9f0a573 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs @@ -20,7 +20,7 @@ public class DbEnumerator : IEnumerator // users must get enumerators off of the datareader interfaces public DbEnumerator(IDataReader reader) { - if (null == reader) + if (reader is null) { throw ADP.ArgumentNull(nameof(reader)); } @@ -29,7 +29,7 @@ public DbEnumerator(IDataReader reader) public DbEnumerator(IDataReader reader, bool closeReader) { - if (null == reader) + if (reader is null) { throw ADP.ArgumentNull(nameof(reader)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs index 2ad35f787cdeee..0e27ebf0182eeb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs @@ -43,7 +43,7 @@ internal ProviderRegistration(string factoryTypeAssemblyQualifiedName, DbProvide public static bool TryGetFactory(string providerInvariantName, [NotNullWhen(true)] out DbProviderFactory? factory) { factory = GetFactory(providerInvariantName, throwOnError: false); - return factory != null; + return factory is not null; } public static DbProviderFactory GetFactory(string providerInvariantName) @@ -56,7 +56,7 @@ public static DbProviderFactory GetFactory(DataRow providerRow) ADP.CheckArgumentNull(providerRow, nameof(providerRow)); DataColumn? assemblyQualifiedNameColumn = providerRow.Table.Columns[AssemblyQualifiedNameColumnName]; - if (null == assemblyQualifiedNameColumn) + if (assemblyQualifiedNameColumn is null) { throw ADP.Argument(SR.ADP_DbProviderFactories_NoAssemblyQualifiedName); } @@ -152,7 +152,7 @@ public static bool UnregisterFactory(string providerInvariantName) return throwOnError ? throw ADP.Argument(SR.Format(SR.ADP_DbProviderFactories_InvariantNameNotFound, providerInvariantName)) : (DbProviderFactory?)null; } DbProviderFactory? toReturn = registration.FactoryInstance; - if (toReturn == null) + if (toReturn is null) { // Deferred registration, do checks now on the type specified and register instance in storage. // Even in the case of throwOnError being false, this will throw when an exception occurs checking the registered type as the user has to be notified the @@ -172,7 +172,7 @@ private static DbProviderFactory GetFactoryInstance(Type providerFactoryClass) } FieldInfo? providerInstance = providerFactoryClass.GetField(InstanceFieldName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static); - if (null == providerInstance) + if (providerInstance is null) { throw ADP.InvalidOperation(SR.ADP_DbProviderFactories_NoInstance); } @@ -181,7 +181,7 @@ private static DbProviderFactory GetFactoryInstance(Type providerFactoryClass) throw ADP.InvalidOperation(SR.ADP_DbProviderFactories_NoInstance); } object? factory = providerInstance.GetValue(null); - if (null == factory) + if (factory is null) { throw ADP.InvalidOperation(SR.ADP_DbProviderFactories_NoInstance); } @@ -192,7 +192,7 @@ private static DbProviderFactory GetFactoryInstance(Type providerFactoryClass) private static Type GetProviderTypeFromTypeName(string assemblyQualifiedName) { Type? providerType = Type.GetType(assemblyQualifiedName); - if (null == providerType) + if (providerType is null) { throw ADP.Argument(SR.Format(SR.ADP_DbProviderFactories_FactoryNotLoadable, assemblyQualifiedName)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs index 70ad0e96c6b92f..c6bcc3533e5b9b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs @@ -20,7 +20,7 @@ public virtual bool CanCreateDataAdapter { using (DbDataAdapter? adapter = CreateDataAdapter()) { - _canCreateDataAdapter = adapter != null; + _canCreateDataAdapter = adapter is not null; } } @@ -36,7 +36,7 @@ public virtual bool CanCreateCommandBuilder { using (DbCommandBuilder? builder = CreateCommandBuilder()) { - _canCreateCommandBuilder = builder != null; + _canCreateCommandBuilder = builder is not null; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs index a102ae412be95b..455fc94cc2b907 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs @@ -169,7 +169,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -188,7 +188,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToDecimal(FormatProvider); } @@ -213,7 +213,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = DefaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs index e27658bfbf9d10..f939e947124267 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs @@ -164,7 +164,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -187,7 +187,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToDouble(FormatProvider); } @@ -217,7 +217,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs b/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs index ddca3b7839ae78..cc87fbf37b8ca4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs @@ -28,7 +28,7 @@ public FieldNameLookup(IDataRecord reader, int defaultLocaleID) for (int i = 0; i < length; ++i) { fieldNames[i] = reader.GetName(i); - Debug.Assert(null != fieldNames[i]); + Debug.Assert(fieldNames[i] is not null); } _fieldNames = fieldNames; _defaultLocaleID = defaultLocaleID; @@ -36,7 +36,7 @@ public FieldNameLookup(IDataRecord reader, int defaultLocaleID) public int GetOrdinal(string fieldName) { - if (null == fieldName) + if (fieldName is null) { throw ADP.ArgumentNull(nameof(fieldName)); } @@ -56,7 +56,7 @@ public int IndexOf(string fieldName) } int index; object? value = _fieldNameLookup![fieldName]; - if (null != value) + if (value is not null) { // via case sensitive search, first match with lowest ordinal matches index = (int)value; @@ -77,13 +77,13 @@ public int IndexOf(string fieldName) private int LinearIndexOf(string fieldName, CompareOptions compareOptions) { CompareInfo? compareInfo = _compareInfo; - if (null == compareInfo) + if (compareInfo is null) { if (-1 != _defaultLocaleID) { compareInfo = CompareInfo.GetCompareInfo(_defaultLocaleID); } - if (null == compareInfo) + if (compareInfo is null) { compareInfo = CultureInfo.InvariantCulture.CompareInfo; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs index ba44cf199a8293..2b56ac5e3f93b7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs @@ -181,7 +181,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -201,7 +201,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToInt16(FormatProvider); } @@ -231,7 +231,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs index 015d46bf7bc249..1497c25b6b7273 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs @@ -180,7 +180,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -200,7 +200,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToInt32(FormatProvider); } @@ -230,7 +230,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs index 2a6dbc03caf36d..68651d17d5cb49 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs @@ -172,7 +172,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -192,7 +192,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToInt64(FormatProvider); } @@ -222,7 +222,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/NameValuePermission.cs b/src/libraries/System.Data.Common/src/System/Data/Common/NameValuePermission.cs index 82ee297e75794c..3bda7864f2bdc5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/NameValuePermission.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/NameValuePermission.cs @@ -46,7 +46,7 @@ // NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[]); // for (int i = 0; i < tree.Length; ++i) // { -// if (null != tree[i]) +// if (tree is not null[i]) // { // tree[i] = tree[i].CopyNameValue(); // deep copy // } @@ -62,16 +62,16 @@ // internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBConnectionString entry) // { -// Debug.Assert(null != entry, "null DBConnectionString"); +// Debug.Assert(entry is not null, "null DBConnectionString"); -// if (null != entry.KeyChain) +// if (entry is not null.KeyChain) // { -// for (NameValuePair keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) +// for (NameValuePair keychain = entry.KeyChain; keychain is not null; keychain = keychain.Next) // { // NameValuePermission kv; // kv = kvtree.CheckKeyForValue(keychain.Name); -// if (null == kv) +// if (kv is null) // { // kv = new NameValuePermission(keychain.Name); // kvtree.Add(kv); // add directly into live tree @@ -79,19 +79,19 @@ // kvtree = kv; // kv = kvtree.CheckKeyForValue(keychain.Value); -// if (null == kv) +// if (kv is null) // { -// DBConnectionString insertValue = ((null != keychain.Next) ? null : entry); +// DBConnectionString insertValue = ((keychain is not null.Next) ? null : entry); // kv = new NameValuePermission(keychain.Value, insertValue); // kvtree.Add(kv); // add directly into live tree -// if (null != insertValue) +// if (insertValue is not null) // { // entries.Add(insertValue); // } // } -// else if (null == keychain.Next) +// else if (keychain is null.Next) // { // shorter chain potential -// if (null != kv._entry) +// if (kv is not null._entry) // { // Debug.Assert(entries.Contains(kv._entry), "entries doesn't contain entry"); // entries.Remove(kv._entry); @@ -110,7 +110,7 @@ // { // // global restrictions // DBConnectionString kentry = kvtree._entry; -// if (null != kentry) +// if (kentry is not null) // { // Debug.Assert(entries.Contains(kentry), "entries doesn't contain entry"); // entries.Remove(kentry); @@ -126,7 +126,7 @@ // internal void Intersect(ArrayList entries, NameValuePermission target) // { -// if (null == target) +// if (target is null) // { // _tree = null; // _entry = null; @@ -139,7 +139,7 @@ // _entry = _entry.Intersect(target._entry); // entries.Add(_entry); // } -// else if (null != target._entry) +// else if (target is not null._entry) // { // _entry = target._entry.Intersect(null); // entries.Add(_entry); @@ -151,7 +151,7 @@ // for (int i = 0; i < _tree.Length; ++i) // { // NameValuePermission kvtree = target.CheckKeyForValue(_tree[i]._value); -// if (null != kvtree) +// if (kvtree is not null) // { // does target tree contain our value // _tree[i].Intersect(entries, kvtree); // } @@ -184,7 +184,7 @@ // private void Add(NameValuePermission permit) // { // NameValuePermission[] tree = _tree; -// int length = ((null != tree) ? tree.Length : 0); +// int length = ((tree is not null) ? tree.Length : 0); // NameValuePermission[] newtree = new NameValuePermission[1 + length]; // for (int i = 0; i < newtree.Length - 1; ++i) // { @@ -197,13 +197,13 @@ // internal bool CheckValueForKeyPermit(DBConnectionString parsetable) // { -// if (null == parsetable) +// if (parsetable is null) // { // return false; // } // bool hasMatch = false; // NameValuePermission[] keytree = _tree; // _tree won't mutate but Add will replace it -// if (null != keytree) +// if (keytree is not null) // { // hasMatch = parsetable.IsEmpty; // if (!hasMatch) @@ -212,11 +212,11 @@ // for (int i = 0; i < keytree.Length; ++i) // { // NameValuePermission permitKey = keytree[i]; -// if (null != permitKey) +// if (permitKey is not null) // { // string keyword = permitKey._value; //#if DEBUG -// Debug.Assert(null == permitKey._entry, "key member has no restrictions"); +// Debug.Assert(permitKey is null._entry, "key member has no restrictions"); //#endif // if (parsetable.ContainsKey(keyword)) // { @@ -224,7 +224,7 @@ // // keyword is restricted to certain values // NameValuePermission permitValue = permitKey.CheckKeyForValue(valueInQuestion); -// if (null != permitValue) +// if (permitValue is not null) // { // //value does match - continue the chain down that branch // if (permitValue.CheckValueForKeyPermit(parsetable)) @@ -253,7 +253,7 @@ // } // DBConnectionString entry = _entry; -// if (null != entry) +// if (entry is not null) // { // // also checking !hasMatch is tempting, but wrong // // user can safetly extend their restrictions for current rule to include missing keyword @@ -268,7 +268,7 @@ // private NameValuePermission CheckKeyForValue(string keyInQuestion) // { // NameValuePermission[] valuetree = _tree; // _tree won't mutate but Add will replace it -// if (null != valuetree) +// if (valuetree is not null) // { // for (int i = 0; i < valuetree.Length; ++i) // { 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 6c2c947aa0156d..6305b93fd1cddf 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 @@ -37,13 +37,13 @@ public override int Compare(int recordNo1, int recordNo2) if (valueNo1 == valueNo2) return 0; - if (valueNo1 == null) + if (valueNo1 is null) return -1; - if (valueNo2 == null) + if (valueNo2 is null) return 1; IComparable? icomparable = (valueNo1 as IComparable); - if (null != icomparable) + if (icomparable is not null) { try { @@ -70,7 +70,7 @@ public override int CompareValueTo(int recordNo1, object? value) if (valueNo1 == value) return 0; - if (valueNo1 == null) + if (valueNo1 is null) { if (_nullValue == value) { @@ -78,7 +78,7 @@ public override int CompareValueTo(int recordNo1, object? value) } return -1; } - if ((_nullValue == value) || (null == value)) + if ((_nullValue == value) || (value is null)) { return 1; } @@ -89,9 +89,9 @@ public override int CompareValueTo(int recordNo1, object? value) private int CompareTo(object? valueNo1, object? valueNo2) { - if (valueNo1 == null) + if (valueNo1 is null) return -1; - if (valueNo2 == null) + if (valueNo2 is null) return 1; if (valueNo1 == valueNo2) return 0; @@ -175,7 +175,7 @@ public override void Copy(int recordNo1, int recordNo2) public override object Get(int recordNo) { object? value = _values[recordNo]; - if (null != value) + if (value is not null) { return value; } @@ -224,7 +224,7 @@ public override bool IsNull(int record) public override void Set(int recordNo, object value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[recordNo] = null; @@ -297,7 +297,7 @@ public override void Set(int recordNo, object value) public override void SetCapacity(int capacity) { object[] newValues = new object[capacity]; - if (_values != null) + if (_values is not null) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } @@ -352,14 +352,14 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute bool isBaseCLRType = false; bool legacyUDT = false; // in 1.0 and 1.1 we used to call ToString on CDT obj. so if we have the same case // we need to handle the case when we have column type as object. - if (null == xmlAttrib) + if (xmlAttrib is null) { // this means type implements IXmlSerializable Type? type = null; string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); - if (typeName == null || typeName.Length == 0) + if (typeName is null || typeName.Length == 0) { // No CDT polumorphism string? xsdTypeName = xmlReader.GetAttribute(Keywords.TYPE, Keywords.XSINS); // this xsd type: Base type polymorphism - if (null != xsdTypeName && xsdTypeName.Length > 0) + if (xsdTypeName is not null && xsdTypeName.Length > 0) { string[] _typename = xsdTypeName.Split(':'); if (_typename.Length == 2) @@ -391,9 +391,9 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute } else { - if (null == type) + if (type is null) { - type = (typeName == null) ? _dataType : DataStorage.GetType(typeName); + type = (typeName is null) ? _dataType : DataStorage.GetType(typeName); } if (type == typeof(char) || type == typeof(Guid)) @@ -446,7 +446,7 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute public override string ConvertObjectToXml(object value) { - if ((value == null) || (value == _nullValue))// this case won't happen, this is added in case if code in xml saver changes + if ((value is null) || (value == _nullValue))// this case won't happen, this is added in case if code in xml saver changes return string.Empty; Type type = _dataType; @@ -486,7 +486,7 @@ public override string ConvertObjectToXml(object value) public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { - if (null == xmlAttrib) + if (xmlAttrib is null) { // implements IXmlSerializable Debug.Assert(xmlWriter is DataTextWriter, "Invalid DataTextWriter is being passed to customer"); ((IXmlSerializable)value).WriteXml(xmlWriter); @@ -569,19 +569,19 @@ internal static XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute attri // _tempAssemblyCache is a readonly instance, lock on write to copy & add then replace the original instance. Dictionary, XmlSerializer>? cache = s_tempAssemblyCache; - if ((null == cache) || !cache.TryGetValue(key, out serializer)) + if ((cache is null) || !cache.TryGetValue(key, out serializer)) { // not in cache, try again with lock because it may need to grow lock (s_tempAssemblyCacheLock) { cache = s_tempAssemblyCache; - if ((null == cache) || !cache.TryGetValue(key, out serializer)) + if ((cache is null) || !cache.TryGetValue(key, out serializer)) { // prevent writing an instance which implements IDynamicMetaObjectProvider and not IXmlSerializable // the check here prevents the instance data from being written VerifyIDynamicMetaObjectProvider(type); // if still not in cache, make cache larger and add new XmlSerializer - if (null != cache) + if (cache is not null) { // create larger cache, because dictionary is not reader/writer safe // copy cache so that all readers don't take lock - only potential new writers // same logic used by DbConnectionFactory @@ -626,8 +626,8 @@ private TempAssemblyComparer() { } public bool Equals(KeyValuePair x, KeyValuePair y) { return ((x.Key == y.Key) && // same type - (((x.Value == null) && (y.Value == null)) || // XmlRootAttribute both null - ((x.Value != null) && (y.Value != null) && // XmlRootAttribute both with value + (((x.Value is null) && (y.Value is null)) || // XmlRootAttribute both null + ((x.Value is not null) && (y.Value is not null) && // XmlRootAttribute both with value (x.Value.ElementName == y.Value.ElementName) && // all attribute elements are equal (x.Value.Namespace == y.Value.Namespace) && (x.Value.DataType == y.Value.DataType) && diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs index 261a68ad56cc54..b050c41bd41787 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs @@ -88,7 +88,7 @@ public int RowCount get { DataRow[]? dataRows = _dataRows; - return ((null != dataRows) ? dataRows.Length : ((null != _dataRow) ? 1 : 0)); + return ((dataRows is not null) ? dataRows.Length : ((null != _dataRow) ? 1 : 0)); } } @@ -135,7 +135,7 @@ internal void AdapterInit(DataRow[] dataRows) _statementType = StatementType.Batch; _dataRows = dataRows; - if ((null != dataRows) && (1 == dataRows.Length)) + if ((dataRows is not null) && (1 == dataRows.Length)) { _dataRow = dataRows[0]; } @@ -154,13 +154,13 @@ public void CopyToRows(DataRow[] array) public void CopyToRows(DataRow[] array, int arrayIndex) { DataRow[]? dataRows = _dataRows; - if (null != dataRows) + if (dataRows is not null) { dataRows.CopyTo(array, arrayIndex); } else { - if (null == array) + if (array is null) { throw ADP.ArgumentNull(nameof(array)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs index b6ddd9fad0be56..4169a03d69dc32 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs @@ -165,7 +165,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -189,7 +189,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToSByte(FormatProvider); } @@ -219,7 +219,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs index b01eeb5f9bcb66..606a015a344a57 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs @@ -11,7 +11,7 @@ internal static class SqlConvert { public static SqlByte ConvertToSqlByte(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlByte"); + Debug.Assert(value is not null, "null argument in ConvertToSqlByte"); if ((value == DBNull.Value)) { // null is not valid, SqlByte is struct return SqlByte.Null; @@ -29,7 +29,7 @@ public static SqlByte ConvertToSqlByte(object value) public static SqlInt16 ConvertToSqlInt16(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlInt16"); + Debug.Assert(value is not null, "null argument in ConvertToSqlInt16"); if (value == DBNull.Value) { return SqlInt16.Null; @@ -48,7 +48,7 @@ public static SqlInt16 ConvertToSqlInt16(object value) public static SqlInt32 ConvertToSqlInt32(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlInt32"); + Debug.Assert(value is not null, "null argument in ConvertToSqlInt32"); if (value == DBNull.Value) { return SqlInt32.Null; @@ -71,7 +71,7 @@ public static SqlInt32 ConvertToSqlInt32(object value) public static SqlInt64 ConvertToSqlInt64(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlInt64"); + Debug.Assert(value is not null, "null argument in ConvertToSqlInt64"); if (value == DBNull.Value) { return SqlInt32.Null; @@ -96,7 +96,7 @@ public static SqlInt64 ConvertToSqlInt64(object value) public static SqlDouble ConvertToSqlDouble(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlDouble"); + Debug.Assert(value is not null, "null argument in ConvertToSqlDouble"); if (value == DBNull.Value) { return SqlDouble.Null; @@ -129,7 +129,7 @@ public static SqlDouble ConvertToSqlDouble(object value) public static SqlDecimal ConvertToSqlDecimal(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlDecimal"); + Debug.Assert(value is not null, "null argument in ConvertToSqlDecimal"); if (value == DBNull.Value) { return SqlDecimal.Null; @@ -159,7 +159,7 @@ public static SqlDecimal ConvertToSqlDecimal(object value) public static SqlSingle ConvertToSqlSingle(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlSingle"); + Debug.Assert(value is not null, "null argument in ConvertToSqlSingle"); if (value == DBNull.Value) { return SqlSingle.Null; @@ -190,7 +190,7 @@ public static SqlSingle ConvertToSqlSingle(object value) public static SqlMoney ConvertToSqlMoney(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlMoney"); + Debug.Assert(value is not null, "null argument in ConvertToSqlMoney"); if (value == DBNull.Value) { return SqlMoney.Null; @@ -220,7 +220,7 @@ public static SqlMoney ConvertToSqlMoney(object value) public static SqlDateTime ConvertToSqlDateTime(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlDateTime"); + Debug.Assert(value is not null, "null argument in ConvertToSqlDateTime"); if (value == DBNull.Value) { return SqlDateTime.Null; @@ -238,8 +238,8 @@ public static SqlDateTime ConvertToSqlDateTime(object value) public static SqlBoolean ConvertToSqlBoolean(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlBoolean"); - if ((value == DBNull.Value) || (value == null)) + Debug.Assert(value is not null, "null argument in ConvertToSqlBoolean"); + if ((value == DBNull.Value) || (value is null)) { return SqlBoolean.Null; } @@ -256,7 +256,7 @@ public static SqlBoolean ConvertToSqlBoolean(object value) public static SqlGuid ConvertToSqlGuid(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlGuid"); + Debug.Assert(value is not null, "null argument in ConvertToSqlGuid"); if (value == DBNull.Value) { return SqlGuid.Null; @@ -274,7 +274,7 @@ public static SqlGuid ConvertToSqlGuid(object value) public static SqlBinary ConvertToSqlBinary(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlBinary"); + Debug.Assert(value is not null, "null argument in ConvertToSqlBinary"); if (value == DBNull.Value) { return SqlBinary.Null; @@ -292,8 +292,8 @@ public static SqlBinary ConvertToSqlBinary(object value) public static SqlString ConvertToSqlString(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlString"); - if ((value == DBNull.Value) || (value == null)) + Debug.Assert(value is not null, "null argument in ConvertToSqlString"); + if ((value == DBNull.Value) || (value is null)) { return SqlString.Null; } @@ -310,7 +310,7 @@ public static SqlString ConvertToSqlString(object value) public static SqlChars ConvertToSqlChars(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlChars"); + Debug.Assert(value is not null, "null argument in ConvertToSqlChars"); if (value == DBNull.Value) { return SqlChars.Null; @@ -326,7 +326,7 @@ public static SqlChars ConvertToSqlChars(object value) public static SqlBytes ConvertToSqlBytes(object value) { - Debug.Assert(value != null, "null argument in ConvertToSqlBytes"); + Debug.Assert(value is not null, "null argument in ConvertToSqlBytes"); if (value == DBNull.Value) { return SqlBytes.Null; @@ -349,7 +349,7 @@ public static object ChangeTypeForDefaultValue(object value, Type type, IFormatP { if (type == typeof(System.Numerics.BigInteger)) { - if ((DBNull.Value == value) || (null == value)) { return DBNull.Value; } + if ((DBNull.Value == value) || (value is null)) { return DBNull.Value; } return BigIntegerStorage.ConvertToBigInteger(value, formatProvider); } else if (value is System.Numerics.BigInteger) @@ -402,7 +402,7 @@ public static object ChangeType2(object value, StorageType stype, Type type, IFo goto default; */ default: // destination is CLR - if ((DBNull.Value == value) || (null == value)) + if ((DBNull.Value == value) || (value is null)) { return DBNull.Value; } @@ -475,13 +475,13 @@ public static object ChangeType2(object value, StorageType stype, Type type, IFo break; default: IConvertible? iconvertible = (value as IConvertible); - if (null != iconvertible) + if (iconvertible is not null) { return iconvertible.ToString(formatProvider); } // catch additional classes like Guid IFormattable? iformattable = (value as IFormattable); - if (null != iformattable) + if (iformattable is not null) { return iformattable.ToString(null, formatProvider); } @@ -646,7 +646,7 @@ public static object ChangeTypeForXML(object value, Type type) }; default: { - if ((DBNull.Value == value) || (null == value)) + if ((DBNull.Value == value) || (value is null)) { return DBNull.Value; } @@ -723,13 +723,13 @@ public static object ChangeTypeForXML(object value, Type type) return XmlConvert.ToString((DateTimeOffset)value); default: IConvertible? iconvertible = (value as IConvertible); - if (null != iconvertible) + if (iconvertible is not null) { return iconvertible.ToString(System.Globalization.CultureInfo.InvariantCulture); } // catch additional classes like Guid IFormattable? iformattable = (value as IFormattable); - if (null != iformattable) + if (iformattable is not null) { return iformattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs index ce27245f79a9ac..084856e3cc9ed6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs @@ -55,13 +55,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlBinary)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlBinary(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs index 8b15f077390323..6e32dec8bf5cc4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs @@ -164,13 +164,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlByte)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlByte(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs index 76ba3946f7a98f..b4f1cf477044d6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs @@ -76,7 +76,7 @@ public override bool IsNull(int record) public override void Set(int record, object value) { - if ((value == DBNull.Value) || (value == null)) + if ((value == DBNull.Value) || (value is null)) { _values[record] = SqlBytes.Null; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs index 74dc0329170eb7..43bc93da2ca117 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs @@ -78,7 +78,7 @@ public override bool IsNull(int record) public override void Set(int record, object value) { - if ((value == DBNull.Value) || (value == null)) + if ((value == DBNull.Value) || (value is null)) { _values[record] = SqlChars.Null; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs index e36e4e03a3ae19..bceb8fdfe17950 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs @@ -91,13 +91,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlDateTime)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlDateTime(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs index 9245967133ec62..2a3ab7c228d81e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs @@ -163,13 +163,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlDecimal)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlDecimal(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs index df041e67744253..206ef7f0631b0f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs @@ -164,13 +164,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlDouble)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlDouble(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs index bb91efab77c675..8a377c36fbc604 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs @@ -56,13 +56,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlGuid)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlGuid(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs index 17f1aac7213ca7..cd1bdb5bee5463 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs @@ -164,13 +164,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlInt16)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlInt16(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs index dd48d0237f2f12..bedd9620589b12 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs @@ -164,13 +164,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlInt32)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlInt32(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs index e469f3218b5b1c..19a7ff1c497b70 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs @@ -165,13 +165,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlInt64)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlInt64(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs index a036989e6d8465..00869c40bb8505 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs @@ -164,13 +164,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlMoney)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlMoney(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs index 7a492b26382059..3f09d9bebb766e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs @@ -162,13 +162,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlSingle)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlSingle(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs index 7e8094c93610c8..d4a6fe3404adf4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs @@ -111,13 +111,13 @@ public int Compare(SqlString valueNo1, SqlString valueNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return Compare(_values[recordNo], (SqlString)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlString(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs index 4bfadc6eb08571..94662dbaa47cbc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs @@ -89,13 +89,13 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); return _values[recordNo].CompareTo((SqlBoolean)value); } public override object ConvertValue(object? value) { - if (null != value) + if (value is not null) { return SqlConvert.ConvertToSqlBoolean(value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs index 3b10386f663dca..6e78760b9d101d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs @@ -165,7 +165,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -188,7 +188,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToSingle(FormatProvider); } @@ -218,7 +218,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs index 1743d3f667a0ea..e7cdba15ce44c4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs @@ -38,13 +38,13 @@ internal static object GetStaticNullForUdtType(Type type) => s_typeToNull.GetOrA { // TODO: Is it OK for the null value of a UDT to be null? For now annotating is non-nullable. PropertyInfo? propInfo = type.GetProperty("Null", BindingFlags.Public | BindingFlags.Static); - if (propInfo != null) + if (propInfo is not null) { return propInfo.GetValue(null, null)!; } FieldInfo fieldInfo = type.GetField("Null", BindingFlags.Public | BindingFlags.Static)!; - if (fieldInfo != null) + if (fieldInfo is not null) { return fieldInfo.GetValue(null)!; } @@ -106,7 +106,7 @@ public override void Set(int recordNo, object value) _values[recordNo] = _nullValue; SetNullBit(recordNo, true); } - else if (null == value) + else if (value is null) { if (_isValueType) { @@ -133,7 +133,7 @@ public override void Set(int recordNo, object value) public override void SetCapacity(int capacity) { object[] newValues = new object[capacity]; - if (_values != null) + if (_values is not null) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } @@ -168,18 +168,18 @@ public override object ConvertXmlToObject(string s) [MethodImpl(MethodImplOptions.NoInlining)] public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) { - if (null == xmlAttrib) + if (xmlAttrib is null) { string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); - if (typeName == null) + if (typeName is null) { string? xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type - if (null != xsdTypeName) + if (xsdTypeName is not null) { typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName!; } } - Type type = (typeName == null) ? _dataType : Type.GetType(typeName)!; + Type type = (typeName is null) ? _dataType : Type.GetType(typeName)!; object Obj = System.Activator.CreateInstance(type, true)!; Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer"); ((IXmlSerializable)Obj).ReadXml(xmlReader); @@ -213,7 +213,7 @@ public override string ConvertObjectToXml(object value) public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { - if (null == xmlAttrib) + if (xmlAttrib is null) { Debug.Assert(xmlWriter is DataTextWriter, "Invalid DataTextWriter is being passed to customer"); ((IXmlSerializable)value).WriteXml(xmlWriter); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs index fa919b377e891e..cffca1ae1508e2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs @@ -72,7 +72,7 @@ public override object Aggregate(int[] recordNos, AggregateType kind) for (i = 0; i < recordNos.Length; i++) { object? value = _values[recordNos[i]]; - if (value != null) + if (value is not null) count++; } return count; @@ -88,9 +88,9 @@ public override int Compare(int recordNo1, int recordNo2) if (valueNo1 == (object?)valueNo2) return 0; - if (valueNo1 == null) + if (valueNo1 is null) return -1; - if (valueNo2 == null) + if (valueNo2 is null) return 1; return _table.Compare(valueNo1, valueNo2); @@ -99,10 +99,10 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(recordNo != -1, "Invalid (-1) parameter: 'recordNo'"); - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); string? valueNo1 = _values[recordNo]; - if (null == valueNo1) + if (valueNo1 is null) { if (_nullValue == value) { @@ -124,7 +124,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = value.ToString()!; } @@ -145,7 +145,7 @@ public override object Get(int recordNo) { string? value = _values[recordNo]; - if (null != value) + if (value is not null) { return value; } @@ -155,7 +155,7 @@ public override object Get(int recordNo) public override int GetStringLength(int record) { string? value = _values[record]; - return ((null != value) ? value.Length : 0); + return ((value is not null) ? value.Length : 0); } public override bool IsNull(int record) @@ -165,7 +165,7 @@ public override bool IsNull(int record) public override void Set(int record, object value) { - Debug.Assert(null != value, "null value"); + Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = null; @@ -179,7 +179,7 @@ public override void Set(int record, object value) public override void SetCapacity(int capacity) { string[] newValues = new string[capacity]; - if (_values != null) + if (_values is not null) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs index 5ce9037b61bef6..f70b4ae7988290 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs @@ -160,7 +160,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -206,7 +206,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ConvertToTimeSpan(value); } @@ -237,7 +237,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = s_defaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs index 25d3b7c80d814d..946c3f75da4e44 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs @@ -180,7 +180,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -200,7 +200,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToUInt16(FormatProvider); } @@ -230,7 +230,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = DefaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs index b801841aa1e0fd..350630f048e557 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs @@ -179,7 +179,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -199,7 +199,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToUInt32(FormatProvider); } @@ -229,7 +229,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = DefaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs index 9dc67b24137cf6..b78fe16bf46b38 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs @@ -170,7 +170,7 @@ public override int Compare(int recordNo1, int recordNo2) public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { @@ -190,7 +190,7 @@ public override object ConvertValue(object? value) { if (_nullValue != value) { - if (null != value) + if (value is not null) { value = ((IConvertible)value).ToUInt64(FormatProvider); } @@ -220,7 +220,7 @@ public override object Get(int record) public override void Set(int record, object value) { - System.Diagnostics.Debug.Assert(null != value, "null value"); + System.Diagnostics.Debug.Assert(value is not null, "null value"); if (_nullValue == value) { _values[record] = DefaultValue; diff --git a/src/libraries/System.Data.Common/src/System/Data/Constraint.cs b/src/libraries/System.Data.Common/src/System/Data/Constraint.cs index 3667e104da9ba9..09736920d28aec 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Constraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Constraint.cs @@ -32,20 +32,20 @@ public virtual string ConstraintName get { return _name; } set { - if (value == null) + if (value is null) { value = string.Empty; } - if (string.IsNullOrEmpty(value) && (Table != null) && InCollection) + if (string.IsNullOrEmpty(value) && (Table is not null) && InCollection) { throw ExceptionBuilder.NoConstraintName(); } - CultureInfo locale = (Table != null ? Table.Locale : CultureInfo.CurrentCulture); + CultureInfo locale = (Table is not null ? Table.Locale : CultureInfo.CurrentCulture); if (string.Compare(_name, value, true, locale) != 0) { - if ((Table != null) && InCollection) + if ((Table is not null) && InCollection) { Table.Constraints.RegisterName(value); if (_name.Length != 0) diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs index a9d8ac3f1f0218..02890aba911337 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -29,7 +29,7 @@ public sealed class ConstraintCollection : InternalDataCollectionBase /// internal ConstraintCollection(DataTable table) { - Debug.Assert(table != null); + Debug.Assert(table is not null); _table = table; } @@ -83,7 +83,7 @@ public Constraint? this[string? name] // To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { - if (constraint == null) + if (constraint is null) { throw ExceptionBuilder.ArgumentNull(nameof(constraint)); } @@ -106,7 +106,7 @@ internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { if (((UniqueConstraint)constraint)._bPrimaryKey) { - if (Table._primaryKey != null) + if (Table._primaryKey is not null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } @@ -119,7 +119,7 @@ internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) if (addUniqueWhenAddingForeign) { UniqueConstraint? key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); - if (key == null) + if (key is null) { if (constraint.ConstraintName.Length == 0) constraint.ConstraintName = AssignName(); @@ -205,11 +205,11 @@ public void AddRange(Constraint[]? constraints) return; } - if (constraints != null) + if (constraints is not null) { foreach (Constraint constr in constraints) { - if (constr != null) + if (constr is not null) { Add(constr); } @@ -250,7 +250,7 @@ private void AddForeignKeyConstraint(ForeignKeyConstraint constraint) private bool AutoGenerated(Constraint constraint) { ForeignKeyConstraint? fk = (constraint as ForeignKeyConstraint); - if (null != fk) + if (fk is not null) { return XmlTreeGen.AutoGenerated(fk, false); } @@ -282,7 +282,7 @@ public event CollectionChangeEventHandler? CollectionChanged /// private void ArrayAdd(Constraint constraint) { - Debug.Assert(constraint != null, "Attempt to add null constraint to constraint array"); + Debug.Assert(constraint is not null, "Attempt to add null constraint to constraint array"); List.Add(constraint); } @@ -310,7 +310,7 @@ internal string AssignName() /// private void BaseAdd(Constraint constraint) { - if (constraint == null) + if (constraint is null) throw ExceptionBuilder.ArgumentNull(nameof(constraint)); if (constraint.ConstraintName.Length == 0) @@ -370,7 +370,7 @@ private void BaseGroupSwitch(Constraint[] oldArray, int oldLength, Constraint[] /// private void BaseRemove(Constraint constraint) { - if (constraint == null) + if (constraint is null) { throw ExceptionBuilder.ArgumentNull(nameof(constraint)); } @@ -434,7 +434,7 @@ public void Clear() _table.ChildRelations[i].SetParentKeyConstraint(null); } - if (_table.fInitInProgress && _delayLoadingConstraints != null) + if (_table.fInitInProgress && _delayLoadingConstraints is not null) { _delayLoadingConstraints = null; _fLoadForeignKeyConstraintsOnly = false; @@ -485,7 +485,7 @@ internal bool Contains(string? name, bool caseSensitive) public void CopyTo(Constraint[] array, int index) { - if (array == null) + if (array is null) throw ExceptionBuilder.ArgumentNull(nameof(array)); if (index < 0) throw ExceptionBuilder.ArgumentOutOfRange(nameof(index)); @@ -520,7 +520,7 @@ public void CopyTo(Constraint[] array, int index) for (int i = 0; i < constraintCount; i++) { UniqueConstraint? constraint = (List[i] as UniqueConstraint); - if ((null != constraint) && CompareArrays(constraint.Key.ColumnsReference, columns)) + if ((constraint is not null) && CompareArrays(constraint.Key.ColumnsReference, columns)) { return constraint; } @@ -537,7 +537,7 @@ public void CopyTo(Constraint[] array, int index) for (int i = 0; i < constraintCount; i++) { UniqueConstraint? constraint = (List[i] as UniqueConstraint); - if ((null != constraint) && (constraint.Key.ColumnsReference.Length == 1) && (constraint.Key.ColumnsReference[0] == column)) + if ((constraint is not null) && (constraint.Key.ColumnsReference.Length == 1) && (constraint.Key.ColumnsReference[0] == column)) return constraint; } return null; @@ -552,7 +552,7 @@ public void CopyTo(Constraint[] array, int index) for (int i = 0; i < constraintCount; i++) { ForeignKeyConstraint? constraint = (List[i] as ForeignKeyConstraint); - if ((null != constraint) && + if ((constraint is not null) && CompareArrays(constraint.ParentKey.ColumnsReference, parentColumns) && CompareArrays(constraint.ChildKey.ColumnsReference, childColumns)) return constraint; @@ -562,7 +562,7 @@ public void CopyTo(Constraint[] array, int index) private static bool CompareArrays(DataColumn[] a1, DataColumn[] a2) { - Debug.Assert(a1 != null && a2 != null, "Invalid Arguments"); + Debug.Assert(a1 is not null && a2 is not null, "Invalid Arguments"); if (a1.Length != a2.Length) return false; @@ -592,7 +592,7 @@ private static bool CompareArrays(DataColumn[] a1, DataColumn[] a2) /// public int IndexOf(Constraint? constraint) { - if (null != constraint) + if (constraint is not null) { int count = Count; for (int i = 0; i < count; ++i) @@ -621,7 +621,7 @@ public int IndexOf(string? constraintName) internal int InternalIndexOf(string? constraintName) { int cachedI = -1; - if ((null != constraintName) && (0 < constraintName.Length)) + if ((constraintName is not null) && (0 < constraintName.Length)) { int constraintCount = List.Count; int result = 0; @@ -666,7 +666,7 @@ private void OnCollectionChanged(CollectionChangeEventArgs ccevent) /// internal void RegisterName(string name) { - Debug.Assert(name != null); + Debug.Assert(name is not null); int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) @@ -687,7 +687,7 @@ internal void RegisterName(string name) /// public void Remove(Constraint constraint) { - if (constraint == null) + if (constraint is null) throw ExceptionBuilder.ArgumentNull(nameof(constraint)); // this will throw an exception if it can't be removed, otherwise indicates @@ -712,7 +712,7 @@ public void Remove(Constraint constraint) public void RemoveAt(int index) { Constraint c = this[index]; - if (c == null) + if (c is null) throw ExceptionBuilder.ConstraintOutOfRange(index); Remove(c); } @@ -723,7 +723,7 @@ public void RemoveAt(int index) public void Remove(string name) { Constraint? c = this[name]; - if (c == null) + if (c is null) throw ExceptionBuilder.ConstraintNotInTheTable(name); Remove(c); } @@ -747,7 +747,7 @@ internal void UnregisterName(string name) internal void FinishInitConstraints() { - if (_delayLoadingConstraints == null) + if (_delayLoadingConstraints is null) return; int colCount; @@ -760,7 +760,7 @@ internal void FinishInitConstraints() continue; UniqueConstraint constr = (UniqueConstraint)_delayLoadingConstraints[i]; - if (constr._columnNames == null) + if (constr._columnNames is null) { Add(constr); continue; @@ -771,7 +771,7 @@ internal void FinishInitConstraints() parents[j] = _table.Columns[constr._columnNames[j]]!; if (constr._bPrimaryKey) { - if (_table._primaryKey != null) + if (_table._primaryKey is not null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } @@ -782,21 +782,21 @@ internal void FinishInitConstraints() continue; } UniqueConstraint newConstraint = new UniqueConstraint(constr._constraintName, parents); - if (FindConstraint(newConstraint) == null) + if (FindConstraint(newConstraint) is null) Add(newConstraint); } else { ForeignKeyConstraint constr = (ForeignKeyConstraint)_delayLoadingConstraints[i]; - if (constr._parentColumnNames == null || constr._childColumnNames == null) + if (constr._parentColumnNames is null || constr._childColumnNames is null) { Add(constr); continue; } - Debug.Assert(constr._parentTableName != null); + Debug.Assert(constr._parentTableName is not null); - if (_table.DataSet == null) + if (_table.DataSet is null) { _fLoadForeignKeyConstraintsOnly = true; continue; @@ -807,7 +807,7 @@ internal void FinishInitConstraints() childs = new DataColumn[colCount]; for (int j = 0; j < colCount; j++) { - if (constr._parentTableNamespace == null) + if (constr._parentTableNamespace is null) parents[j] = _table.DataSet.Tables[constr._parentTableName]!.Columns[constr._parentColumnNames[j]]!; else parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace]!.Columns[constr._parentColumnNames[j]]!; diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs index 7a074f9d342f3b..877121cae9be47 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs @@ -29,7 +29,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -40,7 +40,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { UniqueConstraint constr = (UniqueConstraint)value; Reflection.ConstructorInfo ctor = typeof(UniqueConstraint).GetConstructor(new Type[] { typeof(string), typeof(string[]), typeof(bool) })!; - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { constr.ConstraintName, constr.ColumnNames, constr.IsPrimaryKey }); } @@ -51,7 +51,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul System.Reflection.ConstructorInfo ctor = typeof(ForeignKeyConstraint).GetConstructor(new Type[] { typeof(string), typeof(string), typeof(string[]), typeof(string[]), typeof(AcceptRejectRule), typeof(Rule), typeof(Rule) })!; - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { constr.ConstraintName, constr.ParentKey.Table.TableName, constr.ParentColumnNames, constr.ChildColumnNames, constr.AcceptRejectRule, constr.DeleteRule, constr.UpdateRule }); diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs index f296e4aee5fb37..3b4dd54eeaee17 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs @@ -17,7 +17,7 @@ internal class ConstraintEnumerator public ConstraintEnumerator(DataSet? dataSet) { - _tables = (dataSet != null) ? dataSet.Tables.GetEnumerator() : null; + _tables = (dataSet is not null) ? dataSet.Tables.GetEnumerator() : null; _currentObject = null; } @@ -25,9 +25,9 @@ public bool GetNext() { Constraint candidate; _currentObject = null; - while (_tables != null) + while (_tables is not null) { - if (_constraints == null) + if (_constraints is null) { if (!_tables.MoveNext()) { @@ -57,7 +57,7 @@ public bool GetNext() public Constraint GetConstraint() { // If currentObject is null we are before first GetNext or after last GetNext--consumer is bad - Debug.Assert(_currentObject != null, "GetObject should never be called w/ null currentObject."); + Debug.Assert(_currentObject is not null, "GetObject should never be called w/ null currentObject."); return _currentObject; } @@ -75,7 +75,7 @@ public ForeignKeyConstraintEnumerator(DataSet? dataSet) : base(dataSet) { } public ForeignKeyConstraint GetForeignKeyConstraint() { // If CurrentObject is null we are before first GetNext or after last GetNext--consumer is bad - Debug.Assert(CurrentObject != null, "GetObject should never be called w/ null currentObject."); + Debug.Assert(CurrentObject is not null, "GetObject should never be called w/ null currentObject."); return (ForeignKeyConstraint)CurrentObject; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs b/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs index 1fd430e5ca10c2..8da7caca4987dd 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs @@ -46,7 +46,7 @@ public DataRow? Row get { DataRow[]? rows = _dataRows; - return (((null != rows) && (0 < rows.Length)) ? rows[0] : null); + return (((rows is not null) && (0 < rows.Length)) ? rows[0] : null); } set { @@ -59,7 +59,7 @@ public int RowCount get { DataRow[]? dataRows = _dataRows; - return ((null != dataRows) ? dataRows.Length : 0); + return ((dataRows is not null) ? dataRows.Length : 0); } } @@ -71,7 +71,7 @@ public void CopyToRows(DataRow[] array) public void CopyToRows(DataRow[] array, int arrayIndex) { DataRow[]? dataRows = _dataRows; - if (null != dataRows) + if (dataRows is not null) { dataRows.CopyTo(array, arrayIndex); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs index eec4b1d090f54f..007752bdc40277 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -116,7 +116,7 @@ public DataColumn(string? columnName, Type dataType, string? expr, MappingType t GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" {0}, columnName='{1}', expr='{2}', type={3}", ObjectID, columnName, expr, type); - if (dataType == null) + if (dataType is null) { throw ExceptionBuilder.ArgumentNull(nameof(dataType)); } @@ -129,7 +129,7 @@ public DataColumn(string? columnName, Type dataType, string? expr, MappingType t _columnName = columnName ?? string.Empty; SimpleType? stype = SimpleType.CreateSimpleType(typeCode, dataType); - if (null != stype) + if (stype is not null) { SimpleType = stype; } @@ -185,7 +185,7 @@ public bool AllowDBNull { if (_allowNull != value) { - if (_table != null) + if (_table is not null) { if (!value && _table.EnforceConstraints) { @@ -218,7 +218,7 @@ public bool AutoIncrement { if (value) { - if (_expression != null) + if (_expression is not null) { throw ExceptionBuilder.AutoIncrementAndExpression(); } @@ -305,15 +305,15 @@ public long AutoIncrementStep [AllowNull] public string Caption { - get { return (_caption != null) ? _caption : _columnName; } + get { return (_caption is not null) ? _caption : _columnName; } set { - if (value == null) + if (value is null) { value = string.Empty; } - if (_caption == null || string.Compare(_caption, value, true, Locale) != 0) + if (_caption is null || string.Compare(_caption, value, true, Locale) != 0) { _caption = value; } @@ -326,7 +326,7 @@ public string Caption /// private void ResetCaption() { - if (_caption != null) + if (_caption is not null) { _caption = null; } @@ -335,7 +335,7 @@ private void ResetCaption() /// /// Gets a value indicating whether the has been explicitly set. /// - private bool ShouldSerializeCaption() => _caption != null; + private bool ShouldSerializeCaption() => _caption is not null; /// /// Gets or sets the name of the column within the . @@ -351,14 +351,14 @@ public string ColumnName long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, '{1}'", ObjectID, value); try { - if (value == null) + if (value is null) { value = string.Empty; } if (string.Compare(_columnName, value, true, Locale) != 0) { - if (_table != null) + if (_table is not null) { if (value.Length == 0) { @@ -375,7 +375,7 @@ public string ColumnName RaisePropertyChanging(nameof(ColumnName)); _columnName = value; _encodedColumnName = null; - if (_table != null) + if (_table is not null) { _table.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this)); } @@ -385,7 +385,7 @@ public string ColumnName RaisePropertyChanging(nameof(ColumnName)); _columnName = value; _encodedColumnName = null; - if (_table != null) + if (_table is not null) { _table.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this)); } @@ -402,7 +402,7 @@ internal string EncodedColumnName { get { - if (_encodedColumnName == null) + if (_encodedColumnName is null) { _encodedColumnName = XmlConvert.EncodeLocalName(ColumnName); } @@ -429,7 +429,7 @@ public string Prefix get { return _columnPrefix; } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -459,14 +459,14 @@ public string Prefix } string value = ConvertObjectToXml(objValue); - Debug.Assert(value != null); + Debug.Assert(value is not null); return value; } /// /// Whether this column computes values. /// - internal bool Computed => _expression != null; + internal bool Computed => _expression is not null; /// /// The internal expression object that computes the values. @@ -491,7 +491,7 @@ public Type DataType { throw ExceptionBuilder.CantChangeDataType(); } - if (value == null) + if (value is null) { throw ExceptionBuilder.NullDataType(); } @@ -500,11 +500,11 @@ public Type DataType { throw ExceptionBuilder.ColumnTypeNotSupported(); } - if (_table != null && IsInRelation()) + if (_table is not null && IsInRelation()) { throw ExceptionBuilder.ColumnsTypeMismatch(); } - if (typeCode == StorageType.BigInteger && _expression != null) + if (typeCode == StorageType.BigInteger && _expression is not null) { throw ExprException.UnsupportedDataType(value); } @@ -649,11 +649,11 @@ public object DefaultValue { get { - Debug.Assert(_defaultValue != null, "It should not have been set to null."); + Debug.Assert(_defaultValue is not null, "It should not have been set to null."); if (_defaultValue == DBNull.Value && _implementsINullable) { // for perf I dont access property - if (_storage != null) + if (_storage is not null) { _defaultValue = _storage._nullValue; } @@ -664,7 +664,7 @@ public object DefaultValue else if (_implementsINullable) { PropertyInfo propInfo = _dataType.GetProperty("Null", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)!; - if (propInfo != null) + if (propInfo is not null) { _defaultValue = propInfo.GetValue(null, null)!; } @@ -676,14 +676,14 @@ public object DefaultValue set { DataCommonEventSource.Log.Trace(" {0}", ObjectID); - if (_defaultValue == null || !DefaultValue.Equals(value)) + if (_defaultValue is null || !DefaultValue.Equals(value)) { if (AutoIncrement) { throw ExceptionBuilder.DefaultValueAndAutoIncrement(); } - object newDefaultValue = (value == null) ? DBNull.Value : value; + object newDefaultValue = (value is null) ? DBNull.Value : value; if (newDefaultValue != DBNull.Value && DataType != typeof(object)) { // If the DefualtValue is different from the Column DataType, we will coerce the value to the DataType @@ -715,12 +715,12 @@ public object DefaultValue [AllowNull] public string Expression { - get { return (_expression == null ? "" : _expression.Expression); } + get { return (_expression is null ? "" : _expression.Expression); } set { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, '{1}'", ObjectID, value); - if (value == null) + if (value is null) { value = string.Empty; } @@ -737,7 +737,7 @@ public string Expression } } - if (_expression == null && newExpression != null) + if (_expression is null && newExpression is not null) { if (AutoIncrement || Unique) { @@ -745,7 +745,7 @@ public string Expression } // We need to make sure the column is not involved in any Constriants - if (_table != null) + if (_table is not null) { for (int i = 0; i < _table.Constraints.Count; i++) { @@ -770,9 +770,9 @@ public string Expression } // re-calculate the evaluation queue - if (_table != null) + if (_table is not null) { - if (newExpression != null && newExpression.DependsOn(this)) + if (newExpression is not null && newExpression.DependsOn(this)) { throw ExceptionBuilder.ExpressionCircular(); } @@ -785,7 +785,7 @@ public string Expression // because the column is attached to a table we need to re-calc values try { - if (newExpression == null) + if (newExpression is null) { for (int i = 0; i < _table.RecordCapacity; i++) { @@ -808,7 +808,7 @@ public string Expression // in the case of error we need to set the column expression to the old value _expression = oldExpression; HandleDependentColumnList(newExpression, _expression); - if (oldExpression == null) + if (oldExpression is null) { for (int i = 0; i < _table.RecordCapacity; i++) { @@ -851,7 +851,7 @@ public string Expression /// /// Indicates whether this column is now storing data. /// - internal bool HasData => _storage != null; + internal bool HasData => _storage is not null; internal bool ImplementsINullable => _implementsINullable; @@ -890,7 +890,7 @@ internal bool IsValueType private void SetMaxLengthSimpleType() { - if (_simpleType != null) + if (_simpleType is not null) { Debug.Assert(_simpleType.CanHaveMaxLength(), "expected simpleType to be string"); @@ -904,7 +904,7 @@ private void SetMaxLengthSimpleType() else { // Named Simple Type's Name should not be null - if (_simpleType.Name != null && XmlDataType != null) + if (_simpleType.Name is not null && XmlDataType is not null) { // if MaxLength is changed, we need to make namedsimpletype annonymous simpletype _simpleType.ConvertToAnnonymousSimpleType(); @@ -963,9 +963,9 @@ public string Namespace { get { - if (_columnUri == null) + if (_columnUri is null) { - if (Table != null && _columnMapping != MappingType.Attribute) + if (Table is not null && _columnMapping != MappingType.Attribute) { return Table.Namespace; } @@ -992,7 +992,7 @@ public string Namespace } } - private bool ShouldSerializeNamespace() => _columnUri != null; + private bool ShouldSerializeNamespace() => _columnUri is not null; private void ResetNamespace() => Namespace = null; @@ -1024,7 +1024,7 @@ internal void SetOrdinalInternal(int ordinal) if (Unique && _ordinal != -1 && ordinal == -1) { UniqueConstraint? key = _table!.Constraints.FindKeyConstraint(this); - if (key != null) + if (key is not null) { _table.Constraints.Remove(key); } @@ -1064,7 +1064,7 @@ public bool ReadOnly DataCommonEventSource.Log.Trace(" {0}, {1}", ObjectID, value); if (_readOnly != value) { - if (!value && _expression != null) + if (!value && _expression is not null) { throw ExceptionBuilder.ReadOnlyAndExpression(); } @@ -1078,7 +1078,7 @@ private Index SortIndex { get { - if (_sortIndex == null) + if (_sortIndex is null) { var indexDesc = new IndexField[] { new IndexField(this, false) }; _sortIndex = _table!.GetIndex(indexDesc, DataViewRowState.CurrentRows, null); @@ -1100,22 +1100,22 @@ private Index SortIndex /// internal void SetTable(DataTable? table) { - Debug.Assert(table != null || !Unique); + Debug.Assert(table is not null || !Unique); if (_table != table) { if (Computed) { - if ((table == null) || (!table.fInitInProgress && ((table.DataSet == null) || (!table.DataSet._fIsSchemaLoading && !table.DataSet._fInitInProgress)))) + if ((table is null) || (!table.fInitInProgress && ((table.DataSet is null) || (!table.DataSet._fIsSchemaLoading && !table.DataSet._fInitInProgress)))) { // We need to re-bind all expression columns. DataExpression!.Bind(table); } } - if (Unique && _table != null) + if (Unique && _table is not null) { UniqueConstraint? constraint = table!.Constraints.FindKeyConstraint(this); - if (constraint != null) + if (constraint is not null) { table.Constraints.CanRemove(constraint, true); } @@ -1144,7 +1144,7 @@ internal object this[int record] { _table!._recordManager.VerifyRecord(record); Debug.Assert(null != _storage, "no storage"); - Debug.Assert(null != value, "setting null, expecting dbnull"); + Debug.Assert(value is not null, "setting null, expecting dbnull"); _storage.Set(record, value); Debug.Assert(null != _table, "storage with no DataTable on column"); } @@ -1165,7 +1165,7 @@ internal object this[int record] { // if and only if it is Expression column, we will cache LastChangedColumn, otherwise DO NOT DataRow dr = GetDataRow(record); - if (dr != null) + if (dr is not null) { // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we won't have datarow) dr.LastChangedColumn = this; @@ -1185,7 +1185,7 @@ internal void SetValue(int record, object value) // just silently set the value try { - Debug.Assert(null != value, "setting null, expecting dbnull"); + Debug.Assert(value is not null, "setting null, expecting dbnull"); Debug.Assert(null != _table, "storage with no DataTable on column"); Debug.Assert(null != _storage, "no storage"); _storage.Set(record, value); @@ -1197,7 +1197,7 @@ internal void SetValue(int record, object value) } DataRow dr = GetDataRow(record); - if (dr != null) + if (dr is not null) { // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we won't have datarow) dr.LastChangedColumn = this; } @@ -1224,13 +1224,13 @@ public bool Unique { if (_unique != value) { - if (value && _expression != null) + if (value && _expression is not null) { throw ExceptionBuilder.UniqueAndExpression(); } UniqueConstraint? oldConstraint = null; - if (_table != null) + if (_table is not null) { if (value) { @@ -1241,17 +1241,17 @@ public bool Unique for (IEnumerator e = _table.Constraints.GetEnumerator(); e.MoveNext();) { UniqueConstraint? o = (e.Current as UniqueConstraint); - if ((null != o) && (o.ColumnsReference.Length == 1) && (o.ColumnsReference[0] == this)) + if ((o is not null) && (o.ColumnsReference.Length == 1) && (o.ColumnsReference[0] == this)) oldConstraint = o; } - Debug.Assert(oldConstraint != null, "Should have found a column to remove from the collection."); + Debug.Assert(oldConstraint is not null, "Should have found a column to remove from the collection."); _table.Constraints.CanRemove(oldConstraint, true); } } _unique = value; - if (_table != null) + if (_table is not null) { if (value) { @@ -1259,7 +1259,7 @@ public bool Unique // already been true if there was an existed UniqueConstraint for this column UniqueConstraint constraint = new UniqueConstraint(this); - Debug.Assert(_table.Constraints.FindKeyConstraint(this) == null, "Should not be a duplication constraint in collection"); + Debug.Assert(_table.Constraints.FindKeyConstraint(this) is null, "Should not be a duplication constraint in collection"); _table.Constraints.Add(constraint); } else @@ -1289,7 +1289,7 @@ internal SimpleType? SimpleType _simpleType = value; // there is a change, since we are supporting hierarchy(bacause of Names Simple Type) old check (just one leel base check) is wrong - if (value != null && value.CanHaveMaxLength()) + if (value is not null && value.CanHaveMaxLength()) { _maxLength = value.MaxLength; // this is temp solution, since we dont let simple content to have } @@ -1311,7 +1311,7 @@ public virtual MappingType ColumnMapping DataCommonEventSource.Log.Trace(" {0}, {1}", ObjectID, value); if (value != _columnMapping) { - if (value == MappingType.SimpleContent && _table != null) + if (value == MappingType.SimpleContent && _table is not null) { int threshold = 0; if (_columnMapping == MappingType.Element) @@ -1323,7 +1323,7 @@ public virtual MappingType ColumnMapping throw ExceptionBuilder.CannotSetSimpleContent(ColumnName, _dataType); } - if (_table.XmlText != null && _table.XmlText != this) + if (_table.XmlText is not null && _table.XmlText != this) { throw ExceptionBuilder.CannotAddColumn3(); } @@ -1335,7 +1335,7 @@ public virtual MappingType ColumnMapping RaisePropertyChanging(nameof(ColumnMapping)); - if (_table != null) + if (_table is not null) { if (_columnMapping == MappingType.SimpleContent) { @@ -1356,7 +1356,7 @@ public virtual MappingType ColumnMapping if (value == MappingType.SimpleContent) { _columnUri = null; - if (_table != null) + if (_table is not null) { _table.XmlText = this; } @@ -1379,7 +1379,7 @@ internal void CheckColumnConstraint(DataRow row, DataRowAction action) internal bool CheckMaxLength() { - if ((0 <= _maxLength) && (null != Table) && (0 < Table.Rows.Count)) + if ((0 <= _maxLength) && (Table is not null) && (0 < Table.Rows.Count)) { Debug.Assert(IsStringType, "not a String or SqlString column"); foreach (DataRow dr in Table.Rows) @@ -1411,12 +1411,12 @@ internal void CheckMaxLength(DataRow dr) protected internal void CheckNotAllowNull() { - if (_storage == null) + if (_storage is null) { return; } - if (_sortIndex != null) + if (_sortIndex is not null) { if (_sortIndex.IsKeyInIndex(_storage._nullValue)) { @@ -1552,7 +1552,7 @@ internal DataColumn Clone() // so if we have set it, we should continue preserving the information // ...Extended Properties - if (_extendedProperties != null) + if (_extendedProperties is not null) { foreach (object key in _extendedProperties.Keys) { @@ -1587,7 +1587,7 @@ internal DataColumn Clone() internal object GetAggregateValue(int[] records, AggregateType kind) { - if (_storage == null) + if (_storage is null) { return kind == AggregateType.Count ? (object)0 : DBNull.Value; } @@ -1629,7 +1629,7 @@ internal static bool IsAutoIncrementType(Type dataType) => private bool IsColumnMappingValid(StorageType typeCode, MappingType mapping) => !((mapping != MappingType.Element) && DataStorage.IsTypeCustomType(typeCode)); - internal bool IsCustomType => _storage != null ? + internal bool IsCustomType => _storage is not null ? _storage._isCustomDefinedType : DataStorage.IsTypeCustomType(DataType); @@ -1653,7 +1653,7 @@ internal bool IsInRelation() DataKey key; DataRelationCollection rels = _table!.ParentRelations; - Debug.Assert(rels != null, "Invalid ParentRelations"); + Debug.Assert(rels is not null, "Invalid ParentRelations"); for (int i = 0; i < rels.Count; i++) { key = rels[i].ChildKey; @@ -1665,7 +1665,7 @@ internal bool IsInRelation() } rels = _table.ChildRelations; - Debug.Assert(rels != null, "Invalid ChildRelations"); + Debug.Assert(rels is not null, "Invalid ChildRelations"); for (int i = 0; i < rels.Count; i++) { key = rels[i].ParentKey; @@ -1695,9 +1695,9 @@ internal bool IsMaxLengthViolated() value = dr[this]; if (!_isSqlType) { - if (value != null && value != DBNull.Value && ((string)value).Length > MaxLength) + if (value is not null && value != DBNull.Value && ((string)value).Length > MaxLength) { - if (errorText == null) + if (errorText is null) { errorText = ExceptionBuilder.MaxLengthViolationText(ColumnName); } @@ -1710,7 +1710,7 @@ internal bool IsMaxLengthViolated() { if (!DataStorage.IsObjectNull(value) && ((SqlString)value).Value.Length > MaxLength) { - if (errorText == null) + if (errorText is null) { errorText = ExceptionBuilder.MaxLengthViolationText(ColumnName); } @@ -1755,7 +1755,7 @@ protected internal void RaisePropertyChanging(string name) private DataStorage InsureStorage() { - if (_storage == null) + if (_storage is null) { _storage = DataStorage.CreateStorage(this, _dataType, _storageType); } @@ -1773,13 +1773,13 @@ internal void SetCapacity(int capacity) internal void OnSetDataSet() { } // Returns the of the column, if one exists. - public override string ToString() => _expression == null ? + public override string ToString() => _expression is null ? ColumnName : ColumnName + " + " + Expression; internal object ConvertXmlToObject(string s) { - Debug.Assert(s != null, "Caller is resposible for missing element/attribute case"); + Debug.Assert(s is not null, "Caller is resposible for missing element/attribute case"); return InsureStorage().ConvertXmlToObject(s); } @@ -1791,13 +1791,13 @@ internal object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttr internal string ConvertObjectToXml(object value) { - Debug.Assert(value != null && (value != DBNull.Value), "Caller is resposible for checking on DBNull"); + Debug.Assert(value is not null && (value != DBNull.Value), "Caller is resposible for checking on DBNull"); return InsureStorage().ConvertObjectToXml(value); } internal void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { - Debug.Assert(value != null && (value != DBNull.Value), "Caller is resposible for checking on DBNull"); + Debug.Assert(value is not null && (value != DBNull.Value), "Caller is resposible for checking on DBNull"); InsureStorage().ConvertObjectToXml(value, xmlWriter, xmlAttrib); } @@ -1819,7 +1819,7 @@ internal void SetStorage(object store, BitArray nullbits) internal void AddDependentColumn(DataColumn expressionColumn) { - if (_dependentColumns == null) + if (_dependentColumns is null) { _dependentColumns = new List(); } @@ -1831,7 +1831,7 @@ internal void AddDependentColumn(DataColumn expressionColumn) internal void RemoveDependentColumn(DataColumn expressionColumn) { - if (_dependentColumns != null && _dependentColumns.Contains(expressionColumn)) + if (_dependentColumns is not null && _dependentColumns.Contains(expressionColumn)) { _dependentColumns.Remove(expressionColumn); } @@ -1840,16 +1840,16 @@ internal void RemoveDependentColumn(DataColumn expressionColumn) internal void HandleDependentColumnList(DataExpression? oldExpression, DataExpression? newExpression) { - Debug.Assert(_table != null); + Debug.Assert(_table is not null); DataColumn[] dependency; // remove this column from the dependentColumn list of the columns this column depends on. - if (oldExpression != null) + if (oldExpression is not null) { dependency = oldExpression.GetDependency(); foreach (DataColumn col in dependency) { - Debug.Assert(null != col, "null datacolumn in expression dependencies"); + Debug.Assert(col is not null, "null datacolumn in expression dependencies"); col.RemoveDependentColumn(this); if (col._table != _table) { @@ -1859,7 +1859,7 @@ internal void HandleDependentColumnList(DataExpression? oldExpression, DataExpre _table.RemoveDependentColumn(this); } - if (newExpression != null) + if (newExpression is not null) { // get the list of columns that this expression depends on dependency = newExpression.GetDependency(); @@ -1970,7 +1970,7 @@ internal override void SetCurrent(object value, IFormatProvider formatProvider) internal override void SetCurrentAndIncrement(object value) { - Debug.Assert(null != value && DataColumn.IsAutoIncrementType(value.GetType()) && !(value is BigInteger), "unexpected value for autoincrement"); + Debug.Assert(value is not null && DataColumn.IsAutoIncrementType(value.GetType()) && !(value is BigInteger), "unexpected value for autoincrement"); long v = (long)SqlConvert.ChangeType2(value, StorageType.Int64, typeof(long), CultureInfo.InvariantCulture); if (BoundaryCheck(v)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs index 5a8742ae06965d..b312db80d17a8b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs @@ -79,13 +79,13 @@ public DataColumn? this[string name] { get { - if (null == name) + if (name is null) { throw ExceptionBuilder.ArgumentNull(nameof(name)); } DataColumn? column; - if ((!_columnFromName.TryGetValue(name, out column)) || (column == null)) + if ((!_columnFromName.TryGetValue(name, out column)) || (column is null)) { // Case-Insensitive compares int index = IndexOfCaseInsensitive(name); @@ -108,7 +108,7 @@ public DataColumn? this[string name] get { DataColumn? column; - if ((_columnFromName.TryGetValue(name, out column)) && (column != null) && (column.Namespace == ns)) + if ((_columnFromName.TryGetValue(name, out column)) && (column is not null) && (column.Namespace == ns)) { return column; } @@ -136,9 +136,9 @@ public void Add(DataColumn column) internal void AddAt(int index, DataColumn column) { - if (column != null && column.ColumnMapping == MappingType.SimpleContent) + if (column is not null && column.ColumnMapping == MappingType.SimpleContent) { - if (_table.XmlText != null && _table.XmlText != column) + if (_table.XmlText is not null && _table.XmlText != column) { throw ExceptionBuilder.CannotAddColumn3(); } @@ -180,7 +180,7 @@ internal void AddAt(int index, DataColumn column) _table.ElementColumnCount++; } } - if (!_table.fInitInProgress && column != null && column.Computed) + if (!_table.fInitInProgress && column is not null && column.Computed) { column.Expression = column.Expression; } @@ -195,11 +195,11 @@ public void AddRange(DataColumn[] columns) return; } - if (columns != null) + if (columns is not null) { foreach (DataColumn column in columns) { - if (column != null) + if (column is not null) { Add(column); } @@ -317,7 +317,7 @@ internal string AssignName() /// private void BaseAdd([NotNull] DataColumn? column) { - if (column == null) + if (column is null) { throw ExceptionBuilder.ArgumentNull(nameof(column)); } @@ -325,7 +325,7 @@ private void BaseAdd([NotNull] DataColumn? column) { throw ExceptionBuilder.CannotAddColumn1(column.ColumnName); } - if (column._table != null) + if (column._table is not null) { throw ExceptionBuilder.CannotAddColumn2(column.ColumnName); } @@ -359,7 +359,7 @@ private void BaseAdd([NotNull] DataColumn? column) column.InitializeRecord(record); } - if (_table.DataSet != null) + if (_table.DataSet is not null) { column.OnSetDataSet(); } @@ -450,7 +450,7 @@ private void BaseRemove(DataColumn column) internal bool CanRemove(DataColumn? column, bool fThrowException) { - if (column == null) + if (column is null) { if (!fThrowException) { @@ -478,7 +478,7 @@ internal bool CanRemove(DataColumn? column, bool fThrowException) _table.OnRemoveColumnInternal(column); // We need to make sure the column is not involved in any Relations or Constriants - if (_table._primaryKey != null && _table._primaryKey.Key.ContainsColumn(column)) + if (_table._primaryKey is not null && _table._primaryKey.Key.ContainsColumn(column)) { if (!fThrowException) { @@ -521,7 +521,7 @@ internal bool CanRemove(DataColumn? column, bool fThrowException) throw ExceptionBuilder.CannotRemoveConstraint(_table.Constraints[i].ConstraintName, _table.Constraints[i].Table!.TableName); } - if (_table.DataSet != null) + if (_table.DataSet is not null) { for (ParentForeignKeyConstraintEnumerator en = new ParentForeignKeyConstraintEnumerator(_table.DataSet, _table); en.GetNext();) { @@ -534,24 +534,24 @@ internal bool CanRemove(DataColumn? column, bool fThrowException) } } - if (column._dependentColumns != null) + if (column._dependentColumns is not null) { for (int i = 0; i < column._dependentColumns.Count; i++) { DataColumn col = column._dependentColumns[i]; - if (_fInClear && (col.Table == _table || col.Table == null)) + if (_fInClear && (col.Table == _table || col.Table is null)) { continue; } - if (col.Table == null) + if (col.Table is null) { continue; } Debug.Assert(col.Computed, "invalid (non an expression) column in the expression dependent columns"); DataExpression? expr = col.DataExpression; - if ((expr != null) && (expr.DependsOn(column))) + if ((expr is not null) && (expr.DependsOn(column))) { if (!fThrowException) return false; @@ -597,7 +597,7 @@ public void Clear() OnCollectionChanging(s_refreshEventArgs); - if (_table.fInitInProgress && _delayedAddRangeColumns != null) + if (_table.fInitInProgress && _delayedAddRangeColumns is not null) { _delayedAddRangeColumns = null; } @@ -633,7 +633,7 @@ public void Clear() public bool Contains(string name) { DataColumn? column; - if ((_columnFromName.TryGetValue(name, out column)) && (column != null)) + if ((_columnFromName.TryGetValue(name, out column)) && (column is not null)) { return true; } @@ -644,7 +644,7 @@ public bool Contains(string name) internal bool Contains(string name, bool caseSensitive) { DataColumn? column; - if ((_columnFromName.TryGetValue(name, out column)) && (column != null)) + if ((_columnFromName.TryGetValue(name, out column)) && (column is not null)) { return true; } @@ -655,7 +655,7 @@ internal bool Contains(string name, bool caseSensitive) public void CopyTo(DataColumn[] array, int index) { - if (array == null) + if (array is null) { throw ExceptionBuilder.ArgumentNull(nameof(array)); } @@ -695,11 +695,11 @@ public int IndexOf(DataColumn? column) /// public int IndexOf(string? columnName) { - if ((null != columnName) && (0 < columnName.Length)) + if ((columnName is not null) && (0 < columnName.Length)) { int count = Count; DataColumn? column; - if ((_columnFromName.TryGetValue(columnName, out column)) && (column != null)) + if ((_columnFromName.TryGetValue(columnName, out column)) && (column is not null)) { for (int j = 0; j < count; j++) { @@ -744,11 +744,11 @@ internal int IndexOfCaseInsensitive(string name) internal void FinishInitCollection() { - if (_delayedAddRangeColumns != null) + if (_delayedAddRangeColumns is not null) { foreach (DataColumn? column in _delayedAddRangeColumns) { - if (column != null) + if (column is not null) { Add(column); } @@ -756,7 +756,7 @@ internal void FinishInitCollection() foreach (DataColumn? column in _delayedAddRangeColumns) { - if (column != null) + if (column is not null) { column.FinishInitInProgress(); } @@ -826,13 +826,13 @@ internal void OnColumnPropertyChanged(CollectionChangeEventArgs ccevent) /// internal void RegisterColumnName(string name, DataColumn? column) { - Debug.Assert(name != null); + Debug.Assert(name is not null); try { _columnFromName.Add(name, column); - if (null != column) + if (column is not null) { column._hashCode = _table.GetSpecialHashCode(name); } @@ -840,9 +840,9 @@ internal void RegisterColumnName(string name, DataColumn? column) catch (ArgumentException) { // Argument exception means that there is already an existing key - if (_columnFromName[name] != null) + if (_columnFromName[name] is not null) { - if (column != null) + if (column is not null) { throw ExceptionBuilder.CannotAddDuplicate(name); } @@ -855,7 +855,7 @@ internal void RegisterColumnName(string name, DataColumn? column) } // If we're adding a child table, then update defaultNameIndex to avoid colisions between the child table and auto-generated column names - if ((column == null) && NamesEqual(name, MakeName(_defaultNameIndex), true, _table.Locale) != 0) + if ((column is null) && NamesEqual(name, MakeName(_defaultNameIndex), true, _table.Locale) != 0) { do { @@ -866,7 +866,7 @@ internal void RegisterColumnName(string name, DataColumn? column) internal bool CanRegisterName(string name) { - Debug.Assert(name != null, "Must specify a name"); + Debug.Assert(name is not null, "Must specify a name"); return (!_columnFromName.ContainsKey(name)); } @@ -893,7 +893,7 @@ public void Remove(DataColumn column) public void RemoveAt(int index) { DataColumn dc = this[index]; - if (dc == null) + if (dc is null) { throw ExceptionBuilder.ColumnOutOfRange(index); } @@ -906,7 +906,7 @@ public void RemoveAt(int index) public void Remove(string name) { DataColumn? dc = this[name]; - if (dc == null) + if (dc is null) { throw ExceptionBuilder.ColumnNotInTheTable(name, _table.TableName); } 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 3ef950a651eea6..5234827743ac64 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataError.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataError.cs @@ -37,16 +37,16 @@ internal string Text // this method resets the error to the new value. 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) + Debug.Assert(column is not null, "Invalid (null) argument"); + Debug.Assert(column.Table is not null, "Invalid (loose) column"); + if (error is null || error.Length == 0) { // remove error from the collection Clear(column); } else { - if (_errorList == null) + if (_errorList is null) { _errorList = new ColumnError[initialCapacity]; } @@ -121,7 +121,7 @@ internal DataColumn[] GetColumnsInError() /// private void SetText(string? errorText) { - if (null == errorText) + if (errorText is null) { errorText = string.Empty; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataException.cs b/src/libraries/System.Data.Common/src/System/Data/DataException.cs index dfc6806e2efdc8..3479198a75cd33 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataException.cs @@ -288,8 +288,8 @@ internal static class ExceptionBuilder // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it private static void TraceException(string trace, Exception e) { - Debug.Assert(null != e, "TraceException: null Exception"); - if (e != null) + Debug.Assert(e is not null, "TraceException: null Exception"); + if (e is not null) { DataCommonEventSource.Log.Trace(trace, e); } @@ -693,7 +693,7 @@ public static Exception RemovePrimaryKey(DataTable table) => table.TableName.Len /// throw DataException for multitarget failure internal static void ThrowMultipleTargetConverter(Exception? innerException) { - string res = (null != innerException) ? SR.Xml_MultipleTargetConverterError : SR.Xml_MultipleTargetConverterEmpty; + string res = (innerException is not null) ? SR.Xml_MultipleTargetConverterError : SR.Xml_MultipleTargetConverterEmpty; ThrowDataException(res, innerException); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataKey.cs b/src/libraries/System.Data.Common/src/System/Data/DataKey.cs index df6edda565e4a7..f5382909ff0344 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataKey.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataKey.cs @@ -13,7 +13,7 @@ internal readonly struct DataKey internal DataKey(DataColumn[] columns, bool copyColumns) { - if (columns == null) + if (columns is null) { throw ExceptionBuilder.ArgumentNull(nameof(columns)); } @@ -30,7 +30,7 @@ internal DataKey(DataColumn[] columns, bool copyColumns) for (int i = 0; i < columns.Length; i++) { - if (columns[i] == null) + if (columns[i] is null) { throw ExceptionBuilder.ArgumentNull("column"); } @@ -71,14 +71,14 @@ internal void CheckState() { DataTable? table = _columns[0].Table; - if (table == null) + if (table is null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } for (int i = 1; i < _columns.Length; i++) { - if (_columns[i].Table == null) + if (_columns[i].Table is null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } @@ -99,7 +99,7 @@ internal static bool ColumnsEqual(DataColumn[] column1, DataColumn[] column2) { return true; } - else if (column1 == null || column2 == null) + else if (column1 is null || column2 is null) { return false; } @@ -164,7 +164,7 @@ internal bool Equals(DataKey value) { return true; } - else if (column1 == null || column2 == null) + else if (column1 is null || column2 is null) { return false; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs index 31ea7240274378..83459ce9583eb8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs @@ -86,7 +86,7 @@ public DataRelation(string? relationName, DataColumn parentColumn, DataColumn ch public DataRelation(string? relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) { DataCommonEventSource.Log.Trace(" {0}, relationName='{1}', parentColumn={2}, childColumn={3}, createConstraints={4}", - ObjectID, relationName, (parentColumn != null) ? parentColumn.ObjectID : 0, (childColumn != null) ? childColumn.ObjectID : 0, + ObjectID, relationName, (parentColumn is not null) ? parentColumn.ObjectID : 0, (childColumn is not null) ? childColumn.ObjectID : 0, createConstraints); DataColumn[] parentColumns = new DataColumn[1]; @@ -359,15 +359,15 @@ public virtual string RelationName long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, '{1}'", ObjectID, value); try { - if (value == null) + if (value is null) { value = string.Empty; } - CultureInfo locale = (_dataSet != null ? _dataSet.Locale : CultureInfo.CurrentCulture); + CultureInfo locale = (_dataSet is not null ? _dataSet.Locale : CultureInfo.CurrentCulture); if (string.Compare(_relationName, value, true, locale) != 0) { - if (_dataSet != null) + if (_dataSet is not null) { if (value.Length == 0) { @@ -415,7 +415,7 @@ internal void CheckNestedRelations() { DataCommonEventSource.Log.Trace(" {0}", ObjectID); - Debug.Assert(DataSet == null || !_nested, "this relation supposed to be not in dataset or not nested"); + Debug.Assert(DataSet is null || !_nested, "this relation supposed to be not in dataset or not nested"); // 1. There is no other relation (R) that has this.ChildTable as R.ChildTable // This is not valid for Whidbey anymore so the code has been removed @@ -477,7 +477,7 @@ public virtual bool Nested { if (_nested != value) { - if (_dataSet != null) + if (_dataSet is not null) { if (value) { @@ -485,9 +485,9 @@ public virtual bool Nested { // if not added to collection, don't do this check CheckNamespaceValidityForNestedRelations(ParentTable.Namespace); } - Debug.Assert(ChildTable != null, "On a DataSet, but not on Table. Bad state"); + Debug.Assert(ChildTable is not null, "On a DataSet, but not on Table. Bad state"); ForeignKeyConstraint? constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference); - if (constraint != null) + if (constraint is not null) { constraint.CheckConstraint(); } @@ -512,7 +512,7 @@ public virtual bool Nested if (value) { CheckNestedRelations(); - if (DataSet != null) + if (DataSet is not null) if (ParentTable == ChildTable) { foreach (DataRow row in ChildTable.Rows) @@ -520,7 +520,7 @@ public virtual bool Nested row.CheckForLoops(this); } - if (ChildTable.DataSet != null && (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0)) + if (ChildTable.DataSet is not null && (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0)) { throw ExceptionBuilder.DatasetConflictingName(DataSet.DataSetName); } @@ -553,7 +553,7 @@ public virtual bool Nested { if (rel.Nested) { - if (null == parentNs) + if (parentNs is null) { parentNs = rel.ParentTable.Namespace; } @@ -568,7 +568,7 @@ public virtual bool Nested } } // if not already in memory , form == unqualified - if (CheckMultipleNested && ChildTable._tableNamespace != null && ChildTable._tableNamespace.Length == 0) + if (CheckMultipleNested && ChildTable._tableNamespace is not null && ChildTable._tableNamespace.Length == 0) { throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName); } @@ -598,7 +598,7 @@ public virtual UniqueConstraint? ParentKeyConstraint internal void SetParentKeyConstraint(UniqueConstraint? value) { - Debug.Assert(_parentKeyConstraint == null || value == null, "ParentKeyConstraint should not have been set already."); + Debug.Assert(_parentKeyConstraint is null || value is null, "ParentKeyConstraint should not have been set already."); _parentKeyConstraint = value; } @@ -629,7 +629,7 @@ internal bool CheckMultipleNested internal void SetChildKeyConstraint(ForeignKeyConstraint? value) { - Debug.Assert(_childKeyConstraint == null || value == null, "ChildKeyConstraint should not have been set already."); + Debug.Assert(_childKeyConstraint is null || value is null, "ChildKeyConstraint should not have been set already."); _childKeyConstraint = value; } @@ -639,7 +639,7 @@ internal void SetChildKeyConstraint(ForeignKeyConstraint? value) // still a good relation object. internal void CheckState() { - if (_dataSet == null) + if (_dataSet is null) { _parentKey.CheckState(); _childKey.CheckState(); @@ -699,7 +699,7 @@ private void Create(string? relationName, DataColumn[] parentColumns, DataColumn for (int i = 0; i < parentColumns.Length; i++) { - if ((parentColumns[i].Table!.DataSet == null) || (childColumns[i].Table!.DataSet == null)) + if ((parentColumns[i].Table!.DataSet is null) || (childColumns[i].Table!.DataSet is null)) { throw ExceptionBuilder.ParentOrChildColumnsDoNotHaveDataSet(); } @@ -707,7 +707,7 @@ private void Create(string? relationName, DataColumn[] parentColumns, DataColumn CheckState(); - _relationName = (relationName == null ? "" : relationName); + _relationName = (relationName is null ? "" : relationName); _createConstraints = createConstraints; } finally @@ -718,8 +718,8 @@ private void Create(string? relationName, DataColumn[] parentColumns, DataColumn internal DataRelation Clone(DataSet destination) { - DataCommonEventSource.Log.Trace(" {0}, destination={1}", ObjectID, (destination != null) ? destination.ObjectID : 0); - Debug.Assert(destination != null); + DataCommonEventSource.Log.Trace(" {0}, destination={1}", ObjectID, (destination is not null) ? destination.ObjectID : 0); + Debug.Assert(destination is not null); DataTable parent = destination.Tables[ParentTable.TableName, ParentTable.Namespace]!; DataTable child = destination.Tables[ChildTable.TableName, ChildTable.Namespace]!; @@ -741,7 +741,7 @@ internal DataRelation Clone(DataSet destination) clone.CheckMultipleNested = true; // enable the check // ...Extended Properties - if (_extendedProperties != null) + if (_extendedProperties is not null) { foreach (object key in _extendedProperties.Keys) { @@ -753,7 +753,7 @@ internal DataRelation Clone(DataSet destination) protected internal void OnPropertyChanging(PropertyChangedEventArgs pcevent) { - if (PropertyChanging != null) + if (PropertyChanging is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); PropertyChanging(this, pcevent); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs index 1bec593c84971e..0b02f83007070c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs @@ -46,7 +46,7 @@ public abstract class DataRelationCollection : InternalDataCollectionBase /// public void Add(DataRelation relation) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, relation={1}", ObjectID, (relation != null) ? relation.ObjectID : 0); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, relation={1}", ObjectID, (relation is not null) ? relation.ObjectID : 0); try { if (_inTransition == relation) @@ -74,11 +74,11 @@ public void Add(DataRelation relation) public virtual void AddRange(DataRelation[]? relations) { - if (relations != null) + if (relations is not null) { foreach (DataRelation relation in relations) { - if (relation != null) + if (relation is not null) { Add(relation); } @@ -182,8 +182,8 @@ public virtual DataRelation Add(DataColumn parentColumn, DataColumn childColumn) /// protected virtual void AddCore(DataRelation relation) { - DataCommonEventSource.Log.Trace(" {0}, relation={1}", ObjectID, (relation != null) ? relation.ObjectID : 0); - if (relation == null) + DataCommonEventSource.Log.Trace(" {0}, relation={1}", ObjectID, (relation is not null) ? relation.ObjectID : 0); + if (relation is null) { throw ExceptionBuilder.ArgumentNull(nameof(relation)); } @@ -194,7 +194,7 @@ protected virtual void AddCore(DataRelation relation) { throw ExceptionBuilder.RelationAlreadyInTheDataSet(); } - if (relation.DataSet != null) + if (relation.DataSet is not null) { throw ExceptionBuilder.RelationAlreadyInOtherDataSet(); } @@ -281,7 +281,7 @@ public virtual void Clear() public void CopyTo(DataRelation[] array, int index) { - if (array == null) + if (array is null) { throw ExceptionBuilder.ArgumentNull(nameof(array)); } @@ -333,7 +333,7 @@ public virtual int IndexOf(string? relationName) internal int InternalIndexOf(string? name) { int cachedI = -1; - if ((null != name) && (0 < name.Length)) + if ((name is not null) && (0 < name.Length)) { int count = List.Count; int result = 0; @@ -373,7 +373,7 @@ private string MakeName(int index) => index == 1 ? /// protected virtual void OnCollectionChanged(CollectionChangeEventArgs ccevent) { - if (_onCollectionChangedDelegate != null) + if (_onCollectionChangedDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onCollectionChangedDelegate(this, ccevent); @@ -382,7 +382,7 @@ protected virtual void OnCollectionChanged(CollectionChangeEventArgs ccevent) protected virtual void OnCollectionChanging(CollectionChangeEventArgs ccevent) { - if (_onCollectionChangingDelegate != null) + if (_onCollectionChangingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onCollectionChangingDelegate(this, ccevent); @@ -397,7 +397,7 @@ protected virtual void OnCollectionChanging(CollectionChangeEventArgs ccevent) internal void RegisterName(string name) { DataCommonEventSource.Log.Trace(" {0}, name='{1}'", ObjectID, name); - Debug.Assert(name != null); + Debug.Assert(name is not null); CultureInfo locale = GetDataSet().Locale; int relationCount = Count; @@ -417,7 +417,7 @@ internal void RegisterName(string name) /// /// Verifies if a given relation can be removed from the collection. /// - public virtual bool CanRemove(DataRelation? relation) => relation != null && relation.DataSet == GetDataSet(); + public virtual bool CanRemove(DataRelation? relation) => relation is not null && relation.DataSet == GetDataSet(); /// /// Removes the given relation from the collection. @@ -427,7 +427,7 @@ internal void RegisterName(string name) /// public void Remove(DataRelation relation) { - DataCommonEventSource.Log.Trace(" {0}, relation={1}", ObjectID, (relation != null) ? relation.ObjectID : 0); + DataCommonEventSource.Log.Trace(" {0}, relation={1}", ObjectID, (relation is not null) ? relation.ObjectID : 0); if (_inTransition == relation) { return; @@ -455,7 +455,7 @@ public void RemoveAt(int index) { DataRelation dr = this[index]; // TODO: Not needed, this[] throws - if (dr == null) + if (dr is null) { throw ExceptionBuilder.RelationOutOfRange(index); } @@ -470,7 +470,7 @@ public void RemoveAt(int index) public void Remove(string name) { DataRelation? dr = this[name]; - if (dr == null) + if (dr is null) { throw ExceptionBuilder.RelationNotInTheDataSet(name); } @@ -484,8 +484,8 @@ public void Remove(string name) /// protected virtual void RemoveCore(DataRelation relation) { - DataCommonEventSource.Log.Trace(" {0}, relation={1}", ObjectID, (relation != null) ? relation.ObjectID : 0); - if (relation == null) + DataCommonEventSource.Log.Trace(" {0}, relation={1}", ObjectID, (relation is not null) ? relation.ObjectID : 0); + if (relation is null) { throw ExceptionBuilder.ArgumentNull(nameof(relation)); } @@ -528,7 +528,7 @@ internal sealed class DataTableRelationCollection : DataRelationCollection internal DataTableRelationCollection(DataTable table, bool fParentCollection) { - if (table == null) + if (table is null) { throw ExceptionBuilder.RelationTableNull(); } @@ -541,7 +541,7 @@ internal DataTableRelationCollection(DataTable table, bool fParentCollection) private void EnsureDataSet() { - if (_table.DataSet == null) + if (_table.DataSet is null) { throw ExceptionBuilder.RelationTableWasRemoved(); } @@ -626,7 +626,7 @@ public override bool CanRemove(DataRelation? relation) return false; } - Debug.Assert(relation != null); + Debug.Assert(relation is not null); if (_fParentCollection) { @@ -693,7 +693,7 @@ internal sealed class DataSetRelationCollection : DataRelationCollection internal DataSetRelationCollection(DataSet dataSet) { - if (dataSet == null) + if (dataSet is null) { throw ExceptionBuilder.RelationDataSetNull(); } @@ -711,11 +711,11 @@ public override void AddRange(DataRelation[]? relations) return; } - if (relations != null) + if (relations is not null) { foreach (DataRelation relation in relations) { - if (relation != null) + if (relation is not null) { Add(relation); } @@ -726,7 +726,7 @@ public override void AddRange(DataRelation[]? relations) public override void Clear() { base.Clear(); - if (_dataSet._fInitInProgress && _delayLoadingRelations != null) + if (_dataSet._fInitInProgress && _delayLoadingRelations is not null) { _delayLoadingRelations = null; } @@ -807,7 +807,7 @@ protected override void AddCore(DataRelation relation) ForeignKeyConstraint? foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference); if (relation._createConstraints) { - if (foreignKey == null) + if (foreignKey is null) { relation.ChildTable.Constraints.Add(foreignKey = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference)); @@ -865,7 +865,7 @@ protected override void RemoveCore(DataRelation relation) internal void FinishInitRelations() { - if (_delayLoadingRelations == null) + if (_delayLoadingRelations is null) { return; } @@ -876,7 +876,7 @@ internal void FinishInitRelations() for (int i = 0; i < _delayLoadingRelations.Length; i++) { rel = _delayLoadingRelations[i]; - if (rel._parentColumnNames == null || rel._childColumnNames == null) + if (rel._parentColumnNames is null || rel._childColumnNames is null) { Add(rel); continue; @@ -888,7 +888,7 @@ internal void FinishInitRelations() for (int j = 0; j < colCount; j++) { - if (rel._parentTableNamespace == null) + if (rel._parentTableNamespace is null) { parents[j] = _dataSet.Tables[rel._parentTableName!]!.Columns[rel._parentColumnNames[j]]!; } @@ -897,7 +897,7 @@ internal void FinishInitRelations() parents[j] = _dataSet.Tables[rel._parentTableName!, rel._parentTableNamespace]!.Columns[rel._parentColumnNames[j]]!; } - if (rel._childTableNamespace == null) + if (rel._childTableNamespace is null) { childs[j] = _dataSet.Tables[rel._childTableName!]!.Columns[rel._childColumnNames[j]]!; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs index 1a1c4d70f2b72c..9c5cbefb05ba52 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs @@ -88,11 +88,11 @@ internal int RBTreeNodeId [AllowNull] public string RowError { - get { return _error == null ? string.Empty : _error.Text; } + get { return _error is null ? string.Empty : _error.Text; } set { DataCommonEventSource.Log.Trace(" {0}, value='{1}'", _objectID, value); - if (_error == null) + if (_error is null) { if (!string.IsNullOrEmpty(value)) { @@ -202,7 +202,7 @@ internal void CheckForLoops(DataRelation rel) // and index creation may fail. The check will be done // after all the loading is done _and_ we are sure there // are no holes in the collection. - if (_table._fInLoadDiffgram || (_table.DataSet != null && _table.DataSet._fInLoadDiffgram)) + if (_table._fInLoadDiffgram || (_table.DataSet is not null && _table.DataSet._fInLoadDiffgram)) { return; } @@ -210,7 +210,7 @@ internal void CheckForLoops(DataRelation rel) int count = _table.Rows.Count, i = 0; // need to optimize this for count > 100 DataRow? parent = GetParentRow(rel); - while (parent != null) + while (parent is not null) { if ((parent == this) || (i > count)) { @@ -227,7 +227,7 @@ internal int GetNestedParentCount() DataRelation[] nestedParentRelations = _table.NestedParentRelations; foreach (DataRelation rel in nestedParentRelations) { - if (rel == null) // don't like this but done for backward code compatability + if (rel is null) // don't like this but done for backward code compatability { continue; } @@ -236,7 +236,7 @@ internal int GetNestedParentCount() CheckForLoops(rel); } DataRow? row = GetParentRow(rel); - if (row != null) + if (row is not null) { count++; } @@ -315,8 +315,8 @@ public object this[DataColumn column] throw ExceptionBuilder.ReadOnly(column.ColumnName); } - object? proposed = ((null != e) ? e.ProposedValue : value); - if (null == proposed) + object? proposed = ((e is not null) ? e.ProposedValue : value); + if (proposed is null) { if (column.IsValueType) { @@ -346,7 +346,7 @@ public object this[DataColumn column] // note: we intentionally do not try/catch this event. // infinite loops are possible if user calls Item or ItemArray during the event - if (null != e) + if (e is not null) { _table.OnColumnChanged(e); // user may call CancelEdit or EndEdit } @@ -432,7 +432,7 @@ public object?[] ItemArray } set { - if (null == value) + if (value is null) { throw ExceptionBuilder.ArgumentNull(nameof(ItemArray)); } @@ -464,7 +464,7 @@ public object?[] ItemArray // note: we intentionally do not try/catch this event. // note: we also allow user to do anything at this point // infinite loops are possible if user calls Item or ItemArray during the event - if (null != e) + if (e is not null) { e.InitializeColumnChangeEvent(column, item); _table.OnColumnChanging(e); @@ -486,8 +486,8 @@ public object?[] ItemArray BeginEditInternal(); } - object? proposed = (null != e) ? e.ProposedValue : item; - if (null == proposed) + object? proposed = (e is not null) ? e.ProposedValue : item; + if (proposed is null) { if (column.IsValueType) { @@ -518,7 +518,7 @@ public object?[] ItemArray // note: we intentionally do not try/catch this event. // infinite loops are possible if user calls Item or ItemArray during the event - if (null != e) + if (e is not null) { _table.OnColumnChanged(e); // user may call CancelEdit or EndEdit } @@ -628,7 +628,7 @@ public void CancelEdit() private void CheckColumn(DataColumn column) { - if (column == null) + if (column is null) { throw ExceptionBuilder.ArgumentNull(nameof(column)); } @@ -705,7 +705,7 @@ public void EndEdit() public void SetColumnError(int columnIndex, string? error) { DataColumn column = _columns[columnIndex]; - if (column == null) + if (column is null) { throw ExceptionBuilder.ColumnOutOfRange(columnIndex); } @@ -731,7 +731,7 @@ public void SetColumnError(DataColumn column, string? error) long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, column={1}, error='{2}'", _objectID, column.ObjectID, error); try { - if (_error == null) _error = new DataError(); + if (_error is null) _error = new DataError(); if (GetColumnError(column) != error) { _error.SetColumnError(column, error); @@ -760,7 +760,7 @@ public void SetColumnError(DataColumn column, string? error) public string GetColumnError(DataColumn column) { CheckColumn(column); - if (_error == null) _error = new DataError(); + if (_error is null) _error = new DataError(); return _error.GetColumnError(column); } @@ -770,7 +770,7 @@ public string GetColumnError(DataColumn column) /// public void ClearErrors() { - if (_error != null) + if (_error is not null) { _error.Clear(); RowErrorChanged(); @@ -779,7 +779,7 @@ public void ClearErrors() internal void ClearError(DataColumn column) { - if (_error != null) + if (_error is not null) { _error.Clear(column); RowErrorChanged(); @@ -789,12 +789,12 @@ internal void ClearError(DataColumn column) /// /// Gets a value indicating whether there are errors in a columns collection. /// - public bool HasErrors => _error == null ? false : _error.HasErrors; + public bool HasErrors => _error is null ? false : _error.HasErrors; /// /// Gets an array of columns that have errors. /// - public DataColumn[] GetColumnsInError() => _error == null ? + public DataColumn[] GetColumnsInError() => _error is null ? Array.Empty() : _error.GetColumnsInError(); public DataRow[] GetChildRows(string? relationName) => @@ -815,7 +815,7 @@ public DataRow[] GetChildRows(DataRelation? relation) => /// public DataRow[] GetChildRows(DataRelation? relation, DataRowVersion version) { - if (relation == null) + if (relation is null) { return _table.NewRowArray(0); } @@ -834,7 +834,7 @@ public DataRow[] GetChildRows(DataRelation? relation, DataRowVersion version) internal DataColumn GetDataColumn(string columnName) { DataColumn? column = _columns[columnName]; - if (null != column) + if (column is not null) { return column; } @@ -859,7 +859,7 @@ internal DataColumn GetDataColumn(string columnName) /// public DataRow? GetParentRow(DataRelation? relation, DataRowVersion version) { - if (relation == null) + if (relation is null) { return null; } @@ -885,7 +885,7 @@ internal DataColumn GetDataColumn(string columnName) DataRelation[] nestedParentRelations = _table.NestedParentRelations; foreach (DataRelation rel in nestedParentRelations) { - if (rel == null) // don't like this but done for backward code compatability + if (rel is null) // don't like this but done for backward code compatability { continue; } @@ -895,7 +895,7 @@ internal DataColumn GetDataColumn(string columnName) } DataRow? row = GetParentRow(rel, version); - if (row != null) + if (row is not null) { return row; } @@ -921,7 +921,7 @@ public DataRow[] GetParentRows(DataRelation? relation) => /// public DataRow[] GetParentRows(DataRelation? relation, DataRowVersion version) { - if (relation == null) + if (relation is null) { return _table.NewRowArray(0); } @@ -1266,7 +1266,7 @@ protected void SetNull(DataColumn column) internal void SetNestedParentRow(DataRow? parentRow, bool setNonNested) { - if (parentRow == null) + if (parentRow is null) { SetParentRowToDBNull(); return; @@ -1307,13 +1307,13 @@ public void SetParentRow(DataRow? parentRow) /// public void SetParentRow(DataRow? parentRow, DataRelation? relation) { - if (relation == null) + if (relation is null) { SetParentRow(parentRow); return; } - if (parentRow == null) + if (parentRow is null) { SetParentRowToDBNull(relation); return; @@ -1348,7 +1348,7 @@ internal void SetParentRowToDBNull() internal void SetParentRowToDBNull(DataRelation relation) { - Debug.Assert(relation != null, "The relation should not be null here."); + Debug.Assert(relation is not null, "The relation should not be null here."); if (relation.ChildKey.Table != _table) { @@ -1434,7 +1434,7 @@ internal int CopyValuesIntoStore(ArrayList storeList, ArrayList nullbitList, int private void VerifyValueFromStorage(DataColumn column, DataRowVersion version, object valueFromStorage) { // ignore deleted rows by adding "newRecord != -1" condition - we do not evaluate computed rows if they are deleted - if (column.DataExpression != null && !_inChangingEvent && _tempRecord == -1 && _newRecord != -1) + if (column.DataExpression is not null && !_inChangingEvent && _tempRecord == -1 && _newRecord != -1) { // for unchanged rows, check current if original is asked for. // this is because by design, there is only single storage for an unchanged row. diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs index 9a2daa68701bca..03fdbf43094af1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs @@ -75,7 +75,7 @@ internal void DiffInsertAt(DataRow row, int pos) // get into trouble if table has JUST a nested parent? how about multi parent! if (pos < _list.Count) { - if (_list[pos] != null) + if (_list[pos] is not null) { throw ExceptionBuilder.RowInsertTwice(pos, _table.TableName); } @@ -99,7 +99,7 @@ internal void DiffInsertAt(DataRow row, int pos) } } - public int IndexOf(DataRow? row) => (null == row) || (row.Table != _table) || ((0 == row.RBTreeNodeId) && (row.RowState == DataRowState.Detached)) ? + public int IndexOf(DataRow? row) => (row is null) || (row.Table != _table) || ((0 == row.RBTreeNodeId) && (row.RowState == DataRowState.Detached)) ? -1 : _list.IndexOf(row.RBTreeNodeId, row); @@ -157,13 +157,13 @@ internal void ArrayRemove(DataRow row) /// Gets a value indicating whether the primary key of any row in the /// collection contains the specified value. /// - public bool Contains(object? key) => (_table.FindByPrimaryKey(key) != null); + public bool Contains(object? key) => (_table.FindByPrimaryKey(key) is not null); /// /// Gets a value indicating if the with /// the specified primary key values exists. /// - public bool Contains(object?[] keys) => (_table.FindByPrimaryKey(keys) != null); + public bool Contains(object?[] keys) => (_table.FindByPrimaryKey(keys) is not null); public override void CopyTo(Array ar, int index) => _list.CopyTo(ar, index); @@ -176,7 +176,7 @@ internal void ArrayRemove(DataRow row) /// public void Remove(DataRow row) { - if ((null == row) || (row.Table != _table) || (-1 == row.rowID)) + if ((row is null) || (row.Table != _table) || (-1 == row.rowID)) { throw ExceptionBuilder.RowOutOfRange(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs index b3e042a701076e..f850e75ed1965f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs @@ -51,7 +51,7 @@ private static bool AreElementEqual(object? a, object? b) private static bool CompareArray(Array a, Array? b) { - if ((null == b) || + if ((b is null) || (1 != a.Rank) || (1 != b.Rank) || (a.Length != b.Length)) @@ -96,13 +96,13 @@ private static bool CompareArray(Array a, Array? b) private static bool CompareEquatableArray(TElem[] a, TElem[] b) where TElem : IEquatable { Debug.Assert(!ReferenceEquals(a, b)); - Debug.Assert(a != null); - Debug.Assert(b != null); + Debug.Assert(a is not null); + Debug.Assert(b is not null); Debug.Assert(a.Length == b.Length); for (int i = 0; i < a.Length; ++i) { - if (!a[i]?.Equals(b[i]) ?? b[i] != null) + if (!a[i]?.Equals(b[i]) ?? b[i] is not null) { return false; } @@ -185,7 +185,7 @@ public int GetHashCode(TRow row) } int hash = 0; - Debug.Assert(row.Table != null); + Debug.Assert(row.Table is not null); if (row.Table.Columns.Count > 0) { // if the row has at least one column, then use the first column value diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs index 8f0813ba1ce089..aef0c7a472491d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs @@ -75,11 +75,11 @@ public object this[string property] get { DataColumn? column = _dataView.Table!.Columns[property]; - if (null != column) + if (column is not null) { return Row[column, RowVersionDefault]; } - else if (_dataView.Table.DataSet != null && _dataView.Table.DataSet.Relations.Contains(property)) + else if (_dataView.Table.DataSet is not null && _dataView.Table.DataSet.Relations.Contains(property)) { return CreateChildView(property); } @@ -88,7 +88,7 @@ public object this[string property] set { DataColumn? column = _dataView.Table!.Columns[property]; - if (null == column) + if (column is null) { throw ExceptionBuilder.SetFailed(property); } @@ -148,7 +148,7 @@ internal void SetColumnValue(DataColumn column, object? value) /// null or mismatch between and . public DataView CreateChildView(DataRelation relation, bool followParent) { - if (relation == null || relation.ParentKey.Table != DataView.Table) + if (relation is null || relation.ParentKey.Table != DataView.Table) { throw ExceptionBuilder.CreateChildView(); } @@ -244,7 +244,7 @@ public void EndEdit() EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) => new EventDescriptorCollection(null); PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() => ((ICustomTypeDescriptor)this).GetProperties(null); PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) => - (_dataView.Table != null ? _dataView.Table.GetPropertyDescriptorCollection(attributes) : s_zeroPropertyDescriptorCollection); + (_dataView.Table is not null ? _dataView.Table.GetPropertyDescriptorCollection(attributes) : s_zeroPropertyDescriptorCollection); object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) => this; #nullable enable #endregion 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 9e4a168c8822bd..69d1d002130d62 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -190,7 +190,7 @@ protected SchemaSerializationMode DetermineSchemaSerializationMode(XmlReader rea { schemaSerializationMode = SchemaSerializationMode.IncludeSchema; } - else if (attribValue != null) + else if (attribValue is not null) { // if attrib does not exist, then don't throw throw ExceptionBuilder.InvalidSchemaSerializationMode(typeof(SchemaSerializationMode), attribValue); @@ -275,7 +275,7 @@ protected virtual void InitializeDerivedDataSet() { } // Serialize all the tables. private void SerializeDataSet(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat) { - Debug.Assert(info != null); + Debug.Assert(info is not null); info.AddValue("DataSet.RemotingVersion", new Version(2, 0)); // SqlHotFix 299, SerializationFormat enumeration types don't exist in V1.1 SP1 @@ -417,7 +417,7 @@ private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext c { string? strSchema = (string?)info.GetValue(KEY_XMLSCHEMA, typeof(string)); - if (strSchema != null) + if (strSchema is not null) { ReadXmlSchema(new XmlTextReader(new StringReader(strSchema)), true); } @@ -438,7 +438,7 @@ private void DeserializeDataSetData(SerializationInfo info, StreamingContext con { string? strData = (string?)info.GetValue(KEY_XMLDIFFGRAM, typeof(string)); - if (strData != null) + if (strData is not null) { ReadXml(new XmlTextReader(new StringReader(strData)), XmlReadMode.DiffGram); } @@ -607,11 +607,11 @@ public DataViewManager DefaultViewManager { get { - if (_defaultViewManager == null) + if (_defaultViewManager is null) { lock (_defaultViewManagerLock) { - if (_defaultViewManager == null) + if (_defaultViewManager is null) { _defaultViewManager = new DataViewManager(this, true); } @@ -705,13 +705,13 @@ public string DataSetName DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); if (value != _dataSetName) { - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) { throw ExceptionBuilder.SetDataSetNameToEmpty(); } DataTable? conflicting = Tables[value, Namespace]; - if ((conflicting != null) && (!conflicting._fNestedInDataset)) + if ((conflicting is not null) && (!conflicting._fNestedInDataset)) { throw ExceptionBuilder.SetDataSetNameConflicting(value); } @@ -730,7 +730,7 @@ public string Namespace set { DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); - if (value == null) + if (value is null) { value = string.Empty; } @@ -740,7 +740,7 @@ public string Namespace RaisePropertyChanging(nameof(Namespace)); foreach (DataTable dt in Tables) { - if (dt._tableNamespace != null) + if (dt._tableNamespace is not null) { continue; } @@ -773,7 +773,7 @@ public string Prefix get { return _datasetPrefix; } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -836,7 +836,7 @@ public CultureInfo Locale long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { - if (value != null) + if (value is not null) { if (!_culture.Equals(value)) { @@ -950,15 +950,15 @@ public override ISite Site set { ISite oldSite = Site; - if (value == null && oldSite != null) + if (value is null && oldSite is not null) { IContainer cont = oldSite.Container; - if (cont != null) + if (cont is not null) { for (int i = 0; i < Tables.Count; i++) { - if (Tables[i].Site != null) + if (Tables[i].Site is not null) { cont.Remove(Tables[i]); } @@ -1159,7 +1159,7 @@ public virtual DataSet Clone() } // ...Extended Properties... - if (_extendedProperties != null) + if (_extendedProperties is not null) { foreach (object key in _extendedProperties.Keys) { @@ -1301,7 +1301,7 @@ internal bool this[int index] Debug.Assert(0 <= bitMatrix[i].HasChanges, "negative change count"); if (0 < bitMatrix[i].HasChanges) { - if (null == dsNew) + if (dsNew is null) { dsNew = Clone(); fEnforceConstraints = dsNew.EnforceConstraints; @@ -1324,7 +1324,7 @@ internal bool this[int index] } } - if (null != dsNew) + if (dsNew is not null) { dsNew.EnforceConstraints = fEnforceConstraints; } @@ -1453,7 +1453,7 @@ internal string GetXmlSchemaForRemoting(DataTable? table) StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter); writer.Formatting = Formatting.Indented; - if (table == null) + if (table is null) { if (SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema) { @@ -1525,7 +1525,7 @@ public void InferXmlSchema(XmlReader? reader, string[]? nsArray) long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { - if (reader == null) + if (reader is null) { return; } @@ -1541,7 +1541,7 @@ public void InferXmlSchema(XmlReader? reader, string[]? nsArray) xdoc.Load(reader); } - if (xdoc.DocumentElement == null) + if (xdoc.DocumentElement is null) { return; } @@ -1559,7 +1559,7 @@ public void InferXmlSchema(XmlReader? reader, string[]? nsArray) /// public void InferXmlSchema(Stream? stream, string[]? nsArray) { - if (stream == null) + if (stream is null) { return; } @@ -1572,7 +1572,7 @@ public void InferXmlSchema(Stream? stream, string[]? nsArray) /// public void InferXmlSchema(TextReader? reader, string[]? nsArray) { - if (reader == null) + if (reader is null) { return; } @@ -1608,7 +1608,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) { int iCurrentDepth = -1; - if (reader == null) + if (reader is null) { return; } @@ -1800,7 +1800,7 @@ internal void ReadXDRSchema(XmlReader reader) /// public void ReadXmlSchema(Stream? stream) { - if (stream == null) + if (stream is null) { return; } @@ -1813,7 +1813,7 @@ public void ReadXmlSchema(Stream? stream) /// public void ReadXmlSchema(TextReader? reader) { - if (reader == null) + if (reader is null) { return; } @@ -1908,7 +1908,7 @@ private void WriteXmlSchema(string fileName, SchemaFormat schemaFormat, Converte private void WriteXmlSchema(Stream? stream, SchemaFormat schemaFormat, Converter? multipleTargetConverter) { - if (stream == null) + if (stream is null) { return; } @@ -1921,7 +1921,7 @@ private void WriteXmlSchema(Stream? stream, SchemaFormat schemaFormat, Converter private void WriteXmlSchema(TextWriter? writer, SchemaFormat schemaFormat, Converter? multipleTargetConverter) { - if (writer == null) + if (writer is null) { return; } @@ -1938,7 +1938,7 @@ private void WriteXmlSchema(XmlWriter? writer, SchemaFormat schemaFormat, Conver try { // Generate SchemaTree and write it out - if (writer != null) + if (writer is not null) { XmlTreeGen? treeGen = null; if (schemaFormat == SchemaFormat.WebService && @@ -1987,7 +1987,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) // clear the hashtable to avoid conflicts between diffgrams, SqlHotFix 782 rowDiffIdUsage.Prepare(this); - if (reader == null) + if (reader is null) { return ret; } @@ -2126,7 +2126,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) } else { - if (xmlload == null) + if (xmlload is null) { xmlload = new XmlDataLoader(this, fIsXdr, topNode, false); } @@ -2154,14 +2154,14 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) //We shoule not come add SC of root elemnt to topNode if we are not inferring _fTopLevelTable = true; isfTopLevelTableSet = true; - if ((rootNodeSimpleContent != null && rootNodeSimpleContent.Length > 0)) + if ((rootNodeSimpleContent is not null && rootNodeSimpleContent.Length > 0)) { topNode.InnerText = rootNodeSimpleContent; } } if (!isEmptyDataSet) { - if ((rootNodeSimpleContent != null && rootNodeSimpleContent.Length > 0)) + if ((rootNodeSimpleContent is not null && rootNodeSimpleContent.Length > 0)) { topNode.InnerText = rootNodeSimpleContent; } @@ -2170,7 +2170,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) // now top node contains the data part xdoc.AppendChild(topNode); - if (xmlload == null) + if (xmlload is null) { xmlload = new XmlDataLoader(this, fIsXdr, topNode, false); } @@ -2178,7 +2178,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) if (!isEmptyDataSet && !topNodeIsProcessed) { XmlElement root = xdoc.DocumentElement!; - Debug.Assert(root.NamespaceURI != null, "root.NamespaceURI should not ne null, it should be empty string"); + Debug.Assert(root.NamespaceURI is not null, "root.NamespaceURI should not ne null, it should be empty string"); // just recognize that below given Xml represents datatable in toplevel //text
// only allow root element with simple content, if any @@ -2245,7 +2245,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) public XmlReadMode ReadXml(Stream? stream) { - if (stream == null) + if (stream is null) { return XmlReadMode.Auto; } @@ -2260,7 +2260,7 @@ public XmlReadMode ReadXml(Stream? stream) public XmlReadMode ReadXml(TextReader? reader) { - if (reader == null) + if (reader is null) { return XmlReadMode.Auto; } @@ -2295,7 +2295,7 @@ internal void InferSchema(XmlDocument xdoc, string[]? excludedNamespaces, XmlRea long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, mode={1}", ObjectID, mode); try { - if (null == excludedNamespaces) + if (excludedNamespaces is null) { excludedNamespaces = Array.Empty(); } @@ -2482,7 +2482,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol restictedScope = TypeLimiter.EnterRestrictedScope(this); XmlReadMode ret = mode; - if (reader == null) + if (reader is null) { return ret; } @@ -2671,7 +2671,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol } else { - if (xmlload == null) + if (xmlload is null) { xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema); } @@ -2684,7 +2684,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol // now top node contains the data part xdoc.AppendChild(topNode); - if (xmlload == null) + if (xmlload is null) xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema); if (mode == XmlReadMode.DiffGram) @@ -2728,7 +2728,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol public XmlReadMode ReadXml(Stream? stream, XmlReadMode mode) { - if (stream == null) + if (stream is null) { return XmlReadMode.Auto; } @@ -2741,7 +2741,7 @@ public XmlReadMode ReadXml(Stream? stream, XmlReadMode mode) public XmlReadMode ReadXml(TextReader? reader, XmlReadMode mode) { - if (reader == null) + if (reader is null) { return XmlReadMode.Auto; } @@ -2791,7 +2791,7 @@ public XmlReadMode ReadXml(string fileName, XmlReadMode mode) /// public void WriteXml(Stream? stream, XmlWriteMode mode) { - if (stream != null) + if (stream is not null) { XmlTextWriter w = new XmlTextWriter(stream, null); w.Formatting = Formatting.Indented; @@ -2802,7 +2802,7 @@ public void WriteXml(Stream? stream, XmlWriteMode mode) public void WriteXml(TextWriter? writer, XmlWriteMode mode) { - if (writer != null) + if (writer is not null) { XmlTextWriter w = new XmlTextWriter(writer); w.Formatting = Formatting.Indented; @@ -2817,7 +2817,7 @@ public void WriteXml(XmlWriter? writer, XmlWriteMode mode) try { // Generate SchemaTree and write it out - if (writer != null) + if (writer is not null) { if (mode == XmlWriteMode.DiffGram) { @@ -2875,8 +2875,8 @@ public void WriteXml(string fileName, XmlWriteMode mode) /// public void Merge(DataSet dataSet) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0); - Debug.Assert(dataSet != null); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}", ObjectID, (dataSet is not null) ? dataSet.ObjectID : 0); + Debug.Assert(dataSet is not null); try { Merge(dataSet, false, MissingSchemaAction.Add); @@ -2893,8 +2893,8 @@ public void Merge(DataSet dataSet) /// public void Merge(DataSet dataSet, bool preserveChanges) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}, preserveChanges={2}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0, preserveChanges); - Debug.Assert(dataSet != null); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}, preserveChanges={2}", ObjectID, (dataSet is not null) ? dataSet.ObjectID : 0, preserveChanges); + Debug.Assert(dataSet is not null); try { Merge(dataSet, preserveChanges, MissingSchemaAction.Add); @@ -2912,11 +2912,11 @@ public void Merge(DataSet dataSet, bool preserveChanges) /// public void Merge(DataSet dataSet, bool preserveChanges, MissingSchemaAction missingSchemaAction) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}, preserveChanges={2}, missingSchemaAction={3}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0, preserveChanges, missingSchemaAction); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}, preserveChanges={2}, missingSchemaAction={3}", ObjectID, (dataSet is not null) ? dataSet.ObjectID : 0, preserveChanges, missingSchemaAction); try { // Argument checks - if (dataSet == null) + if (dataSet is null) { throw ExceptionBuilder.ArgumentNull(nameof(dataSet)); } @@ -2945,8 +2945,8 @@ public void Merge(DataSet dataSet, bool preserveChanges, MissingSchemaAction mis /// public void Merge(DataTable table) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table != null) ? table.ObjectID : 0); - Debug.Assert(table != null); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table is not null) ? table.ObjectID : 0); + Debug.Assert(table is not null); try { Merge(table, false, MissingSchemaAction.Add); @@ -2963,11 +2963,11 @@ public void Merge(DataTable table) /// public void Merge(DataTable table, bool preserveChanges, MissingSchemaAction missingSchemaAction) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, preserveChanges={2}, missingSchemaAction={3}", ObjectID, (table != null) ? table.ObjectID : 0, preserveChanges, missingSchemaAction); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, preserveChanges={2}, missingSchemaAction={3}", ObjectID, (table is not null) ? table.ObjectID : 0, preserveChanges, missingSchemaAction); try { // Argument checks - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(table)); } @@ -3010,7 +3010,7 @@ public void Merge(DataRow[] rows, bool preserveChanges, MissingSchemaAction miss try { // Argument checks - if (rows == null) + if (rows is null) { throw ExceptionBuilder.ArgumentNull(nameof(rows)); } @@ -3046,7 +3046,7 @@ protected virtual void OnPropertyChanging(PropertyChangedEventArgs pcevent) /// internal void OnMergeFailed(MergeFailedEventArgs mfevent) { - if (MergeFailed != null) + if (MergeFailed is not null) { MergeFailed(this, mfevent); } @@ -3080,7 +3080,7 @@ protected internal virtual void OnRemoveTable(DataTable table) { } internal void OnRemovedTable(DataTable table) { DataViewManager? viewManager = _defaultViewManager; - if (null != viewManager) + if (viewManager is not null) { viewManager.DataViewSettings.Remove(table); } @@ -3279,7 +3279,7 @@ internal bool ValidateLocaleConstraint() PropertyDescriptor currentProp = props[propStart]; - if (baseTable == null) + if (baseTable is null) { // the accessor is the table name. if we don't find it, return null. if (currentProp is DataTablePropertyDescriptor) @@ -3359,7 +3359,7 @@ public static XmlSchemaComplexType GetDataSetSchema(XmlSchemaSet? schemaSet) { // For performance reasons we are exploiting the fact that config files content is constant // for a given appdomain so we can safely cache the prepared schema complex type and reuse it - if (s_schemaTypeForWSDL == null) + if (s_schemaTypeForWSDL is null) { // to change the config file, appdomain needs to restart; so it seems safe to cache the schema XmlSchemaComplexType tempWSDL = new XmlSchemaComplexType(); @@ -3398,7 +3398,7 @@ public static XmlSchemaComplexType GetDataSetSchema(XmlSchemaSet? schemaSet) MemoryStream stream = new MemoryStream(); // WriteXmlSchema(new XmlTextWriter(stream, null)); XmlWriter writer = new XmlTextWriter(stream, null); - if (writer != null) + if (writer is not null) { (new XmlTreeGen(SchemaFormat.WebService)).Save(this, writer); } @@ -3411,7 +3411,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) bool fNormalization = true; XmlTextReader? xmlTextReader = null; IXmlTextParser? xmlTextParser = reader as IXmlTextParser; - if (xmlTextParser != null) + if (xmlTextParser is not null) { fNormalization = xmlTextParser.Normalized; xmlTextParser.Normalized = false; @@ -3419,7 +3419,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) else { xmlTextReader = reader as XmlTextReader; - if (xmlTextReader != null) + if (xmlTextReader is not null) { fNormalization = xmlTextReader.Normalization; xmlTextReader.Normalization = false; @@ -3428,11 +3428,11 @@ void IXmlSerializable.ReadXml(XmlReader reader) ReadXmlSerializable(reader); - if (xmlTextParser != null) + if (xmlTextParser is not null) { xmlTextParser.Normalized = fNormalization; } - else if (xmlTextReader != null) + else if (xmlTextReader is not null) { xmlTextReader.Normalization = fNormalization; } @@ -3462,7 +3462,7 @@ public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEve var adapter = new LoadAdapter(); adapter.FillLoadOption = loadOption; adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; - if (null != errorHandler) + if (errorHandler is not null) { adapter.FillError += errorHandler; } @@ -3489,7 +3489,7 @@ public void Load(IDataReader reader, LoadOption loadOption, params string[] tabl for (int i = 0; i < tables.Length; i++) { DataTable? tempDT = Tables[tables[i]]; - if (null == tempDT) + if (tempDT is null) { tempDT = new DataTable(tables[i]); Tables.Add(tempDT); @@ -3526,7 +3526,7 @@ public DataTableReader CreateDataReader(params DataTable[] dataTables) for (int i = 0; i < dataTables.Length; i++) { - if (dataTables[i] == null) + if (dataTables[i] is null) { throw ExceptionBuilder.ArgumentContainsNullValue(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs b/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs index fd125f1cd9bbf1..20ef7021ec0344 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs @@ -9,7 +9,7 @@ internal static class DataSetUtil { internal static void CheckArgumentNull(T argumentValue, string argumentName) where T : class { - if (null == argumentValue) + if (argumentValue is null) { throw ArgumentNull(argumentName); } @@ -17,7 +17,7 @@ internal static void CheckArgumentNull(T argumentValue, string argumentName) private static T TraceException(string trace, T e) { - Debug.Assert(null != e, "TraceException: null Exception"); + Debug.Assert(e is not null, "TraceException: null Exception"); return e; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 8b4c1083b60882..17cc4370d5b38c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -182,7 +182,7 @@ public DataTable() /// public DataTable(string? tableName) : this() { - _tableName = tableName == null ? "" : tableName; + _tableName = tableName is null ? "" : tableName; } public DataTable(string? tableName, string? tableNamespace) : this(tableName) @@ -193,7 +193,7 @@ public DataTable(string? tableName, string? tableNamespace) : this(tableName) // Deserialize the table from binary/xml stream. protected DataTable(SerializationInfo info, StreamingContext context) : this() { - bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true; + bool isSingleTable = context.Context is not null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true; SerializationFormat remotingFormat = SerializationFormat.Xml; SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) @@ -212,7 +212,7 @@ protected DataTable(SerializationInfo info, StreamingContext context) : this() public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { SerializationFormat remotingFormat = RemotingFormat; - bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true; + bool isSingleTable = context.Context is not null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true; SerializeDataTable(info, context, isSingleTable, remotingFormat); } @@ -242,7 +242,7 @@ private void SerializeDataTable(SerializationInfo info, StreamingContext context string tempDSNamespace = string.Empty; bool fCreatedDataSet = false; - if (_dataSet == null) + if (_dataSet is null) { DataSet ds = new DataSet("tmpDataSet"); // if user set values on DataTable, it isn't necessary @@ -298,7 +298,7 @@ internal void DeserializeDataTable(SerializationInfo info, StreamingContext cont string? strSchema = (string?)info.GetValue(KEY_XMLSCHEMA, typeof(string)); string? strData = (string?)info.GetValue(KEY_XMLDIFFGRAM, typeof(string)); - if (strSchema != null) + if (strSchema is not null) { DataSet ds = new DataSet(); ds.ReadXmlSchema(new XmlTextReader(new StringReader(strSchema))); @@ -309,7 +309,7 @@ internal void DeserializeDataTable(SerializationInfo info, StreamingContext cont //this is to avoid the cascading rules in the namespace Namespace = table.Namespace; - if (strData != null) + if (strData is not null) { ds.Tables.Remove(ds.Tables[0]); ds.Tables.Add(this); @@ -473,7 +473,7 @@ internal void DeserializeTableSchema(SerializationInfo info, StreamingContext co { for (int i = 0; i < colCount; i++) { - if (expressions[i] != null) + if (expressions[i] is not null) { Columns[i].Expression = expressions[i]; } @@ -496,7 +496,7 @@ internal void SerializeConstraints(SerializationInfo info, StreamingContext cont { if (allConstraints) { - Debug.Assert(DataSet != null); + Debug.Assert(DataSet is not null); } ArrayList constraintList = new ArrayList(); @@ -506,7 +506,7 @@ internal void SerializeConstraints(SerializationInfo info, StreamingContext cont Constraint c = Constraints[i]; UniqueConstraint? uc = c as UniqueConstraint; - if (uc != null) + if (uc is not null) { int[] colInfo = new int[uc.Columns.Length]; for (int j = 0; j < colInfo.Length; j++) @@ -526,7 +526,7 @@ internal void SerializeConstraints(SerializationInfo info, StreamingContext cont else { ForeignKeyConstraint? fk = c as ForeignKeyConstraint; - Debug.Assert(fk != null); + Debug.Assert(fk is not null); bool shouldSerialize = (allConstraints == true) || (fk.Table == this && fk.RelatedTable == this); if (shouldSerialize) @@ -837,7 +837,7 @@ internal void DeserializeTableData(SerializationInfo info, StreamingContext cont // Constructs the RowState from the two bits in the bitarray. private DataRowState ConvertToRowState(BitArray bitStates, int bitIndex) { - Debug.Assert(bitStates != null); + Debug.Assert(bitStates is not null); Debug.Assert(bitStates.Length > bitIndex); bool b1 = bitStates[bitIndex]; @@ -869,8 +869,8 @@ private DataRowState ConvertToRowState(BitArray bitStates, int bitIndex) internal void GetRowAndColumnErrors(int rowIndex, Hashtable rowErrors, Hashtable colErrors) { Debug.Assert(Rows.Count > rowIndex); - Debug.Assert(rowErrors != null); - Debug.Assert(colErrors != null); + Debug.Assert(rowErrors is not null); + Debug.Assert(colErrors is not null); DataRow row = Rows[rowIndex]; @@ -899,8 +899,8 @@ internal void GetRowAndColumnErrors(int rowIndex, Hashtable rowErrors, Hashtable private void ConvertToRowError(int rowIndex, Hashtable rowErrors, Hashtable colErrors) { Debug.Assert(Rows.Count > rowIndex); - Debug.Assert(rowErrors != null); - Debug.Assert(colErrors != null); + Debug.Assert(rowErrors is not null); + Debug.Assert(colErrors is not null); DataRow row = Rows[rowIndex]; @@ -936,7 +936,7 @@ public bool CaseSensitive _caseSensitive = value; _caseSensitiveUserSet = true; - if (DataSet != null && !DataSet.ValidateCaseConstraint()) + if (DataSet is not null && !DataSet.ValidateCaseConstraint()) { _caseSensitive = oldValue; _caseSensitiveUserSet = oldUserSet; @@ -983,13 +983,13 @@ internal void RestoreIndexEvents(bool forceReset) catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); - if (null == first) + if (first is null) { first = e; } } } - if (null != first) + if (first is not null) { throw first; } @@ -1075,7 +1075,7 @@ internal bool SelfNested { get { - // Is this correct? if ((top[i].nestedParentRelation!= null) && (top[i].nestedParentRelation.ParentTable == top[i])) + // Is this correct? if ((top[i].nestedParentRelationis not null) && (top[i].nestedParentRelation.ParentTable == top[i])) foreach (DataRelation rel in ParentRelations) { if (rel.Nested && rel.ParentTable == this) @@ -1118,7 +1118,7 @@ public SerializationFormat RemotingFormat throw ExceptionBuilder.InvalidRemotingFormat(value); } // table can not have different format than its dataset, unless it is stand alone datatable - if (DataSet != null && value != DataSet.RemotingFormat) + if (DataSet is not null && value != DataSet.RemotingFormat) { throw ExceptionBuilder.CanNotSetRemotingFormat(); } @@ -1189,12 +1189,12 @@ internal void SetDataSet(DataSet? dataSet) cols[i].OnSetDataSet(); } - if (DataSet != null) + if (DataSet is not null) { _defaultView = null; } //Set the remoting format variable directly - if (dataSet != null) + if (dataSet is not null) { _remotingFormat = dataSet.RemotingFormat; } @@ -1211,7 +1211,7 @@ public DataView DefaultView get { DataView? view = _defaultView; - if (null == view) + if (view is null) { if (null != _dataSet) { @@ -1224,7 +1224,7 @@ public DataView DefaultView } view = Interlocked.CompareExchange(ref _defaultView, view, null); - if (null == view) + if (view is null) { view = _defaultView; } @@ -1249,7 +1249,7 @@ public string DisplayExpression null; } } - internal string DisplayExpressionInternal => _displayExpression != null ? _displayExpression.Expression : string.Empty; + internal string DisplayExpressionInternal => _displayExpression is not null ? _displayExpression.Expression : string.Empty; internal bool EnforceConstraints { @@ -1259,7 +1259,7 @@ internal bool EnforceConstraints { return false; } - if (_dataSet != null) + if (_dataSet is not null) { return _dataSet.EnforceConstraints; } @@ -1268,7 +1268,7 @@ internal bool EnforceConstraints } set { - if (_dataSet == null && _enforceConstraints != value) + if (_dataSet is null && _enforceConstraints != value) { if (value) { @@ -1380,7 +1380,7 @@ public CultureInfo Locale try { bool userSet = true; - if (null == value) + if (value is null) { // reset Locale to inherit from DataSet userSet = false; @@ -1396,7 +1396,7 @@ public CultureInfo Locale { _cultureUserSet = true; SetLocaleValue(value, true, false); - if ((null == DataSet) || DataSet.ValidateLocaleConstraint()) + if ((DataSet is null) || DataSet.ValidateLocaleConstraint()) { flag = false; SetLocaleValue(value, true, true); @@ -1442,7 +1442,7 @@ public CultureInfo Locale internal bool SetLocaleValue(CultureInfo culture, bool userSet, bool resetIndexes) { - Debug.Assert(null != culture, "SetLocaleValue: no locale"); + Debug.Assert(culture is not null, "SetLocaleValue: no locale"); if (userSet || resetIndexes || (!_cultureUserSet && !_culture.Equals(culture))) { _culture = culture; @@ -1501,7 +1501,7 @@ internal int ElementColumnCount get { return _elementColumnCount; } set { - if ((value > 0) && (_xmlText != null)) + if ((value > 0) && (_xmlText is not null)) { throw ExceptionBuilder.TableCannotAddToSimpleContent(); } @@ -1535,7 +1535,7 @@ internal DataRelation[] NestedParentRelations Debug.Assert(nRel.Length == _nestedParentRelations.Length, "nestedParent cache is broken"); for (int i = 0; i < nRel.Length; i++) { - Debug.Assert(null != nRel[i], "null relation"); + Debug.Assert(nRel[i] is not null, "null relation"); Debug.Assert(null != _nestedParentRelations[i], "null relation"); Debug.Assert(nRel[i] == _nestedParentRelations[i], "unequal relations"); } @@ -1556,7 +1556,7 @@ private DataRelation[] FindNestedParentRelations() { if (relation.Nested) { - if (null == nestedParents) + if (nestedParents is null) { nestedParents = new List(); } @@ -1564,7 +1564,7 @@ private DataRelation[] FindNestedParentRelations() } } - return (null == nestedParents) || (nestedParents.Count == 0) ? + return (nestedParents is null) || (nestedParents.Count == 0) ? Array.Empty() : nestedParents.ToArray(); } @@ -1597,7 +1597,7 @@ public DataColumn[] PrimaryKey get { UniqueConstraint? primayKeyConstraint = _primaryKey; - if (null != primayKeyConstraint) + if (primayKeyConstraint is not null) { Debug.Assert(2 <= primayKeyConstraint.ConstraintIndex.RefCount, "bad primaryKey index RefCount"); return primayKeyConstraint.Key.ToArray(); @@ -1610,18 +1610,18 @@ public DataColumn[] PrimaryKey UniqueConstraint? existingKey = null; // Loading with persisted property - if (fInitInProgress && value != null) + if (fInitInProgress && value is not null) { _delayedSetPrimaryKey = value; return; } - if ((value != null) && (value.Length != 0)) + if ((value is not null) && (value.Length != 0)) { int count = 0; for (int i = 0; i < value.Length; i++) { - if (value[i] != null) + if (value[i] is not null) { count++; } @@ -1648,13 +1648,13 @@ public DataColumn[] PrimaryKey } } - if (key == _primaryKey || (key != null && key.Equals(_primaryKey))) + if (key == _primaryKey || (key is not null && key.Equals(_primaryKey))) { return; } // Use an existing UniqueConstraint that matches if one exists - if ((existingKey = (UniqueConstraint?)Constraints.FindConstraint(key)) != null) + if ((existingKey = (UniqueConstraint?)Constraints.FindConstraint(key)) is not null) { key!.ColumnsReference.CopyTo(existingKey.Key.ColumnsReference, 0); key = existingKey; @@ -1662,7 +1662,7 @@ public DataColumn[] PrimaryKey UniqueConstraint? oldKey = _primaryKey; _primaryKey = null; - if (oldKey != null) + if (oldKey is not null) { oldKey.ConstraintIndex.RemoveRef(); @@ -1686,17 +1686,17 @@ public DataColumn[] PrimaryKey } // Add the key if there isnt an existing matching key in collection - if (key != null && existingKey == null) + if (key is not null && existingKey is null) { Constraints.Add(key); } _primaryKey = key; - Debug.Assert(_primaryKey == null || Constraints.FindConstraint(_primaryKey) == _primaryKey, "PrimaryKey is not in ConstraintCollection"); - _primaryIndex = (key != null) ? key.Key.GetIndexDesc() : Array.Empty(); + Debug.Assert(_primaryKey is null || Constraints.FindConstraint(_primaryKey) == _primaryKey, "PrimaryKey is not in ConstraintCollection"); + _primaryIndex = (key is not null) ? key.Key.GetIndexDesc() : Array.Empty(); - if (_primaryKey != null) + if (_primaryKey is not null) { // must set index for DataView.Sort before setting AllowDBNull which can fail key!.ConstraintIndex.AddRef(); @@ -1712,7 +1712,7 @@ public DataColumn[] PrimaryKey /// /// Indicates whether the property should be persisted. /// - private bool ShouldSerializePrimaryKey() => _primaryKey != null; + private bool ShouldSerializePrimaryKey() => _primaryKey is not null; /// /// Resets the property to its default state. @@ -1742,14 +1742,14 @@ public string TableName long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, value='{1}'", ObjectID, value); try { - if (value == null) + if (value is null) { value = string.Empty; } CultureInfo currentLocale = Locale; if (string.Compare(_tableName, value, true, currentLocale) != 0) { - if (_dataSet != null) + if (_dataSet is not null) { if (value.Length == 0) { @@ -1812,7 +1812,7 @@ internal string EncodedTableName get { string? encodedTblName = _encodedTableName; - if (null == encodedTblName) + if (encodedTblName is null) { encodedTblName = XmlConvert.EncodeLocalName(TableName); _encodedTableName = encodedTblName; @@ -1831,7 +1831,7 @@ private string GetInheritedNamespace(List visitedTables) for (int i = 0; i < nestedRelations.Length; i++) { DataRelation rel = nestedRelations[i]; - if (rel.ParentTable._tableNamespace != null) + if (rel.ParentTable._tableNamespace is not null) { return rel.ParentTable._tableNamespace; // if parent table has a non-null NS, return it } @@ -1852,7 +1852,7 @@ private string GetInheritedNamespace(List visitedTables) } } // dont put else - if (DataSet != null) + if (DataSet is not null) { // if it cant return from parent tables, return NS from dataset, if exists return DataSet.Namespace; @@ -1877,9 +1877,9 @@ public string Namespace { if (value != _tableNamespace) { - if (_dataSet != null) + if (_dataSet is not null) { - string realNamespace = (value == null ? GetInheritedNamespace(new List()) : value); + string realNamespace = (value is null ? GetInheritedNamespace(new List()) : value); if (realNamespace != Namespace) { // do this extra check only if the namespace is really going to change @@ -1907,7 +1907,7 @@ internal void CheckCascadingNamespaceConflict(string realNamespace) { foreach (DataRelation rel in ChildRelations) { - if ((rel.Nested) && (rel.ChildTable != this) && (rel.ChildTable._tableNamespace == null)) + if ((rel.Nested) && (rel.ChildTable != this) && (rel.ChildTable._tableNamespace is null)) { DataTable childTable = rel.ChildTable; if (_dataSet!.Tables.Contains(childTable.TableName, realNamespace, false, true)) @@ -1924,7 +1924,7 @@ internal void CheckNamespaceValidityForNestedRelations(string? realNamespace) { if (rel.Nested) { - if (realNamespace != null) + if (realNamespace is not null) { rel.ChildTable.CheckNamespaceValidityForNestedParentRelations(realNamespace, this); } @@ -1935,7 +1935,7 @@ internal void CheckNamespaceValidityForNestedRelations(string? realNamespace) } } - if (realNamespace == null) + if (realNamespace is null) { // this will affect this table if it has parent relations CheckNamespaceValidityForNestedParentRelations(GetInheritedNamespace(new List()), this); @@ -1962,7 +1962,7 @@ internal void DoRaiseNamespaceChange() foreach (DataColumn col in Columns) { - if (col._columnUri == null) + if (col._columnUri is null) { col.RaisePropertyChanging(nameof(Namespace)); } @@ -1980,7 +1980,7 @@ internal void DoRaiseNamespaceChange() /// /// Indicates whether the property should be persisted. /// - private bool ShouldSerializeNamespace() => _tableNamespace != null; + private bool ShouldSerializeNamespace() => _tableNamespace is not null; /// /// Resets the property to its default state. @@ -1997,7 +1997,7 @@ public virtual void BeginInit() public virtual void EndInit() { - if (_dataSet == null || !_dataSet._fInitInProgress) + if (_dataSet is null || !_dataSet._fInitInProgress) { Columns.FinishInitCollection(); Constraints.FinishInitConstraints(); @@ -2011,7 +2011,7 @@ public virtual void EndInit() } fInitInProgress = false; // It is must that we set off this flag after calling FinishInitxxx(); - if (_delayedSetPrimaryKey != null) + if (_delayedSetPrimaryKey is not null) { PrimaryKey = _delayedSetPrimaryKey; _delayedSetPrimaryKey = null; @@ -2036,7 +2036,7 @@ public string Prefix get { return _tablePrefix; } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -2057,9 +2057,9 @@ internal DataColumn? XmlText { if (_xmlText != value) { - if (_xmlText != null) + if (_xmlText is not null) { - if (value != null) + if (value is not null) { throw ExceptionBuilder.MultipleTextOnlyColumns(); } @@ -2067,7 +2067,7 @@ internal DataColumn? XmlText } else { - Debug.Assert(value != null, "Value shoud not be null ??"); + Debug.Assert(value is not null, "Value shoud not be null ??"); Debug.Assert(value.ColumnMapping == MappingType.SimpleContent, "should be text node here"); if (value != Columns[value.ColumnName]) { @@ -2112,7 +2112,7 @@ internal void SetKeyValues(DataKey key, object[] keyValues, int record) // Primary key match if (key.HasValue) { - Debug.Assert(ndx != null); + Debug.Assert(ndx is not null); int findRecord = (row._oldRecord == -1) ? row._newRecord : row._oldRecord; object[] values = key.GetKeyValues(findRecord); targetRow = FindByIndex(ndx, values); @@ -2140,7 +2140,7 @@ private void SetMergeRecords(DataRow row, int newRecord, int oldRecord, DataRowA internal DataRow MergeRow(DataRow row, DataRow? targetRow, bool preserveChanges, Index? idxSearch) { - if (targetRow == null) + if (targetRow is null) { targetRow = NewEmptyRow(); targetRow._oldRecord = _recordManager.ImportRecord(row.Table, row._oldRecord); @@ -2300,7 +2300,7 @@ public void AcceptChanges() internal DataTable Clone(DataSet? cloneDS) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, cloneDS={1}", ObjectID, (cloneDS != null) ? cloneDS.ObjectID : 0); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, cloneDS={1}", ObjectID, (cloneDS is not null) ? cloneDS.ObjectID : 0); try { DataTable clone = CreateInstance(); @@ -2321,7 +2321,7 @@ private DataTable IncrementalCloneTo(DataTable sourceTable, DataTable targetTabl { foreach (DataColumn dc in sourceTable.Columns) { - if (targetTable.Columns[dc.ColumnName] == null) + if (targetTable.Columns[dc.ColumnName] is null) { targetTable.Columns.Add(dc.Clone()); } @@ -2332,7 +2332,7 @@ private DataTable IncrementalCloneTo(DataTable sourceTable, DataTable targetTabl private DataTable CloneHierarchy(DataTable sourceTable, DataSet ds, Hashtable? visitedMap) { - if (visitedMap == null) + if (visitedMap is null) { visitedMap = new Hashtable(); } @@ -2343,14 +2343,14 @@ private DataTable CloneHierarchy(DataTable sourceTable, DataSet ds, Hashtable? v DataTable? destinationTable = ds.Tables[sourceTable.TableName, sourceTable.Namespace]; - if ((destinationTable != null && destinationTable.Columns.Count > 0)) + if ((destinationTable is not null && destinationTable.Columns.Count > 0)) { destinationTable = IncrementalCloneTo(sourceTable, destinationTable); // get extra columns from source into destination , increamental read } else { - if (destinationTable == null) + if (destinationTable is null) { destinationTable = new DataTable(); // fxcop: new DataTable values for CaseSensitive, Locale, Namespace will come from CloneTo @@ -2373,7 +2373,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression { // we do clone datatables while we do readxmlschema, so we do not want to clone columnexpressions if we call this from ReadXmlSchema // it will cause exception to be thrown in cae expression refers to a table that is not in hirerachy or not created yet - Debug.Assert(clone != null, "The table passed in has to be newly created empty DataTable."); + Debug.Assert(clone is not null, "The table passed in has to be newly created empty DataTable."); // set All properties clone._tableName = _tableName; @@ -2405,7 +2405,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression } // add all expressions if Clone is invoked only on DataTable otherwise DataSet.Clone will assign expressions after creating all relationships. - if (!skipExpressionColumns && cloneDS == null) + if (!skipExpressionColumns && cloneDS is null) { for (int i = 0; i < clmns.Count; i++) { @@ -2431,7 +2431,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression { ForeignKeyConstraint? foreign = Constraints[j] as ForeignKeyConstraint; UniqueConstraint? unique = Constraints[j] as UniqueConstraint; - if (foreign != null) + if (foreign is not null) { if (foreign.Table == foreign.RelatedTable) { @@ -2442,7 +2442,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression } } } - else if (unique != null) + else if (unique is not null) { if (unique.Clone(clone) is UniqueConstraint clonedConstraint && clone.Constraints.FindConstraint(clonedConstraint) is Constraint oldConstraint) @@ -2463,7 +2463,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression { ForeignKeyConstraint? foreign = Constraints[j] as ForeignKeyConstraint; UniqueConstraint? unique = Constraints[j] as UniqueConstraint; - if (foreign != null) + if (foreign is not null) { if (foreign.Table == foreign.RelatedTable && foreign.Clone(clone) is ForeignKeyConstraint newforeign) @@ -2472,7 +2472,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression clone.Constraints.Add(newforeign); } } - else if (unique != null) + else if (unique is not null) { clone.Constraints.Add(unique.Clone(clone)!); } @@ -2481,7 +2481,7 @@ private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpression // ...Extended Properties... - if (_extendedProperties != null) + if (_extendedProperties is not null) { foreach (object key in _extendedProperties.Keys) { @@ -2680,15 +2680,15 @@ public override ISite Site set { ISite oldSite = Site; - if (value == null && oldSite != null) + if (value is null && oldSite is not null) { IContainer cont = oldSite.Container; - if (cont != null) + if (cont is not null) { for (int i = 0; i < Columns.Count; i++) { - if (Columns[i].Site != null) + if (Columns[i].Site is not null) { cont.Remove(Columns[i]); } @@ -2728,7 +2728,7 @@ internal void InsertRow(DataRow row, long proposedID, int pos, bool fireEvent) { Exception? deferredException = null; - if (row == null) + if (row is null) { throw ExceptionBuilder.ArgumentNull(nameof(row)); } @@ -2777,7 +2777,7 @@ internal void InsertRow(DataRow row, long proposedID, int pos, bool fireEvent) // since expression evaluation occurred in SetNewRecordWorker, there may have been a problem that // was deferred to this point. If so, throw now since row has already been added. - if (deferredException != null) + if (deferredException is not null) throw deferredException; if (EnforceConstraints) @@ -2822,7 +2822,7 @@ internal void Clear(bool clearAll) Debug.Assert(null == _rowDiffId, "wasn't previously cleared"); _rowDiffId = null; - if (_dataSet != null) + if (_dataSet is not null) _dataSet.OnClearFunctionCalled(this); bool shouldFireClearEvents = (Rows.Count != 0); // if Rows is already empty, this is noop @@ -2833,7 +2833,7 @@ internal void Clear(bool clearAll) OnTableClearing(e); } - if (_dataSet != null && _dataSet.EnforceConstraints) + if (_dataSet is not null && _dataSet.EnforceConstraints) { for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, this); constraints.GetNext();) { @@ -2875,7 +2875,7 @@ internal void Clear(bool clearAll) internal void CascadeAll(DataRow row, DataRowAction action) { - if (_dataSet != null && _dataSet._fEnableCascading) + if (_dataSet is not null && _dataSet._fEnableCascading) { for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, this); constraints.GetNext();) { @@ -2909,11 +2909,11 @@ internal int Compare(string s1, string s2, CompareInfo? comparer) { return 0; } - if (obj1 == null) + if (obj1 is null) { return -1; } - if (obj2 == null) + if (obj2 is null) { return 1; } @@ -2959,7 +2959,7 @@ internal void CopyRow(DataTable table, DataRow row) { int oldRecord = -1, newRecord = -1; - if (row == null) + if (row is null) { return; } @@ -3009,7 +3009,7 @@ internal void DeleteRow(DataRow row) private void CheckPrimaryKey() { - if (_primaryKey == null) throw ExceptionBuilder.TableMissingPrimaryKey(); + if (_primaryKey is null) throw ExceptionBuilder.TableMissingPrimaryKey(); } internal DataRow? FindByPrimaryKey(object?[] values) @@ -3167,7 +3167,7 @@ internal Index GetIndex(IndexField[] indexDesc, DataViewRowState recordStates, I for (int i = 0; i < _indexes.Count; i++) { Index index = _indexes[i]; - if (index != null) + if (index is not null) { if (index.Equal(indexDesc, recordStates, rowFilter)) { @@ -3220,7 +3220,7 @@ public void ImportRow(DataRow? row) { int oldRecord = -1, newRecord = -1; - if (row == null) + if (row is null) { return; } @@ -3338,7 +3338,7 @@ internal void InsertRow(DataRow row, long proposedID) row._newRecord, DataViewRowState.None, row.GetRecordState(row._newRecord)); } - if (_dependentColumns != null && _dependentColumns.Count > 0) + if (_dependentColumns is not null && _dependentColumns.Count > 0) { EvaluateExpressions(row, DataRowAction.Add, null); } @@ -3459,7 +3459,7 @@ internal DataRow CreateEmptyRow() { row[c] = DBNull.Value; } - else if (c.DefaultValue != null) + else if (c.DefaultValue is not null) { row[c] = c.DefaultValue; } @@ -3534,8 +3534,8 @@ protected internal DataRow[] NewRowArray(int size) protected internal virtual void OnColumnChanging(DataColumnChangeEventArgs e) { // intentionally allow exceptions to bubble up. We haven't committed anything yet. - Debug.Assert(e != null, "e should not be null"); - if (_onColumnChangingDelegate != null) + Debug.Assert(e is not null, "e should not be null"); + if (_onColumnChangingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onColumnChangingDelegate(this, e); @@ -3544,8 +3544,8 @@ protected internal virtual void OnColumnChanging(DataColumnChangeEventArgs e) protected internal virtual void OnColumnChanged(DataColumnChangeEventArgs e) { - Debug.Assert(e != null, "e should not be null"); - if (_onColumnChangedDelegate != null) + Debug.Assert(e is not null, "e should not be null"); + if (_onColumnChangedDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onColumnChangedDelegate(this, e); @@ -3554,7 +3554,7 @@ protected internal virtual void OnColumnChanged(DataColumnChangeEventArgs e) protected virtual void OnPropertyChanging(PropertyChangedEventArgs pcevent) { - if (_onPropertyChangingDelegate != null) + if (_onPropertyChangingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onPropertyChangingDelegate(this, pcevent); @@ -3573,7 +3573,7 @@ protected virtual void OnRemoveColumn(DataColumn column) { } { if ((null != _onRowChangedDelegate) || IsTypedDataTable) { - if (null == args) + if (args is null) { args = new DataRowChangeEventArgs(eRow, eAction); } @@ -3586,7 +3586,7 @@ protected virtual void OnRemoveColumn(DataColumn column) { } { if ((null != _onRowChangingDelegate) || IsTypedDataTable) { - if (null == args) + if (args is null) { args = new DataRowChangeEventArgs(eRow, eAction); } @@ -3600,8 +3600,8 @@ protected virtual void OnRemoveColumn(DataColumn column) { } /// protected virtual void OnRowChanged(DataRowChangeEventArgs e) { - Debug.Assert((null != e) && ((null != _onRowChangedDelegate) || IsTypedDataTable), "OnRowChanged arguments"); - if (_onRowChangedDelegate != null) + Debug.Assert((e is not null) && ((null != _onRowChangedDelegate) || IsTypedDataTable), "OnRowChanged arguments"); + if (_onRowChangedDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onRowChangedDelegate(this, e); @@ -3613,8 +3613,8 @@ protected virtual void OnRowChanged(DataRowChangeEventArgs e) /// protected virtual void OnRowChanging(DataRowChangeEventArgs e) { - Debug.Assert((null != e) && ((null != _onRowChangingDelegate) || IsTypedDataTable), "OnRowChanging arguments"); - if (_onRowChangingDelegate != null) + Debug.Assert((e is not null) && ((null != _onRowChangingDelegate) || IsTypedDataTable), "OnRowChanging arguments"); + if (_onRowChangingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onRowChangingDelegate(this, e); @@ -3626,8 +3626,8 @@ protected virtual void OnRowChanging(DataRowChangeEventArgs e) /// protected virtual void OnRowDeleting(DataRowChangeEventArgs e) { - Debug.Assert((null != e) && ((null != _onRowDeletingDelegate) || IsTypedDataTable), "OnRowDeleting arguments"); - if (_onRowDeletingDelegate != null) + Debug.Assert((e is not null) && ((null != _onRowDeletingDelegate) || IsTypedDataTable), "OnRowDeleting arguments"); + if (_onRowDeletingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onRowDeletingDelegate(this, e); @@ -3639,8 +3639,8 @@ protected virtual void OnRowDeleting(DataRowChangeEventArgs e) /// protected virtual void OnRowDeleted(DataRowChangeEventArgs e) { - Debug.Assert((null != e) && ((null != _onRowDeletedDelegate) || IsTypedDataTable), "OnRowDeleted arguments"); - if (_onRowDeletedDelegate != null) + Debug.Assert((e is not null) && ((null != _onRowDeletedDelegate) || IsTypedDataTable), "OnRowDeleted arguments"); + if (_onRowDeletedDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onRowDeletedDelegate(this, e); @@ -3649,7 +3649,7 @@ protected virtual void OnRowDeleted(DataRowChangeEventArgs e) protected virtual void OnTableCleared(DataTableClearEventArgs e) { - if (_onTableClearedDelegate != null) + if (_onTableClearedDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onTableClearedDelegate(this, e); @@ -3658,7 +3658,7 @@ protected virtual void OnTableCleared(DataTableClearEventArgs e) protected virtual void OnTableClearing(DataTableClearEventArgs e) { - if (_onTableClearingDelegate != null) + if (_onTableClearingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onTableClearingDelegate(this, e); @@ -3667,7 +3667,7 @@ protected virtual void OnTableClearing(DataTableClearEventArgs e) protected virtual void OnTableNewRow(DataTableNewRowEventArgs e) { - if (_onTableNewRowDelegate != null) + if (_onTableNewRowDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onTableNewRowDelegate(this, e); @@ -3676,7 +3676,7 @@ protected virtual void OnTableNewRow(DataTableNewRowEventArgs e) private void OnInitialized() { - if (_onInitialized != null) + if (_onInitialized is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onInitialized(this, EventArgs.Empty); @@ -3686,7 +3686,7 @@ private void OnInitialized() internal IndexField[] ParseSortString(string? sortString) { IndexField[] indexDesc = Array.Empty(); - if ((null != sortString) && (0 < sortString.Length)) + if ((sortString is not null) && (0 < sortString.Length)) { string[] split = sortString.Split(',', StringSplitOptions.TrimEntries); indexDesc = new IndexField[split.Length]; @@ -3723,7 +3723,7 @@ internal IndexField[] ParseSortString(string? sortString) // find the column. DataColumn? column = Columns[current]; - if (column == null) + if (column is null) { throw ExceptionBuilder.ColumnOutOfRange(current); } @@ -3935,7 +3935,7 @@ internal void SilentlySetValue(DataRow dr, DataColumn dc, DataRowVersion version { dr.Table.RecordChanged(oldIndex, newIndex); } - if (dc._dependentColumns != null) + if (dc._dependentColumns is not null) { dc.Table!.EvaluateDependentExpressions(dc._dependentColumns, dr, version, null); } @@ -3974,7 +3974,7 @@ internal void RemoveRow(DataRow row, bool check) throw ExceptionBuilder.RowAlreadyRemoved(); } - if (check && _dataSet != null) + if (check && _dataSet is not null) { for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, this); constraints.GetNext();) { @@ -4056,7 +4056,7 @@ internal void ResetInternalIndexes(DataColumn? column) Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy() if (0 < ndx.RefCount) { - if (null == column) + if (column is null) { ndx.Reset(); } @@ -4102,7 +4102,7 @@ internal void RollbackRow(DataRow row) // check if we deleting good row else if (DataRowAction.Delete == eAction && eRow._newRecord == -1 && (IsTypedDataTable || (null != _onRowDeletedDelegate))) { - if (null == args) + if (args is null) { args = new DataRowChangeEventArgs(eRow, eAction); } @@ -4139,7 +4139,7 @@ internal void RollbackRow(DataRow row) // don't catch try { - if (null == args) + if (args is null) { args = new DataRowChangeEventArgs(eRow, eAction); } @@ -4234,7 +4234,7 @@ internal void SetNewRecord(DataRow row, int proposedRecord, DataRowAction action { Exception? deferredException = null; SetNewRecordWorker(row, proposedRecord, action, isInMerge, suppressEnsurePropertyChanged, -1, fireEvent, out deferredException); // we are going to call below overload from insert - if (deferredException != null) + if (deferredException is not null) { throw deferredException; } @@ -4257,7 +4257,7 @@ private void SetNewRecordWorker(DataRow row, int proposedRecord, DataRowAction a // 7) Raise RowChanged/ RowDeleted // 8) Check constraints for expression columns - Debug.Assert(row != null, "Row can't be null."); + Debug.Assert(row is not null, "Row can't be null."); deferredException = null; if (row._tempRecord != proposedRecord) @@ -4325,7 +4325,7 @@ private void SetNewRecordWorker(DataRow row, int proposedRecord, DataRowAction a List? cachedRows = null; if ((action == DataRowAction.Delete || action == DataRowAction.Change) && - _dependentColumns != null && _dependentColumns.Count > 0) + _dependentColumns is not null && _dependentColumns.Count > 0) { // if there are expression columns, need to cache related rows for deletes and updates (key changes) // before indexes are modified. @@ -4423,7 +4423,7 @@ private void SetNewRecordWorker(DataRow row, int proposedRecord, DataRowAction a RemoveRow(row, false); } - if (_dependentColumns != null && _dependentColumns.Count > 0) + if (_dependentColumns is not null && _dependentColumns.Count > 0) { try { @@ -4564,7 +4564,7 @@ internal void ShadowIndexCopy() /// /// Returns the and , if there is one as a concatenated string. /// - public override string ToString() => _displayExpression == null ? + public override string ToString() => _displayExpression is null ? TableName : TableName + " + " + DisplayExpressionInternal; @@ -4592,17 +4592,17 @@ public void BeginLoadData() } else { - if (_primaryKey != null) + if (_primaryKey is not null) { _loadIndex = _primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows); } - if (_loadIndex != null) + if (_loadIndex is not null) { _loadIndex.AddRef(); } } - if (DataSet != null) + if (DataSet is not null) { _savedEnforceConstraints = DataSet.EnforceConstraints; DataSet.EnforceConstraints = false; @@ -4628,15 +4628,15 @@ public void EndLoadData() return; } - if (_loadIndex != null) + if (_loadIndex is not null) { _loadIndex.RemoveRef(); } - if (_loadIndexwithOriginalAdded != null) + if (_loadIndexwithOriginalAdded is not null) { _loadIndexwithOriginalAdded.RemoveRef(); } - if (_loadIndexwithCurrentDeleted != null) + if (_loadIndexwithCurrentDeleted is not null) { _loadIndexwithCurrentDeleted.RemoveRef(); } @@ -4649,7 +4649,7 @@ public void EndLoadData() RestoreIndexEvents(false); - if (DataSet != null) + if (DataSet is not null) { DataSet.EnforceConstraints = _savedEnforceConstraints; } @@ -4677,7 +4677,7 @@ public DataRow LoadDataRow(object?[] values, bool fAcceptChanges) if (_inDataLoad) { int record = NewRecordFromArray(values); - if (_loadIndex != null) + if (_loadIndex is not null) { // not expecting LiveIndexes to clear the index we use between calls to LoadDataRow Debug.Assert(2 <= _loadIndex.RefCount, "bad loadIndex.RefCount"); @@ -4687,7 +4687,7 @@ public DataRow LoadDataRow(object?[] values, bool fAcceptChanges) { int resultRecord = _loadIndex.GetRecord(result); row = _recordManager[resultRecord]!; - Debug.Assert(row != null, "Row can't be null for index record"); + Debug.Assert(row is not null, "Row can't be null for index record"); row.CancelEdit(); if (row.RowState == DataRowState.Deleted) { @@ -4735,16 +4735,16 @@ public DataRow LoadDataRow(object?[] values, LoadOption loadOption) try { Index? indextoUse = null; - if (_primaryKey != null) + if (_primaryKey is not null) { if (loadOption == LoadOption.Upsert) { // CurrentVersion, and Deleted - if (_loadIndexwithCurrentDeleted == null) + if (_loadIndexwithCurrentDeleted is null) { _loadIndexwithCurrentDeleted = _primaryKey.Key.GetSortIndex(DataViewRowState.CurrentRows | DataViewRowState.Deleted); - Debug.Assert(_loadIndexwithCurrentDeleted != null, "loadIndexwithCurrentDeleted should not be null"); - if (_loadIndexwithCurrentDeleted != null) + Debug.Assert(_loadIndexwithCurrentDeleted is not null, "loadIndexwithCurrentDeleted should not be null"); + if (_loadIndexwithCurrentDeleted is not null) { _loadIndexwithCurrentDeleted.AddRef(); } @@ -4754,11 +4754,11 @@ public DataRow LoadDataRow(object?[] values, LoadOption loadOption) else { // CurrentVersion, and Deleted : OverwriteRow, PreserveCurrentValues - if (_loadIndexwithOriginalAdded == null) + if (_loadIndexwithOriginalAdded is null) { _loadIndexwithOriginalAdded = _primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added); - Debug.Assert(_loadIndexwithOriginalAdded != null, "loadIndexwithOriginalAdded should not be null"); - if (_loadIndexwithOriginalAdded != null) + Debug.Assert(_loadIndexwithOriginalAdded is not null, "loadIndexwithOriginalAdded should not be null"); + if (_loadIndexwithOriginalAdded is not null) { _loadIndexwithOriginalAdded.AddRef(); } @@ -4774,7 +4774,7 @@ public DataRow LoadDataRow(object?[] values, LoadOption loadOption) SuspendIndexEvents(); // so suspend events here(not suspended == table already has some rows initially) } - DataRow dataRow = LoadRow(values, loadOption, indextoUse); // if indextoUse == null, it means we dont have PK, + DataRow dataRow = LoadRow(values, loadOption, indextoUse); // if indextoUse is null, it means we dont have PK, // so LoadRow will take care of just adding the row to end return dataRow; @@ -4788,12 +4788,12 @@ public DataRow LoadDataRow(object?[] values, LoadOption loadOption) internal DataRow UpdatingAdd(object?[] values) { Index? index = null; - if (_primaryKey != null) + if (_primaryKey is not null) { index = _primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows); } - if (index != null) + if (index is not null) { int record = NewRecordFromArray(values); int result = index.FindRecord(record); @@ -4801,7 +4801,7 @@ internal DataRow UpdatingAdd(object?[] values) { int resultRecord = index.GetRecord(result); DataRow row = _recordManager[resultRecord]!; - Debug.Assert(row != null, "Row can't be null for index record"); + Debug.Assert(row is not null, "Row can't be null for index record"); row.RejectChanges(); SetNewRecord(row, record); return row; @@ -4823,7 +4823,7 @@ internal bool UpdatingCurrent(DataRow row, DataRowAction action) internal DataColumn AddUniqueKey(int position) { - if (_colUnique != null) + if (_colUnique is not null) return _colUnique; // check to see if we can use already existent PrimaryKey @@ -4870,7 +4870,7 @@ internal DataColumn AddUniqueKey(int position) internal DataColumn AddForeignKey(DataColumn parentKey) { - Debug.Assert(parentKey != null, "AddForeignKey: Invalid paramter.. related primary key is null"); + Debug.Assert(parentKey is not null, "AddForeignKey: Invalid paramter.. related primary key is null"); string keyName = XMLSchema.GenUniqueColumnName(parentKey.ColumnName, this); DataColumn foreignKey = new DataColumn(keyName, parentKey.DataType, null, MappingType.Hidden); @@ -4893,7 +4893,7 @@ internal void UpdatePropertyDescriptorCollectionCache() /// internal PropertyDescriptorCollection GetPropertyDescriptorCollection(Attribute[]? attributes) { - if (_propertyDescriptorCollectionCache == null) + if (_propertyDescriptorCollectionCache is null) { int columnsCount = Columns.Count; int relationsCount = ChildRelations.Count; @@ -4915,7 +4915,7 @@ internal PropertyDescriptorCollection GetPropertyDescriptorCollection(Attribute[ internal XmlQualifiedName TypeName { - get { return ((_typeName == null) ? XmlQualifiedName.Empty : (XmlQualifiedName)_typeName); } + get { return ((_typeName is null) ? XmlQualifiedName.Empty : (XmlQualifiedName)_typeName); } set { _typeName = value; } } @@ -4927,10 +4927,10 @@ public void Merge(DataTable table, bool preserveChanges) => public void Merge(DataTable table, bool preserveChanges, MissingSchemaAction missingSchemaAction) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, preserveChanges={2}, missingSchemaAction={3}", ObjectID, (table != null) ? table.ObjectID : 0, preserveChanges, missingSchemaAction); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, preserveChanges={2}, missingSchemaAction={3}", ObjectID, (table is not null) ? table.ObjectID : 0, preserveChanges, missingSchemaAction); try { - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(table)); } @@ -4966,7 +4966,7 @@ public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEve if (PrimaryKey.Length == 0) { DataTableReader? dtReader = reader as DataTableReader; - if (dtReader != null && dtReader.CurrentDataTable == this) + if (dtReader is not null && dtReader.CurrentDataTable == this) { return; // if not return, it will go to infinite loop } @@ -4974,7 +4974,7 @@ public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEve Common.LoadAdapter adapter = new Common.LoadAdapter(); adapter.FillLoadOption = loadOption; adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; - if (null != errorHandler) + if (errorHandler is not null) { adapter.FillError += errorHandler; } @@ -4996,10 +4996,10 @@ private DataRow LoadRow(object?[] values, LoadOption loadOption, Index? searchIn int recordNo; DataRow? dataRow = null; - if (searchIndex != null) + if (searchIndex is not null) { int[] primaryKeyIndex = Array.Empty(); - if (_primaryKey != null) + if (_primaryKey is not null) { // we do check above for PK, but in case if someone else gives us some index unrelated to PK primaryKeyIndex = new int[_primaryKey.ColumnsReference.Length]; @@ -5031,7 +5031,7 @@ private DataRow LoadRow(object?[] values, LoadOption loadOption, Index? searchIn // values array is being reused by DataAdapter, do not modify the values array for (int count = 0; count < values.Length; count++) { - if (null == values[count]) + if (values[count] is null) { _columnCollection[count].Copy(resultRecord, recordNo); } @@ -5318,7 +5318,7 @@ private void SetDataRowWithLoadOption(DataRow dataRow, int recordNo, LoadOption public void WriteXml(Stream? stream, XmlWriteMode mode, bool writeHierarchy) { - if (stream != null) + if (stream is not null) { XmlTextWriter w = new XmlTextWriter(stream, null); w.Formatting = Formatting.Indented; @@ -5334,7 +5334,7 @@ public void WriteXml(TextWriter? writer, XmlWriteMode mode) public void WriteXml(TextWriter? writer, XmlWriteMode mode, bool writeHierarchy) { - if (writer != null) + if (writer is not null) { XmlTextWriter w = new XmlTextWriter(writer); w.Formatting = Formatting.Indented; @@ -5357,7 +5357,7 @@ public void WriteXml(XmlWriter? writer, XmlWriteMode mode, bool writeHierarchy) throw ExceptionBuilder.CanNotSerializeDataTableWithEmptyName(); } // Generate SchemaTree and write it out - if (writer != null) + if (writer is not null) { if (mode == XmlWriteMode.DiffGram) { @@ -5371,7 +5371,7 @@ public void WriteXml(XmlWriter? writer, XmlWriteMode mode, bool writeHierarchy) { DataSet? ds = null; string? tablenamespace = _tableNamespace; - if (null == DataSet) + if (DataSet is null) { ds = new DataSet(); @@ -5389,12 +5389,12 @@ public void WriteXml(XmlWriter? writer, XmlWriteMode mode, bool writeHierarchy) ds.Tables.Add(this); } - if (writer != null) + if (writer is not null) { XmlDataTreeWriter xmldataWriter = new XmlDataTreeWriter(this, writeHierarchy); xmldataWriter.Save(writer, /*mode == XmlWriteMode.WriteSchema*/true); } - if (null != ds) + if (ds is not null) { ds.Tables.Remove(this); _tableNamespace = tablenamespace; @@ -5441,7 +5441,7 @@ public void WriteXml(string fileName, XmlWriteMode mode, bool writeHierarchy) public void WriteXmlSchema(Stream? stream, bool writeHierarchy) { - if (stream == null) + if (stream is null) { return; } @@ -5456,7 +5456,7 @@ public void WriteXmlSchema(Stream? stream, bool writeHierarchy) public void WriteXmlSchema(TextWriter? writer, bool writeHierarchy) { - if (writer == null) + if (writer is null) { return; } @@ -5480,7 +5480,7 @@ private bool CheckForClosureOnExpressions(DataTable dt, bool writeHierarchy) private bool CheckForClosureOnExpressionTables(List tableList) { - Debug.Assert(tableList != null, "tableList shouldnot be null"); + Debug.Assert(tableList is not null, "tableList shouldnot be null"); foreach (DataTable datatable in tableList) { @@ -5523,7 +5523,7 @@ public void WriteXmlSchema(XmlWriter? writer, bool writeHierarchy) string? tablenamespace = _tableNamespace; //SQL BU Defect Tracking 286968 // Generate SchemaTree and write it out - if (null == DataSet) + if (DataSet is null) { ds = new DataSet(); // if user set values on DataTable, it isn't necessary @@ -5540,12 +5540,12 @@ public void WriteXmlSchema(XmlWriter? writer, bool writeHierarchy) ds.Tables.Add(this); } - if (writer != null) + if (writer is not null) { XmlTreeGen treeGen = new XmlTreeGen(SchemaFormat.Public); treeGen.Save(null, this, writer, writeHierarchy); } - if (null != ds) + if (ds is not null) { ds.Tables.Remove(this); _tableNamespace = tablenamespace; @@ -5577,7 +5577,7 @@ public void WriteXmlSchema(string fileName, bool writeHierarchy) public XmlReadMode ReadXml(Stream? stream) { - if (stream == null) + if (stream is null) { return XmlReadMode.Auto; } @@ -5592,7 +5592,7 @@ public XmlReadMode ReadXml(Stream? stream) public XmlReadMode ReadXml(TextReader? reader) { - if (reader == null) + if (reader is null) { return XmlReadMode.Auto; } @@ -5626,7 +5626,7 @@ public XmlReadMode ReadXml(string fileName) private void RestoreConstraint(bool originalEnforceConstraint) { - if (DataSet != null) + if (DataSet is not null) { DataSet.EnforceConstraints = originalEnforceConstraint; } @@ -5679,13 +5679,13 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) // clear the hashtable to avoid conflicts between diffgrams, SqlHotFix 782 rowDiffIdUsage.Prepare(this); - if (reader == null) + if (reader is null) { return ret; } bool originalEnforceConstraint = false; - if (DataSet != null) + if (DataSet is not null) { originalEnforceConstraint = DataSet.EnforceConstraints; DataSet.EnforceConstraints = false; @@ -5757,7 +5757,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) { - if (DataSet != null) + if (DataSet is not null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property DataSet.RestoreEnforceConstraints(originalEnforceConstraint); } @@ -5826,7 +5826,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) { - if (DataSet != null) + if (DataSet is not null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property DataSet.RestoreEnforceConstraints(originalEnforceConstraint); @@ -5856,7 +5856,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) } else { - if (xmlload == null) + if (xmlload is null) { xmlload = new XmlDataLoader(this, fIsXdr, topNode, false); } @@ -5881,7 +5881,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) throw ExceptionBuilder.DataTableInferenceNotSupported(); } - if (xmlload == null) + if (xmlload is null) xmlload = new XmlDataLoader(this, fIsXdr, false); // so we InferSchema @@ -5921,13 +5921,13 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol // prepare and cleanup rowDiffId hashtable rowDiffIdUsage.Prepare(this); - if (reader == null) + if (reader is null) { return ret; } bool originalEnforceConstraint = false; - if (DataSet != null) + if (DataSet is not null) { originalEnforceConstraint = DataSet.EnforceConstraints; DataSet.EnforceConstraints = false; @@ -6029,7 +6029,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) { - if (DataSet != null) + if (DataSet is not null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property DataSet.RestoreEnforceConstraints(originalEnforceConstraint); @@ -6123,7 +6123,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) { - if (DataSet != null) + if (DataSet is not null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property DataSet.RestoreEnforceConstraints(originalEnforceConstraint); @@ -6156,7 +6156,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol { throw ExceptionBuilder.DataTableInferenceNotSupported(); } - if (xmlload == null) + if (xmlload is null) { xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema); } @@ -6170,7 +6170,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol // now top node contains the data part xdoc.AppendChild(topNode); - if (xmlload == null) + if (xmlload is null) { xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema); } @@ -6322,7 +6322,7 @@ private void ReadXmlDiffgram(XmlReader reader) DataRelation[] relations = tableList[i].NestedParentRelations; foreach (DataRelation rel in relations) { - if (rel != null && rel.ParentTable == tableList[i]) + if (rel is not null && rel.ParentTable == tableList[i]) { foreach (DataRow r in tableList[i].Rows) { @@ -6360,7 +6360,7 @@ internal void ReadXSDSchema(XmlReader reader, bool denyResolving) public void ReadXmlSchema(Stream? stream) { - if (stream == null) + if (stream is null) { return; } @@ -6370,7 +6370,7 @@ public void ReadXmlSchema(Stream? stream) public void ReadXmlSchema(TextReader? reader) { - if (reader == null) + if (reader is null) { return; } @@ -6443,7 +6443,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) currentTable = ds.Tables[CurrentTableName, CurrentTableNamespace]; } - if (currentTable == null) + if (currentTable is null) { string qTableName = string.Empty; if (!string.IsNullOrEmpty(_tableName)) @@ -6472,7 +6472,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) DataTable tempTable = currentTable; tempTable.CloneTo(this, null, false); // we may have issue Amir - if (DataSet == null && _tableNamespace == null) + if (DataSet is null && _tableNamespace is null) { // for standalone table, clone won't get these correctly, since they may come with inheritance _tableNamespace = tempTable.Namespace; @@ -6490,7 +6490,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) Namespace = currentTable.Namespace; } } - if (DataSet == null) + if (DataSet is null) { DataSet dataset = new DataSet(ds.DataSetName); @@ -6510,7 +6510,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) dataset.Tables.Add(this); } - Debug.Assert(DataSet != null); + Debug.Assert(DataSet is not null); CloneHierarchy(currentTable, DataSet, null); @@ -6521,7 +6521,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) foreach (Constraint tempConstrain in sourceTable.Constraints) { ForeignKeyConstraint? fkc = tempConstrain as ForeignKeyConstraint; // we have already cloned the UKC when cloning the datatable - if (fkc != null) + if (fkc is not null) { if (fkc.Table != fkc.RelatedTable) { @@ -6638,7 +6638,7 @@ public static XmlSchemaComplexType GetDataTableSchema(XmlSchemaSet? schemaSet) MemoryStream stream = new MemoryStream(); XmlWriter writer = new XmlTextWriter(stream, null); - if (writer != null) + if (writer is not null) { (new XmlTreeGen(SchemaFormat.WebService)).Save(this, writer); } @@ -6653,14 +6653,14 @@ void IXmlSerializable.ReadXml(XmlReader reader) { IXmlTextParser? textReader = reader as IXmlTextParser; bool fNormalization = true; - if (textReader != null) + if (textReader is not null) { fNormalization = textReader.Normalized; textReader.Normalized = false; } ReadXmlSerializable(reader); - if (textReader != null) + if (textReader is not null) { textReader.Normalized = fNormalization; } @@ -6698,7 +6698,7 @@ internal struct RowDiffIdUsageSection // This list contains tables currently used in diffgram processing, not including new tables that might be added later during. // if diffgram processing is not started, this value must be null. when it starts, relevant method should call Prepare. // Notes: - // * in case of ReadXml on empty DataSet, this list can be initialized as empty (so empty list != null). + // * in case of ReadXml on empty DataSet, this list can be initialized as empty (so empty list is not null). // * only one scope is allowed on single thread, either for datatable or dataset // * assert is triggered if same table is added to this list twice // @@ -6711,16 +6711,16 @@ internal struct RowDiffIdUsageSection internal void Prepare(DataTable table) { - Debug.Assert(_targetTable == null, "do not reuse this section"); - Debug.Assert(table != null); - Debug.Assert(table._rowDiffId == null, "rowDiffId wasn't previously cleared"); + Debug.Assert(_targetTable is null, "do not reuse this section"); + Debug.Assert(table is not null); + Debug.Assert(table._rowDiffId is null, "rowDiffId wasn't previously cleared"); #if DEBUG - Debug.Assert(t_usedTables == null || !t_usedTables.Contains(table), + Debug.Assert(t_usedTables is null || !t_usedTables.Contains(table), "Nested call with same table can cause data corruption!"); #endif #if DEBUG - if (t_usedTables == null) + if (t_usedTables is null) t_usedTables = new List(); t_usedTables.Add(table); #endif @@ -6732,11 +6732,11 @@ internal void Prepare(DataTable table) internal void Cleanup() { // cannot assume target table was set - if (_targetTable != null) + if (_targetTable is not null) { #if DEBUG - Debug.Assert(t_usedTables != null && t_usedTables.Contains(_targetTable), "missing Prepare before Cleanup"); - if (t_usedTables != null) + Debug.Assert(t_usedTables is not null && t_usedTables.Contains(_targetTable), "missing Prepare before Cleanup"); + if (t_usedTables is not null) { t_usedTables.Remove(_targetTable); if (t_usedTables.Count == 0) @@ -6753,7 +6753,7 @@ internal static void Assert(string message) #if DEBUG // this code asserts scope was created, but it does not assert that the table was included in it // note that in case of DataSet, new tables might be added to the list in which case they won't appear in t_usedTables. - Debug.Assert(t_usedTables != null, message); + Debug.Assert(t_usedTables is not null, message); #endif } } @@ -6764,14 +6764,14 @@ internal struct DSRowDiffIdUsageSection internal void Prepare(DataSet ds) { - Debug.Assert(_targetDS == null, "do not reuse this section"); - Debug.Assert(ds != null); + Debug.Assert(_targetDS is null, "do not reuse this section"); + Debug.Assert(ds is not null); _targetDS = ds; #if DEBUG // initialize list of tables out of current tables // note: it might remain empty (still initialization is needed for assert to operate) - if (RowDiffIdUsageSection.t_usedTables == null) + if (RowDiffIdUsageSection.t_usedTables is null) RowDiffIdUsageSection.t_usedTables = new List(); #endif for (int tableIndex = 0; tableIndex < ds.Tables.Count; ++tableIndex) @@ -6781,7 +6781,7 @@ internal void Prepare(DataSet ds) Debug.Assert(!RowDiffIdUsageSection.t_usedTables.Contains(table), "Nested call with same table can cause data corruption!"); RowDiffIdUsageSection.t_usedTables.Add(table); #endif - Debug.Assert(table._rowDiffId == null, "rowDiffId wasn't previously cleared"); + Debug.Assert(table._rowDiffId is null, "rowDiffId wasn't previously cleared"); table._rowDiffId = null; } } @@ -6790,10 +6790,10 @@ internal void Prepare(DataSet ds) internal void Cleanup() { // cannot assume target was set - if (_targetDS != null) + if (_targetDS is not null) { #if DEBUG - Debug.Assert(RowDiffIdUsageSection.t_usedTables != null, "missing Prepare before Cleanup"); + Debug.Assert(RowDiffIdUsageSection.t_usedTables is not null, "missing Prepare before Cleanup"); #endif for (int tableIndex = 0; tableIndex < _targetDS.Tables.Count; ++tableIndex) @@ -6802,13 +6802,13 @@ internal void Cleanup() #if DEBUG // cannot assert that table exists in the usedTables - new tables might be // created during diffgram processing in DataSet.ReadXml. - if (RowDiffIdUsageSection.t_usedTables != null) + if (RowDiffIdUsageSection.t_usedTables is not null) RowDiffIdUsageSection.t_usedTables.Remove(table); #endif table._rowDiffId = null; } #if DEBUG - if (RowDiffIdUsageSection.t_usedTables != null && RowDiffIdUsageSection.t_usedTables.Count == 0) + if (RowDiffIdUsageSection.t_usedTables is not null && RowDiffIdUsageSection.t_usedTables.Count == 0) RowDiffIdUsageSection.t_usedTables = null; // out-of-scope #endif } @@ -6822,7 +6822,7 @@ internal Hashtable RowDiffId // assert scope has been created either with RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare RowDiffIdUsageSection.Assert("missing call to RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare"); - if (_rowDiffId == null) + if (_rowDiffId is null) { _rowDiffId = new Hashtable(); } @@ -6834,7 +6834,7 @@ internal Hashtable RowDiffId internal void AddDependentColumn(DataColumn expressionColumn) { - if (_dependentColumns == null) + if (_dependentColumns is null) { _dependentColumns = new List(); } @@ -6848,7 +6848,7 @@ internal void AddDependentColumn(DataColumn expressionColumn) internal void RemoveDependentColumn(DataColumn expressionColumn) { - if (_dependentColumns != null && _dependentColumns.Contains(expressionColumn)) + if (_dependentColumns is not null && _dependentColumns.Contains(expressionColumn)) { _dependentColumns.Remove(expressionColumn); } @@ -6902,11 +6902,11 @@ internal void EvaluateExpressions(DataRow row, DataRowAction action, List? columns, DataRow row, DataRowVersion version, List? cachedRows) { - if (columns == null) + if (columns is null) { return; } @@ -7048,7 +7048,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro { // if this column is in my table DataColumn dc = columns[i]; - if (dc.DataExpression != null && dc.DataExpression.HasLocalAggregate()) + if (dc.DataExpression is not null && dc.DataExpression.HasLocalAggregate()) { // if column expression references a local Table aggregate we need to recalc it for the each row in the local table DataRowVersion expressionVersion = (version == DataRowVersion.Proposed) ? DataRowVersion.Default : version; @@ -7089,7 +7089,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro { continue; } - SilentlySetValue(row, dc, version, dc.DataExpression == null ? dc.DefaultValue : dc.DataExpression.Evaluate(row, version)); + SilentlySetValue(row, dc, version, dc.DataExpression is null ? dc.DefaultValue : dc.DataExpression.Evaluate(row, version)); } } } @@ -7099,12 +7099,12 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro { DataColumn dc = columns[i]; // if this column is NOT in my table or it is in the table and is not a local aggregate (self refs) - if (dc.Table != this || (dc.DataExpression != null && !dc.DataExpression.HasLocalAggregate())) + if (dc.Table != this || (dc.DataExpression is not null && !dc.DataExpression.HasLocalAggregate())) { DataRowVersion foreignVer = (version == DataRowVersion.Proposed) ? DataRowVersion.Default : version; // first - evaluate expressions for cachedRows (deletes & updates) - if (cachedRows != null) + if (cachedRows is not null) { foreach (DataRow cachedRow in cachedRows) { @@ -7119,7 +7119,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro continue; } - if (cachedRow != null && ((cachedRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || cachedRow._oldRecord != -1))) + if (cachedRow is not null && ((cachedRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || cachedRow._oldRecord != -1))) { // if deleted GetRecordFromVersion will throw // TODO: Possible bug, dc.DataExpression may be null @@ -7140,7 +7140,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro foreach (DataRow parentRow in row.GetParentRows(relation, version)) { - if (cachedRows != null && cachedRows.Contains(parentRow)) + if (cachedRows is not null && cachedRows.Contains(parentRow)) { continue; } @@ -7151,7 +7151,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro continue; } - if (parentRow != null && ((parentRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || parentRow._oldRecord != -1))) + if (parentRow is not null && ((parentRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || parentRow._oldRecord != -1))) { // if deleted GetRecordFromVersion will throw // TODO: Possible bug, dc.DataExpression may be null @@ -7173,7 +7173,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro foreach (DataRow childRow in row.GetChildRows(relation, version)) { // don't update original version if child row doesn't have an oldRecord. - if (cachedRows != null && cachedRows.Contains(childRow)) + if (cachedRows is not null && cachedRows.Contains(childRow)) { continue; } @@ -7183,7 +7183,7 @@ internal void EvaluateDependentExpressions(List? columns, DataRow ro continue; } - if (childRow != null && ((childRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || childRow._oldRecord != -1))) + if (childRow is not null && ((childRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || childRow._oldRecord != -1))) { // if deleted GetRecordFromVersion will throw // TODO: Possible bug, dc.DataExpression may be null diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs index 5677da8639e5d1..d0fa81768adc49 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs @@ -35,7 +35,7 @@ public sealed class DataTableCollection : InternalDataCollectionBase /// internal DataTableCollection(DataSet dataSet) { - DataCommonEventSource.Log.Trace(" {0}, dataSet={1}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0); + DataCommonEventSource.Log.Trace(" {0}, dataSet={1}", ObjectID, (dataSet is not null) ? dataSet.ObjectID : 0); _dataSet = dataSet!; } @@ -89,7 +89,7 @@ public DataTable? this[string? name] { get { - if (tableNamespace == null) + if (tableNamespace is null) { throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace)); } @@ -146,7 +146,7 @@ public DataTable? this[string? name] /// public void Add(DataTable table) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table != null) ? table.ObjectID : 0); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table is not null) ? table.ObjectID : 0); try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Add, table)); @@ -177,11 +177,11 @@ public void AddRange(DataTable?[]? tables) return; } - if (tables != null) + if (tables is not null) { foreach (DataTable? table in tables) { - if (table != null) + if (table is not null) { Add(table); } @@ -276,7 +276,7 @@ internal string AssignName() /// private void BaseAdd([NotNull] DataTable table) { - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(table)); } @@ -284,7 +284,7 @@ private void BaseAdd([NotNull] DataTable table) { throw ExceptionBuilder.TableAlreadyInTheDataSet(); } - if (table.DataSet != null) + if (table.DataSet is not null) { throw ExceptionBuilder.TableAlreadyInOtherDataSet(); } @@ -379,10 +379,10 @@ private void BaseRemove(DataTable? table) internal bool CanRemove([NotNullWhen(true)] DataTable? table, bool fThrowException) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, fThrowException={2}", ObjectID, (table != null) ? table.ObjectID : 0, fThrowException); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, fThrowException={2}", ObjectID, (table is not null) ? table.ObjectID : 0, fThrowException); try { - if (table == null) + if (table is null) { if (!fThrowException) { @@ -468,7 +468,7 @@ public void Clear() OnCollectionChanging(s_refreshEventArgs); - if (_dataSet._fInitInProgress && _delayedAddRangeTables != null) + if (_dataSet._fInitInProgress && _delayedAddRangeTables is not null) { _delayedAddRangeTables = null; } @@ -491,12 +491,12 @@ public void Clear() public bool Contains(string name, string tableNamespace) { - if (name == null) + if (name is null) { throw ExceptionBuilder.ArgumentNull(nameof(name)); } - if (tableNamespace == null) + if (tableNamespace is null) { throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace)); } @@ -548,7 +548,7 @@ internal bool Contains(string name, bool caseSensitive) public void CopyTo(DataTable[] array, int index) { - if (array == null) + if (array is null) { throw ExceptionBuilder.ArgumentNull(nameof(array)); } @@ -600,11 +600,11 @@ internal int IndexOf(string tableName, string tableNamespace, bool chekforNull) // this should be public! why it is missing? if (chekforNull) { - if (tableName == null) + if (tableName is null) { throw ExceptionBuilder.ArgumentNull(nameof(tableName)); } - if (tableNamespace == null) + if (tableNamespace is null) { throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace)); } @@ -628,7 +628,7 @@ internal void ReplaceFromInference(List tableList) internal int InternalIndexOf(string? tableName) { int cachedI = -1; - if ((null != tableName) && (0 < tableName.Length)) + if ((tableName is not null) && (0 < tableName.Length)) { int count = _list.Count; int result = 0; @@ -665,7 +665,7 @@ internal int InternalIndexOf(string? tableName) internal int InternalIndexOf(string? tableName, string tableNamespace) { int cachedI = -1; - if ((null != tableName) && (0 < tableName.Length)) + if ((tableName is not null) && (0 < tableName.Length)) { int count = _list.Count; int result = 0; @@ -685,11 +685,11 @@ internal int InternalIndexOf(string? tableName, string tableNamespace) internal void FinishInitCollection() { - if (_delayedAddRangeTables != null) + if (_delayedAddRangeTables is not null) { foreach (DataTable? table in _delayedAddRangeTables) { - if (table != null) + if (table is not null) { Add(table); } @@ -710,7 +710,7 @@ private string MakeName(int index) => 1 == index ? /// private void OnCollectionChanged(CollectionChangeEventArgs ccevent) { - if (_onCollectionChangedDelegate != null) + if (_onCollectionChangedDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onCollectionChangedDelegate(this, ccevent); @@ -719,7 +719,7 @@ private void OnCollectionChanged(CollectionChangeEventArgs ccevent) private void OnCollectionChanging(CollectionChangeEventArgs ccevent) { - if (_onCollectionChangingDelegate != null) + if (_onCollectionChangingDelegate is not null) { DataCommonEventSource.Log.Trace(" {0}", ObjectID); _onCollectionChangingDelegate(this, ccevent); @@ -734,7 +734,7 @@ private void OnCollectionChanging(CollectionChangeEventArgs ccevent) internal void RegisterName(string name, string tbNamespace) { DataCommonEventSource.Log.Trace(" {0}, name='{1}', tbNamespace='{2}'", ObjectID, name, tbNamespace); - Debug.Assert(name != null); + Debug.Assert(name is not null); CultureInfo locale = _dataSet.Locale; int tableCount = _list.Count; @@ -757,7 +757,7 @@ internal void RegisterName(string name, string tbNamespace) /// public void Remove(DataTable table) { - long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table != null) ? table.ObjectID : 0); + long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table is not null) ? table.ObjectID : 0); try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Remove, table)); @@ -779,7 +779,7 @@ public void RemoveAt(int index) try { DataTable dt = this[index]; - if (dt == null) + if (dt is null) { throw ExceptionBuilder.TableOutOfRange(index); } @@ -800,7 +800,7 @@ public void Remove(string name) try { DataTable? dt = this[name]; - if (dt == null) + if (dt is null) { throw ExceptionBuilder.TableNotInTheDataSet(name); } @@ -814,16 +814,16 @@ public void Remove(string name) public void Remove(string name, string tableNamespace) { - if (name == null) + if (name is null) { throw ExceptionBuilder.ArgumentNull(nameof(name)); } - if (tableNamespace == null) + if (tableNamespace is null) { throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace)); } DataTable? dt = this[name, tableNamespace]; - if (dt == null) + if (dt is null) { throw ExceptionBuilder.TableNotInTheDataSet(name); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs index c5a04f760f67be..44e8f37b681be7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs @@ -106,10 +106,10 @@ private static DataTable LoadTableFromEnumerable(IEnumerable source, DataT } DataRow current; - if (table == null) + if (table is null) { current = rows.Current; - if (current == null) + if (current is null) { throw DataSetUtil.InvalidOperation(SR.DataSetLinq_NullDataRow); } @@ -136,7 +136,7 @@ private static DataTable LoadTableFromEnumerable(IEnumerable source, DataT do { current = rows.Current; - if (current == null) + if (current is null) { continue; } @@ -180,7 +180,7 @@ private static DataTable LoadTableFromEnumerable(IEnumerable source, DataT } FillErrorEventArgs? fillError = null; - if (null != errorHandler) + if (errorHandler is not null) { fillError = new FillErrorEventArgs(table, values) { @@ -188,7 +188,7 @@ private static DataTable LoadTableFromEnumerable(IEnumerable source, DataT }; errorHandler.Invoke(rows, fillError); } - if (null == fillError) + if (fillError is null) { throw; } @@ -215,7 +215,7 @@ private static DataTable LoadTableFromEnumerable(IEnumerable source, DataT table.EndLoadData(); } } - Debug.Assert(null != table, "null DataTable"); + Debug.Assert(table is not null, "null DataTable"); return table; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs index 59b2a5cff7cbf3..27f9b3375a5bc7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs @@ -28,7 +28,7 @@ public sealed class DataTableReader : DbDataReader public DataTableReader(DataTable dataTable) { - if (dataTable == null) + if (dataTable is null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } @@ -39,7 +39,7 @@ public DataTableReader(DataTable dataTable) public DataTableReader(DataTable[] dataTables) { - if (dataTables == null) + if (dataTables is null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } @@ -51,7 +51,7 @@ public DataTableReader(DataTable[] dataTables) _tables = new DataTable[dataTables.Length]; for (int i = 0; i < dataTables.Length; i++) { - if (dataTables[i] == null) + if (dataTables[i] is null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } @@ -72,7 +72,7 @@ private bool ReaderIsInvalid } _readerIsInvalid = value; - if (_readerIsInvalid && _listener != null) + if (_readerIsInvalid && _listener is not null) { _listener.CleanUp(); } @@ -90,7 +90,7 @@ private bool IsSchemaChanged } _schemaIsChanged = value; - if (_listener != null) + if (_listener is not null) { _listener.CleanUp(); } @@ -120,7 +120,7 @@ public override void Close() } // no need to listen to events after close - if (_listener != null) + if (_listener is not null) { _listener.CleanUp(); } @@ -137,7 +137,7 @@ public override DataTable GetSchemaTable() // each time, we just get schema table of current table for once, no need to recreate each time, if schema is changed, reader is already // is invalid - if (_schemaTable == null) + if (_schemaTable is null) { _schemaTable = GetSchemaTableFromDataTable(_currentDataTable); } @@ -157,7 +157,7 @@ public override bool NextResult() _currentDataTable = _tables[++_tableCounter]; - if (_listener != null) + if (_listener is not null) { _listener.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events } @@ -194,7 +194,7 @@ public override bool Read() if (_rowCounter >= _currentDataTable.Rows.Count - 1) { _reachEORows = true; - if (_listener != null) + if (_listener is not null) { _listener.CleanUp(); } @@ -211,7 +211,7 @@ public override bool Read() if (_rowCounter == _currentDataTable.Rows.Count) { _reachEORows = true; - if (_listener != null) + if (_listener is not null) { _listener.CleanUp(); } @@ -265,7 +265,7 @@ public override object this[int ordinal] { ValidateOpen("Item"); ValidateReader(); - if ((_currentDataRow == null) || (_currentDataRow.RowState == DataRowState.Deleted)) + if ((_currentDataRow is null) || (_currentDataRow.RowState == DataRowState.Deleted)) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); @@ -289,7 +289,7 @@ public override object this[string name] { ValidateOpen("Item"); ValidateReader(); - if ((_currentDataRow == null) || (_currentDataRow.RowState == DataRowState.Deleted)) + if ((_currentDataRow is null) || (_currentDataRow.RowState == DataRowState.Deleted)) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); @@ -377,7 +377,7 @@ public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int b throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } - if (buffer == null) + if (buffer is null) { return tempBuffer.Length; } @@ -440,7 +440,7 @@ public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int b throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } - if (buffer == null) + if (buffer is null) { return tempBuffer.Length; } @@ -642,7 +642,7 @@ public override int GetOrdinal(string name) ValidateReader(); DataColumn? dc = _currentDataTable.Columns[name]; - if (dc != null) + if (dc is not null) { return dc.Ordinal; } @@ -689,7 +689,7 @@ public override int GetValues(object[] values) ValidateState(nameof(GetValues)); ValidateReader(); - if (values == null) + if (values is null) { throw ExceptionBuilder.ArgumentNull(nameof(values)); } @@ -721,7 +721,7 @@ public override IEnumerator GetEnumerator() internal static DataTable GetSchemaTableFromDataTable(DataTable table) { - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } @@ -757,7 +757,7 @@ internal static DataTable GetSchemaTableFromDataTable(DataTable table) ColumnSize.DefaultValue = -1; - if (table.DataSet != null) + if (table.DataSet is not null) { BaseCatalogName.DefaultValue = table.DataSet.DataSetName; } @@ -894,7 +894,7 @@ private void ValidateState(string caller) } // see if without any event raising, if our current row has some changes!if so reader is invalid. - if ((_currentDataRow == null) || (_currentDataTable == null)) + if ((_currentDataRow is null) || (_currentDataTable is null)) { ReaderIsInvalid = true; // TODO: This will throw an NRE diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs index 5008247f62d621..19ad1545f03941 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs @@ -13,17 +13,17 @@ internal sealed class DataTableReaderListener internal DataTableReaderListener(DataTableReader reader) { - if (reader == null) + if (reader is null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTableReader)); } - if (_currentDataTable != null) + if (_currentDataTable is not null) { UnSubscribeEvents(); } _readerWeak = new WeakReference(reader); _currentDataTable = reader.CurrentDataTable; - if (_currentDataTable != null) + if (_currentDataTable is not null) { SubscribeEvents(); } @@ -33,7 +33,7 @@ internal DataTableReaderListener(DataTableReader reader) internal void UpdataTable(DataTable datatable) { - if (datatable == null) + if (datatable is null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } @@ -45,7 +45,7 @@ internal void UpdataTable(DataTable datatable) private void SubscribeEvents() { - if (_currentDataTable == null) + if (_currentDataTable is null) { return; } @@ -65,7 +65,7 @@ private void SubscribeEvents() private void UnSubscribeEvents() { - if (_currentDataTable == null) + if (_currentDataTable is null) { return; } @@ -87,7 +87,7 @@ private void UnSubscribeEvents() private void DataTableCleared(object sender, DataTableClearEventArgs e) { DataTableReader? reader = (DataTableReader?)_readerWeak.Target; - if (reader != null) + if (reader is not null) { reader.DataTableCleared(); } @@ -100,7 +100,7 @@ private void DataTableCleared(object sender, DataTableClearEventArgs e) private void SchemaChanged(object sender, CollectionChangeEventArgs e) { DataTableReader? reader = (DataTableReader?)_readerWeak.Target; - if (reader != null) + if (reader is not null) { reader.SchemaChanged(); } @@ -113,7 +113,7 @@ private void SchemaChanged(object sender, CollectionChangeEventArgs e) private void DataChanged(object sender, DataRowChangeEventArgs args) { DataTableReader? reader = (DataTableReader?)_readerWeak.Target; - if (reader != null) + if (reader is not null) { reader.DataChanged(args); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataView.cs b/src/libraries/System.Data.Common/src/System/Data/DataView.cs index 11ed8cd79f61d9..174890300cbbf4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataView.cs @@ -97,7 +97,7 @@ private DataRowReferenceComparer() { } internal DataView(DataTable? table, bool locked) { GC.SuppressFinalize(this); - DataCommonEventSource.Log.Trace(" {0}, table={1}, locked={2}", ObjectID, (table != null) ? table.ObjectID : 0, locked); + DataCommonEventSource.Log.Trace(" {0}, table={1}, locked={2}", ObjectID, (table is not null) ? table.ObjectID : 0, locked); _dvListener = new DataViewListener(this); _locked = locked; @@ -130,9 +130,9 @@ public DataView(DataTable table, string? RowFilter, string? Sort, DataViewRowSta { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" {0}, table={1}, RowFilter='{2}', Sort='{3}', RowState={4}", - ObjectID, (table != null) ? table.ObjectID : 0, RowFilter, Sort, RowState); + ObjectID, (table is not null) ? table.ObjectID : 0, RowFilter, Sort, RowState); - if (table == null) + if (table is null) { throw ExceptionBuilder.CanNotUse(); } @@ -152,12 +152,12 @@ public DataView(DataTable table, string? RowFilter, string? Sort, DataViewRowSta throw ExceptionBuilder.SetRowStateFilter(); } - if (Sort == null) + if (Sort is null) { Sort = string.Empty; } - if (RowFilter == null) + if (RowFilter is null) { RowFilter = string.Empty; } @@ -170,9 +170,9 @@ internal DataView(DataTable table, System.Predicate? predicate, System. { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" %d#, table=%d, RowState=%d{ds.DataViewRowState}\n", - ObjectID, (table != null) ? table.ObjectID : 0, (int)RowState); + ObjectID, (table is not null) ? table.ObjectID : 0, (int)RowState); - if (table == null) + if (table is null) { throw ExceptionBuilder.CanNotUse(); } @@ -193,7 +193,7 @@ internal DataView(DataTable table, System.Predicate? predicate, System. } _comparison = comparison; - SetIndex2("", RowState, ((null != predicate) ? new RowPredicateFilter(predicate) : null), true); + SetIndex2("", RowState, ((predicate is not null) ? new RowPredicateFilter(predicate) : null), true); } /// @@ -312,11 +312,11 @@ public virtual string? RowFilter get { DataExpression? expression = (_rowFilter as DataExpression); - return (expression == null ? "" : expression.Expression); // CONSIDER: return optimized expression here + return (expression is null ? "" : expression.Expression); // CONSIDER: return optimized expression here } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -328,7 +328,7 @@ public virtual string? RowFilter return; } - CultureInfo locale = (_table != null ? _table.Locale : CultureInfo.CurrentCulture); + CultureInfo locale = (_table is not null ? _table.Locale : CultureInfo.CurrentCulture); if (null == _rowFilter || (string.Compare(RowFilter, value, false, locale) != 0)) { DataExpression newFilter = new DataExpression(_table, value); @@ -347,13 +347,13 @@ internal Predicate? RowPredicate get { RowPredicateFilter? filter = (GetFilter() as RowPredicateFilter); - return ((null != filter) ? filter._predicateFilter : null); + return ((filter is not null) ? filter._predicateFilter : null); } set { if (!ReferenceEquals(RowPredicate, value)) { - SetIndex(Sort, RowStateFilter, ((null != value) ? new RowPredicateFilter(value) : null)); + SetIndex(Sort, RowStateFilter, ((value is not null) ? new RowPredicateFilter(value) : null)); } } } @@ -365,7 +365,7 @@ private sealed class RowPredicateFilter : System.Data.IFilter /// internal RowPredicateFilter(Predicate predicate) { - Debug.Assert(null != predicate, "null predicate"); + Debug.Assert(predicate is not null, "null predicate"); _predicateFilter = predicate; } @@ -421,7 +421,7 @@ public string Sort { get { - if (_sort.Length == 0 && _applyDefaultSort && _table != null && _table._primaryIndex.Length > 0) + if (_sort.Length == 0 && _applyDefaultSort && _table is not null && _table._primaryIndex.Length > 0) { return _table.FormatSortString(_table._primaryIndex); } @@ -432,7 +432,7 @@ public string Sort } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -444,7 +444,7 @@ public string Sort return; } - CultureInfo locale = (_table != null ? _table.Locale : CultureInfo.CurrentCulture); + CultureInfo locale = (_table is not null ? _table.Locale : CultureInfo.CurrentCulture); if (string.Compare(_sort, value, false, locale) != 0 || (null != _comparison)) { CheckSort(value); @@ -483,8 +483,8 @@ public DataTable? Table get { return _table; } set { - DataCommonEventSource.Log.Trace(" {0}, {1}", ObjectID, (value != null) ? value.ObjectID : 0); - if (_fInitInProgress && value != null) + DataCommonEventSource.Log.Trace(" {0}, {1}", ObjectID, (value is not null) ? value.ObjectID : 0); + if (_fInitInProgress && value is not null) { _delayedTable = value; return; @@ -494,11 +494,11 @@ public DataTable? Table { throw ExceptionBuilder.SetTable(); } - if (_dataViewManager != null) + if (_dataViewManager is not null) { throw ExceptionBuilder.CanNotSetTable(); } - if (value != null && value.TableName.Length == 0) + if (value is not null && value.TableName.Length == 0) { throw ExceptionBuilder.CanNotBindTable(); } @@ -507,13 +507,13 @@ public DataTable? Table { _dvListener.UnregisterMetaDataEvents(); _table = value; - if (_table != null) + if (_table is not null) { _dvListener.RegisterMetaDataEvents(_table); } SetIndex2("", DataViewRowState.CurrentRows, null, false); - if (_table != null) + if (_table is not null) { OnListChanged(new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, new DataTablePropertyDescriptor(_table))); } @@ -552,7 +552,7 @@ public virtual DataRowView AddNew() { throw ExceptionBuilder.AddNewNotAllowNull(); } - if (_addNewRow != null) + if (_addNewRow is not null) { _rowViewCache[_addNewRow].EndEdit(); } @@ -579,7 +579,7 @@ public void BeginInit() public void EndInit() { - if (_delayedTable != null && _delayedTable.fInitInProgress) + if (_delayedTable is not null && _delayedTable.fInitInProgress) { _delayedTable._delayedViews.Add(this); return; @@ -587,17 +587,17 @@ public void EndInit() _fInitInProgress = false; _fEndInitInProgress = true; - if (_delayedTable != null) + if (_delayedTable is not null) { Table = _delayedTable; _delayedTable = null; } - if (_delayedSort != null) + if (_delayedSort is not null) { Sort = _delayedSort; _delayedSort = null; } - if (_delayedRowFilter != null) + if (_delayedRowFilter is not null) { RowFilter = _delayedRowFilter; _delayedRowFilter = null; @@ -620,7 +620,7 @@ private void CheckOpen() private void CheckSort(string sort) { - if (_table == null) + if (_table is null) { throw ExceptionBuilder.CanNotUse(); } @@ -688,7 +688,7 @@ private void CopyTo(DataRowView[] array, int index) internal void Delete(DataRow row) { - if (null != row) + if (row is not null) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, row={1}", ObjectID, row._objectID); try @@ -846,7 +846,7 @@ public IEnumerator GetEnumerator() int IList.Add(object? value) { - if (value == null) + if (value is null) { // null is default value, so we AddNew. AddNew(); @@ -868,7 +868,7 @@ void IList.Clear() /// Behavioral change: will now return -1 once a DataRowView becomes detached. internal int IndexOf(DataRowView? rowview) { - if (null != rowview) + if (rowview is not null) { if (ReferenceEquals(_addNewRow, rowview.Row)) { @@ -917,7 +917,7 @@ void IList.Remove(object? value) internal Index? GetFindIndex(string column, bool keepIndex) { - if (_findIndexes == null) + if (_findIndexes is null) { _findIndexes = new Dictionary(); } @@ -965,7 +965,7 @@ void IList.Remove(object? value) internal PropertyDescriptor GetSortProperty() { - if (_table != null && _index != null && _index._indexFields.Length == 1) + if (_table is not null && _index is not null && _index._indexFields.Length == 1) { return new DataColumnPropertyDescriptor(_index._indexFields[0].Column); } @@ -1013,7 +1013,7 @@ void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direc int IBindingList.Find(PropertyDescriptor property, object key) { // NOTE: this function had keepIndex previosely - if (property != null) + if (property is not null) { bool created = false; Index? findIndex = null; @@ -1035,7 +1035,7 @@ int IBindingList.Find(PropertyDescriptor property, object key) } finally { - if (created && (null != findIndex)) + if (created && (findIndex is not null)) { findIndex.RemoveRef(); if (findIndex.RefCount == 1) @@ -1067,7 +1067,7 @@ void IBindingList.RemoveSort() void IBindingListView.ApplySort(ListSortDescriptionCollection sorts) { - if (sorts == null) + if (sorts is null) { throw ExceptionBuilder.ArgumentNull(nameof(sorts)); } @@ -1076,13 +1076,13 @@ void IBindingListView.ApplySort(ListSortDescriptionCollection sorts) bool addCommaToString = false; foreach (ListSortDescription sort in sorts) { - if (sort == null) + if (sort is null) { throw ExceptionBuilder.ArgumentContainsNull(nameof(sorts)); } PropertyDescriptor property = sort.PropertyDescriptor; - if (property == null) + if (property is null) { throw ExceptionBuilder.ArgumentNull(nameof(PropertyDescriptor)); } @@ -1110,7 +1110,7 @@ void IBindingListView.ApplySort(ListSortDescriptionCollection sorts) private string CreateSortString(PropertyDescriptor property, ListSortDirection direction) { - Debug.Assert(property != null, "property is null"); + Debug.Assert(property is not null, "property is null"); StringBuilder resultString = new StringBuilder(); resultString.Append('['); resultString.Append(property.Name); @@ -1143,7 +1143,7 @@ string IBindingListView.Filter internal ListSortDescriptionCollection GetSortDescriptions() { ListSortDescription[] sortDescArray = Array.Empty(); - if (_table != null && _index != null && _index._indexFields.Length > 0) + if (_table is not null && _index is not null && _index._indexFields.Length > 0) { sortDescArray = new ListSortDescription[_index._indexFields.Length]; for (int i = 0; i < _index._indexFields.Length; i++) @@ -1173,19 +1173,19 @@ internal ListSortDescriptionCollection GetSortDescriptions() string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAccessors) { - if (_table != null) + if (_table is not null) { - if (listAccessors == null || listAccessors.Length == 0) + if (listAccessors is null || listAccessors.Length == 0) { return _table.TableName; } else { DataSet? dataSet = _table.DataSet; - if (dataSet != null) + if (dataSet is not null) { DataTable? foundTable = dataSet.FindTable(_table, listAccessors, 0); - if (foundTable != null) + if (foundTable is not null) { return foundTable.TableName; } @@ -1197,22 +1197,22 @@ string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAcc PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { - if (_table != null) + if (_table is not null) { - if (listAccessors == null || listAccessors.Length == 0) + if (listAccessors is null || listAccessors.Length == 0) { return _table.GetPropertyDescriptorCollection(null); } else { DataSet? dataSet = _table.DataSet; - if (dataSet == null) + if (dataSet is null) { return new PropertyDescriptorCollection(null); } DataTable? foundTable = dataSet.FindTable(_table, listAccessors, 0); - if (foundTable != null) + if (foundTable is not null) { return foundTable.GetPropertyDescriptorCollection(null); } @@ -1248,7 +1248,7 @@ internal DataRow GetRow(int index) { throw ExceptionBuilder.GetElementIndex(index); } - if ((index == (count - 1)) && (_addNewRow != null)) + if ((index == (count - 1)) && (_addNewRow is not null)) { // if we could rely on tempRecord being registered with recordManager // then this special case code would go away @@ -1268,7 +1268,7 @@ protected virtual void IndexListChanged(object sender, ListChangedEventArgs e) OnListChanged(e); } - if (_addNewRow != null && _index!.RecordCount == 0) + if (_addNewRow is not null && _index!.RecordCount == 0) { FinishAddNew(false); } @@ -1308,7 +1308,7 @@ internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool t switch (changedType) { case ListChangedType.ItemAdded: - Debug.Assert(null != row, "MaintainDataView.ItemAdded with null DataRow"); + Debug.Assert(row is not null, "MaintainDataView.ItemAdded with null DataRow"); if (trackAddRemove) { if (_rowViewBuffer.TryGetValue(row, out buffer)) @@ -1337,14 +1337,14 @@ internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool t } break; case ListChangedType.ItemDeleted: - Debug.Assert(null != row, "MaintainDataView.ItemDeleted with null DataRow"); + Debug.Assert(row is not null, "MaintainDataView.ItemDeleted with null DataRow"); Debug.Assert(row != _addNewRow, "addNewRow being deleted"); if (trackAddRemove) { // help turn expression add/remove into a changed/move _rowViewCache.TryGetValue(row, out buffer); - if (null != buffer) + if (buffer is not null) { _rowViewBuffer.Add(row, buffer); } @@ -1359,7 +1359,7 @@ internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool t } break; case ListChangedType.Reset: - Debug.Assert(null == row, "MaintainDataView.Reset with non-null DataRow"); + Debug.Assert(row is null, "MaintainDataView.Reset with non-null DataRow"); ResetRowViewCache(); break; case ListChangedType.ItemChanged: @@ -1404,7 +1404,7 @@ protected virtual void OnListChanged(ListChangedEventArgs e) if (dr.HasPropertyChanged) { col = dr.LastChangedColumn; - propertyName = (null != col) ? col.ColumnName : string.Empty; + propertyName = (col is not null) ? col.ColumnName : string.Empty; } } @@ -1419,9 +1419,9 @@ protected virtual void OnListChanged(ListChangedEventArgs e) break; } - if (_onListChanged != null) + if (_onListChanged is not null) { - if ((col != null) && (e.NewIndex == e.OldIndex)) + if ((col is not null) && (e.NewIndex == e.OldIndex)) { ListChangedEventArgs newEventArg = new ListChangedEventArgs(e.ListChangedType, e.NewIndex, new DataColumnPropertyDescriptor(col)); _onListChanged(this, newEventArg); @@ -1431,7 +1431,7 @@ protected virtual void OnListChanged(ListChangedEventArgs e) _onListChanged(this, e); } } - if (null != propertyName) + if (propertyName is not null) { // empty string if more than 1 column changed this[e.NewIndex].RaisePropertyChangedEvent(propertyName); @@ -1488,7 +1488,7 @@ internal void ResetRowViewCache() if (null != _addNewRow) { _rowViewCache.TryGetValue(_addNewRow, out drv); - Debug.Assert(null != drv, "didn't contain addNewRow"); + Debug.Assert(drv is not null, "didn't contain addNewRow"); rvc.Add(_addNewRow, drv); } Debug.Assert(rvc.Count == CountFromIndex, "didn't add expected count"); @@ -1497,18 +1497,18 @@ internal void ResetRowViewCache() internal void SetDataViewManager(DataViewManager? dataViewManager) { - if (_table == null) + if (_table is null) throw ExceptionBuilder.CanNotUse(); if (_dataViewManager != dataViewManager) { - if (dataViewManager != null) + if (dataViewManager is not null) { dataViewManager._nViews--; } _dataViewManager = dataViewManager; - if (dataViewManager != null) + if (dataViewManager is not null) { dataViewManager._nViews++; DataViewSetting dataViewSetting = dataViewManager.DataViewSettings[_table]; @@ -1592,9 +1592,9 @@ internal void UpdateIndex(bool force, bool fireEvent) Index? newIndex = null; if (_open) { - if (_table != null) + if (_table is not null) { - if (null != SortComparison) + if (SortComparison is not null) { // because an Index with a Comparison {0}, TableName='{1}', distinct={2}", ObjectID, tableName, distinct); - if (columnNames == null) + if (columnNames is null) { throw ExceptionBuilder.ArgumentNull(nameof(columnNames)); } @@ -1698,7 +1698,7 @@ public DataTable ToTable(string? tableName, bool distinct, params string[] colum DataTable dt = new DataTable(); dt.Locale = _table!.Locale; dt.CaseSensitive = _table.CaseSensitive; - dt.TableName = ((null != tableName) ? tableName : _table.TableName); + dt.TableName = ((tableName is not null) ? tableName : _table.TableName); dt.Namespace = _table.Namespace; dt.Prefix = _table.Prefix; @@ -1718,7 +1718,7 @@ public DataTable ToTable(string? tableName, bool distinct, params string[] colum for (int i = 0; i < columnNames.Length; i++) { DataColumn? dc = Table!.Columns[columnNames[i]]; - if (dc == null) + if (dc is null) { throw ExceptionBuilder.ColumnNotInTheUnderlyingTable(columnNames[i], Table.TableName); } @@ -1768,7 +1768,7 @@ private bool RowExist(List arraylist, object[] objectArray) /// public virtual bool Equals(DataView? view) { - if ((null == view) || + if ((view is null) || Table != view.Table || Count != view.Count || !string.Equals(RowFilter, view.RowFilter, StringComparison.OrdinalIgnoreCase) || // case insensitive diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs index b278f160c6ad7f..54b80154d73b47 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs @@ -25,7 +25,7 @@ internal DataViewListener(DataView dv) private void ChildRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { DataView? dv = (DataView?)_dvWeak.Target; - if (dv != null) + if (dv is not null) { dv.ChildRelationCollectionChanged(sender, e); } @@ -38,7 +38,7 @@ private void ChildRelationCollectionChanged(object sender, CollectionChangeEvent private void ParentRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { DataView? dv = (DataView?)_dvWeak.Target; - if (dv != null) + if (dv is not null) { dv.ParentRelationCollectionChanged(sender, e); } @@ -51,7 +51,7 @@ private void ParentRelationCollectionChanged(object sender, CollectionChangeEven private void ColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { DataView? dv = (DataView?)_dvWeak.Target; - if (dv != null) + if (dv is not null) { dv.ColumnCollectionChangedInternal(sender, e); } @@ -67,7 +67,7 @@ private void ColumnCollectionChanged(object sender, CollectionChangeEventArgs e) internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool trackAddRemove) { DataView? dv = (DataView?)_dvWeak.Target; - if (dv != null) + if (dv is not null) { dv.MaintainDataView(changedType, row, trackAddRemove); } @@ -80,7 +80,7 @@ internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool t internal void IndexListChanged(ListChangedEventArgs e) { DataView? dv = (DataView?)_dvWeak.Target; - if (dv != null) + if (dv is not null) { dv.IndexListChangedInternal(e); } @@ -94,7 +94,7 @@ internal void RegisterMetaDataEvents(DataTable? table) { Debug.Assert(null == _table, "DataViewListener already registered table"); _table = table; - if (table != null) + if (table is not null) { // actively remove listeners without a target RegisterListener(table); @@ -121,7 +121,7 @@ private void UnregisterMetaDataEvents(bool updateListeners) DataTable? table = _table; _table = null; - if (table != null) + if (table is not null) { CollectionChangeEventHandler handlerCollection = new CollectionChangeEventHandler(ColumnCollectionChanged); table.Columns.ColumnPropertyChanged -= handlerCollection; @@ -150,7 +150,7 @@ internal void RegisterListChangedEvent(Index index) { Debug.Assert(null == _index, "DataviewListener already registered index"); _index = index; - if (null != index) + if (index is not null) { lock (index) { @@ -165,7 +165,7 @@ internal void UnregisterListChangedEvent() Index? index = _index; _index = null; - if (index != null) + if (index is not null) { lock (index) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs index 0f76e3d604c85f..20c076d9826c1e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs @@ -29,7 +29,7 @@ internal DataViewManager(DataSet? dataSet, bool locked) { GC.SuppressFinalize(this); _dataSet = dataSet; - if (_dataSet != null) + if (_dataSet is not null) { _dataSet.Tables.CollectionChanged += new CollectionChangeEventHandler(TableCollectionChanged); _dataSet.Relations.CollectionChanged += new CollectionChangeEventHandler(RelationCollectionChanged); @@ -46,7 +46,7 @@ public DataSet? DataSet get { return _dataSet; } set { - if (value == null) + if (value is null) { throw ExceptionBuilder.SetFailed("DataSet to null"); } @@ -56,7 +56,7 @@ public DataSet? DataSet throw ExceptionBuilder.SetDataSetFailed(); } - if (_dataSet != null) + if (_dataSet is not null) { if (_nViews > 0) { @@ -82,7 +82,7 @@ public string DataViewSettingCollectionString { get { - if (_dataSet == null) + if (_dataSet is null) { return string.Empty; } @@ -257,19 +257,19 @@ void IBindingList.RemoveSort() string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAccessors) { DataSet? dataSet = DataSet; - if (dataSet == null) + if (dataSet is null) { throw ExceptionBuilder.CanNotUseDataViewManager(); } - if (listAccessors == null || listAccessors.Length == 0) + if (listAccessors is null || listAccessors.Length == 0) { return dataSet.DataSetName; } else { DataTable? table = dataSet.FindTable(null, listAccessors, 0); - if (table != null) + if (table is not null) { return table.TableName; } @@ -280,19 +280,19 @@ string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAcc PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { DataSet? dataSet = DataSet; - if (dataSet == null) + if (dataSet is null) { throw ExceptionBuilder.CanNotUseDataViewManager(); } - if (listAccessors == null || listAccessors.Length == 0) + if (listAccessors is null || listAccessors.Length == 0) { return ((ICustomTypeDescriptor)(new DataViewManagerListItemTypeDescriptor(this))).GetProperties(); } else { DataTable? table = dataSet.FindTable(null, listAccessors, 0); - if (table != null) + if (table is not null) { return table.GetPropertyDescriptorCollection(null); } @@ -302,7 +302,7 @@ PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties( public DataView CreateDataView(DataTable table) { - if (_dataSet == null) + if (_dataSet is null) { throw ExceptionBuilder.CanNotUseDataViewManager(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs index 24059e62ad0504..09fe3df4b68c8c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs @@ -103,11 +103,11 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() => /// PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { - if (_propsCollection == null) + if (_propsCollection is null) { PropertyDescriptor[] props = null; DataSet dataSet = _dataViewManager.DataSet; - if (dataSet != null) + if (dataSet is not null) { int tableCount = dataSet.Tables.Count; props = new PropertyDescriptor[tableCount]; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs index 2ec0f4fcfa7389..bbc093c016635f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs @@ -58,7 +58,7 @@ public string RowFilter get { return _rowFilter; } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -88,7 +88,7 @@ public string Sort get { return _sort; } set { - if (value == null) + if (value is null) { value = string.Empty; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs index 8145dadcdd5891..498a0efe950367 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs @@ -16,7 +16,7 @@ public class DataViewSettingCollection : ICollection internal DataViewSettingCollection(DataViewManager dataViewManager) { - if (dataViewManager == null) + if (dataViewManager is null) { throw ExceptionBuilder.ArgumentNull(nameof(dataViewManager)); } @@ -27,12 +27,12 @@ public virtual DataViewSetting this[DataTable table] { get { - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(table)); } DataViewSetting? dataViewSetting = (DataViewSetting?)_list[table]; - if (dataViewSetting == null) + if (dataViewSetting is null) { dataViewSetting = new DataViewSetting(); this[table] = dataViewSetting; @@ -41,7 +41,7 @@ public virtual DataViewSetting this[DataTable table] } set { - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(table)); } @@ -55,7 +55,7 @@ public virtual DataViewSetting this[DataTable table] { DataTable? dt = null; DataSet? ds = _dataViewManager.DataSet; - if (ds != null) + if (ds is not null) { dt = ds.Tables[tableName]; } @@ -66,7 +66,7 @@ public virtual DataViewSetting this[DataTable table] { DataTable? dt = null; DataSet? ds = _dataViewManager.DataSet; - if (ds != null) + if (ds is not null) { dt = ds.Tables[index]; } @@ -78,7 +78,7 @@ public virtual DataViewSetting? this[string tableName] get { DataTable? dt = GetTable(tableName); - if (dt != null) + if (dt is not null) { return this[dt]; } @@ -92,7 +92,7 @@ public virtual DataViewSetting? this[int index] get { DataTable? dt = GetTable(index); - if (dt != null) + if (dt is not null) { return this[dt]; } @@ -101,7 +101,7 @@ public virtual DataViewSetting? this[int index] set { DataTable? dt = GetTable(index); - if (dt != null) + if (dt is not null) { this[dt] = value; } @@ -132,7 +132,7 @@ public virtual int Count get { DataSet? ds = _dataViewManager.DataSet; - return (ds == null) ? 0 : ds.Tables.Count; + return (ds is null) ? 0 : ds.Tables.Count; } } @@ -163,7 +163,7 @@ private sealed class DataViewSettingsEnumerator : IEnumerator public DataViewSettingsEnumerator(DataViewManager dvm) { DataSet? ds = dvm.DataSet; - if (ds != null) + if (ds is not null) { _dataViewSettings = dvm.DataViewSettings; _tableEnumerator = dvm.DataSet!.Tables.GetEnumerator(); diff --git a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs index 7e2edf3d37730a..0a55466a09efff 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs @@ -23,14 +23,14 @@ public DefaultValueTypeConverter() #nullable disable public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { - if (value == null) + if (value is null) { return NullString; } @@ -45,7 +45,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value != null && value.GetType() == typeof(string)) + if (value is not null && value.GetType() == typeof(string)) { string strValue = (string)value; if (string.Equals(strValue, NullString, StringComparison.OrdinalIgnoreCase)) diff --git a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs index bbdf6b51a75183..0a68ae819fe32b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs @@ -72,7 +72,7 @@ internal override DataTable? Table /// internal EnumerableRowCollection(IEnumerable enumerableRows, bool isDataViewable, DataTable? table) { - Debug.Assert(!isDataViewable || table != null, "isDataViewable bug table is null"); + Debug.Assert(!isDataViewable || table is not null, "isDataViewable bug table is null"); _enumerableRows = enumerableRows; if (isDataViewable) @@ -100,13 +100,13 @@ internal EnumerableRowCollection(DataTable table) /// internal EnumerableRowCollection(EnumerableRowCollection? source, IEnumerable enumerableRows, Func? selector) { - Debug.Assert(null != enumerableRows, "null enumerableRows"); + Debug.Assert(enumerableRows is not null, "null enumerableRows"); _enumerableRows = enumerableRows; _selector = selector; - if (null != source) + if (source is not null) { - if (null == source._selector) + if (source._selector is null) { _table = source._table; } @@ -216,7 +216,7 @@ internal LinqDataView GetLinqDataView() // Called by AsLinqDataView // Filter AND Sort - if ((null != finalPredicate) && (0 < _sortExpression.Count)) + if ((finalPredicate is not null) && (0 < _sortExpression.Count)) { // A lot more work here because constructor does not know type K, // so the responsibility to create appropriate delegate comparers @@ -235,7 +235,7 @@ internal LinqDataView GetLinqDataView() // Called by AsLinqDataView _sortExpression.Select((TRow)(object)row)), _sortExpression.CloneCast()); } - else if (null != finalPredicate) + else if (finalPredicate is not null) { // Only Filtering view = new LinqDataView( @@ -276,7 +276,7 @@ internal LinqDataView GetLinqDataView() // Called by AsLinqDataView /// internal void AddPredicate(Func pred) { - Debug.Assert(pred != null); + Debug.Assert(pred is not null); _listOfPredicates.Add(pred); } diff --git a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs index 54f875bc878a11..02bd3f620a9000 100644 --- a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs @@ -141,7 +141,7 @@ public static EnumerableRowCollection Cast(this EnumerableRowC { // Since Cast does not have the signature Cast_T_R(..) this call is routed through the non-generic base class EnumerableDataTable - if ((null != source) && source.ElementType.Equals(typeof(TResult))) + if ((source is not null) && source.ElementType.Equals(typeof(TResult))) { return (EnumerableRowCollection)source; } @@ -150,7 +150,7 @@ public static EnumerableRowCollection Cast(this EnumerableRowC //Anonymous type or some other type //The only thing that matters from this point on is _enumerableRows - Debug.Assert(source != null); + Debug.Assert(source is not null); IEnumerable typedEnumerable = Enumerable.Cast(source); diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs index 98760f2ecbf9b7..d671a09a90eb63 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs @@ -40,7 +40,7 @@ internal AggregateNode(DataTable? table, FunctionId aggregateType, string column internal AggregateNode(DataTable? table, FunctionId aggregateType, string columnName, bool local, string? relationName) : base(table) { - Debug.Assert(columnName != null, "Invalid parameter column name (null)."); + Debug.Assert(columnName is not null, "Invalid parameter column name (null)."); _aggregate = (Aggregate)(int)aggregateType; if (aggregateType == FunctionId.Sum) @@ -69,7 +69,7 @@ internal AggregateNode(DataTable? table, FunctionId aggregateType, string column internal override void Bind(DataTable table, List list) { BindTable(table); - if (table == null) + if (table is null) throw ExprException.AggregateUnbound(ToString()!); if (_local) @@ -81,7 +81,7 @@ internal override void Bind(DataTable table, List list) DataRelationCollection relations; relations = table.ChildRelations; - if (_relationName == null) + if (_relationName is null) { // must have one and only one relation @@ -104,16 +104,16 @@ internal override void Bind(DataTable table, List list) } } - _childTable = (_relation == null) ? table : _relation.ChildTable; + _childTable = (_relation is null) ? table : _relation.ChildTable; _column = _childTable.Columns[_columnName]; - if (_column == null) + if (_column is null) throw ExprException.UnboundName(_columnName); // add column to the dependency list, do not add duplicate columns - Debug.Assert(_column != null, "Failed to bind column " + _columnName); + Debug.Assert(_column is not null, "Failed to bind column " + _columnName); int i; for (i = 0; i < list.Count; i++) @@ -135,7 +135,7 @@ internal override void Bind(DataTable table, List list) internal static void Bind(DataRelation? relation, List list) { - if (null != relation) + if (relation is not null) { // add the ends of the relationship the expression depends on foreach (DataColumn c in relation.ChildColumnsReference) @@ -162,7 +162,7 @@ internal override object Eval() internal override object Eval(DataRow? row, DataRowVersion version) { - if (_childTable == null) + if (_childTable is null) throw ExprException.AggregateUnbound(ToString()!); DataRow[] rows; @@ -174,11 +174,11 @@ internal override object Eval(DataRow? row, DataRowVersion version) } else { - if (row == null) + if (row is null) { throw ExprException.EvalNoContext(); } - if (_relation == null) + if (_relation is null) { throw ExprException.AggregateUnbound(ToString()!); } @@ -222,7 +222,7 @@ internal override object Eval(DataRow? row, DataRowVersion version) // Helper for the DataTable.Compute method internal override object Eval(int[] records) { - if (_childTable == null) + if (_childTable is null) throw ExprException.AggregateUnbound(ToString()!); if (!_local) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs index fb537bdce17a1f..e22967db7c3ccd 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs @@ -136,7 +136,7 @@ internal void SetTypeMismatchError(int op, Type left, Type right) private static object Eval(ExpressionNode expr, DataRow? row, DataRowVersion version, int[]? recordNos) { - if (recordNos == null) + if (recordNos is null) { return expr.Eval(row, version); } @@ -1522,7 +1522,7 @@ internal override object Eval(DataRow? row, DataRowVersion version) if ((vLeft == DBNull.Value) || (_left.IsSqlColumn && DataStorage.IsObjectSqlNull(vLeft))) return DBNull.Value; - if (_pattern == null) + if (_pattern is null) { object vRight = _right.Eval(row, version); diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs index 63d3676890094f..653629a20c38be 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs @@ -109,14 +109,14 @@ internal override ExpressionNode Optimize() private object SmallestDecimal(object constant) { - if (null == constant) + if (constant is null) { return 0d; } else { string? sval = (constant as string); - if (null != sval) + if (sval is not null) { decimal r12; if (decimal.TryParse(sval, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out r12)) @@ -133,7 +133,7 @@ private object SmallestDecimal(object constant) else { IConvertible? convertible = (constant as IConvertible); - if (null != convertible) + if (convertible is not null) { try { @@ -183,14 +183,14 @@ private object SmallestDecimal(object constant) private object SmallestNumeric(object constant) { - if (null == constant) + if (constant is null) { return 0; } else { string? sval = (constant as string); - if (null != sval) + if (sval is not null) { int i4; if (int.TryParse(sval, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out i4)) @@ -211,7 +211,7 @@ private object SmallestNumeric(object constant) else { IConvertible? convertible = (constant as IConvertible); - if (null != convertible) + if (convertible is not null) { try { diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs index 8be3afbd84d3cf..bcc416cde333be 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs @@ -33,7 +33,7 @@ internal DataExpression(DataTable? table, string? expression, Type? type) _expr = null; // Note: nobody seems to pass a null expression in the codebase - if (expression != null) + if (expression is not null) { _storageType = DataStorage.GetStorageType(type); if (_storageType == StorageType.BigInteger) @@ -44,7 +44,7 @@ internal DataExpression(DataTable? table, string? expression, Type? type) _dataType = type; _expr = parser.Parse(); _parsed = true; - if (_expr != null && table != null) + if (_expr is not null && table is not null) { Bind(table); } @@ -59,7 +59,7 @@ internal string Expression { get { - return (_originalExpression != null ? _originalExpression : ""); // CONSIDER: return optimized expression here (if bound) + return (_originalExpression is not null ? _originalExpression : ""); // CONSIDER: return optimized expression here (if bound) } } @@ -83,10 +83,10 @@ internal void Bind(DataTable? table) { _table = table; - if (table == null) + if (table is null) return; - if (_expr != null) + if (_expr is not null) { Debug.Assert(_parsed, "Invalid calling order: Bind() before Parse()"); List list = new List(); @@ -100,7 +100,7 @@ internal void Bind(DataTable? table) internal bool DependsOn(DataColumn column) { - if (_expr != null) + if (_expr is not null) { return _expr.DependsOn(column); } @@ -124,7 +124,7 @@ internal object Evaluate(DataRow? row, DataRowVersion version) Bind(_table); } // Note: _expr is always non-null in the current codebase - if (_expr != null) + if (_expr is not null) { result = _expr.Eval(row, version); // if the type is a SqlType (StorageType.Uri < _storageType), convert DBNull values. @@ -165,7 +165,7 @@ internal object Evaluate(DataRow[] rows, DataRowVersion version) { Bind(_table); } - if (_expr != null) + if (_expr is not null) { List recordList = new List(); foreach (DataRow row in rows) @@ -187,10 +187,10 @@ internal object Evaluate(DataRow[] rows, DataRowVersion version) public bool Invoke(DataRow row, DataRowVersion version) { - if (_expr == null) + if (_expr is null) return true; - if (row == null) + if (row is null) { throw ExprException.InvokeArgument(); } @@ -209,13 +209,13 @@ public bool Invoke(DataRow row, DataRowVersion version) internal DataColumn[] GetDependency() { - Debug.Assert(_dependency != null, "GetDependencies: null, we should have created an empty list"); + Debug.Assert(_dependency is not null, "GetDependencies: null, we should have created an empty list"); return _dependency; } internal bool IsTableAggregate() { - if (_expr != null) + if (_expr is not null) return _expr.IsTableConstant(); else return false; @@ -228,7 +228,7 @@ internal static bool IsUnknown(object value) internal bool HasLocalAggregate() { - if (_expr != null) + if (_expr is not null) return _expr.HasLocalAggregate(); else return false; @@ -236,7 +236,7 @@ internal bool HasLocalAggregate() internal bool HasRemoteAggregate() { - if (_expr != null) + if (_expr is not null) return _expr.HasRemoteAggregate(); else return false; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs index d6e20b5a9f0c74..f3deb2a178cdea 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs @@ -123,7 +123,7 @@ internal void LoadExpression(string? data) { int length; - if (data == null) + if (data is null) { length = 0; _text = new char[length + 1]; @@ -137,7 +137,7 @@ internal void LoadExpression(string? data) _text[length] = '\0'; - if (_expression != null) + if (_expression is not null) { // free all nodes _expression = null; @@ -347,7 +347,7 @@ internal ExpressionNode Parse() _prevOperand = Empty; ExpressionNode? nodebefore = NodePeek(); - if (nodebefore == null || nodebefore.GetType() != typeof(NameNode)) + if (nodebefore is null || nodebefore.GetType() != typeof(NameNode)) { // this is more like an assert, so we not care about "nice" exception text.. throw ExprException.SyntaxError(); @@ -527,7 +527,7 @@ internal ExpressionNode Parse() //if there is a name on the stack append it. ExpressionNode? before = NodePeek(); - if (before != null && before.GetType() == typeof(NameNode)) + if (before is not null && before.GetType() == typeof(NameNode)) { Scan(); @@ -618,7 +618,7 @@ private ExpressionNode NodePop() { Debug.Assert(_topNode > 0, "NodePop(): Corrupted node stack"); ExpressionNode node = _nodeStack[--_topNode]; - Debug.Assert(null != node, "null NodePop"); + Debug.Assert(node is not null, "null NodePop"); return node; } @@ -638,7 +638,7 @@ private ExpressionNode NodePop() /// private void NodePush(ExpressionNode node) { - Debug.Assert(null != node, "null NodePush"); + Debug.Assert(node is not null, "null NodePush"); if (_topNode >= MaxPredicates - 2) { @@ -717,8 +717,8 @@ private void BuildExpression(int pri) break; } - Debug.Assert(nodeLeft != null, "Invalid left operand"); - Debug.Assert(nodeRight != null, "Invalid right operand"); + Debug.Assert(nodeLeft is not null, "Invalid left operand"); + Debug.Assert(nodeRight is not null, "Invalid right operand"); if (opInfo._op == Operators.Like) { @@ -749,8 +749,8 @@ private void BuildExpression(int pri) break; } - Debug.Assert(nodeLeft == null, "Invalid left operand"); - Debug.Assert(nodeRight != null, "Invalid right operand"); + Debug.Assert(nodeLeft is null, "Invalid left operand"); + Debug.Assert(nodeRight is not null, "Invalid right operand"); expr = new UnaryNode(_table, opInfo._op, nodeRight); break; @@ -764,7 +764,7 @@ private void BuildExpression(int pri) Debug.Fail("Unhandled operator type"); goto end_loop; } - Debug.Assert(expr != null, "Failed to create expression"); + Debug.Assert(expr is not null, "Failed to create expression"); NodePush(expr); // countinue while loop; @@ -1113,7 +1113,7 @@ private void ScanReserved() Debug.Assert(_pos > _start, "Exprecing an identifier."); string name = new string(text, _start, _pos - _start); - Debug.Assert(name != null, "Make sure the arguments for Compare method are OK"); + Debug.Assert(name is not null, "Make sure the arguments for Compare method are OK"); CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; @@ -1123,7 +1123,7 @@ private void ScanReserved() do { int i = (lo + hi) / 2; - Debug.Assert(s_reservedwords[i]._word != null, "Make sure the arguments for Compare method are OK"); + Debug.Assert(s_reservedwords[i]._word is not null, "Make sure the arguments for Compare method are OK"); int c = comparer.Compare(s_reservedwords[i]._word, name, CompareOptions.IgnoreCase); if (c == 0) diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs index 6a666e60718f4b..6aec46741f3814 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs @@ -68,7 +68,7 @@ internal void AddArgument(ExpressionNode argument) if (!s_funcs[_info]._isVariantArgumentList && _argumentCount >= s_funcs[_info]._argumentCount) throw ExprException.FunctionArgumentCount(_name); - if (_arguments == null) + if (_arguments is null) { _arguments = new ExpressionNode[initialCapacity]; } @@ -284,14 +284,14 @@ private Type GetDataType(ExpressionNode node) typeName = ((ConstNode)node)._val.ToString(); } - if (typeName == null) + if (typeName is null) { throw ExprException.ArgumentType(s_funcs[_info]._name, 2, typeof(Type)); } Type? dataType = Type.GetType(typeName); - if (dataType == null) + if (dataType is null) { throw ExprException.InvalidType(typeName); } @@ -512,7 +512,7 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row // If there was a type limiter scope on the stack at the time this Convert function was created, // we must manually re-enter the Serialization Guard scope. - DeserializationToken deserializationToken = (_capturedLimiter != null) ? SerializationInfo.StartDeserialization() : default; + DeserializationToken deserializationToken = (_capturedLimiter is not null) ? SerializationInfo.StartDeserialization() : default; using (deserializationToken) { return SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider); @@ -681,11 +681,11 @@ internal Function(string name, FunctionId id, Type result, bool IsValidateArgume _isVariantArgumentList = IsVariantArgumentList; _argumentCount = argumentCount; - if (a1 != null) + if (a1 is not null) _parameters[0] = a1; - if (a2 != null) + if (a2 is not null) _parameters[1] = a2; - if (a3 != null) + if (a3 is not null) _parameters[2] = a3; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs index bacf6d2fabc71f..661e749c501988 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs @@ -26,7 +26,7 @@ internal override void Bind(DataTable table, List list) _column = null; // clear for rebinding (if original binding was valid) _relation = null; - if (table == null) + if (table is null) throw ExprException.ExpressionUnbound(ToString()!); // First find parent table @@ -34,7 +34,7 @@ internal override void Bind(DataTable table, List list) DataRelationCollection relations; relations = table.ParentRelations; - if (_relationName == null) + if (_relationName is null) { // must have one and only one relation @@ -54,12 +54,12 @@ internal override void Bind(DataTable table, List list) } DataTable parentTable = _relation.ParentTable; - Debug.Assert(_relation != null, "Invalid relation: no parent table."); - Debug.Assert(_columnName != null, "All Lookup expressions have columnName set."); + Debug.Assert(_relation is not null, "Invalid relation: no parent table."); + Debug.Assert(_columnName is not null, "All Lookup expressions have columnName set."); _column = parentTable.Columns[_columnName]; - if (_column == null) + if (_column is null) throw ExprException.UnboundName(_columnName); // add column to the dependency list @@ -89,11 +89,11 @@ internal override object Eval() internal override object Eval(DataRow? row, DataRowVersion version) { - if (_column == null || _relation == null) + if (_column is null || _relation is null) throw ExprException.ExpressionUnbound(ToString()!); DataRow? parent = row!.GetParentRow(_relation, version); - if (parent == null) + if (parent is null) return DBNull.Value; return parent[_column, parent.HasVersion(version) ? version : DataRowVersion.Current]; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs index 8cb163db379f2d..add2acd0afe5c9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs @@ -33,7 +33,7 @@ internal override bool IsSqlColumn internal override void Bind(DataTable table, List list) { BindTable(table); - if (table == null) + if (table is null) throw ExprException.UnboundName(_name); try @@ -50,14 +50,14 @@ internal override void Bind(DataTable table, List list) throw ExprException.UnboundName(_name); } - if (_column == null) + if (_column is null) throw ExprException.UnboundName(_name); _name = _column.ColumnName; _found = true; // add column to the dependency list, do not add duplicate columns - Debug.Assert(_column != null, "Failed to bind column " + _name); + Debug.Assert(_column is not null, "Failed to bind column " + _name); int i; for (i = 0; i < list.Count; i++) @@ -88,7 +88,7 @@ internal override object Eval(DataRow? row, DataRowVersion version) throw ExprException.UnboundName(_name); } - if (row == null) + if (row is null) { if (IsTableConstant()) // this column is TableConstant Aggregate Function return _column!.DataExpression!.Evaluate(); @@ -113,7 +113,7 @@ internal override bool IsConstant() internal override bool IsTableConstant() { - if (_column != null && _column.Computed) + if (_column is not null && _column.Computed) { return _column.DataExpression!.IsTableAggregate(); } @@ -122,7 +122,7 @@ internal override bool IsTableConstant() internal override bool HasLocalAggregate() { - if (_column != null && _column.Computed) + if (_column is not null && _column.Computed) { return _column.DataExpression!.HasLocalAggregate(); } @@ -131,7 +131,7 @@ internal override bool HasLocalAggregate() internal override bool HasRemoteAggregate() { - if (_column != null && _column.Computed) + if (_column is not null && _column.Computed) { return _column.DataExpression!.HasRemoteAggregate(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs index a57fd09b1e4b33..28d1fe30dacf2e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs @@ -198,7 +198,7 @@ internal override bool IsConstraintViolated() internal override bool CanEnableConstraint() { - if (Table!.DataSet == null || !Table.DataSet.EnforceConstraints) + if (Table!.DataSet is null || !Table.DataSet.EnforceConstraints) { return true; } @@ -256,7 +256,7 @@ internal void CascadeCommit(DataRow row) internal void CascadeDelete(DataRow row) { - Debug.Assert(row.Table.DataSet != null); + Debug.Assert(row.Table.DataSet is not null); if (-1 == row._newRecord) { @@ -356,7 +356,7 @@ internal void CascadeDelete(DataRow row) internal void CascadeRollback(DataRow row) { - Debug.Assert(row.Table.DataSet != null); + Debug.Assert(row.Table.DataSet is not null); Index childIndex = _childKey.GetSortIndex(row.RowState == DataRowState.Deleted ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows); object[] key = row.GetKeyValues(_parentKey, row.RowState == DataRowState.Modified ? DataRowVersion.Current : DataRowVersion.Default); @@ -401,7 +401,7 @@ internal void CascadeRollback(DataRow row) internal void CascadeUpdate(DataRow row) { - Debug.Assert(Table?.DataSet != null && row.Table.DataSet != null); + Debug.Assert(Table?.DataSet is not null && row.Table.DataSet is not null); if (-1 == row._newRecord) { @@ -494,7 +494,7 @@ internal void CascadeUpdate(DataRow row) internal void CheckCanClearParentTable(DataTable table) { - Debug.Assert(Table?.DataSet != null); + Debug.Assert(Table?.DataSet is not null); if (Table.DataSet.EnforceConstraints && Table.Rows.Count > 0) { throw ExceptionBuilder.FailedClearParentTable(table.TableName, ConstraintName, Table.TableName); @@ -503,7 +503,7 @@ internal void CheckCanClearParentTable(DataTable table) internal void CheckCanRemoveParentRow(DataRow row) { - Debug.Assert(Table?.DataSet != null, "Relation " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); + Debug.Assert(Table?.DataSet is not null, "Relation " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); if (!Table.DataSet.EnforceConstraints) { return; @@ -516,7 +516,7 @@ internal void CheckCanRemoveParentRow(DataRow row) internal void CheckCascade(DataRow row, DataRowAction action) { - Debug.Assert(Table?.DataSet != null, "ForeignKeyConstraint " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); + Debug.Assert(Table?.DataSet is not null, "ForeignKeyConstraint " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); if (row._inCascade) { @@ -564,7 +564,7 @@ internal override void CheckConstraint(DataRow childRow, DataRowAction action) if ((action == DataRowAction.Change || action == DataRowAction.Add || action == DataRowAction.Rollback) && - Table!.DataSet != null && Table.DataSet.EnforceConstraints && + Table!.DataSet is not null && Table.DataSet.EnforceConstraints && childRow.HasKeyChanged(_childKey)) { // This branch is for cascading case verification. @@ -575,7 +575,7 @@ internal override void CheckConstraint(DataRow childRow, DataRowAction action) { // this is the new proposed value for the parent. DataRow? parentRow = DataRelation.GetParentRow(ParentKey, ChildKey, childRow, version); - if (parentRow != null && parentRow._inCascade) + if (parentRow is not null && parentRow._inCascade) { object[] parentKeyValues = parentRow.GetKeyValues(_parentKey, action == DataRowAction.Rollback ? version : DataRowVersion.Default); @@ -621,7 +621,7 @@ internal override void CheckConstraint(DataRow childRow, DataRowAction action) private void NonVirtualCheckState() { - if (_DataSet == null) + if (_DataSet is null) { // Make sure columns arrays are valid _parentKey.CheckState(); diff --git a/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs b/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs index 92753db288013c..99a5a51efc5a63 100644 --- a/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs @@ -35,7 +35,7 @@ internal sealed class LinqDataView : DataView, IBindingList, IBindingListView internal LinqDataView(DataTable table, SortExpressionBuilder? sortExpressionBuilder) : base(table) { - Debug.Assert(table != null, "null DataTable"); + Debug.Assert(table is not null, "null DataTable"); this.sortExpressionBuilder = sortExpressionBuilder ?? new SortExpressionBuilder(); } @@ -62,7 +62,7 @@ internal LinqDataView( comparison, DataViewRowState.CurrentRows) { - this.sortExpressionBuilder = (sortExpressionBuilder == null) ? this.sortExpressionBuilder : sortExpressionBuilder; + this.sortExpressionBuilder = (sortExpressionBuilder is null) ? this.sortExpressionBuilder : sortExpressionBuilder; this.comparerKeyRow = comparerKeyRow; } @@ -73,7 +73,7 @@ public override string? RowFilter { get { - if (base.RowPredicate == null)// using string based filter or no filter + if (base.RowPredicate is null)// using string based filter or no filter { return base.RowFilter; } @@ -85,7 +85,7 @@ public override string? RowFilter set { - if (value == null) + if (value is null) { base.RowPredicate = null; base.RowFilter = string.Empty; // INDEX rebuild twice @@ -107,15 +107,15 @@ public override string? RowFilter /// Index of the first match of input key internal override int FindByKey(object? key) { - Debug.Assert(base.Sort != null); - Debug.Assert(!(!string.IsNullOrEmpty(base.Sort) && base.SortComparison != null), + Debug.Assert(base.Sort is not null); + Debug.Assert(!(!string.IsNullOrEmpty(base.Sort) && base.SortComparison is not null), "string and expression based sort cannot both be set"); if (!string.IsNullOrEmpty(base.Sort)) // use find for DV's sort string { return base.FindByKey(key); } - else if (base.SortComparison == null) // neither string or expr set + else if (base.SortComparison is null) // neither string or expr set { // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); @@ -144,17 +144,17 @@ internal override int FindByKey(object? key) internal override int FindByKey(object?[] key) { // must have string or expression based sort specified - if (base.SortComparison == null && string.IsNullOrEmpty(base.Sort)) + if (base.SortComparison is null && string.IsNullOrEmpty(base.Sort)) { // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } - else if (base.SortComparison != null && key.Length != sortExpressionBuilder!.Count) + else if (base.SortComparison is not null && key.Length != sortExpressionBuilder!.Count) { throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); } - if (base.SortComparison == null) + if (base.SortComparison is null) { // using string to sort return base.FindByKey(key); @@ -184,17 +184,17 @@ internal override int FindByKey(object?[] key) internal override DataRowView[] FindRowsByKey(object?[] key) { // must have string or expression based sort specified - if (base.SortComparison == null && string.IsNullOrEmpty(base.Sort)) + if (base.SortComparison is null && string.IsNullOrEmpty(base.Sort)) { // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } - else if (base.SortComparison != null && key.Length != sortExpressionBuilder!.Count) + else if (base.SortComparison is not null && key.Length != sortExpressionBuilder!.Count) { throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); } - if (base.SortComparison == null)// using string to sort + if (base.SortComparison is null)// using string to sort { return base.FindRowsByKey(key); } @@ -217,7 +217,7 @@ internal override DataRowView[] FindRowsByKey(object?[] key) internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter? newRowFilter) { // Throw only if expressions (filter or sort) are used and rowstate is not current rows - if ((base.SortComparison != null || base.RowPredicate != null) && newRowStates != DataViewRowState.CurrentRows) + if ((base.SortComparison is not null || base.RowPredicate is not null) && newRowStates != DataViewRowState.CurrentRows) { throw DataSetUtil.Argument(SR.LDVRowStateError); } @@ -249,7 +249,7 @@ PropertyDescriptor IBindingList.SortProperty { get { - return (base.SortComparison == null) ? base.GetSortProperty() : null; + return (base.SortComparison is null) ? base.GetSortProperty() : null; } } @@ -261,7 +261,7 @@ ListSortDescriptionCollection IBindingListView.SortDescriptions { get { - if (base.SortComparison == null) + if (base.SortComparison is null) { return base.GetSortDescriptions(); } @@ -279,7 +279,7 @@ bool IBindingList.IsSorted { get { // Sorted if either expression based sort or string based sort is set - return !(base.SortComparison == null && base.Sort.Length == 0); + return !(base.SortComparison is null && base.Sort.Length == 0); } } #nullable enable diff --git a/src/libraries/System.Data.Common/src/System/Data/Merger.cs b/src/libraries/System.Data.Common/src/System/Data/Merger.cs index a06f531ab1ce91..a598660dd6bb6a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -41,7 +41,7 @@ internal Merger(DataTable dataTable, bool preserveChanges, MissingSchemaAction m internal void MergeDataSet(DataSet source) { - Debug.Assert(_dataSet != null); + Debug.Assert(_dataSet is not null); if (source == _dataSet) return; //somebody is doing an 'automerge' bool fEnforce = _dataSet.EnforceConstraints; @@ -134,11 +134,11 @@ internal void MergeTable(DataTable src) _dataTable!.SuspendEnforceConstraints = true; } - if (_dataSet != null) + if (_dataSet is not null) { // this is ds.Merge // if source does not have a DS, or if NS of both DS does not match, ignore the NS - if (src.DataSet == null || src.DataSet._namespaceURI != _dataSet._namespaceURI) + if (src.DataSet is null || src.DataSet._namespaceURI != _dataSet._namespaceURI) { _IgnoreNSforTableLookup = true; } @@ -146,7 +146,7 @@ internal void MergeTable(DataTable src) else { // this is dt.Merge - if (_dataTable!.DataSet == null || src.DataSet == null || src.DataSet._namespaceURI != _dataTable.DataSet._namespaceURI) + if (_dataTable!.DataSet is null || src.DataSet is null || src.DataSet._namespaceURI != _dataTable.DataSet._namespaceURI) { _IgnoreNSforTableLookup = true; } @@ -155,14 +155,14 @@ internal void MergeTable(DataTable src) MergeTableData(src); DataTable? dt = _dataTable; - if (dt == null && _dataSet != null) + if (dt is null && _dataSet is not null) { dt = _IgnoreNSforTableLookup ? _dataSet.Tables[src.TableName] : _dataSet.Tables[src.TableName, src.Namespace]; } - if (dt != null) + if (dt is not null) { dt.EvaluateExpressions(); } @@ -183,7 +183,7 @@ internal void MergeTable(DataTable src) } catch (ConstraintException) { - if (_dataTable.DataSet != null) + if (_dataTable.DataSet is not null) { _dataTable.DataSet.EnforceConstraints = false; } @@ -203,7 +203,7 @@ private void MergeTable(DataTable src, DataTable dst) dst.SuspendIndexEvents(); try { - if (!wasEmpty && dst._primaryKey != null) + if (!wasEmpty && dst._primaryKey is not null) { key = GetSrcKey(src, dst); if (key.HasValue) @@ -216,7 +216,7 @@ private void MergeTable(DataTable src, DataTable dst) foreach (DataRow sourceRow in src.Rows) { DataRow? targetRow = null; - if (ndxSearch != null) + if (ndxSearch is not null) { targetRow = dst.FindMergeTarget(sourceRow, key, ndxSearch); } @@ -233,7 +233,7 @@ private void MergeTable(DataTable src, DataTable dst) internal void MergeRows(DataRow[] rows) { - Debug.Assert(_dataSet != null); + Debug.Assert(_dataSet is not null); DataTable? src = null; DataTable? dst = null; @@ -247,11 +247,11 @@ internal void MergeRows(DataRow[] rows) { DataRow row = rows[i]; - if (row == null) + if (row is null) { throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}]"); } - if (row.Table == null) + if (row.Table is null) { throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}].{nameof(DataRow.Table)}"); } @@ -266,13 +266,13 @@ internal void MergeRows(DataRow[] rows) { // row.Table changed from prev. row. src = row.Table; dst = MergeSchema(row.Table); - if (dst == null) + if (dst is null) { Debug.Assert(MissingSchemaAction.Ignore == _missingSchemaAction, "MergeSchema failed"); _dataSet.EnforceConstraints = fEnforce; return; } - if (dst._primaryKey != null) + if (dst._primaryKey is not null) { key = GetSrcKey(src, dst); } @@ -281,7 +281,7 @@ internal void MergeRows(DataRow[] rows) // Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex(); // IMO, Better would be to reuse index // ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added ); - if (null != ndxSearch) + if (ndxSearch is not null) { ndxSearch.RemoveRef(); ndxSearch = null; @@ -298,19 +298,19 @@ internal void MergeRows(DataRow[] rows) } DataRow? targetRow = null; - if (0 < dst!.Rows.Count && ndxSearch != null) + if (0 < dst!.Rows.Count && ndxSearch is not null) { targetRow = dst.FindMergeTarget(row, key, ndxSearch); } targetRow = dst.MergeRow(row, targetRow, _preserveChanges, ndxSearch); - if (targetRow.Table._dependentColumns != null && targetRow.Table._dependentColumns.Count > 0) + if (targetRow.Table._dependentColumns is not null && targetRow.Table._dependentColumns.Count > 0) { targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null); } } - if (null != ndxSearch) + if (ndxSearch is not null) { ndxSearch.RemoveRef(); ndxSearch = null; @@ -341,7 +341,7 @@ internal void MergeRows(DataRow[] rows) targetTable = _dataTable; } - if (targetTable == null) + if (targetTable is null) { // in case of standalone table, we make sure that targetTable is not null, so if this check passes, it will be when it is called via detaset if (MissingSchemaAction.Add == _missingSchemaAction) @@ -366,7 +366,7 @@ internal void MergeRows(DataRow[] rows) { DataColumn src = table.Columns[i]; DataColumn? dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null; - if (dest == null) + if (dest is null) { if (MissingSchemaAction.Add == _missingSchemaAction) { @@ -453,7 +453,7 @@ internal void MergeRows(DataRow[] rows) private void MergeTableData(DataTable src) { DataTable? dest = MergeSchema(src); - if (dest == null) return; + if (dest is null) return; dest.MergingData = true; try @@ -476,7 +476,7 @@ private void MergeConstraints(DataSet source) private void MergeConstraints(DataTable table) { - Debug.Assert(_dataSet != null); + Debug.Assert(_dataSet is not null); // Merge constraints for (int i = 0; i < table.Constraints.Count; i++) @@ -484,7 +484,7 @@ private void MergeConstraints(DataTable table) Constraint src = table.Constraints[i]; Constraint? dest = src.Clone(_dataSet, _IgnoreNSforTableLookup); - if (dest == null) + if (dest is null) { _dataSet.RaiseMergeFailed(table, SR.Format(SR.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName), @@ -494,7 +494,7 @@ private void MergeConstraints(DataTable table) else { Constraint? cons = dest.Table!.Constraints.FindConstraint(dest); - if (cons == null) + if (cons is null) { if (MissingSchemaAction.Add == _missingSchemaAction) { @@ -528,7 +528,7 @@ private void MergeConstraints(DataTable table) private void MergeRelation(DataRelation relation) { - Debug.Assert(_dataSet != null); + Debug.Assert(_dataSet is not null); Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction || MissingSchemaAction.Add == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); @@ -626,7 +626,7 @@ private void MergeExtendedProperties(PropertyCollection src, PropertyCollection IDictionaryEnumerator srcDE = src.GetEnumerator(); while (srcDE.MoveNext()) { - if (!_preserveChanges || dst[srcDE.Key] == null) + if (!_preserveChanges || dst[srcDE.Key] is null) { dst[srcDE.Key] = srcDE.Value; } @@ -635,13 +635,13 @@ private void MergeExtendedProperties(PropertyCollection src, PropertyCollection private DataKey GetSrcKey(DataTable src, DataTable dst) { - if (src._primaryKey != null) + if (src._primaryKey is not null) { return src._primaryKey.Key; } DataKey key = default(DataKey); - if (dst._primaryKey != null) + if (dst._primaryKey is not null) { DataColumn[] dstColumns = dst._primaryKey.Key.ColumnsReference; DataColumn[] srcColumns = new DataColumn[dstColumns.Length]; diff --git a/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs index 118814e3e0ffb3..4e63c8c08c3d85 100644 --- a/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs @@ -21,7 +21,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs index 830983f36f1f24..7be75fd145bc66 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs @@ -16,7 +16,7 @@ internal static DataReaderContainer Create(IDataReader dataReader, bool returnPr if (returnProviderSpecificTypes) { DbDataReader? providerSpecificDataReader = (dataReader as DbDataReader); - if (null != providerSpecificDataReader) + if (providerSpecificDataReader is not null) { return new ProviderSpecificDataReader(dataReader, providerSpecificDataReader); } @@ -26,7 +26,7 @@ internal static DataReaderContainer Create(IDataReader dataReader, bool returnPr protected DataReaderContainer(IDataReader dataReader) { - Debug.Assert(null != dataReader, "null dataReader"); + Debug.Assert(dataReader is not null, "null dataReader"); _dataReader = dataReader; } @@ -48,8 +48,8 @@ internal int FieldCount internal string GetName(int ordinal) { string fieldName = _dataReader.GetName(ordinal); - Debug.Assert(null != fieldName, "null GetName"); - return ((null != fieldName) ? fieldName : ""); + Debug.Assert(fieldName is not null, "null GetName"); + return ((fieldName is not null) ? fieldName : ""); } internal DataTable? GetSchemaTable() { @@ -76,7 +76,7 @@ private sealed class ProviderSpecificDataReader : DataReaderContainer internal ProviderSpecificDataReader(IDataReader dataReader, DbDataReader dbDataReader) : base(dataReader) { - Debug.Assert(null != dataReader, "null dbDataReader"); + Debug.Assert(dataReader is not null, "null dbDataReader"); _providerSpecificDataReader = dbDataReader; _fieldCount = VisibleFieldCount; } @@ -101,7 +101,7 @@ protected override int VisibleFieldCount internal override Type GetFieldType(int ordinal) { Type fieldType = _providerSpecificDataReader.GetProviderSpecificFieldType(ordinal); - Debug.Assert(null != fieldType, "null FieldType"); + Debug.Assert(fieldType is not null, "null FieldType"); return fieldType; } internal override object GetValue(int ordinal) diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs index 849908991e48a8..7df1787b3fd7ce 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs @@ -59,10 +59,10 @@ internal SchemaMapping(DataAdapter adapter, DataSet? dataset, DataTable? datatab SchemaType schemaType, string? sourceTableName, bool gettingData, DataColumn? parentChapterColumn, object? parentChapterValue) { - Debug.Assert(null != adapter, nameof(adapter)); - Debug.Assert(null != dataReader, nameof(dataReader)); + Debug.Assert(adapter is not null, nameof(adapter)); + Debug.Assert(dataReader is not null, nameof(dataReader)); Debug.Assert(0 < dataReader.FieldCount, "FieldCount"); - Debug.Assert(null != dataset || null != datatable, "SchemaMapping - null dataSet"); + Debug.Assert(dataset is not null || null != datatable, "SchemaMapping - null dataSet"); Debug.Assert(SchemaType.Mapped == schemaType || SchemaType.Source == schemaType, "SetupSchema - invalid schemaType"); _dataSet = dataset; // setting DataSet implies chapters are supported @@ -305,7 +305,7 @@ private void MappedValues() private object?[] GetMappedValues() { // mode 0 - Debug.Assert(_readerDataValues != null); + Debug.Assert(_readerDataValues is not null); if (null != _xmlMap) { @@ -315,7 +315,7 @@ private void MappedValues() { // get the string/SqlString xml value string? xml = _readerDataValues[i] as string; - if ((null == xml) && (_readerDataValues[i] is System.Data.SqlTypes.SqlString x)) + if ((xml is null) && (_readerDataValues[i] is System.Data.SqlTypes.SqlString x)) { if (!x.IsNull) { @@ -332,7 +332,7 @@ private void MappedValues() }; } } - if (null != xml) + if (xml is not null) { switch (_xmlMap[i]) { @@ -437,7 +437,7 @@ private void FreeDataRowChapters() if (_chapterMap[i]) { IDisposable? disposable = (_readerDataValues![i] as IDisposable); - if (null != disposable) + if (disposable is not null) { _readerDataValues[i] = null; disposable.Dispose(); @@ -456,7 +456,7 @@ internal int LoadDataRowChapters(DataRow dataRow) if (_chapterMap[i]) { object? readerValue = _readerDataValues![i]; - if ((null != readerValue) && !Convert.IsDBNull(readerValue)) + if ((readerValue is not null) && !Convert.IsDBNull(readerValue)) { _readerDataValues[i] = null; @@ -515,7 +515,7 @@ private static string[] GenerateFieldNames(DataReaderContainer dataReader) private DataColumn[] ResizeColumnArray(DataColumn[] rgcol, int len) { - Debug.Assert(rgcol != null, "invalid call to ResizeArray"); + Debug.Assert(rgcol is not null, "invalid call to ResizeArray"); Debug.Assert(len <= rgcol.Length, "invalid len passed to ResizeArray"); var tmp = new DataColumn[len]; Array.Copy(rgcol, tmp, len); @@ -524,7 +524,7 @@ private DataColumn[] ResizeColumnArray(DataColumn[] rgcol, int len) private void AddItemToAllowRollback(ref List? items, object value) { - if (null == items) + if (items is null) { items = new List(); } @@ -533,17 +533,17 @@ private void AddItemToAllowRollback(ref List? items, object value) private void RollbackAddedItems(List? items) { - if (null != items) + if (items is not null) { for (int i = items.Count - 1; 0 <= i; --i) { // remove columns that were added now that we are failing - if (null != items[i]) + if (items[i] is not null) { DataColumn? column = (items[i] as DataColumn); - if (null != column) + if (column is not null) { - if (null != column.Table) + if (column.Table is not null) { column.Table.Columns.Remove(column); } @@ -551,9 +551,9 @@ private void RollbackAddedItems(List? items) else { DataTable? table = (items[i] as DataTable); - if (null != table) + if (table is not null) { - if (null != table.DataSet) + if (table.DataSet is not null) { table.DataSet.Tables.Remove(table); } @@ -566,9 +566,9 @@ private void RollbackAddedItems(List? items) private object[]? SetupSchemaWithoutKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn? parentChapterColumn, object? chapterValue) { - Debug.Assert(_dataTable != null); - Debug.Assert(_fieldNames != null); - Debug.Assert(_tableMapping != null); + Debug.Assert(_dataTable is not null); + Debug.Assert(_fieldNames is not null); + Debug.Assert(_tableMapping is not null); int[]? columnIndexMap = null; bool[]? chapterIndexMap = null; @@ -581,16 +581,16 @@ private void RollbackAddedItems(List? items) try { DataColumnCollection columnCollection = _dataTable.Columns; - columnCollection.EnsureAdditionalCapacity(count + (chapterValue != null ? 1 : 0)); + columnCollection.EnsureAdditionalCapacity(count + (chapterValue is not null ? 1 : 0)); // We can always just create column if there are no existing column or column mappings, and the mapping action is passthrough - bool alwaysCreateColumns = ((_dataTable.Columns.Count == 0) && ((_tableMapping.ColumnMappings == null) || (_tableMapping.ColumnMappings.Count == 0)) && (mappingAction == MissingMappingAction.Passthrough)); + bool alwaysCreateColumns = ((_dataTable.Columns.Count == 0) && ((_tableMapping.ColumnMappings is null) || (_tableMapping.ColumnMappings.Count == 0)) && (mappingAction == MissingMappingAction.Passthrough)); for (int i = 0; i < count; ++i) { bool ischapter = false; Type fieldType = _dataReader.GetFieldType(i); - if (null == fieldType) + if (fieldType is null) { throw ADP.MissingDataReaderFieldType(i); } @@ -598,7 +598,7 @@ private void RollbackAddedItems(List? items) // if IDataReader, hierarchy exists and we will use an Int32,AutoIncrementColumn in this table if (typeof(IDataReader).IsAssignableFrom(fieldType)) { - if (null == chapterIndexMap) + if (chapterIndexMap is null) { chapterIndexMap = new bool[count]; } @@ -633,9 +633,9 @@ private void RollbackAddedItems(List? items) dataColumn = _tableMapping.GetDataColumn(_fieldNames[i], fieldType, _dataTable, mappingAction, schemaAction); } - if (null == dataColumn) + if (dataColumn is null) { - if (null == columnIndexMap) + if (columnIndexMap is null) { columnIndexMap = CreateIndexMap(count, i); } @@ -668,7 +668,7 @@ private void RollbackAddedItems(List? items) } } - if (null == dataColumn.Table) + if (dataColumn.Table is null) { if (ischapter) { @@ -685,7 +685,7 @@ private void RollbackAddedItems(List? items) } - if (null != columnIndexMap) + if (columnIndexMap is not null) { columnIndexMap[i] = dataColumn.Ordinal; } @@ -700,18 +700,18 @@ private void RollbackAddedItems(List? items) } bool addDataRelation = false; DataColumn? chapterColumn = null; - if (null != chapterValue) + if (chapterValue is not null) { // add the extra column in the child table Type fieldType = chapterValue.GetType(); chapterColumn = _tableMapping.GetDataColumn(_tableMapping.SourceTable, fieldType, _dataTable, mappingAction, schemaAction); - if (null != chapterColumn) + if (chapterColumn is not null) { - if (null == chapterColumn.Table) + if (chapterColumn.Table is null) { AddItemToAllowRollback(ref addedItems, chapterColumn); columnCollection.Add(chapterColumn); - addDataRelation = (null != parentChapterColumn); + addDataRelation = (parentChapterColumn is not null); } mappingCount++; } @@ -727,7 +727,7 @@ private void RollbackAddedItems(List? items) } if (gettingData) { - if (null == columnCollection) + if (columnCollection is null) { columnCollection = _dataTable.Columns; } @@ -761,14 +761,14 @@ private void RollbackAddedItems(List? items) private object[]? SetupSchemaWithKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn? parentChapterColumn, object? chapterValue) { - Debug.Assert(_dataTable != null); - Debug.Assert(_schemaTable != null); - Debug.Assert(_fieldNames != null); - Debug.Assert(_tableMapping != null); + Debug.Assert(_dataTable is not null); + Debug.Assert(_schemaTable is not null); + Debug.Assert(_fieldNames is not null); + Debug.Assert(_tableMapping is not null); // must sort rows from schema table by ordinal because Jet is sorted by coumn name DbSchemaRow[] schemaRows = DbSchemaRow.GetSortedSchemaRows(_schemaTable, _dataReader.ReturnProviderSpecificTypes); - Debug.Assert(null != schemaRows, "SchemaSetup - null DbSchemaRow[]"); + Debug.Assert(schemaRows is not null, "SchemaSetup - null DbSchemaRow[]"); Debug.Assert(_dataReader.FieldCount <= schemaRows.Length, "unexpected fewer rows in Schema than FieldCount"); if (0 == schemaRows.Length) @@ -810,11 +810,11 @@ private void RollbackAddedItems(List? items) bool ischapter = false; Type? fieldType = schemaRow.DataType; - if (null == fieldType) + if (fieldType is null) { fieldType = _dataReader.GetFieldType(sortedIndex); } - if (null == fieldType) + if (fieldType is null) { throw ADP.MissingDataReaderFieldType(sortedIndex); } @@ -822,7 +822,7 @@ private void RollbackAddedItems(List? items) // if IDataReader, hierarchy exists and we will use an Int32,AutoIncrementColumn in this table if (typeof(IDataReader).IsAssignableFrom(fieldType)) { - if (null == chapterIndexMap) + if (chapterIndexMap is null) { chapterIndexMap = new bool[schemaRows.Length]; } @@ -854,9 +854,9 @@ private void RollbackAddedItems(List? items) } string basetable = /*schemaRow.BaseServerName+schemaRow.BaseCatalogName+schemaRow.BaseSchemaName+*/ schemaRow.BaseTableName; - if (null == dataColumn) + if (dataColumn is null) { - if (null == columnIndexMap) + if (columnIndexMap is null) { columnIndexMap = CreateIndexMap(schemaRows.Length, unsortedIndex); } @@ -905,7 +905,7 @@ private void RollbackAddedItems(List? items) { if (basetable != keyBaseTable) { - if (null == keyBaseTable) + if (keyBaseTable is null) { keyBaseTable = basetable; } @@ -915,7 +915,7 @@ private void RollbackAddedItems(List? items) if (ischapter) { - if (null == dataColumn.Table) + if (dataColumn.Table is null) { dataColumn.AllowDBNull = false; dataColumn.AutoIncrement = true; @@ -932,7 +932,7 @@ private void RollbackAddedItems(List? items) { if ((basetable != commonBaseTable) && (!string.IsNullOrEmpty(basetable))) { - if (null == commonBaseTable) + if (commonBaseTable is null) { commonBaseTable = basetable; } @@ -984,7 +984,7 @@ private void RollbackAddedItems(List? items) } } } - else if (null == dataColumn.Table) + else if (dataColumn.Table is null) { dataColumn.AutoIncrement = schemaRow.IsAutoIncrement; dataColumn.AllowDBNull = schemaRow.AllowDBNull; @@ -998,7 +998,7 @@ private void RollbackAddedItems(List? items) } } } - if (null == dataColumn.Table) + if (dataColumn.Table is null) { if (4 > (int)_loadOption) { @@ -1020,7 +1020,7 @@ private void RollbackAddedItems(List? items) // if (addPrimaryKeys && schemaRow.IsKey) { - if (keys == null) + if (keys is null) { keys = new DataColumn[schemaRows.Length]; } @@ -1034,7 +1034,7 @@ private void RollbackAddedItems(List? items) } } - if (null != columnIndexMap) + if (columnIndexMap is not null) { columnIndexMap[unsortedIndex] = dataColumn.Ordinal; } @@ -1048,20 +1048,20 @@ private void RollbackAddedItems(List? items) bool addDataRelation = false; DataColumn? chapterColumn = null; - if (null != chapterValue) + if (chapterValue is not null) { // add the extra column in the child table Type fieldType = chapterValue.GetType(); chapterColumn = _tableMapping.GetDataColumn(_tableMapping.SourceTable, fieldType, _dataTable, mappingAction, schemaAction); - if (null != chapterColumn) + if (chapterColumn is not null) { - if (null == chapterColumn.Table) + if (chapterColumn.Table is null) { chapterColumn.ReadOnly = true; chapterColumn.AllowDBNull = false; AddItemToAllowRollback(ref addedItems, chapterColumn); columnCollection.Add(chapterColumn); - addDataRelation = (null != parentChapterColumn); + addDataRelation = (parentChapterColumn is not null); } mappingCount++; } @@ -1075,7 +1075,7 @@ private void RollbackAddedItems(List? items) _dataSet.Tables.Add(_dataTable); } // setup the key - if (addPrimaryKeys && (null != keys)) + if (addPrimaryKeys && (keys is not null)) { if (keyCount < keys.Length) { @@ -1099,7 +1099,7 @@ private void RollbackAddedItems(List? items) break; } } - if (null != unique) + if (unique is not null) { constraints.Add(unique); } @@ -1144,13 +1144,13 @@ private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) DataColumn? column; column = columns[SchemaTableOptionalColumn.DefaultValue]; - if (null != column) + if (column is not null) { targetColumn.DefaultValue = schemaRow[column]; } column = columns[SchemaTableOptionalColumn.AutoIncrementSeed]; - if (null != column) + if (column is not null) { object value = schemaRow[column]; if (DBNull.Value != value) @@ -1160,7 +1160,7 @@ private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) } column = columns[SchemaTableOptionalColumn.AutoIncrementStep]; - if (null != column) + if (column is not null) { object value = schemaRow[column]; if (DBNull.Value != value) @@ -1170,7 +1170,7 @@ private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) } column = columns[SchemaTableOptionalColumn.ColumnMapping]; - if (null != column) + if (column is not null) { object value = schemaRow[column]; if (DBNull.Value != value) @@ -1180,7 +1180,7 @@ private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) } column = columns[SchemaTableOptionalColumn.BaseColumnNamespace]; - if (null != column) + if (column is not null) { object value = schemaRow[column]; if (DBNull.Value != value) @@ -1190,7 +1190,7 @@ private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) } column = columns[SchemaTableOptionalColumn.Expression]; - if (null != column) + if (column is not null) { object value = schemaRow[column]; if (DBNull.Value != value) @@ -1254,7 +1254,7 @@ private object[] SetupMapping(int count, DataColumnCollection columnCollection, _mappedMode = ((null == _chapterMap) ? MapReorderedValues : MapChaptersReordered); _mappedLength = count; } - if (null != chapterColumn) + if (chapterColumn is not null) { // value from parent tracked into child table _mappedDataValues![chapterColumn.Ordinal] = chapterValue; } diff --git a/src/libraries/System.Data.Common/src/System/Data/RbTree.cs b/src/libraries/System.Data.Common/src/System/Data/RbTree.cs index a5f75b089899bc..33d241108b97e1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RbTree.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RbTree.cs @@ -289,12 +289,12 @@ private int GetIndexOfPageWithFreeSlot(bool allocatedPage) pageIndex = (pageTableMapPos * TreePage.slotLineSize) + GetIntValueFromBitMap(pageWithFreeSlot); // segment + offset if (allocatedPage) { - if (_pageTable[pageIndex] != null) + if (_pageTable[pageIndex] is not null) return pageIndex; } else { - if (_pageTable[pageIndex] == null) + if (_pageTable[pageIndex] is null) return pageIndex; // pageIndex points to an unallocated Page } pageIndex = -1; @@ -1623,7 +1623,7 @@ public void Clear() public void CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw ExceptionBuilder.ArgumentNull(nameof(array)); } @@ -1648,7 +1648,7 @@ public void CopyTo(Array array, int index) public void CopyTo(K[] array, int index) { - if (array == null) + if (array is null) { throw ExceptionBuilder.ArgumentNull(nameof(array)); } @@ -1904,7 +1904,7 @@ internal NodePath(int nodeID, int mainTreeNodeID) #if VerifyPath internal void VerifyPath(RBTree tree) { - Debug.Assert(null != tree, "null tree"); + Debug.Assert(tree is not null, "null tree"); Debug.Assert((NIL == _nodeID && NIL == _mainTreeNodeID) || (NIL != _nodeID), "MainTreeNodeID is not NIL"); if (NIL != _mainTreeNodeID) diff --git a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs index dfffcc6e52c216..bd1f376af34099 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs @@ -19,7 +19,7 @@ internal sealed class RecordManager internal RecordManager(DataTable table) { - if (table == null) + if (table is null) { throw ExceptionBuilder.ArgumentNull(nameof(table)); } @@ -34,7 +34,7 @@ private void GrowRecordCapacity() // set up internal map : record --> row DataRow[] newRows = _table.NewRowArray(_recordCapacity); - if (_rows != null) + if (_rows is not null) { Array.Copy(_rows, newRows, Math.Min(_lastFreeRecord, _rows.Length)); } @@ -208,7 +208,7 @@ internal int ImportRecord(DataTable src, int record) // No impact on AutoIncrementCurrent if over written internal int CopyRecord(DataTable src, int record, int copy) { - Debug.Assert(src != null, "Can not Merge record without a table"); + Debug.Assert(src is not null, "Can not Merge record without a table"); if (record == -1) { @@ -226,11 +226,11 @@ internal int CopyRecord(DataTable src, int record, int copy) { DataColumn dstColumn = _table.Columns[i]; DataColumn? srcColumn = src.Columns[dstColumn.ColumnName]; - if (null != srcColumn) + if (srcColumn is not null) { object value = srcColumn[record]; ICloneable? cloneableObject = value as ICloneable; - if (null != cloneableObject) + if (cloneableObject is not null) { dstColumn[newRecord] = cloneableObject.Clone(); } @@ -268,7 +268,7 @@ internal void VerifyRecord(int record) { Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accessing free record"); var r = _rows[record]; - Debug.Assert((null == r) || + Debug.Assert((r is null) || (record == r._oldRecord) || (record == r._newRecord) || (record == r._tempRecord), "record of a different row"); diff --git a/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs b/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs index 3a121937972e70..dea59d912276c6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs @@ -14,7 +14,7 @@ internal sealed class RelatedView : DataView, IFilter public RelatedView(DataColumn[] columns, object[] values) : base(columns[0].Table, false) { - if (values == null) + if (values is null) { throw ExceptionBuilder.ArgumentNull(nameof(values)); } @@ -39,7 +39,7 @@ public RelatedView(DataRowView parentRowView, DataKey parentKey, DataColumn[] ch private object[]? GetParentValues() { - if (_filterValues != null) + if (_filterValues is not null) { return _filterValues; } @@ -55,7 +55,7 @@ public RelatedView(DataRowView parentRowView, DataKey parentKey, DataColumn[] ch public bool Invoke(DataRow row, DataRowVersion version) { object[]? parentValues = GetParentValues(); - if (parentValues == null) + if (parentValues is null) { return false; } @@ -80,7 +80,7 @@ public bool Invoke(DataRow row, DataRowVersion version) } IFilter? baseFilter = base.GetFilter(); - if (baseFilter != null) + if (baseFilter is not null) { allow &= baseFilter.Invoke(row, version); } @@ -107,7 +107,7 @@ internal override void SetIndex(string newSort, DataViewRowState newRowStates, I public override bool Equals(DataView? dv) { RelatedView? other = dv as RelatedView; - if (other == null) + if (other is null) { return false; } @@ -115,13 +115,13 @@ public override bool Equals(DataView? dv) { return false; } - if (_filterValues != null) + if (_filterValues is not null) { return (CompareArray(_childKey.ColumnsReference, other._childKey.ColumnsReference) && CompareArray(_filterValues, other._filterValues)); } else { - if (other._filterValues != null) + if (other._filterValues is not null) { return false; } @@ -134,7 +134,7 @@ public override bool Equals(DataView? dv) private bool CompareArray(object?[]? value1, object?[]? value2) { - if (value1 == null || value2 == null) + if (value1 is null || value2 is null) { return value1 == value2; } diff --git a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs index a14f40eccc171f..f64b448440cc65 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs @@ -36,7 +36,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs index ab176703b4657b..114c2c2c32ca21 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs @@ -27,7 +27,7 @@ private SqlBinary(bool fNull) public SqlBinary(byte[]? value) { // if value is null, this generates a SqlBinary.Null - if (value == null) + if (value is null) { _value = null; } @@ -93,7 +93,7 @@ public int Length { get { - if (_value != null) + if (_value is not null) { return _value.Length; } @@ -425,7 +425,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); @@ -434,7 +434,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) else { string base64 = reader.ReadElementString(); - if (base64 == null) + if (base64 is null) { _value = Array.Empty(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs index b76f3d16c7d2d2..8061f3c2712331 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs @@ -191,7 +191,7 @@ public override string ToString() public static SqlBoolean Parse(string s) { - if (null == s) + if (s is null) // Let Boolean.Parse throw exception return new SqlBoolean(bool.Parse(s!)); if (s == SQLResource.NullString) @@ -490,7 +490,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs index fd353138851358..b2eb47280833a9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs @@ -499,7 +499,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs index caeff12be45661..ebb00a20c1491b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs @@ -69,7 +69,7 @@ public SqlBytes(byte[]? buffer) { _rgbBuf = buffer; _stream = null; - if (_rgbBuf == null) + if (_rgbBuf is null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; @@ -96,7 +96,7 @@ public SqlBytes(Stream? s) _rgbBuf = null; _lCurLen = x_lNull; _stream = s; - _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; + _state = (s is null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgbWorkBuf = null; @@ -156,7 +156,7 @@ public long MaxLength return _state switch { SqlBytesCharsState.Stream => -1L, - _ => (_rgbBuf == null) ? -1L : _rgbBuf.Length, + _ => (_rgbBuf is null) ? -1L : _rgbBuf.Length, }; } } @@ -200,7 +200,7 @@ public byte this[long offset] if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); - if (_rgbWorkBuf == null) + if (_rgbWorkBuf is null) _rgbWorkBuf = new byte[1]; Read(offset, _rgbWorkBuf, 0, 1); @@ -208,7 +208,7 @@ public byte this[long offset] } set { - if (_rgbWorkBuf == null) + if (_rgbWorkBuf is null) _rgbWorkBuf = new byte[1]; _rgbWorkBuf[0] = value; Write(offset, _rgbWorkBuf, 0, 1); @@ -239,7 +239,7 @@ public Stream Stream { _lCurLen = x_lNull; _stream = value; - _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; + _state = (value is null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } @@ -298,7 +298,7 @@ public long Read(long offset, byte[] buffer, int offsetInBuffer, int count) throw new SqlNullValueException(); // Validate the arguments - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset > Length || offset < 0) @@ -344,10 +344,10 @@ public void Write(long offset, byte[] buffer, int offsetInBuffer, int count) else { // Validate the arguments - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); - if (_rgbBuf == null) + if (_rgbBuf is null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (offset < 0) @@ -437,10 +437,10 @@ private void AssertValid() else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); - Debug.Assert(FStream() || (_rgbBuf != null && _lCurLen <= _rgbBuf.Length)); + Debug.Assert(FStream() || (_rgbBuf is not null && _lCurLen <= _rgbBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } - Debug.Assert(_rgbWorkBuf == null || _rgbWorkBuf.Length == 1); + Debug.Assert(_rgbWorkBuf is null || _rgbWorkBuf.Length == 1); } // Copy the data from the Stream to the array buffer. @@ -454,7 +454,7 @@ private void CopyStreamToBuffer() if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); - if (_rgbBuf == null || _rgbBuf.Length < lStreamLen) + if (_rgbBuf is null || _rgbBuf.Length < lStreamLen) _rgbBuf = new byte[lStreamLen]; if (_stream.Position != 0) @@ -478,9 +478,9 @@ internal bool FStream() private void SetBuffer(byte[]? buffer) { _rgbBuf = buffer; - _lCurLen = (_rgbBuf == null) ? x_lNull : _rgbBuf.Length; + _lCurLen = (_rgbBuf is null) ? x_lNull : _rgbBuf.Length; _stream = null; - _state = (_rgbBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; + _state = (_rgbBuf is null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } @@ -500,7 +500,7 @@ void IXmlSerializable.ReadXml(XmlReader r) string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadElementString(); @@ -509,7 +509,7 @@ void IXmlSerializable.ReadXml(XmlReader r) else { string base64 = r.ReadElementString(); - if (base64 == null) + if (base64 is null) { value = Array.Empty(); } @@ -606,7 +606,7 @@ public override bool CanRead { get { - return _sb != null && !_sb.IsNull; + return _sb is not null && !_sb.IsNull; } } @@ -614,7 +614,7 @@ public override bool CanSeek { get { - return _sb != null; + return _sb is not null; } } @@ -622,7 +622,7 @@ public override bool CanWrite { get { - return _sb != null && (!_sb.IsNull || _sb._rgbBuf != null); + return _sb is not null && (!_sb.IsNull || _sb._rgbBuf is not null); } } @@ -696,7 +696,7 @@ public override int Read(byte[] buffer, int offset, int count) { CheckIfStreamClosed(); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -713,7 +713,7 @@ public override void Write(byte[] buffer, int offset, int count) { CheckIfStreamClosed(); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -784,7 +784,7 @@ protected override void Dispose(bool disposing) private bool FClosed() { - return _sb == null; + return _sb is null; } private void CheckIfStreamClosed([CallerMemberName] string methodname = "") diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs index dfb18b73ab6529..99cb4547b2642d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs @@ -61,7 +61,7 @@ public SqlChars(char[]? buffer) { _rgchBuf = buffer; _stream = null; - if (_rgchBuf == null) + if (_rgchBuf is null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; @@ -88,7 +88,7 @@ internal SqlChars(SqlStreamChars s) _rgchBuf = null; _lCurLen = x_lNull; _stream = s; - _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; + _state = (s is null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; @@ -149,7 +149,7 @@ public long MaxLength return _state switch { SqlBytesCharsState.Stream => -1L, - _ => (_rgchBuf == null) ? -1L : _rgchBuf.Length, + _ => (_rgchBuf is null) ? -1L : _rgchBuf.Length, }; } } @@ -195,7 +195,7 @@ public char this[long offset] if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); - if (_rgchWorkBuf == null) + if (_rgchWorkBuf is null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); @@ -203,7 +203,7 @@ public char this[long offset] } set { - if (_rgchWorkBuf == null) + if (_rgchWorkBuf is null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); @@ -220,7 +220,7 @@ internal SqlStreamChars Stream { _lCurLen = x_lNull; _stream = value; - _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; + _state = (value is null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } @@ -295,7 +295,7 @@ public long Read(long offset, char[] buffer, int offsetInBuffer, int count) throw new SqlNullValueException(); // Validate the arguments - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset > Length || offset < 0) @@ -342,10 +342,10 @@ public void Write(long offset, char[] buffer, int offsetInBuffer, int count) else { // Validate the arguments - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); - if (_rgchBuf == null) + if (_rgchBuf is null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (offset < 0) @@ -435,10 +435,10 @@ private void AssertValid() else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); - Debug.Assert(FStream() || (_rgchBuf != null && _lCurLen <= _rgchBuf.Length)); + Debug.Assert(FStream() || (_rgchBuf is not null && _lCurLen <= _rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } - Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); + Debug.Assert(_rgchWorkBuf is null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream @@ -458,7 +458,7 @@ private void CopyStreamToBuffer() if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); - if (_rgchBuf == null || _rgchBuf.Length < lStreamLen) + if (_rgchBuf is null || _rgchBuf.Length < lStreamLen) _rgchBuf = new char[lStreamLen]; if (_stream.Position != 0) @@ -475,9 +475,9 @@ private void CopyStreamToBuffer() private void SetBuffer(char[] buffer) { _rgchBuf = buffer; - _lCurLen = (_rgchBuf == null) ? x_lNull : _rgchBuf.Length; + _lCurLen = (_rgchBuf is null) ? x_lNull : _rgchBuf.Length; _stream = null; - _state = (_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; + _state = (_rgchBuf is null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } @@ -498,7 +498,7 @@ void IXmlSerializable.ReadXml(XmlReader r) string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadElementString(); @@ -651,7 +651,7 @@ public int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed(); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -668,7 +668,7 @@ public void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed(); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -694,7 +694,7 @@ public void SetLength(long value) private bool FClosed() { - return _sqlchars == null; + return _sqlchars is null; } private void CheckIfStreamClosed([CallerMemberName] string methodname = "") diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs index 2e08f0eb4d20e5..61f1e6532d30f8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs @@ -646,7 +646,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs index 0297adacd4f57c..59fcc4ef76f324 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs @@ -579,7 +579,7 @@ public SqlDecimal(long value) public SqlDecimal(byte bPrecision, byte bScale, bool fPositive, int[] bits) { CheckValidPrecScale(bPrecision, bScale); - if (bits == null) + if (bits is null) throw new ArgumentNullException(nameof(bits)); else if (bits.Length != 4) throw new ArgumentException(SQLResource.InvalidArraySizeMessage, nameof(bits)); @@ -988,7 +988,7 @@ public override string ToString() public static SqlDecimal Parse(string s) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); if (s == SQLResource.NullString) @@ -3335,7 +3335,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs index aa8ea8cb9dd257..2ff4432027700c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs @@ -415,7 +415,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs index 263cf292444095..c9c98a8c0ce348 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs @@ -35,7 +35,7 @@ private SqlGuid(bool fNull) public SqlGuid(byte[] value) { - if (value == null || value.Length != SizeOfGuid) + if (value is null || value.Length != SizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); m_value = new byte[SizeOfGuid]; @@ -44,7 +44,7 @@ public SqlGuid(byte[] value) internal SqlGuid(byte[] value, bool ignored) { - if (value == null || value.Length != SizeOfGuid) + if (value is null || value.Length != SizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); m_value = value; @@ -306,7 +306,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs index 7da5e90509aa0d..180b4ef708c1f0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs @@ -500,7 +500,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs index c02908e39f7505..f07f68224fc836 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs @@ -515,7 +515,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs index d65fcd73f6c009..92044eb1d1e5af 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs @@ -574,7 +574,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs index 83ecd1c80166e3..3a09c808de594a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs @@ -565,7 +565,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs index 9e61441618cc46..2a052560636c47 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs @@ -425,7 +425,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs index e16012f11647bb..3864af38183ef1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs @@ -104,7 +104,7 @@ public SqlString(int lcid, SqlCompareOptions compareOptions, byte[]? data, int i m_lcid = lcid; ValidateSqlCompareOptions(compareOptions); m_flag = compareOptions; - if (data == null) + if (data is null) { m_fNotNull = false; m_value = null; @@ -165,7 +165,7 @@ public SqlString(string? data, int lcid, SqlCompareOptions compareOptions) ValidateSqlCompareOptions(compareOptions); m_flag = compareOptions; m_cmpInfo = null; - if (data == null) + if (data is null) { m_fNotNull = false; m_value = null; @@ -196,7 +196,7 @@ private SqlString(int lcid, SqlCompareOptions compareOptions, string? data, Comp m_lcid = lcid; ValidateSqlCompareOptions(compareOptions); m_flag = compareOptions; - if (data == null) + if (data is null) { m_fNotNull = false; m_value = null; @@ -260,7 +260,7 @@ public CultureInfo CultureInfo private void SetCompareInfo() { Debug.Assert(!IsNull); - if (m_cmpInfo == null) + if (m_cmpInfo is null) m_cmpInfo = (CultureInfo.GetCultureInfo(m_lcid)).CompareInfo; } @@ -350,7 +350,7 @@ internal int GetSQLCID() { throw new SqlTypeException(SQLResource.ConcatDiffCollationMessage); return new SqlString(x.m_lcid, x.m_flag, x.m_value + y.m_value, - (x.m_cmpInfo == null) ? y.m_cmpInfo : x.m_cmpInfo); + (x.m_cmpInfo is null) ? y.m_cmpInfo : x.m_cmpInfo); } // StringCompare: Common compare function which is used by Compare and CompareTo @@ -367,8 +367,8 @@ private static int StringCompare(SqlString x, SqlString y) x.SetCompareInfo(); y.SetCompareInfo(); - Debug.Assert(x.FBinarySort() || (x.m_cmpInfo != null && y.m_cmpInfo != null), - "x.FBinarySort() || (x.m_cmpInfo != null && y.m_cmpInfo != null)", ""); + Debug.Assert(x.FBinarySort() || (x.m_cmpInfo is not null && y.m_cmpInfo is not null), + "x.FBinarySort() || (x.m_cmpInfo is not null && y.m_cmpInfo is not null)", ""); int iCmpResult; @@ -923,7 +923,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs index eeff48caa91d20..509fbce866250c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs @@ -47,7 +47,7 @@ protected SqlTypeException(SerializationInfo si, StreamingContext sc) : base(Sql private static SerializationInfo SqlTypeExceptionSerialization(SerializationInfo? si, StreamingContext sc) { - if ((null != si) && (1 == si.MemberCount)) + if ((si is not null) && (1 == si.MemberCount)) { string? message = si.GetString("SqlTypeExceptionMessage"); SqlTypeException fakeValue = new SqlTypeException(message); @@ -82,7 +82,7 @@ private SqlNullValueException(SerializationInfo si, StreamingContext sc) : base( private static SerializationInfo SqlNullValueExceptionSerialization(SerializationInfo si, StreamingContext sc) { - if ((null != si) && (1 == si.MemberCount)) + if ((si is not null) && (1 == si.MemberCount)) { string? message = si.GetString("SqlNullValueExceptionMessage"); SqlNullValueException fakeValue = new SqlNullValueException(message); @@ -117,7 +117,7 @@ private SqlTruncateException(SerializationInfo si, StreamingContext sc) : base(S private static SerializationInfo SqlTruncateExceptionSerialization(SerializationInfo si, StreamingContext sc) { - if ((null != si) && (1 == si.MemberCount)) + if ((si is not null) && (1 == si.MemberCount)) { string? message = si.GetString("SqlTruncateExceptionMessage"); SqlTruncateException fakeValue = new SqlTruncateException(message); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs index 8c6726a6dbe24b..86b0b260fd2198 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs @@ -41,7 +41,7 @@ private SqlXml(bool fNull) public SqlXml(XmlReader? value) { // whoever pass in the XmlReader is responsible for closing it - if (value == null) + if (value is null) { SetNull(); } @@ -57,7 +57,7 @@ public SqlXml(Stream? value) { // whoever pass in the stream is responsible for closing it // similar to SqlBytes implementation - if (value == null) + if (value is null) { SetNull(); } @@ -85,11 +85,11 @@ public XmlReader CreateReader() } // NOTE: Maintaining createSqlReaderMethodInfo private field member to preserve the serialization of the class - if (_createSqlReaderMethodInfo == null) + if (_createSqlReaderMethodInfo is null) { _createSqlReaderMethodInfo = CreateSqlReaderMethodInfo; } - Debug.Assert(_createSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); + Debug.Assert(_createSqlReaderMethodInfo is not null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); XmlReader r = CreateSqlXmlReader(stream); _firstCreateReader = false; @@ -120,7 +120,7 @@ internal static XmlReader CreateSqlXmlReader(Stream stream, bool closeInput = fa private static Func CreateSqlReaderDelegate() { - Debug.Assert(CreateSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); + Debug.Assert(CreateSqlReaderMethodInfo is not null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); return CreateSqlReaderMethodInfo.CreateDelegate>(); } @@ -129,7 +129,7 @@ private static MethodInfo CreateSqlReaderMethodInfo { get { - if (s_createSqlReaderMethodInfo == null) + if (s_createSqlReaderMethodInfo is null) { s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic)!; } @@ -222,7 +222,7 @@ void IXmlSerializable.ReadXml(XmlReader r) { string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); - if (isNull != null && XmlConvert.ToBoolean(isNull)) + if (isNull is not null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadInnerXml(); @@ -293,7 +293,7 @@ internal sealed class SqlXmlStreamWrapper : Stream internal SqlXmlStreamWrapper(Stream stream) { _stream = stream; - Debug.Assert(_stream != null, "stream can not be null"); + Debug.Assert(_stream is not null, "stream can not be null"); _lPosition = 0; _isClosed = false; } @@ -408,7 +408,7 @@ public override int Read(byte[] buffer, int offset, int count) ThrowIfStreamClosed(nameof(Read)); ThrowIfStreamCannotRead(nameof(Read)); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -429,7 +429,7 @@ public override void Write(byte[] buffer, int offset, int count) ThrowIfStreamClosed(nameof(Write)); ThrowIfStreamCannotWrite(nameof(Write)); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -483,7 +483,7 @@ public override void SetLength(long value) public override void Flush() { - if (_stream != null) + if (_stream is not null) _stream.Flush(); } @@ -528,7 +528,7 @@ private bool IsStreamClosed() { // Check the .CanRead and .CanWrite and .CanSeek properties to make sure stream is really closed - if (_isClosed || _stream == null || (!_stream.CanRead && !_stream.CanWrite && !_stream.CanSeek)) + if (_isClosed || _stream is null || (!_stream.CanRead && !_stream.CanWrite && !_stream.CanSeek)) return true; else return false; diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 97fbb80c7b08fc..9cc66267baff5f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -38,7 +38,7 @@ public Select(DataTable table, string? filterExpression, string? sort, DataViewR { _table = table; _indexFields = table.ParseSortString(sort); - if (filterExpression != null && filterExpression.Length > 0) + if (filterExpression is not null && filterExpression.Length > 0) { _rowFilter = new DataExpression(_table, filterExpression); _expression = _rowFilter.ExpressionNode; @@ -54,7 +54,7 @@ private bool IsSupportedOperator(int op) // Gathers all linear expressions in to this.linearExpression and all binary expressions in to their respective candidate columns expressions private void AnalyzeExpression(BinaryNode expr) { - Debug.Assert(_candidateColumns != null); + Debug.Assert(_candidateColumns is not null); if (_linearExpression == _expression) return; @@ -78,7 +78,7 @@ private void AnalyzeExpression(BinaryNode expr) else { UnaryNode? unaryNode = expr._left as UnaryNode; - if (unaryNode != null) + if (unaryNode is not null) { while (unaryNode._op == Operators.Noop && unaryNode._right is UnaryNode && ((UnaryNode)unaryNode._right)._op == Operators.Noop) { @@ -106,7 +106,7 @@ private void AnalyzeExpression(BinaryNode expr) else { UnaryNode? unaryNode = expr._right as UnaryNode; - if (unaryNode != null) + if (unaryNode is not null) { while (unaryNode._op == Operators.Noop && unaryNode._right is UnaryNode && ((UnaryNode)unaryNode._right)._op == Operators.Noop) { @@ -129,7 +129,7 @@ private void AnalyzeExpression(BinaryNode expr) return; ExpressionNode e = isLeft ? expr._right : expr._left; - _linearExpression = (_linearExpression == null ? e : new BinaryNode(_table, Operators.And, e, _linearExpression)); + _linearExpression = (_linearExpression is null ? e : new BinaryNode(_table, Operators.And, e, _linearExpression)); return; } else @@ -138,7 +138,7 @@ private void AnalyzeExpression(BinaryNode expr) if (expr._left is NameNode && expr._right is ConstNode) { ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column!.Ordinal]; - canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr)); + canColumn.expr = (canColumn.expr is null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr)); if (expr._op == Operators.EqualTo) { canColumn.equalsOperator = true; @@ -161,7 +161,7 @@ private void AnalyzeExpression(BinaryNode expr) default: break; } ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column!.Ordinal]; - canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr)); + canColumn.expr = (canColumn.expr is null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr)); if (expr._op == Operators.EqualTo) { canColumn.equalsOperator = true; @@ -171,13 +171,13 @@ private void AnalyzeExpression(BinaryNode expr) } } - _linearExpression = (_linearExpression == null ? expr : new BinaryNode(_table, Operators.And, expr, _linearExpression)); + _linearExpression = (_linearExpression is null ? expr : new BinaryNode(_table, Operators.And, expr, _linearExpression)); return; } private bool CompareSortIndexDesc(IndexField[] fields) { - Debug.Assert(_candidateColumns != null); + Debug.Assert(_candidateColumns is not null); if (fields.Length < _indexFields.Length) return false; @@ -191,7 +191,7 @@ private bool CompareSortIndexDesc(IndexField[] fields) else { ColumnInfo canColumn = _candidateColumns[fields[i].Column.Ordinal]; - if (!(canColumn != null && canColumn.equalsOperator)) + if (!(canColumn is not null && canColumn.equalsOperator)) return false; } } @@ -231,14 +231,14 @@ private bool FindSortIndex() // Returns no. of columns that are matched private int CompareClosestCandidateIndexDesc(IndexField[] fields) { - Debug.Assert(_candidateColumns != null); + Debug.Assert(_candidateColumns is not null); int count = (fields.Length < _nCandidates ? fields.Length : _nCandidates); int i = 0; for (; i < count; i++) { ColumnInfo canColumn = _candidateColumns[fields[i].Column.Ordinal]; - if (canColumn == null || canColumn.expr == null) + if (canColumn is null || canColumn.expr is null) { break; } @@ -286,7 +286,7 @@ private bool FindClosestCandidateIndex() _table._indexesLock.ExitUpgradeableReadLock(); } - return (_index != null ? sortPriority : false); + return (_index is not null ? sortPriority : false); } // Initialize candidate columns to new columnInfo and leave all non candidate columns to null @@ -294,7 +294,7 @@ private void InitCandidateColumns() { _nCandidates = 0; _candidateColumns = new ColumnInfo[_table.Columns.Count]; - if (_rowFilter == null) + if (_rowFilter is null) return; DataColumn[] depColumns = _rowFilter.GetDependency(); for (int i = 0; i < depColumns.Length; i++) @@ -310,9 +310,9 @@ private void InitCandidateColumns() // Based on the required sorting and candidate columns settings, create a new index; Should be called only when there is no existing index to be reused private void CreateIndex() { - Debug.Assert(_candidateColumns != null); + Debug.Assert(_candidateColumns is not null); - if (_index == null) + if (_index is null) { if (_nCandidates == 0) { @@ -327,7 +327,7 @@ private void CreateIndex() bool equalsOperator = true; for (i = 0; i < lenCanColumns; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { if (!_candidateColumns[i].equalsOperator) { @@ -341,7 +341,7 @@ private void CreateIndex() for (i = 0; i < lenIndexDesc; i++) { ColumnInfo candidateColumn = _candidateColumns[_indexFields[i].Column.Ordinal]; - if (candidateColumn != null) + if (candidateColumn is not null) { candidateColumn.flag = true; j++; @@ -355,7 +355,7 @@ private void CreateIndex() j = 0; for (i = 0; i < lenCanColumns; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { ndxFields[j++] = new IndexField(_table.Columns[i], isDescending: false); _candidateColumns[i].flag = false; // this means it is processed @@ -364,10 +364,10 @@ private void CreateIndex() for (i = 0; i < lenIndexDesc; i++) { ColumnInfo canColumn = _candidateColumns[_indexFields[i].Column.Ordinal]; - if (canColumn == null || canColumn.flag) + if (canColumn is null || canColumn.flag) { // if sort column is not a filter col , or not processed ndxFields[j++] = _indexFields[i]; - if (canColumn != null) + if (canColumn is not null) { canColumn.flag = false; } @@ -376,7 +376,7 @@ private void CreateIndex() for (i = 0; i < _candidateColumns.Length; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { _candidateColumns[i].flag = false; // same as before, it is false when it returns } @@ -401,13 +401,13 @@ private void CreateIndex() { ndxFields[i] = _indexFields[i]; ColumnInfo canColumn = _candidateColumns[_indexFields[i].Column.Ordinal]; - if (canColumn != null) + if (canColumn is not null) canColumn.flag = true; } j = i; for (i = 0; i < lenCanColumns; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { if (!_candidateColumns[i].flag) { @@ -429,7 +429,7 @@ private void CreateIndex() while (_matchedCandidates < j) { ColumnInfo canColumn = _candidateColumns[fields[_matchedCandidates].Column.Ordinal]; - if (canColumn == null || canColumn.expr == null) + if (canColumn is null || canColumn.expr is null) break; _matchedCandidates++; if (!canColumn.equalsOperator) @@ -438,7 +438,7 @@ private void CreateIndex() } for (i = 0; i < _candidateColumns.Length; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { _candidateColumns[i].flag = false; // same as before, it is false when it returns } @@ -452,7 +452,7 @@ private void CreateIndex() private bool IsOperatorIn(ExpressionNode? enode) { BinaryNode? bnode = (enode as BinaryNode); - if (null != bnode) + if (bnode is not null) { if (Operators.In == bnode._op || IsOperatorIn(bnode._right) || @@ -469,7 +469,7 @@ private bool IsOperatorIn(ExpressionNode? enode) // Based on the current index and candidate columns settings, build the linear expression; Should be called only when there is atleast something for Binary Searching private void BuildLinearExpression() { - Debug.Assert(_candidateColumns != null); + Debug.Assert(_candidateColumns is not null); int i; IndexField[] fields = _index!._indexFields; @@ -478,7 +478,7 @@ private void BuildLinearExpression() for (i = 0; i < _matchedCandidates; i++) { ColumnInfo canColumn = _candidateColumns[fields[i].Column.Ordinal]; - Debug.Assert(canColumn != null && canColumn.expr != null, "BuildLinearExpression : Must be a matched candidate"); + Debug.Assert(canColumn is not null && canColumn.expr is not null, "BuildLinearExpression : Must be a matched candidate"); canColumn.flag = true; } //this is invalid assert, assumption was that all equals operator exists at the beginning of candidateColumns @@ -487,13 +487,13 @@ private void BuildLinearExpression() int lenCanColumns = _candidateColumns.Length; for (i = 0; i < lenCanColumns; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { if (!_candidateColumns[i].flag) { if (_candidateColumns[i].expr is BinaryNode expr) { - _linearExpression = (_linearExpression == null ? _candidateColumns[i].expr : new BinaryNode(_table, Operators.And, expr, _linearExpression)); + _linearExpression = (_linearExpression is null ? _candidateColumns[i].expr : new BinaryNode(_table, Operators.And, expr, _linearExpression)); } } else @@ -509,7 +509,7 @@ public DataRow[] SelectRows() bool needSorting = true; InitCandidateColumns(); - Debug.Assert(_candidateColumns != null); + Debug.Assert(_candidateColumns is not null); if (_expression is BinaryNode) { @@ -522,7 +522,7 @@ public DataRow[] SelectRows() { for (int i = 0; i < _candidateColumns.Length; i++) { - if (_candidateColumns[i] != null) + if (_candidateColumns[i] is not null) { _candidateColumns[i].equalsOperator = false; _candidateColumns[i].expr = null; @@ -539,12 +539,12 @@ public DataRow[] SelectRows() _linearExpression = _expression; } - if (_index == null && (_indexFields.Length > 0 || _linearExpression == _expression)) + if (_index is null && (_indexFields.Length > 0 || _linearExpression == _expression)) { needSorting = !FindSortIndex(); } - if (_index == null) + if (_index is null) { CreateIndex(); needSorting = false; @@ -600,7 +600,7 @@ private bool AcceptRecord(int record) { DataRow? row = _table._recordManager[record]; - if (row == null) + if (row is null) return true; DataRowVersion version = DataRowVersion.Default; @@ -708,11 +708,11 @@ private int Eval(BinaryNode expr, DataRow row, DataRowVersion version) private int Evaluate(int record) { - Debug.Assert(_index != null && _candidateColumns != null); + Debug.Assert(_index is not null && _candidateColumns is not null); DataRow? row = _table._recordManager[record]; - if (row == null) + if (row is null) return 0; DataRowVersion version = DataRowVersion.Default; @@ -733,8 +733,8 @@ private int Evaluate(int record) for (int i = 0; i < _matchedCandidates; i++) { var candidateColumn = _candidateColumns[fields[i].Column.Ordinal]; - Debug.Assert(candidateColumn != null, "How come this is not a candidate column"); - Debug.Assert(candidateColumn.expr != null, "How come there is no associated expression"); + Debug.Assert(candidateColumn is not null, "How come this is not a candidate column"); + Debug.Assert(candidateColumn.expr is not null, "How come there is no associated expression"); int c = Eval(candidateColumn.expr, row, version); if (c != 0) return fields[i].IsDescending ? -c : c; @@ -744,7 +744,7 @@ private int Evaluate(int record) private int FindFirstMatchingRecord() { - Debug.Assert(_index != null); + Debug.Assert(_index is not null); int rec = -1; int lo = 0; @@ -763,7 +763,7 @@ private int FindFirstMatchingRecord() private int FindLastMatchingRecord(int lo) { - Debug.Assert(_index != null); + Debug.Assert(_index is not null); int rec = -1; int hi = _index.RecordCount - 1; @@ -781,7 +781,7 @@ private int FindLastMatchingRecord(int lo) private Range GetBinaryFilteredRecords() { - Debug.Assert(_index != null); + Debug.Assert(_index is not null); if (_matchedCandidates == 0) { @@ -800,9 +800,9 @@ private Range GetBinaryFilteredRecords() private int[] GetLinearFilteredRecords(Range range) { - Debug.Assert(_index != null); + Debug.Assert(_index is not null); - if (_linearExpression == null) + if (_linearExpression is null) { int[] resultRecords = new int[range.Count]; RBTree.RBTreeEnumerator iterator = _index.GetEnumerator(range.Min); @@ -829,10 +829,10 @@ private int[] GetLinearFilteredRecords(Range range) private DataRow[] GetLinearFilteredRows(Range range) { - Debug.Assert(_index != null); + Debug.Assert(_index is not null); DataRow[] resultRows; - if (_linearExpression == null) + if (_linearExpression is null) { return _index.GetRows(range); } @@ -872,7 +872,7 @@ private int CompareRecords(int record1, int record2) int diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0); // if they're two records in the same row, we need to be able to distinguish them. - if (diff == 0 && record1 != record2 && row1 != null && row2 != null) + if (diff == 0 && record1 != record2 && row1 is not null && row2 is not null) { id1 = (int)row1.GetRecordState(record1); id2 = (int)row2.GetRecordState(record2); diff --git a/src/libraries/System.Data.Common/src/System/Data/Selection.cs b/src/libraries/System.Data.Common/src/System/Data/Selection.cs index c66dc5b648431e..99440e1715b425 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Selection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Selection.cs @@ -15,7 +15,7 @@ internal readonly struct IndexField internal IndexField(DataColumn column, bool isDescending) { - Debug.Assert(column != null, "null column"); + Debug.Assert(column is not null, "null column"); Column = column; IsDescending = isDescending; @@ -108,27 +108,27 @@ private static IndexField[] GetAllFields(DataColumnCollection columns) private Index(DataTable table, IndexField[] indexFields, System.Comparison? comparison, DataViewRowState recordStates, IFilter? rowFilter) { DataCommonEventSource.Log.Trace(" {0}, table={1}, recordStates={2}", - ObjectID, (table != null) ? table.ObjectID : 0, recordStates); - Debug.Assert(indexFields != null); - Debug.Assert(null != table, "null table"); + ObjectID, (table is not null) ? table.ObjectID : 0, recordStates); + Debug.Assert(indexFields is not null); + Debug.Assert(table is not null, "null table"); if ((recordStates & (~(DataViewRowState.CurrentRows | DataViewRowState.OriginalRows))) != 0) { throw ExceptionBuilder.RecordStateRange(); } _table = table; - _listeners = new Listeners(ObjectID, listener => null != listener); + _listeners = new Listeners(ObjectID, listener => listener is not null); _indexFields = indexFields; _recordStates = recordStates; _comparison = comparison; - _isSharable = (rowFilter == null) && (comparison == null); // a filter or comparison make an index unsharable - if (null != rowFilter) + _isSharable = (rowFilter is null) && (comparison is null); // a filter or comparison make an index unsharable + if (rowFilter is not null) { _rowFilter = new WeakReference(rowFilter); DataExpression? expr = (rowFilter as DataExpression); - if (null != expr) + if (expr is not null) { _hasRemoteAggregate = expr.HasRemoteAggregate(); } @@ -144,7 +144,7 @@ public bool Equal(IndexField[] indexDesc, DataViewRowState recordStates, IFilter if (!_isSharable || _indexFields.Length != indexDesc.Length || _recordStates != recordStates || - null != rowFilter) + rowFilter is not null) { return false; } @@ -186,14 +186,14 @@ public int GetRecord(int recordIndex) private bool AcceptRecord(int record, IFilter? filter) { DataCommonEventSource.Log.Trace(" {0}, record={1}", ObjectID, record); - if (filter == null) + if (filter is null) { return true; } DataRow? row = _table._recordManager[record]; - if (row == null) + if (row is null) { return true; } @@ -322,8 +322,8 @@ private int CompareRecords(int record1, int record2) { var (row1, row2) = (_table._recordManager[record1], _table._recordManager[record2]); - Debug.Assert(null != row1, "record1 no datarow"); - Debug.Assert(null != row2, "record2 no datarow"); + Debug.Assert(row1 is not null, "record1 no datarow"); + Debug.Assert(row2 is not null, "record2 no datarow"); // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -358,14 +358,14 @@ private int CompareDuplicateRecords(int record1, int record2) } #endif var (row1, row2) = (_table._recordManager[record1], _table._recordManager[record2]); - Debug.Assert(null != row1, "record1 no datarow"); - Debug.Assert(null != row2, "record2 no datarow"); + Debug.Assert(row1 is not null, "record1 no datarow"); + Debug.Assert(row2 is not null, "record2 no datarow"); - if (null == row1) + if (row1 is null) { - return ((null == row2) ? 0 : -1); + return ((row2 is null) ? 0 : -1); } - else if (null == row2) + else if (row2 is null) { return 1; } @@ -491,7 +491,7 @@ private int GetIndex(int record, int changeRecord) public object[] GetUniqueKeyValues() { - if (_indexFields == null || _indexFields.Length == 0) + if (_indexFields is null || _indexFields.Length == 0) { return Array.Empty(); } @@ -575,7 +575,7 @@ private int FindNodeByKey(object? originalKey) private int FindNodeByKeys(object?[]? originalKey) { int x, c; - c = ((null != originalKey) ? originalKey.Length : 0); + c = ((originalKey is not null) ? originalKey.Length : 0); if (originalKey is null || 0 == c || _indexFields.Length != c) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, c); @@ -1024,7 +1024,7 @@ private void GetUniqueKeyValues(List list, int curNodeId) internal static int IndexOfReference(List? list, T item) where T : class { - if (null != list) + if (list is not null) { for (int i = 0; i < list.Count; ++i) { @@ -1068,7 +1068,7 @@ internal Listeners(int ObjectID, Func notifyFilter) /// Only call from inside a lock internal void Add(TElem listener) { - Debug.Assert(null != listener, "null listener"); + Debug.Assert(listener is not null, "null listener"); Debug.Assert(!Index.ContainsReference(_listeners, listener), "already contains reference"); _listeners.Add(listener); } @@ -1081,7 +1081,7 @@ internal int IndexOfReference(TElem listener) /// Only call from inside a lock internal void Remove(TElem listener) { - Debug.Assert(null != listener, "null listener"); + Debug.Assert(listener is not null, "null listener"); int index = IndexOfReference(listener); Debug.Assert(0 <= index, "listeners don't contain listener"); @@ -1099,7 +1099,7 @@ internal void Remove(TElem listener) /// internal void Notify(T1 arg1, T2 arg2, T3 arg3, Action action) { - Debug.Assert(null != action, "no action"); + Debug.Assert(action is not null, "no action"); Debug.Assert(0 <= _listenerReaderCount, "negative _listEventCount"); int count = _listeners.Count; 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 63dbd993fea709..435206a30b05d6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs @@ -38,7 +38,7 @@ internal SimpleType(string baseType) internal SimpleType(XmlSchemaSimpleType node) { // named simpletype _name = node.Name; - _ns = (node.QualifiedName != null) ? node.QualifiedName.Namespace : ""; + _ns = (node.QualifiedName is not null) ? node.QualifiedName.Namespace : ""; LoadTypeValues(node); } @@ -58,7 +58,7 @@ internal void LoadTypeValues(XmlSchemaSimpleType node) XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction)node.Content; XmlSchemaSimpleType? ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType; - if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) + if ((ancestor is not null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) { _baseSimpleType = new SimpleType(ancestor); } @@ -71,7 +71,7 @@ internal void LoadTypeValues(XmlSchemaSimpleType node) _baseType = content.BaseTypeName.ToString(); - if (_baseSimpleType != null && _baseSimpleType.Name != null && _baseSimpleType.Name.Length > 0) + if (_baseSimpleType is not null && _baseSimpleType.Name is not null && _baseSimpleType.Name.Length > 0) { _xmlBaseType = _baseSimpleType.XmlBaseType; // SimpleTypeQualifiedName; } @@ -80,7 +80,7 @@ internal void LoadTypeValues(XmlSchemaSimpleType node) _xmlBaseType = content.BaseTypeName; } - if (_baseType == null || _baseType.Length == 0) + if (_baseType is null || _baseType.Length == 0) { _baseType = content.BaseType!.Name; _xmlBaseType = null; @@ -122,7 +122,7 @@ internal void LoadTypeValues(XmlSchemaSimpleType node) } string tempStr = XSDSchema.GetMsdataAttribute(node, Keywords.TARGETNAMESPACE); - if (tempStr != null) + if (tempStr is not null) _ns = tempStr; } @@ -231,7 +231,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 (_name is not null && _name.Length != 0) { // this is a global type typeNode.SetAttribute(Keywords.NAME, _name); @@ -244,12 +244,12 @@ internal XmlNode ToNode(XmlDocument dc, Hashtable prefixes, bool inRemoting) if (!inRemoting) { - if (_baseSimpleType != null) + if (_baseSimpleType is not null) { - if (_baseSimpleType.Namespace != null && _baseSimpleType.Namespace.Length > 0) + if (_baseSimpleType.Namespace is not null && _baseSimpleType.Namespace.Length > 0) { - string? prefix = (prefixes != null) ? (string?)prefixes[_baseSimpleType.Namespace] : null; - if (prefix != null) + string? prefix = (prefixes is not null) ? (string?)prefixes[_baseSimpleType.Namespace] : null; + if (prefix is not null) { type.SetAttribute(Keywords.BASE, (prefix + ":" + _baseSimpleType.Name)); } @@ -270,7 +270,7 @@ internal XmlNode ToNode(XmlDocument dc, Hashtable prefixes, bool inRemoting) } else { - type.SetAttribute(Keywords.BASE, (_baseSimpleType != null) ? _baseSimpleType.Name : QualifiedName(_baseType!)); + type.SetAttribute(Keywords.BASE, (_baseSimpleType is not null) ? _baseSimpleType.Name : QualifiedName(_baseType!)); } XmlElement constraint; @@ -324,14 +324,14 @@ internal static SimpleType CreateLimitedStringType(int length) // if existing simpletype is being redefined with different facets, then it will return no-empty string defining the error internal string HasConflictingDefinition(SimpleType otherSimpleType) { - if (otherSimpleType == null) + if (otherSimpleType is null) return nameof(otherSimpleType); if (MaxLength != otherSimpleType.MaxLength) return ("MaxLength"); if (!string.Equals(BaseType, otherSimpleType.BaseType, StringComparison.Ordinal)) return ("BaseType"); - if ((BaseSimpleType != null && otherSimpleType.BaseSimpleType != null) && + if ((BaseSimpleType is not null && otherSimpleType.BaseSimpleType is not null) && (BaseSimpleType.HasConflictingDefinition(otherSimpleType.BaseSimpleType)).Length != 0) return ("BaseSimpleType"); return string.Empty; @@ -341,7 +341,7 @@ internal string HasConflictingDefinition(SimpleType otherSimpleType) internal bool CanHaveMaxLength() { SimpleType rootType = this; - while (rootType.BaseSimpleType != null) + while (rootType.BaseSimpleType is not null) { rootType = rootType.BaseSimpleType; } @@ -355,7 +355,7 @@ internal void ConvertToAnnonymousSimpleType() _ns = string.Empty; SimpleType tmpSimpleType = this; - while (tmpSimpleType._baseSimpleType != null) + while (tmpSimpleType._baseSimpleType is not null) { tmpSimpleType = tmpSimpleType._baseSimpleType; } diff --git a/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs index c5304d94ef346a..1ad94bfb66f5d9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs @@ -49,8 +49,8 @@ internal class SortExpressionBuilder : IComparer> /// internal void Add(Func keySelector, Comparison compare, bool isOrderBy) { - Debug.Assert(keySelector != null); - Debug.Assert(compare != null); + Debug.Assert(keySelector is not null); + Debug.Assert(compare is not null); // Inputs are assumed to be valid. The burden for ensuring it is on the caller. if (isOrderBy) @@ -61,8 +61,8 @@ internal void Add(Func keySelector, Comparison compare, bool else { // ThenBy can only be called after OrderBy - Debug.Assert(_currentSelector != null); - Debug.Assert(_currentComparer != null); + Debug.Assert(_currentSelector is not null); + Debug.Assert(_currentComparer is not null); _currentSelector = _selectors.AddAfter(_currentSelector, keySelector); _currentComparer = _comparers.AddAfter(_currentComparer, compare); @@ -94,7 +94,7 @@ public List Select(T row) /// Comparison result of the combined Sort comparer expression public int Compare(List? a, List? b) { - Debug.Assert(a != null && b != null && a.Count == Count); + Debug.Assert(a is not null && b is not null && a.Count == Count); int i = 0; foreach (Comparison compare in _comparers) diff --git a/src/libraries/System.Data.Common/src/System/Data/TypeLimiter.cs b/src/libraries/System.Data.Common/src/System/Data/TypeLimiter.cs index 59258ead096adf..6ecb8a16b51181 100644 --- a/src/libraries/System.Data.Common/src/System/Data/TypeLimiter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/TypeLimiter.cs @@ -22,7 +22,7 @@ internal sealed class TypeLimiter private TypeLimiter(Scope scope) { - Debug.Assert(scope != null); + Debug.Assert(scope is not null); m_instanceScope = scope; } @@ -40,7 +40,7 @@ private static bool IsTypeLimitingDisabled public static TypeLimiter? Capture() { Scope? activeScope = s_activeScope; - return (activeScope != null) ? new TypeLimiter(activeScope) : null; + return (activeScope is not null) ? new TypeLimiter(activeScope) : null; } /// @@ -106,7 +106,7 @@ public static void EnsureTypeIsAllowed(Type? type, TypeLimiter? capturedLimiter /// private static IEnumerable GetPreviouslyDeclaredDataTypes(DataTable dataTable) { - return (dataTable != null) + return (dataTable is not null) ? dataTable.Columns.Cast().Select(column => column.DataType) : Enumerable.Empty(); } @@ -117,7 +117,7 @@ private static IEnumerable GetPreviouslyDeclaredDataTypes(DataTable dataTa /// private static IEnumerable GetPreviouslyDeclaredDataTypes(DataSet dataSet) { - return (dataSet != null) + return (dataSet is not null) ? dataSet.Tables.Cast().SelectMany(table => GetPreviouslyDeclaredDataTypes(table)) : Enumerable.Empty(); } @@ -197,10 +197,10 @@ private sealed class Scope : IDisposable internal Scope(Scope? previousScope, IEnumerable allowedTypes) { - Debug.Assert(allowedTypes != null); + Debug.Assert(allowedTypes is not null); m_previousScope = previousScope; - m_allowedTypes = new HashSet(allowedTypes.Where(type => type != null)); + m_allowedTypes = new HashSet(allowedTypes.Where(type => type is not null)); m_deserializationToken = SerializationInfo.StartDeserialization(); } @@ -220,7 +220,7 @@ public void Dispose() public bool IsAllowedType(Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); // Is the incoming type unconditionally allowed? @@ -232,7 +232,7 @@ public bool IsAllowedType(Type type) // The incoming type is allowed if the current scope or any nested inner // scope allowed it. - for (Scope? currentScope = this; currentScope != null; currentScope = currentScope.m_previousScope) + for (Scope? currentScope = this; currentScope is not null; currentScope = currentScope.m_previousScope) { if (currentScope.m_allowedTypes.Contains(type)) { @@ -243,7 +243,7 @@ public bool IsAllowedType(Type type) // Did the application programmatically allow this type to be deserialized? Type[]? appDomainAllowedTypes = (Type[]?)AppDomain.CurrentDomain.GetData(AppDomainDataSetDefaultAllowedTypesKey); - if (appDomainAllowedTypes != null) + if (appDomainAllowedTypes is not null) { for (int i = 0; i < appDomainAllowedTypes.Length; i++) { @@ -262,7 +262,7 @@ public bool IsAllowedType(Type type) private static bool IsTypeUnconditionallyAllowed(Type type) { TryAgain: - Debug.Assert(type != null); + Debug.Assert(type is not null); // Check the list of unconditionally allowed types. diff --git a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs index 83c7e705f2a889..8d71d784266258 100644 --- a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs @@ -363,7 +363,7 @@ public bool IsPrimaryKey { get { - if (Table == null) + if (Table is null) { return false; } 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 7885dc7f66e75d..109e2241face84 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -29,7 +29,7 @@ internal XDRSchema(DataSet ds, bool fInline) internal void LoadSchema(XmlElement schemaRoot, DataSet ds) { - if (schemaRoot == null) + if (schemaRoot is null) return; _schemaRoot = schemaRoot; @@ -42,13 +42,13 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) // Get Locale and CaseSensitive properties - if (_schemaName == null || _schemaName.Length == 0) + if (_schemaName is null || _schemaName.Length == 0) _schemaName = "NewDataSet"; ds.Namespace = _schemaUri; // Walk all the top level Element tags. - for (XmlNode n = schemaRoot.FirstChild; n != null; n = n.NextSibling) + for (XmlNode n = schemaRoot.FirstChild; n is not null; n = n.NextSibling) { if (!(n is XmlElement)) continue; @@ -62,7 +62,7 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) } _schemaName = XmlConvert.DecodeName(_schemaName); - if (ds.Tables[_schemaName] == null) + if (ds.Tables[_schemaName] is null) ds.DataSetName = _schemaName; } @@ -86,7 +86,7 @@ internal XmlElement FindTypeNode(XmlElement node) if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) { - if (strType == null || strType.Length == 0) + if (strType is null || strType.Length == 0) return null; // Find an ELEMENTTYPE or ATTRIBUTETYPE with name=strType @@ -105,16 +105,16 @@ internal XmlElement FindTypeNode(XmlElement node) } // Move vn node - if (vn.FirstChild != null) + if (vn.FirstChild is not null) vn = vn.FirstChild; - else if (vn.NextSibling != null) + else if (vn.NextSibling is not null) vn = vn.NextSibling; else { while (vn != vnRoof) { vn = vn.ParentNode; - if (vn.NextSibling != null) + if (vn.NextSibling is not null) { vn = vn.NextSibling; break; @@ -134,7 +134,7 @@ internal 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 (value is null || value.Length == 0) { string type = node.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); return !string.IsNullOrEmpty(type); @@ -160,7 +160,7 @@ internal bool IsXDRField(XmlElement node, XmlElement typeNode) if (!IsTextOnlyContent(typeNode)) return false; - for (XmlNode n = typeNode.FirstChild; n != null; n = n.NextSibling) + for (XmlNode n = typeNode.FirstChild; n is not null; n = n.NextSibling) { if (FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(n, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) @@ -190,22 +190,22 @@ internal DataTable HandleTable(XmlElement node) string occurs = node.GetAttribute(Keywords.MINOCCURS); - if (occurs != null && occurs.Length > 0) - if ((Convert.ToInt32(occurs, CultureInfo.InvariantCulture) > 1) && (typeNode == null)) + if (occurs is not null && occurs.Length > 0) + if ((Convert.ToInt32(occurs, CultureInfo.InvariantCulture) > 1) && (typeNode is null)) { return InstantiateSimpleTable(_ds, node); } occurs = node.GetAttribute(Keywords.MAXOCCURS); - if (occurs != null && occurs.Length > 0) - if (!string.Equals(occurs, "1", StringComparison.Ordinal) && (typeNode == null)) + if (occurs is not null && occurs.Length > 0) + if (!string.Equals(occurs, "1", StringComparison.Ordinal) && (typeNode is null)) { return InstantiateSimpleTable(_ds, node); } - if (typeNode == null) + if (typeNode is null) return null; if (IsXDRField(node, typeNode)) @@ -308,7 +308,7 @@ private Type ParseDataType(string dt, string dtValues) } NameType nt = FindNameType(strType); - if (nt == s_enumerationNameType && (dtValues == null || dtValues.Length == 0)) + if (nt == s_enumerationNameType && (dtValues is null || dtValues.Length == 0)) throw ExceptionBuilder.MissingAttribute("type", Keywords.DT_VALUES); return nt.type; } @@ -321,7 +321,7 @@ internal string GetInstanceName(XmlElement node) FEqualIdentity(node, Keywords.XDR_ATTRIBUTETYPE, Keywords.XDRNS)) { instanceName = node.GetAttribute(Keywords.NAME); - if (instanceName == null || instanceName.Length == 0) + if (instanceName is null || instanceName.Length == 0) { throw ExceptionBuilder.MissingAttribute("Element", Keywords.NAME); } @@ -329,7 +329,7 @@ internal string GetInstanceName(XmlElement node) else { instanceName = node.GetAttribute(Keywords.TYPE); - if (instanceName == null || instanceName.Length == 0) + if (instanceName is null || instanceName.Length == 0) throw ExceptionBuilder.MissingAttribute("Element", Keywords.TYPE); } @@ -356,12 +356,12 @@ internal void HandleColumn(XmlElement node, DataTable table) { string strRef = node.GetAttribute(Keywords.REF); - if (strRef != null && strRef.Length > 0) + if (strRef is not null && strRef.Length > 0) return; //skip ref nodes. B2 item strName = instanceName = GetInstanceName(node); column = table.Columns[instanceName, _schemaUri]; - if (column != null) + if (column is not null) { if (column.ColumnMapping == MappingType.Attribute) { @@ -388,7 +388,7 @@ internal void HandleColumn(XmlElement node, DataTable table) SimpleType xsdType = null; - if (typeNode == null) + if (typeNode is null) { strType = node.GetAttribute(Keywords.TYPE); throw ExceptionBuilder.UndefinedDatatype(strType); @@ -396,7 +396,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 (strType is null || strType.Length == 0) { strType = string.Empty; type = typeof(string); @@ -458,7 +458,7 @@ internal void HandleColumn(XmlElement node, DataTable table) column.Namespace = (isAttribute) ? string.Empty : _schemaUri; // We will skip handling expression columns in SetProperties, so we need set the expressions here - if (node.Attributes != null) + if (node.Attributes is not null) { for (int i = 0; i < node.Attributes.Count; i++) { @@ -474,11 +474,11 @@ internal void HandleColumn(XmlElement node, DataTable table) } string targetNamespace = node.GetAttribute(Keywords.TARGETNAMESPACE); - if (targetNamespace != null && targetNamespace.Length > 0) + if (targetNamespace is not null && targetNamespace.Length > 0) column.Namespace = targetNamespace; table.Columns.Add(column); - if (strDefault != null && strDefault.Length != 0) + if (strDefault is not null && strDefault.Length != 0) try { column.DefaultValue = SqlConvert.ChangeTypeForXML(strDefault, type); @@ -497,7 +497,7 @@ internal void GetMinMax(XmlElement elNode, ref int minOccurs, ref int maxOccurs) internal void GetMinMax(XmlElement elNode, bool isAttribute, ref int minOccurs, ref int maxOccurs) { string occurs = elNode.GetAttribute(Keywords.MINOCCURS); - if (occurs != null && occurs.Length > 0) + if (occurs is not null && occurs.Length > 0) { try { @@ -510,7 +510,7 @@ internal void GetMinMax(XmlElement elNode, bool isAttribute, ref int minOccurs, } occurs = elNode.GetAttribute(Keywords.MAXOCCURS); - if (occurs != null && occurs.Length > 0) + if (occurs is not null && occurs.Length > 0) { int bZeroOrMore = string.Compare(occurs, Keywords.STAR, StringComparison.Ordinal); if (bZeroOrMore == 0) @@ -540,7 +540,7 @@ internal void HandleTypeNode(XmlElement typeNode, DataTable table, ArrayList tab { DataTable tableChild; - for (XmlNode n = typeNode.FirstChild; n != null; n = n.NextSibling) + for (XmlNode n = typeNode.FirstChild; n is not null; n = n.NextSibling) { if (!(n is XmlElement)) continue; @@ -548,7 +548,7 @@ internal void HandleTypeNode(XmlElement typeNode, DataTable table, ArrayList tab if (FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { tableChild = HandleTable((XmlElement)n); - if (tableChild != null) + if (tableChild is not null) { tableChildren.Add(tableChild); continue; @@ -580,7 +580,7 @@ internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement { typeName = GetInstanceName(node); table = dataSet.Tables.GetTable(typeName, _schemaUri); - if (table != null) + if (table is not null) { return table; } @@ -603,7 +603,7 @@ internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement // check to see if we fave unique constraint - if (keys != null) + if (keys is not null) { string[] list = keys.TrimEnd(null).Split(null); int keyLength = list.Length; @@ -613,7 +613,7 @@ internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement for (int i = 0; i < keyLength; i++) { DataColumn col = table.Columns[list[i], _schemaUri]; - if (col == null) + if (col is null) throw ExceptionBuilder.ElementTypeNotFound(list[i]); cols[i] = col; } @@ -636,7 +636,7 @@ internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement relation = childRelations[j]; } - if (relation != null) + if (relation is not null) continue; DataColumn parentKey = table.AddUniqueKey(); @@ -666,7 +666,7 @@ internal DataTable InstantiateSimpleTable(DataSet dataSet, XmlElement node) typeName = GetInstanceName(node); table = dataSet.Tables.GetTable(typeName, _schemaUri); - if (table != null) + if (table is not null) { throw ExceptionBuilder.DuplicateDeclaration(typeName); } diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs index 39e1eed9057d7e..56ac026ee8f467 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs @@ -97,11 +97,11 @@ internal void ProcessDiffs(DataSet ds, XmlReader ssync) if (oldRowRecord == -1) continue; - if (tableBefore == null) + if (tableBefore is null) throw ExceptionBuilder.DiffgramMissingSQL(); row = (DataRow)tableBefore.RowDiffId[diffId]; - if (row != null) + if (row is not null) { row._oldRecord = oldRowRecord; tableBefore._recordManager[oldRowRecord] = row; @@ -148,12 +148,12 @@ internal void ProcessDiffs(ArrayList tableList, XmlReader ssync) if (oldRowRecord == -1) continue; - if (tableBefore == null) + if (tableBefore is null) throw ExceptionBuilder.DiffgramMissingSQL(); row = (DataRow)tableBefore.RowDiffId[diffId]; - if (row != null) + if (row is not null) { row._oldRecord = oldRowRecord; tableBefore._recordManager[oldRowRecord] = row; @@ -185,12 +185,12 @@ internal void ProcessErrors(DataSet ds, XmlReader ssync) while (iSsyncDepth < ssync.Depth) { table = ds.Tables.GetTable(XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI); - if (table == null) + if (table is null) throw ExceptionBuilder.DiffgramMissingSQL(); string diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); DataRow row = (DataRow)table.RowDiffId[diffId]; string rowError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); - if (rowError != null) + if (rowError is not null) row.RowError = rowError; int iRowDepth = ssync.Depth; ssync.Read(); // we may be inside a column @@ -199,7 +199,7 @@ internal void ProcessErrors(DataSet ds, XmlReader ssync) if (XmlNodeType.Element == ssync.NodeType) { DataColumn col = table.Columns[XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI]; - //if (col == null) + //if (col is null) // throw exception here string colError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); row.SetColumnError(col, colError); @@ -224,18 +224,18 @@ internal void ProcessErrors(ArrayList dt, XmlReader ssync) while (iSsyncDepth < ssync.Depth) { table = GetTable(XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI); - if (table == null) + if (table is null) throw ExceptionBuilder.DiffgramMissingSQL(); string diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); DataRow row = (DataRow)table.RowDiffId[diffId]; - if (row == null) + if (row is null) { for (int i = 0; i < dt.Count; i++) { row = (DataRow)((DataTable)dt[i]).RowDiffId[diffId]; - if (row != null) + if (row is not null) { table = row.Table; break; @@ -243,7 +243,7 @@ internal void ProcessErrors(ArrayList dt, XmlReader ssync) } } string rowError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); - if (rowError != null) + if (rowError is not null) row.RowError = rowError; int iRowDepth = ssync.Depth; ssync.Read(); // we may be inside a column @@ -253,7 +253,7 @@ internal void ProcessErrors(ArrayList dt, XmlReader ssync) if (XmlNodeType.Element == ssync.NodeType) { DataColumn col = table.Columns[XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI]; - //if (col == null) + //if (col is null) // throw exception here string colError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); row.SetColumnError(col, colError); @@ -268,7 +268,7 @@ internal void ProcessErrors(ArrayList dt, XmlReader ssync) } private DataTable GetTable(string tableName, string ns) { - if (_tables == null) + if (_tables is null) return _dataSet.Tables.GetTable(tableName, ns); if (_tables.Count == 0) @@ -287,7 +287,7 @@ private DataTable GetTable(string tableName, string ns) private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlReader row) { // read table information - if (ds != null) + if (ds is not null) { table = ds.Tables.GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } @@ -296,7 +296,7 @@ private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlRead table = GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } - if (table == null) + if (table is null) { row.Skip(); // need to skip this element if we dont know about it, before returning -1 return -1; @@ -332,7 +332,7 @@ private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlRead value = row.GetAttribute(col.EncodedColumnName, col.Namespace); } - if (value == null) + if (value is null) { continue; } @@ -357,7 +357,7 @@ private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlRead return record; } - if (table.XmlText != null) + if (table.XmlText is not null) { DataColumn col = table.XmlText; col[record] = col.ConvertXmlToObject(row.ReadString()); @@ -370,7 +370,7 @@ private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlRead string ns = row.NamespaceURI; DataColumn column = table.Columns[ln, ns]; - if (column == null) + if (column is null) { while ((row.NodeType != XmlNodeType.EndElement) && (row.LocalName != ln) && (row.NamespaceURI != ns)) row.Read(); // consume the current node @@ -382,11 +382,11 @@ private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlRead if (column.IsCustomType) { // if column's type is object or column type does not implement IXmlSerializable - bool isPolymorphism = (column.DataType == typeof(object) || (row.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS) != null) || - (row.GetAttribute(Keywords.TYPE, Keywords.XSINS) != null)); + bool isPolymorphism = (column.DataType == typeof(object) || (row.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS) is not null) || + (row.GetAttribute(Keywords.TYPE, Keywords.XSINS) is not null)); bool skipped = false; - if (column.Table.DataSet != null && column.Table.DataSet._udtIsWrapped) + if (column.Table.DataSet is not null && column.Table.DataSet._udtIsWrapped) { row.Read(); // if UDT is wrapped, skip the wrapper skipped = true; 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 634b96e20bc811..aebb9a7a28948c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -40,7 +40,7 @@ internal static void SetProperties(object instance, XmlAttributeCollection attrs continue; PropertyDescriptor pd = TypeDescriptor.GetProperties(instance)[name]; - if (pd != null) + if (pd is not null) { // Standard property Type type = pd.PropertyType; @@ -71,7 +71,7 @@ internal static void SetProperties(object instance, XmlAttributeCollection attrs internal static bool FEqualIdentity(XmlNode node, string name, string ns) { - if (node != null && node.LocalName == name && node.NamespaceURI == ns) + if (node is not null && node.LocalName == name && node.NamespaceURI == ns) return true; return false; @@ -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 (value is null || value.Length == 0) { return defVal; } @@ -216,9 +216,9 @@ private void CollectElementsAnnotations(XmlSchema schema, ArrayList schemaList) // if we have a User Defined simple type, cache it so later we may need for mapping // meanwhile more convinient solution would be to directly use schemaTypes, but it would be more complex to handle XmlSchemaSimpleType xmlSimpleType = (item as XmlSchemaSimpleType); - if (xmlSimpleType != null) + if (xmlSimpleType is not null) { - if (_udSimpleTypes == null) + if (_udSimpleTypes is null) { _udSimpleTypes = new Hashtable(); } @@ -226,9 +226,9 @@ private void CollectElementsAnnotations(XmlSchema schema, ArrayList schemaList) _udSimpleTypes[type.QualifiedName.ToString()] = xmlSimpleType; DataColumn dc = (DataColumn)_existingSimpleTypeMap[type.QualifiedName.ToString()]; // Assumption is that our simple type qualified name ihas the same output as XmlSchemaSimpleType type.QualifiedName.ToString() - SimpleType tmpSimpleType = (dc != null) ? dc.SimpleType : null; + SimpleType tmpSimpleType = (dc is not null) ? dc.SimpleType : null; - if (tmpSimpleType != null) + if (tmpSimpleType is not null) { SimpleType tmpDataSimpleType = new SimpleType(xmlSimpleType); string errorStr = tmpSimpleType.HasConflictingDefinition(tmpDataSimpleType); @@ -244,7 +244,7 @@ private void CollectElementsAnnotations(XmlSchema schema, ArrayList schemaList) { if (include is XmlSchemaImport) continue; - if (include.Schema != null) + if (include.Schema is not null) { CollectElementsAnnotations(include.Schema, schemaList); } @@ -263,7 +263,7 @@ internal static void SetProperties(object instance, XmlAttribute[] attrs) { // This is called from both XSD and XDR schemas. // Do we realy need it in XSD ??? - if (attrs == null) + if (attrs is null) return; for (int i = 0; i < attrs.Length; i++) { @@ -281,7 +281,7 @@ internal static void SetProperties(object instance, XmlAttribute[] attrs) if (name == "DataType") { DataColumn col = instance as DataColumn; - if (col != null) + if (col is not null) { col.DataType = DataStorage.GetType(value); } @@ -290,7 +290,7 @@ internal static void SetProperties(object instance, XmlAttribute[] attrs) } PropertyDescriptor pd = TypeDescriptor.GetProperties(instance)[name]; - if (pd != null) + if (pd is not null) { // Standard property Type type = pd.PropertyType; @@ -322,13 +322,13 @@ internal static void SetProperties(object instance, XmlAttribute[] attrs) private static void SetExtProperties(object instance, XmlAttribute[] attrs) { PropertyCollection props = null; - if (attrs == null) + if (attrs is null) return; for (int i = 0; i < attrs.Length; i++) { if (attrs[i].NamespaceURI == Keywords.MSPROPNS) { - if (props == null) + if (props is null) { object val = TypeDescriptor.GetProperties(instance)["ExtendedProperties"].GetValue(instance); Debug.Assert(val is PropertyCollection, "We can set values only for classes that have ExtendedProperties"); @@ -359,11 +359,11 @@ private static void SetExtProperties(object instance, XmlAttribute[] attrs) private void HandleColumnExpression(object instance, XmlAttribute[] attrs) { - if (attrs == null) + if (attrs is null) return; DataColumn dc = instance as DataColumn; - Debug.Assert(dc != null, "HandleColumnExpression is supposed to be called for DataColumn"); - if (dc != null) + Debug.Assert(dc is not null, "HandleColumnExpression is supposed to be called for DataColumn"); + if (dc is not null) { for (int i = 0; i < attrs.Length; i++) { @@ -371,7 +371,7 @@ private void HandleColumnExpression(object instance, XmlAttribute[] attrs) { if (attrs[i].LocalName == "Expression") { - if (_expressions == null) + if (_expressions is null) _expressions = new Hashtable(); _expressions[dc] = attrs[i].Value; _columnExpressions.Add(dc); @@ -385,7 +385,7 @@ private void HandleColumnExpression(object instance, XmlAttribute[] attrs) internal static string GetMsdataAttribute(XmlSchemaAnnotated node, string ln) { XmlAttribute[] nodeAttributes = node.UnhandledAttributes; - if (nodeAttributes != null) + if (nodeAttributes is not null) for (int i = 0; i < nodeAttributes.Length; i++) if (nodeAttributes[i].LocalName == ln && nodeAttributes[i].NamespaceURI == Keywords.MSDNS) return nodeAttributes[i].Value; @@ -399,7 +399,7 @@ private static void SetExtProperties(object instance, XmlAttributeCollection att { if (attrs[i].NamespaceURI == Keywords.MSPROPNS) { - if (props == null) + if (props is null) { object val = TypeDescriptor.GetProperties(instance)["ExtendedProperties"].GetValue(instance); Debug.Assert(val is PropertyCollection, "We can set values only for classes that have ExtendedProperties"); @@ -415,7 +415,7 @@ internal void HandleRefTableProperties(ArrayList RefTables, XmlSchemaElement ele { string typeName = GetInstanceName(element); DataTable table = _ds.Tables.GetTable(XmlConvert.DecodeName(typeName), element.QualifiedName.Namespace); - Debug.Assert(table != null, "ref table should have been already created"); + Debug.Assert(table is not null, "ref table should have been already created"); SetProperties(table, element.UnhandledAttributes); SetExtProperties(table, element.UnhandledAttributes); @@ -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 (parentName is null || parentName.Length == 0) throw ExceptionBuilder.RelationParentNameMissing(strName); parentName = XmlConvert.DecodeName(parentName); childName = node.GetAttribute(Keywords.MSD_CHILD, Keywords.MSDNS); - if (childName == null || childName.Length == 0) + if (childName is null || childName.Length == 0) throw ExceptionBuilder.RelationChildNameMissing(strName); childName = XmlConvert.DecodeName(childName); value = node.GetAttribute(Keywords.MSD_PARENTKEY, Keywords.MSDNS); - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) 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 (value is null || value.Length == 0) throw ExceptionBuilder.RelationChildKeyMissing(strName); childNames = value.TrimEnd(null).Split(new char[] { Keywords.MSD_KEYFIELDSEP, Keywords.MSD_KEYFIELDOLDSEP }); @@ -479,21 +479,21 @@ internal void HandleRelation(XmlElement node, bool fNested) parent = _ds.Tables.GetTableSmart(parentName, parentNs); - if (parent == null) + if (parent is null) throw ExceptionBuilder.ElementTypeNotFound(parentName); child = _ds.Tables.GetTableSmart(childName, childNs); - if (child == null) + if (child is null) throw ExceptionBuilder.ElementTypeNotFound(childName); for (int i = 0; i < keyLength; i++) { parentKey[i] = parent.Columns[XmlConvert.DecodeName(parentNames[i])]; - if (parentKey[i] == null) + if (parentKey[i] is null) throw ExceptionBuilder.ElementTypeNotFound(parentNames[i]); childKey[i] = child.Columns[XmlConvert.DecodeName(childNames[i])]; - if (childKey[i] == null) + if (childKey[i] is null) throw ExceptionBuilder.ElementTypeNotFound(childNames[i]); } relation = new DataRelation(strName, parentKey, childKey, fCreateConstraints); @@ -530,7 +530,7 @@ private bool IsDatasetParticle(XmlSchemaParticle pt) { XmlSchemaObjectCollection items = GetParticleItems(pt); - if (items == null) + if (items is null) return false; // empty element, threat it as table bool isChoice = FromInference && (pt is XmlSchemaChoice); // currently we add this support for choice, just for inference @@ -594,10 +594,10 @@ private XmlSchemaElement FindDatasetElement(XmlSchemaObjectCollection elements) return null; XmlSchemaComplexType ct = node.SchemaType as XmlSchemaComplexType; - if (ct == null) + if (ct is null) return null; - while (ct != null) + while (ct is not null) { if (HasAttributes(ct.Attributes)) return null; @@ -621,7 +621,7 @@ private XmlSchemaElement FindDatasetElement(XmlSchemaObjectCollection elements) XmlSchemaParticle particle = GetParticle(ct); - if (particle != null) + if (particle is not null) { if (!IsDatasetParticle(particle)) return null; // it's a table @@ -642,7 +642,7 @@ private XmlSchemaElement FindDatasetElement(XmlSchemaObjectCollection elements) public void LoadSchema(XmlSchemaSet schemaSet, DataTable dt) { - if (dt.DataSet != null) + if (dt.DataSet is not null) LoadSchema(schemaSet, dt.DataSet); } public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) @@ -654,7 +654,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) bool setRootNStoDataSet = false; bool newDataSet = (ds.Tables.Count == 0); - if (schemaSet == null) + if (schemaSet is null) return; _schemaSet = schemaSet; _ds = ds; @@ -664,15 +664,15 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) { _schemaName = schemaRoot.Id; - if (_schemaName == null || _schemaName.Length == 0) + if (_schemaName is null || _schemaName.Length == 0) { _schemaName = "NewDataSet"; } ds.DataSetName = XmlConvert.DecodeName(_schemaName); string ns = schemaRoot.TargetNamespace; - if (ds._namespaceURI == null || ds._namespaceURI.Length == 0) + if (ds._namespaceURI is null || ds._namespaceURI.Length == 0) {// set just one time, for backward compatibility - ds._namespaceURI = (ns == null) ? string.Empty : ns; // see fx\Data\XDO\ReadXml\SchemaM2.xml for more info + ds._namespaceURI = (ns is null) ? string.Empty : ns; // see fx\Data\XDO\ReadXml\SchemaM2.xml for more info } break; // we just need to take Name and NS from first schema [V1.0 & v1.1 semantics] } @@ -690,7 +690,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) { foreach (DataColumn dc in dt.Columns) { - if (dc.SimpleType != null && dc.SimpleType.Name != null && dc.SimpleType.Name.Length != 0) + if (dc.SimpleType is not null && dc.SimpleType.Name is not null && dc.SimpleType.Name.Length != 0) { _existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName!] = dc; // existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName] = dc.SimpleType; @@ -706,10 +706,10 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) _dsElement = FindDatasetElement(_elements); - if (_dsElement != null) + if (_dsElement is not null) { string mainName = GetStringAttribute(_dsElement, Keywords.MSD_MAINDATATABLE, ""); - if (null != mainName) + if (mainName is not null) { ds.MainTableName = XmlConvert.DecodeName(mainName); } @@ -728,7 +728,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) List qnames = new List(); - if (ds != null && ds._useDataSetSchemaOnly) + if (ds is not null && ds._useDataSetSchemaOnly) { int dataSetElementCount = DatasetElementCount(_elements); if (dataSetElementCount == 0) @@ -741,15 +741,15 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) } XmlSchemaComplexType ct = (XmlSchemaComplexType)FindTypeNode(_dsElement); - if (ct.Particle != null) + if (ct.Particle is not null) { XmlSchemaObjectCollection items = GetParticleItems(ct.Particle); - if (items != null) + if (items is not null) { foreach (XmlSchemaAnnotated el in items) { XmlSchemaElement sel = el as XmlSchemaElement; - if (null != sel) + if (sel is not null) { if (sel.RefName.Name.Length != 0) { @@ -766,7 +766,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) { if (element == _dsElement) continue; - if (ds != null && ds._useDataSetSchemaOnly && _dsElement != null) + if (ds is not null && ds._useDataSetSchemaOnly && _dsElement is not null) { if (_dsElement.Parent != element.Parent) { @@ -788,7 +788,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) } - if (_dsElement != null) + if (_dsElement is not null) HandleDataSet(_dsElement, newDataSet); foreach (XmlSchemaAnnotation annotation in _annotations) @@ -822,7 +822,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) } DataTable tmpTable = ds.Tables[ds.DataSetName, ds.Namespace]; - if (tmpTable != null) // this fix is done to support round-trip problem in case if there is one table with same name and NS + if (tmpTable is not null) // this fix is done to support round-trip problem in case if there is one table with same name and NS tmpTable._fNestedInDataset = true; @@ -892,13 +892,13 @@ internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList ta { XmlSchemaObjectCollection items = GetParticleItems(pt); - if (items == null) + if (items is null) return; foreach (XmlSchemaAnnotated item in items) { XmlSchemaElement el = item as XmlSchemaElement; - if (el != null) + if (el is not null) { if (FromInference && pt is XmlSchemaChoice && pt.MaxOccurs > decimal.One && (el.SchemaType is XmlSchemaComplexType)) el.MaxOccurs = pt.MaxOccurs; @@ -907,7 +907,7 @@ internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList ta DataTable child = null; // to decide if element is our table, we need to match both name and ns // 286043 - SQL BU Defect Tracking - if (((el.Name == null) && (el.RefName.Name == table.EncodedTableName && el.RefName.Namespace == table.Namespace)) || + if (((el.Name is null) && (el.RefName.Name == table.EncodedTableName && el.RefName.Namespace == table.Namespace)) || (IsTable(el) && el.Name == table.TableName)) { if (FromInference) @@ -923,13 +923,13 @@ internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList ta else { child = HandleTable(el); - if (child == null && FromInference && el.Name == table.TableName) + if (child is null && FromInference && el.Name == table.TableName) { child = table; } } - if (child == null) + if (child is null) { if (!FromInference || el.Name != table.TableName) {// check is required to support 1.1 inference behavior @@ -939,7 +939,7 @@ internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList ta else { DataRelation relation = null; - if (el.Annotation != null) + if (el.Annotation is not null) HandleRelations(el.Annotation, true); DataRelationCollection childRelations = table.ChildRelations; @@ -952,7 +952,7 @@ internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList ta relation = childRelations[j]; } - if (relation == null) + if (relation is null) { tableChildren.Add(child); // how about prefix for this? if (FromInference && table.UKColumnPositionForInference == -1) @@ -988,7 +988,7 @@ internal void HandleAttributes(XmlSchemaObjectCollection attributes, DataTable t { // XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef groupRef = so as XmlSchemaAttributeGroupRef; XmlSchemaAttributeGroup schemaGroup = _attributeGroups[groupRef.RefName] as XmlSchemaAttributeGroup; - if (schemaGroup != null) + if (schemaGroup is not null) { HandleAttributeGroup(schemaGroup, table, isBase); } @@ -1008,7 +1008,7 @@ private void HandleAttributeGroup(XmlSchemaAttributeGroup attributeGroup, DataTa { // XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)obj; XmlSchemaAttributeGroup attributeGroupResolved; - if (attributeGroup.RedefinedAttributeGroup != null && attributeGroupRef.RefName == new XmlQualifiedName(attributeGroup.Name, attributeGroupRef.RefName.Namespace)) + if (attributeGroup.RedefinedAttributeGroup is not null && attributeGroupRef.RefName == new XmlQualifiedName(attributeGroup.Name, attributeGroupRef.RefName.Namespace)) { attributeGroupResolved = attributeGroup.RedefinedAttributeGroup; } @@ -1016,7 +1016,7 @@ private void HandleAttributeGroup(XmlSchemaAttributeGroup attributeGroup, DataTa { attributeGroupResolved = (XmlSchemaAttributeGroup)_attributeGroups[attributeGroupRef.RefName]; } - if (attributeGroupResolved != null) + if (attributeGroupResolved is not null) { HandleAttributeGroup(attributeGroupResolved, table, isBase); } @@ -1031,7 +1031,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL _complexTypes.Add(ct); - if (ct.ContentModel != null) + if (ct.ContentModel is not null) { /* HandleParticle(ct.CompiledParticle, table, tableChildren, isBase); @@ -1067,7 +1067,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL HandleSimpleContentColumn(ccExtension.BaseTypeName.Name, table, isBase, ct.ContentModel.UnhandledAttributes, isNillable); } } - if (ccExtension.Particle != null) + if (ccExtension.Particle is not null) HandleParticle(ccExtension.Particle, table, tableChildren, isBase); if (ct.BaseXmlSchemaType is XmlSchemaComplexType && FromInference) HandleAttributes(ccExtension.Attributes, table, isBase); @@ -1078,7 +1078,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL XmlSchemaComplexContentRestriction ccRestriction = ((XmlSchemaComplexContentRestriction)cContent); if (!FromInference) HandleAttributes(ccRestriction.Attributes, table, isBase); - if (ccRestriction.Particle != null) + if (ccRestriction.Particle is not null) HandleParticle(ccRestriction.Particle, table, tableChildren, isBase); if (FromInference) HandleAttributes(ccRestriction.Attributes, table, isBase); @@ -1115,7 +1115,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL isBase = true; if (!FromInference) HandleAttributes(ct.Attributes, table, isBase); - if (ct.Particle != null) + if (ct.Particle is not null) HandleParticle(ct.Particle, table, tableChildren, isBase); if (FromInference) { @@ -1130,7 +1130,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL internal XmlSchemaParticle GetParticle(XmlSchemaComplexType ct) { - if (ct.ContentModel != null) + if (ct.ContentModel is not null) { if (ct.ContentModel is XmlSchemaComplexContent) { @@ -1173,7 +1173,7 @@ internal DataColumn FindField(DataTable table, string field) colName = XmlConvert.DecodeName(colName); DataColumn col = table.Columns[colName]; - if (col == null) + if (col is null) throw ExceptionBuilder.InvalidField(field); bool _attribute = (col.ColumnMapping == MappingType.Attribute) || (col.ColumnMapping == MappingType.Hidden); @@ -1202,7 +1202,7 @@ internal DataColumn[] BuildKey(XmlSchemaIdentityConstraint keyNode, DataTable ta internal bool GetBooleanAttribute(XmlSchemaAnnotated element, string attrName, bool defVal) { string value = GetMsdataAttribute(element, attrName); - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) { return defVal; } @@ -1221,7 +1221,7 @@ internal bool GetBooleanAttribute(XmlSchemaAnnotated element, string attrName, b internal string GetStringAttribute(XmlSchemaAnnotated element, string attrName, string defVal) { string value = GetMsdataAttribute(element, attrName); - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) { return defVal; } @@ -1277,15 +1277,15 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) DataTable table = _ds.Tables.GetTableSmart(tableName, tableNs); - if (table == null) + if (table is null) return; - if (refer == null || refer.Length == 0) + if (refer is null || refer.Length == 0) throw ExceptionBuilder.MissingRefer(name); ConstraintTable key = (ConstraintTable)_constraintNodes[refer]; - if (key == null) + if (key is null) { throw ExceptionBuilder.InvalidKey(name); } @@ -1314,7 +1314,7 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) { string relName = XmlConvert.DecodeName(GetStringAttribute(keyref, Keywords.MSD_RELATIONNAME, keyref.Name)); - if (relName == null || relName.Length == 0) + if (relName is null || relName.Length == 0) relName = name; int iExisting = fKey[0].Table.DataSet.Relations.InternalIndexOf(relName); @@ -1355,15 +1355,15 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) string updateRule = GetMsdataAttribute(keyref, Keywords.MSD_UPDATERULE); string deleteRule = GetMsdataAttribute(keyref, Keywords.MSD_DELETERULE); - if (fkc != null) + if (fkc is not null) { - if (acceptRejectRule != null) + if (acceptRejectRule is not null) fkc.AcceptRejectRule = TranslateAcceptRejectRule(acceptRejectRule); - if (updateRule != null) + if (updateRule is not null) fkc.UpdateRule = TranslateRule(updateRule); - if (deleteRule != null) + if (deleteRule is not null) fkc.DeleteRule = TranslateRule(deleteRule); SetExtProperties(fkc, keyref.UnhandledAttributes); @@ -1376,7 +1376,7 @@ internal void HandleConstraint(XmlSchemaIdentityConstraint keyNode) string name = null; name = XmlConvert.DecodeName(keyNode.Name); - if (name == null || name.Length == 0) + if (name is null || name.Length == 0) throw ExceptionBuilder.MissingAttribute(Keywords.NAME); if (_constraintNodes.ContainsKey(name)) @@ -1388,7 +1388,7 @@ internal void HandleConstraint(XmlSchemaIdentityConstraint keyNode) DataTable table = _ds.Tables.GetTableSmart(tableName, tableNs); - if (table == null) + if (table is null) return; _constraintNodes.Add(name, new ConstraintTable(table, keyNode)); @@ -1404,7 +1404,7 @@ internal void HandleConstraint(XmlSchemaIdentityConstraint keyNode) { UniqueConstraint found = (UniqueConstraint)key[0].Table.Constraints.FindConstraint(new UniqueConstraint(name, key)); - if (found == null) + if (found is null) { key[0].Table.Constraints.Add(name, key, fPrimaryKey); SetExtProperties(key[0].Table.Constraints[name], keyNode.UnhandledAttributes); @@ -1433,12 +1433,12 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) _TableUri = node.QualifiedName.Namespace; table = _ds.Tables.GetTable(typeName, _TableUri); - if (!FromInference && table != null) + if (!FromInference && table is not null) { throw ExceptionBuilder.DuplicateDeclaration(typeName); } - if (table == null) + if (table is null) { table = new DataTable(typeName); table.Namespace = _TableUri; @@ -1453,7 +1453,7 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) else { string prefix = GetPrefix(_TableUri); - if (prefix != null) + if (prefix is not null) table.Prefix = prefix; } @@ -1465,7 +1465,7 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) XmlSchemaComplexType ct = node.SchemaType as XmlSchemaComplexType; // We assume node.ElementSchemaType.BaseSchemaType to be null for // and not null for - bool isSimpleContent = ((node.ElementSchemaType.BaseXmlSchemaType != null) || (ct != null && ct.ContentModel is XmlSchemaSimpleContent)); + bool isSimpleContent = ((node.ElementSchemaType.BaseXmlSchemaType is not null) || (ct is not null && ct.ContentModel is XmlSchemaSimpleContent)); if (!FromInference || (isSimpleContent && table.Columns.Count == 0)) {// for inference backward compatability @@ -1476,7 +1476,7 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) { int i = 0; colName = typeName + "_Text"; - while (table.Columns[colName] != null) + while (table.Columns[colName] is not null) colName = colName + i++; } else @@ -1488,7 +1488,7 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) table.Columns[0].ColumnMapping = MappingType.SimpleContent; } - if (!FromInference || _ds.Tables.GetTable(typeName, _TableUri) == null) + if (!FromInference || _ds.Tables.GetTable(typeName, _TableUri) is null) { // for inference; special case: add table if does not exists in collection _ds.Tables.Add(table); if (FromInference) @@ -1499,7 +1499,7 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) // handle all the unique and key constraints related to this table - if ((_dsElement != null) && (_dsElement.Constraints != null)) + if ((_dsElement is not null) && (_dsElement.Constraints is not null)) { foreach (XmlSchemaIdentityConstraint key in _dsElement.Constraints) { @@ -1524,15 +1524,15 @@ internal string GetInstanceName(XmlSchemaAnnotated node) if (node is XmlSchemaElement) { XmlSchemaElement el = (XmlSchemaElement)node; - instanceName = el.Name != null ? el.Name : el.RefName.Name; + instanceName = el.Name is not null ? el.Name : el.RefName.Name; } else if (node is XmlSchemaAttribute) { XmlSchemaAttribute el = (XmlSchemaAttribute)node; - instanceName = el.Name != null ? el.Name : el.RefName.Name; + instanceName = el.Name is not null ? el.Name : el.RefName.Name; } - Debug.Assert((instanceName != null) && (instanceName.Length != 0), "instanceName cannot be null or empty. There's an error in the XSD compiler"); + Debug.Assert((instanceName is not null) && (instanceName.Length != 0), "instanceName cannot be null or empty. There's an error in the XSD compiler"); return instanceName; } @@ -1550,13 +1550,13 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType table = _ds.Tables.GetTable(XmlConvert.DecodeName(typeName), _TableUri); // TOD: Do not do this fix - // if (table == null && node.RefName.IsEmpty && !IsTopLevelElement(node) && _TableUri != null && _TableUri.Length > 0) { + // if (table is null && node.RefName.IsEmpty && !IsTopLevelElement(node) && _TableUri is not null && _TableUri.Length > 0) { // _TableUri = null; // it means form="qualified", so child element inherits namespace. amirhmy // } - if (!FromInference || (FromInference && table == null)) + if (!FromInference || (FromInference && table is null)) { - if (table != null) + if (table is not null) { if (isRef) return table; @@ -1588,7 +1588,7 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType } value = GetMsdataAttribute(node, Keywords.MSD_LOCALE); - if (null != value) + if (value is not null) { // set by user if (0 < value.Length) { @@ -1611,7 +1611,7 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType else { string prefix = GetPrefix(_TableUri); - if (prefix != null) + if (prefix is not null) table.Prefix = prefix; } @@ -1637,7 +1637,7 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType SetExtProperties(table, node.UnhandledAttributes); // handle all the unique and key constraints related to this table - if ((_dsElement != null) && (_dsElement.Constraints != null)) + if ((_dsElement is not null) && (_dsElement.Constraints is not null)) { foreach (XmlSchemaIdentityConstraint key in _dsElement.Constraints) { @@ -1646,9 +1646,9 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType if (GetTableName(key) == table.TableName) { // respect the NS if it is specified for key, otherwise just go with table name check - if (GetTableNamespace(key) == table.Namespace || GetTableNamespace(key) == null) + if (GetTableNamespace(key) == table.Namespace || GetTableNamespace(key) is null) HandleConstraint(key); - /* if (GetTableNamespace(key) != null) { + /* if (GetTableNamespace(key) is not null) { if (GetTableNamespace(key) == table.Namespace) HandleConstraint(key); } @@ -1665,12 +1665,12 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType if (_tableChild != table && table.Namespace == _tableChild.Namespace) _tableChild._tableNamespace = null; - if ((_dsElement != null) && (_dsElement.Constraints != null)) + if ((_dsElement is not null) && (_dsElement.Constraints is not null)) { foreach (XmlSchemaIdentityConstraint key in _dsElement.Constraints) { XmlSchemaKeyref keyref = key as XmlSchemaKeyref; - if (keyref == null) + if (keyref is null) continue; bool isNested = GetBooleanAttribute(keyref, Keywords.MSD_ISNESTED, /*default:*/ false); @@ -1705,7 +1705,7 @@ internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType relation = childRelations[j]; } - if (relation != null) + if (relation is not null) continue; DataColumn parentKey; @@ -1852,15 +1852,15 @@ private Type ParseDataType(string dt) { if (!IsXsdType(dt)) { - if (_udSimpleTypes != null) + if (_udSimpleTypes is not null) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)_udSimpleTypes[dt]; - if (simpleType == null) + if (simpleType is null) { // it is not named simple type, it is not XSD type, it should be unsupported type like xs:token throw ExceptionBuilder.UndefinedDatatype(dt); } SimpleType rootType = new SimpleType(simpleType); - while (rootType.BaseSimpleType != null) + while (rootType.BaseSimpleType is not null) { rootType = rootType.BaseSimpleType; } @@ -1873,7 +1873,7 @@ private Type ParseDataType(string dt) } /* later we may need such a function private Boolean IsUDSimpleType(string qname) { - if (udSimpleTypes == null) + if (udSimpleTypes is null) return false; return (udSimpleTypes.Contains(qname)); } @@ -1911,7 +1911,7 @@ internal XmlSchemaAnnotated FindTypeNode(XmlSchemaAnnotated node) XmlSchemaAttribute attr = node as XmlSchemaAttribute; XmlSchemaElement el = node as XmlSchemaElement; bool isAttr = false; - if (attr != null) + if (attr is not null) { isAttr = true; } @@ -1921,10 +1921,10 @@ internal XmlSchemaAnnotated FindTypeNode(XmlSchemaAnnotated node) if (_typeNs == Keywords.XSDNS) return null; XmlSchemaAnnotated typeNode; - if (_type == null || _type.Length == 0) + if (_type is null || _type.Length == 0) { _type = isAttr ? attr.RefName.Name : el.RefName.Name; - if (_type == null || _type.Length == 0) + if (_type is null || _type.Length == 0) typeNode = isAttr ? attr.SchemaType : el.SchemaType; else typeNode = isAttr ? FindTypeNode((XmlSchemaAnnotated)_attributes[attr.RefName]) : FindTypeNode((XmlSchemaAnnotated)_elementsTable[el.RefName]); @@ -1938,7 +1938,7 @@ internal XmlSchemaAnnotated FindTypeNode(XmlSchemaAnnotated node) internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, string strType, DataTable table, bool isBase, XmlAttribute[] attrs, bool isNillable) { // disallow multiple simple content columns for the table - if (FromInference && table.XmlText != null) + if (FromInference && table.XmlText is not null) { // backward compatability for inference return; } @@ -1947,7 +1947,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 (typeNode.QualifiedName.Name is not null && typeNode.QualifiedName.Name.Length != 0 && typeNode.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType xsdType = new SimpleType(typeNode); strType = typeNode.QualifiedName.ToString(); // use qualifed name @@ -1956,12 +1956,12 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, else {// previous code V 1.1 XmlSchemaSimpleType ancestor = typeNode.BaseXmlSchemaType as XmlSchemaSimpleType; - if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) + if ((ancestor is not null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) { xsdType = new SimpleType(typeNode); SimpleType rootType = xsdType; - while (rootType.BaseSimpleType != null) + while (rootType.BaseSimpleType is not null) { rootType = rootType.BaseSimpleType; } @@ -1982,7 +1982,7 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, { int i = 0; colName = table.TableName + "_Text"; - while (table.Columns[colName] != null) + while (table.Columns[colName] is not null) { colName = colName + i++; } @@ -2011,7 +2011,7 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, //try to see if attributes contain allownull column.AllowDBNull = isNillable; - if (attrs != null) + if (attrs is not null) for (int i = 0; i < attrs.Length; i++) { if (attrs[i].LocalName == Keywords.MSD_ALLOWDBNULL && attrs[i].NamespaceURI == Keywords.MSDNS) @@ -2027,15 +2027,15 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, //SetExtProperties(column, attr.UnhandledAttributes); - if ((column.Expression != null) && (column.Expression.Length != 0)) + if ((column.Expression is not null) && (column.Expression.Length != 0)) { _columnExpressions.Add(column); } // Update XSD type to point to simple types actual namespace instead of normalized default namespace in case of remoting - if (xsdType != null && xsdType.Name != null && xsdType.Name.Length > 0) + if (xsdType is not null && xsdType.Name is not null && xsdType.Name.Length > 0) { - if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE) != null) + if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE) is not null) { column.XmlDataType = xsdType.SimpleTypeQualifiedName; } @@ -2060,7 +2060,7 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, table.Columns.Add(column); } - if (defValue != null) + if (defValue is not null) try { column.DefaultValue = column.ConvertXmlToObject(defValue); @@ -2076,11 +2076,11 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is // for Named Simple type support : We should not recieved anything here other than string. // there can not be typed simple content // disallow multiple simple content columns for the table - if (FromInference && table.XmlText != null) // backward compatability for inference + if (FromInference && table.XmlText is not null) // backward compatability for inference return; Type type = null; - if (strType == null) + if (strType is null) { return; } @@ -2093,7 +2093,7 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is { int i = 0; colName = table.TableName + "_Text"; - while (table.Columns[colName] != null) + while (table.Columns[colName] is not null) { colName = colName + i++; } @@ -2123,7 +2123,7 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is //try to see if attributes contain allownull column.AllowDBNull = isNillable; - if (attrs != null) + if (attrs is not null) for (int i = 0; i < attrs.Length; i++) { if (attrs[i].LocalName == Keywords.MSD_ALLOWDBNULL && attrs[i].NamespaceURI == Keywords.MSDNS) @@ -2139,7 +2139,7 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is //SetExtProperties(column, attr.UnhandledAttributes); - if ((column.Expression != null) && (column.Expression.Length != 0)) + if ((column.Expression is not null) && (column.Expression.Length != 0)) { _columnExpressions.Add(column); } @@ -2160,7 +2160,7 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is table.Columns.Add(column); } - if (defValue != null) + if (defValue is not null) try { column.DefaultValue = column.ConvertXmlToObject(defValue); @@ -2174,14 +2174,14 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, bool isBase) { Type type = null; - XmlSchemaAttribute attr = attrib.Name != null ? attrib : (XmlSchemaAttribute)_attributes[attrib.RefName]; + XmlSchemaAttribute attr = attrib.Name is not null ? attrib : (XmlSchemaAttribute)_attributes[attrib.RefName]; XmlSchemaAnnotated typeNode = FindTypeNode(attr); string strType = null; SimpleType xsdType = null; - if (typeNode == null) + if (typeNode is null) { strType = attr.SchemaTypeName.Name; if (string.IsNullOrEmpty(strType)) @@ -2201,7 +2201,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 (node.QualifiedName.Name is not null && node.QualifiedName.Name.Length != 0 && node.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType strType = node.QualifiedName.ToString(); // use qualifed name @@ -2224,7 +2224,7 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, } else { - if (typeNode.Id == null) + if (typeNode.Id is null) throw ExceptionBuilder.DatatypeNotDefined(); else throw ExceptionBuilder.UndefinedDatatype(typeNode.Id); @@ -2266,14 +2266,14 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, HandleColumnExpression(column, attr.UnhandledAttributes); SetExtProperties(column, attr.UnhandledAttributes); - if ((column.Expression != null) && (column.Expression.Length != 0)) + if ((column.Expression is not null) && (column.Expression.Length != 0)) { _columnExpressions.Add(column); } - if (xsdType != null && xsdType.Name != null && xsdType.Name.Length > 0) + if (xsdType is not null && xsdType.Name is not null && xsdType.Name.Length > 0) { - if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE) != null) + if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE) is not null) { column.XmlDataType = xsdType.SimpleTypeQualifiedName; } @@ -2305,7 +2305,7 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, column.AllowDBNull = GetBooleanAttribute(attr, Keywords.MSD_ALLOWDBNULL, true); string defValue = GetMsdataAttribute(attr, Keywords.MSD_DEFAULTVALUE); - if (defValue != null) + if (defValue is not null) try { column.DefaultValue = column.ConvertXmlToObject(defValue); @@ -2319,10 +2319,10 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, // XDR March change string strDefault = (attrib.Use == XmlSchemaUse.Required) ? GetMsdataAttribute(attr, Keywords.MSD_DEFAULTVALUE) : attr.DefaultValue; - if ((attr.Use == XmlSchemaUse.Optional) && (strDefault == null)) + if ((attr.Use == XmlSchemaUse.Optional) && (strDefault is null)) strDefault = attr.FixedValue; - if (strDefault != null) + if (strDefault is not null) try { column.DefaultValue = column.ConvertXmlToObject(strDefault); @@ -2336,16 +2336,16 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool isBase) { Type type = null; - XmlSchemaElement el = elem.Name != null ? elem : (XmlSchemaElement)_elementsTable[elem.RefName]; + XmlSchemaElement el = elem.Name is not null ? elem : (XmlSchemaElement)_elementsTable[elem.RefName]; - if (el == null) // it's possible due to some XSD compiler optimizations + if (el is null) // it's possible due to some XSD compiler optimizations return; // do nothing XmlSchemaAnnotated typeNode = FindTypeNode(el); string strType = null; SimpleType xsdType = null; - if (typeNode == null) + if (typeNode is null) { strType = el.SchemaTypeName.Name; if (string.IsNullOrEmpty(strType)) @@ -2362,22 +2362,22 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i { XmlSchemaSimpleType simpleTypeNode = typeNode as XmlSchemaSimpleType; xsdType = new SimpleType(simpleTypeNode); - // ((XmlSchemaSimpleType)typeNode).Name != null && ((XmlSchemaSimpleType)typeNode).Name.Length != 0 check is for annonymos simple type, + // ((XmlSchemaSimpleType)typeNode).Name is not 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 (((XmlSchemaSimpleType)typeNode).Name is not null && ((XmlSchemaSimpleType)typeNode).Name.Length != 0 && ((XmlSchemaSimpleType)typeNode).QualifiedName.Namespace != Keywords.XSDNS) { strType = ((XmlSchemaSimpleType)typeNode).QualifiedName.ToString(); // use qualifed name type = ParseDataType(strType); } else { - simpleTypeNode = (xsdType.XmlBaseType != null && xsdType.XmlBaseType.Namespace != Keywords.XSDNS) ? + simpleTypeNode = (xsdType.XmlBaseType is not null && xsdType.XmlBaseType.Namespace != Keywords.XSDNS) ? _schemaTypes[xsdType.XmlBaseType] as XmlSchemaSimpleType : null; - while (simpleTypeNode != null) + while (simpleTypeNode is not null) { xsdType.LoadTypeValues(simpleTypeNode); - simpleTypeNode = (xsdType.XmlBaseType != null && xsdType.XmlBaseType.Namespace != Keywords.XSDNS) ? + simpleTypeNode = (xsdType.XmlBaseType is not null && xsdType.XmlBaseType.Namespace != Keywords.XSDNS) ? _schemaTypes[xsdType.XmlBaseType] as XmlSchemaSimpleType : null; } @@ -2409,7 +2409,7 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i } else { - if (typeNode.Id == null) + if (typeNode.Id is null) throw ExceptionBuilder.DatatypeNotDefined(); else throw ExceptionBuilder.UndefinedDatatype(typeNode.Id); @@ -2456,9 +2456,9 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i } // Update XSD type to point to simple types actual namespace instead of normalized default namespace in case of remoting - if (xsdType != null && xsdType.Name != null && xsdType.Name.Length > 0) + if (xsdType is not null && xsdType.Name is not null && xsdType.Name.Length > 0) { - if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE) != null) + if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE) is not null) { column.XmlDataType = xsdType.SimpleTypeQualifiedName; } @@ -2486,7 +2486,7 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i else if (elem.Form == XmlSchemaForm.None) { XmlSchemaObject e = elem.Parent; - while (e.Parent != null) + while (e.Parent is not null) { e = e.Parent; } @@ -2522,7 +2522,7 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i } string strDefault = el.DefaultValue; - if (strDefault != null) + if (strDefault is not null) try { column.DefaultValue = column.ConvertXmlToObject(strDefault); @@ -2541,7 +2541,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) List tableSequenceList = new List(); string value = GetMsdataAttribute(node, Keywords.MSD_LOCALE); - if (null != value) + if (value is not null) { // set by user if (0 != value.Length) { @@ -2569,13 +2569,13 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) // reuse variable value = GetMsdataAttribute(node, Keywords.MSD_DATASETNAME); - if (value != null && value.Length != 0) + if (value is not null && value.Length != 0) { dsName = value; } value = GetMsdataAttribute(node, Keywords.MSD_DATASETNAMESPACE); - if (value != null && value.Length != 0) + if (value is not null && value.Length != 0) { dsNamespace = value; } @@ -2584,7 +2584,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) SetExtProperties(_ds, node.UnhandledAttributes); - if (dsName != null && dsName.Length != 0) + if (dsName is not null && dsName.Length != 0) _ds.DataSetName = XmlConvert.DecodeName(dsName); // _ds.Namespace = node.QualifiedName.Namespace; @@ -2594,11 +2594,11 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) _ds.Prefix = GetPrefix(_ds.Namespace); XmlSchemaComplexType ct = (XmlSchemaComplexType)FindTypeNode(node); - if (ct.Particle != null) + if (ct.Particle is not null) { XmlSchemaObjectCollection items = GetParticleItems(ct.Particle); - if (items == null) + if (items is null) { return; } @@ -2616,16 +2616,16 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) else { DataTable tempTable = _ds.Tables.GetTable(XmlConvert.DecodeName(GetInstanceName((XmlSchemaElement)el)), node.QualifiedName.Namespace); - if (tempTable != null) + if (tempTable is not null) { tableSequenceList.Add(tempTable); // if ref table is created, add it } bool isComplexTypeOrValidElementType = false; - if (node.ElementSchemaType != null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)) + if (node.ElementSchemaType is not null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)) { isComplexTypeOrValidElementType = true; } - // bool isComplexTypeOrValidElementType = (node.ElementType != null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)); + // bool isComplexTypeOrValidElementType = (node.ElementType is not null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)); if ((((XmlSchemaElement)el).MaxOccurs != decimal.One) && (!isComplexTypeOrValidElementType)) { continue; @@ -2634,7 +2634,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) } DataTable child = HandleTable((XmlSchemaElement)el); - if (child != null) + if (child is not null) { child._fNestedInDataset = true; } @@ -2646,7 +2646,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) else if (el is XmlSchemaChoice) { // should we check for inference? XmlSchemaObjectCollection choiceItems = ((XmlSchemaChoice)el).Items; - if (choiceItems == null) + if (choiceItems is null) continue; foreach (XmlSchemaAnnotated choiceEl in choiceItems) { @@ -2662,7 +2662,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) { tableSequenceList.Add(child); } - if (child != null) + if (child is not null) { child._fNestedInDataset = true; } @@ -2673,12 +2673,12 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) } // Handle the non-nested keyref constraints - if (node.Constraints != null) + if (node.Constraints is not null) { foreach (XmlSchemaIdentityConstraint key in node.Constraints) { XmlSchemaKeyref keyref = key as XmlSchemaKeyref; - if (keyref == null) + if (keyref is null) continue; bool isNested = GetBooleanAttribute(keyref, Keywords.MSD_ISNESTED, /*default:*/ false); @@ -2713,7 +2713,7 @@ private void AddTablesToList(List tableList, DataTable dt) private string GetPrefix(string ns) { - if (ns == null) + if (ns is null) return null; foreach (XmlSchema schemaRoot in _schemaSet.Schemas()) { @@ -2729,7 +2729,7 @@ private string GetPrefix(string ns) private string GetNamespaceFromPrefix(string prefix) { - if ((prefix == null) || (prefix.Length == 0)) + if ((prefix is null) || (prefix.Length == 0)) return null; foreach (XmlSchema schemaRoot in _schemaSet.Schemas()) { @@ -2752,7 +2752,7 @@ private string GetTableNamespace(XmlSchemaIdentityConstraint key) string QualifiedTableName = split[split.Length - 1]; //get the last string after '/' and ':' - if ((QualifiedTableName == null) || (QualifiedTableName.Length == 0)) + if ((QualifiedTableName is null) || (QualifiedTableName.Length == 0)) throw ExceptionBuilder.InvalidSelector(xpath); if (QualifiedTableName.Contains(':')) @@ -2771,7 +2771,7 @@ private string GetTableName(XmlSchemaIdentityConstraint key) string[] split = xpath.Split('/', ':'); string tableName = split[split.Length - 1]; //get the last string after '/' and ':' - if ((tableName == null) || (tableName.Length == 0)) + if ((tableName is null) || (tableName.Length == 0)) throw ExceptionBuilder.InvalidSelector(xpath); tableName = XmlConvert.DecodeName(tableName); @@ -2784,7 +2784,7 @@ internal bool IsTable(XmlSchemaElement node) return false; XmlAttribute[] attribs = node.UnhandledAttributes; - if (attribs != null) + if (attribs is not null) { for (int i = 0; i < attribs.Length; i++) { @@ -2798,13 +2798,13 @@ internal bool IsTable(XmlSchemaElement node) object typeNode = FindTypeNode(node); - if ((node.MaxOccurs > decimal.One) && typeNode == null) + if ((node.MaxOccurs > decimal.One) && typeNode is null) { return true; } - if ((typeNode == null) || !(typeNode is XmlSchemaComplexType)) + if ((typeNode is null) || !(typeNode is XmlSchemaComplexType)) { return false; } @@ -2827,12 +2827,12 @@ internal DataTable HandleTable(XmlSchemaElement node) object typeNode = FindTypeNode(node); - if ((node.MaxOccurs > decimal.One) && typeNode == null) + if ((node.MaxOccurs > decimal.One) && typeNode is null) { return InstantiateSimpleTable(node); } - DataTable table = InstantiateTable(node, (XmlSchemaComplexType)typeNode, (node.RefName != null)); // this is wrong , correct check should be node.RefName.IsEmpty + DataTable table = InstantiateTable(node, (XmlSchemaComplexType)typeNode, (node.RefName is not null)); // this is wrong , correct check should be node.RefName.IsEmpty table._fNestedInDataset = false; return table; diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs index 1453fe83ce86cd..9c6a170988138b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -96,23 +96,23 @@ internal bool FromInference // after loading, all detached DataRows are attached to their tables private void AttachRows(DataRow parentRow, XmlNode parentElement) { - if (parentElement == null) + if (parentElement is null) return; - for (XmlNode n = parentElement.FirstChild; n != null; n = n.NextSibling) + for (XmlNode n = parentElement.FirstChild; n is not null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element) { XmlElement e = (XmlElement)n; DataRow r = GetRowFromElement(e); - if (r != null && r.RowState == DataRowState.Detached) + if (r is not null && r.RowState == DataRowState.Detached) { - if (parentRow != null) + if (parentRow is not null) r.SetNestedParentRow(parentRow, /*setNonNested*/ false); r.Table.Rows.Add(r); } - else if (r == null) + else if (r is null) { // n is a 'sugar element' AttachRows(parentRow, n); @@ -140,14 +140,14 @@ private string GetValueForTextOnlyColums(XmlNode n) string value = null; // don't consider whitespace - while (n != null && (n.NodeType == XmlNodeType.Whitespace || !IsTextLikeNode(n.NodeType))) + while (n is not null && (n.NodeType == XmlNodeType.Whitespace || !IsTextLikeNode(n.NodeType))) { n = n.NextSibling; } - if (n != null) + if (n is not null) { - if (IsTextLikeNode(n.NodeType) && (n.NextSibling == null || !IsTextLikeNode(n.NodeType))) + if (IsTextLikeNode(n.NodeType) && (n.NextSibling is null || !IsTextLikeNode(n.NodeType))) { // don't use string builder if only one text node exists value = n.Value; @@ -156,7 +156,7 @@ private string GetValueForTextOnlyColums(XmlNode n) else { StringBuilder sb = new StringBuilder(); - while (n != null && IsTextLikeNode(n.NodeType)) + while (n is not null && IsTextLikeNode(n.NodeType)) { sb.Append(n.Value); n = n.NextSibling; @@ -165,7 +165,7 @@ private string GetValueForTextOnlyColums(XmlNode n) } } - if (value == null) + if (value is null) value = string.Empty; return value; @@ -175,13 +175,13 @@ private string GetInitialTextFromNodes(ref XmlNode n) { string value = null; - if (n != null) + if (n is not null) { // don't consider whitespace while (n.NodeType == XmlNodeType.Whitespace) n = n.NextSibling; - if (IsTextLikeNode(n.NodeType) && (n.NextSibling == null || !IsTextLikeNode(n.NodeType))) + if (IsTextLikeNode(n.NodeType) && (n.NextSibling is null || !IsTextLikeNode(n.NodeType))) { // don't use string builder if only one text node exists value = n.Value; @@ -190,7 +190,7 @@ private string GetInitialTextFromNodes(ref XmlNode n) else { StringBuilder sb = new StringBuilder(); - while (n != null && IsTextLikeNode(n.NodeType)) + while (n is not null && IsTextLikeNode(n.NodeType)) { sb.Append(n.Value); n = n.NextSibling; @@ -199,7 +199,7 @@ private string GetInitialTextFromNodes(ref XmlNode n) } } - if (value == null) + if (value is null) value = string.Empty; return value; @@ -225,13 +225,13 @@ internal DataRow GetRowFromElement(XmlElement e) internal bool FColumnElement(XmlElement e) { - if (_nodeToSchemaMap.GetColumnSchema(e, FIgnoreNamespace(e)) == null) + if (_nodeToSchemaMap.GetColumnSchema(e, FIgnoreNamespace(e)) is null) return false; if (CountNonNSAttributes(e) > 0) return false; - for (XmlNode tabNode = e.FirstChild; tabNode != null; tabNode = tabNode.NextSibling) + for (XmlNode tabNode = e.FirstChild; tabNode is not null; tabNode = tabNode.NextSibling) if (tabNode is XmlElement) return false; @@ -294,7 +294,7 @@ internal bool IsTextOnly(DataColumn c) internal void LoadData(XmlDocument xdoc) { - if (xdoc.DocumentElement == null) + if (xdoc.DocumentElement is null) return; bool saveEnforce; @@ -327,10 +327,10 @@ internal void LoadData(XmlDocument xdoc) if (CountNonNSAttributes (rootElement) > 0) dataSet.fTopLevelTable = true; else { - for (tabNode = rootElement.FirstChild; tabNode != null; tabNode = tabNode.NextSibling) { + for (tabNode = rootElement.FirstChild; tabNode is not null; tabNode = tabNode.NextSibling) { if (tabNode is XmlElement && tabNode.LocalName != Keywords.XSD_SCHEMA) { object value = tableAtoms[QualifiedName (tabNode.LocalName, tabNode.NamespaceURI)]; - if (value == null || (bool)value == false) { + if (value is null || (bool)value == false) { dataSet.fTopLevelTable = true; break; } @@ -339,11 +339,11 @@ internal void LoadData(XmlDocument xdoc) } */ DataRow topRow = null; - if (_isTableLevel || (_dataSet != null && _dataSet._fTopLevelTable)) + if (_isTableLevel || (_dataSet is not null && _dataSet._fTopLevelTable)) { XmlElement e = xdoc.DocumentElement; DataTable topTable = (DataTable)_nodeToSchemaMap.GetSchemaForNode(e, FIgnoreNamespace(e)); - if (topTable != null) + if (topTable is not null) { topRow = topTable.CreateEmptyRow(); //enzol perf _nodeToRowMap[e] = topRow; @@ -386,7 +386,7 @@ private void LoadRowData(DataRow row, XmlElement rowElement) // Look for data to fill the TextOnly column DataColumn column = GetTextOnlyColumn(row); - if (column != null) + if (column is not null) { foundColumns[column] = column; string text = GetValueForTextOnlyColums(n); @@ -397,7 +397,7 @@ private void LoadRowData(DataRow row, XmlElement rowElement) } // Walk the region to find elements that map to columns - while (n != null && n != rowElement) + while (n is not null && n != rowElement) { if (n.NodeType == XmlNodeType.Element) { @@ -411,16 +411,16 @@ private void LoadRowData(DataRow row, XmlElement rowElement) } // if element has its own table mapping, it is a separate region - if (schema == null || schema is DataColumn) + if (schema is null || schema is DataColumn) { // descend to examine child elements n = e.FirstChild; - if (schema != null && schema is DataColumn) + if (schema is not null && schema is DataColumn) { DataColumn c = (DataColumn)schema; - if (c.Table == row.Table && c.ColumnMapping != MappingType.Attribute && foundColumns[c] == null) + if (c.Table == row.Table && c.ColumnMapping != MappingType.Attribute && foundColumns[c] is null) { foundColumns[c] = c; string text = GetValueForTextOnlyColums(n); @@ -430,20 +430,20 @@ private void LoadRowData(DataRow row, XmlElement rowElement) SetRowValueFromXmlText(row, c, text); } } - else if ((schema == null) && (n != null)) + else if ((schema is null) && (n is not null)) { continue; } // nothing left down here, continue from element - if (n == null) + if (n is null) n = e; } } // if no more siblings, ascend back toward original element (rowElement) - while (n != rowElement && n.NextSibling == null) + while (n != rowElement && n.NextSibling is null) { n = n.ParentNode; } @@ -458,11 +458,11 @@ private void LoadRowData(DataRow row, XmlElement rowElement) foreach (XmlAttribute attr in rowElement.Attributes) { object schema = _nodeToSchemaMap.GetColumnSchema(attr, FIgnoreNamespace(attr)); - if (schema != null && schema is DataColumn) + if (schema is not null && schema is DataColumn) { DataColumn c = (DataColumn)schema; - if (c.ColumnMapping == MappingType.Attribute && foundColumns[c] == null) + if (c.ColumnMapping == MappingType.Attribute && foundColumns[c] is null) { foundColumns[c] = c; n = attr.FirstChild; @@ -474,7 +474,7 @@ private void LoadRowData(DataRow row, XmlElement rowElement) // Null all columns values that aren't represented in the tree foreach (DataColumn c in row.Table.Columns) { - if (foundColumns[c] == null && XmlToDatasetMap.IsMappedColumn(c)) + if (foundColumns[c] is null && XmlToDatasetMap.IsMappedColumn(c)) { if (!c.AutoIncrement) { @@ -501,7 +501,7 @@ private void LoadRowData(DataRow row, XmlElement rowElement) // load all data from tree structre into datarows private void LoadRows(DataRow parentRow, XmlNode parentElement) { - if (parentElement == null) + if (parentElement is null) return; // Skip schema node as well @@ -510,20 +510,20 @@ private void LoadRows(DataRow parentRow, XmlNode parentElement) parentElement.LocalName == Keywords.XDR_SCHEMA && parentElement.NamespaceURI == Keywords.XDRNS) return; - for (XmlNode n = parentElement.FirstChild; n != null; n = n.NextSibling) + for (XmlNode n = parentElement.FirstChild; n is not null; n = n.NextSibling) { if (n is XmlElement) { XmlElement e = (XmlElement)n; object schema = _nodeToSchemaMap.GetSchemaForNode(e, FIgnoreNamespace(e)); - if (schema != null && schema is DataTable) + if (schema is not null && schema is DataTable) { DataRow r = GetRowFromElement(e); - if (r == null) + if (r is null) { // skip columns which has the same name as another table - if (parentRow != null && FColumnElement(e)) + if (parentRow is not null && FColumnElement(e)) continue; r = ((DataTable)schema).CreateEmptyRow(); @@ -594,7 +594,7 @@ internal void LoadData(XmlReader reader) // Keep constraints status for datataset/table InitNameTable(); // Adds DataSet namespaces to reader's nametable - if (_nodeToSchemaMap == null) + if (_nodeToSchemaMap is null) { // Create XML to dataset map _nodeToSchemaMap = _isTableLevel ? new XmlToDatasetMap(_dataReader.NameTable, _dataTable) : new XmlToDatasetMap(_dataReader.NameTable, _dataSet); @@ -610,13 +610,13 @@ internal void LoadData(XmlReader reader) _dataSet._fInReadXml = true; // We're in ReadXml now } - if (_topMostNode != null) + if (_topMostNode is not null) { // Do we have top node? if (!_isDiffgram && !_isTableLevel) { // Not a diffgram and not DataSet? DataTable table = _nodeToSchemaMap.GetSchemaForNode(_topMostNode, FIgnoreNamespace(_topMostNode)) as DataTable; // Try to match table in the dataset to this node - if (table != null) + if (table is not null) { // Got the table ? LoadTopMostTable(table); // Load top most node } @@ -637,7 +637,7 @@ internal void LoadData(XmlReader reader) } DataTable table = _nodeToSchemaMap.GetTableForNode(_dataReader, FIgnoreNamespace(_dataReader)); // Try to get table for node - if (table == null) + if (table is null) { // Read till table is found if (!ProcessXsdSchema()) // Check for schemas... _dataReader.Read(); // Not found? Read next element. @@ -689,8 +689,8 @@ private void LoadTopMostTable(DataTable table) // \------------------------------ We are here on exit - Debug.Assert(table != null, "Table to be loaded is null on LoadTopMostTable() entry"); - Debug.Assert(_topMostNode != null, "topMostNode is null on LoadTopMostTable() entry"); + Debug.Assert(table is not null, "Table to be loaded is null on LoadTopMostTable() entry"); + Debug.Assert(_topMostNode is not null, "topMostNode is null on LoadTopMostTable() entry"); Debug.Assert(!_isDiffgram, "Diffgram mode is on while we have topMostNode table. This is bad."); bool topNodeIsTable = _isTableLevel || (_dataSet.DataSetName != table.TableName); @@ -723,7 +723,7 @@ private void LoadTopMostTable(DataTable table) c = _nodeToSchemaMap.GetColumnSchema(attr, FIgnoreNamespace(attr)) as DataColumn; // Try to match attribute to column - if ((c != null) && (c.ColumnMapping == MappingType.Attribute)) + if ((c is not null) && (c.ColumnMapping == MappingType.Attribute)) { // If it's a column with attribute mapping n = attr.FirstChild; @@ -748,11 +748,11 @@ private void LoadTopMostTable(DataTable table) // Get dataset element for this XML element c = o as DataColumn; // Perhaps, it's a column? - if (c != null) + if (c is not null) { // Do we have matched column in this table? // Let's load column data - if (foundColumns[c.Ordinal] == null) + if (foundColumns[c.Ordinal] is null) { // If this column was not found before LoadColumn(c, foundColumns); // Get column value. @@ -767,7 +767,7 @@ private void LoadTopMostTable(DataTable table) { DataTable nestedTable = o as DataTable; // Perhaps, it's a nested table ? - if (nestedTable != null) + if (nestedTable is not null) { // Do we have matched table in DataSet ? LoadTable(nestedTable, true /* isNested */); // Yes. Load nested table (recursive) @@ -803,7 +803,7 @@ private void LoadTopMostTable(DataTable table) // Get text node value. c = table._xmlText; // Get XML Text column from our table - if (c != null && foundColumns[c.Ordinal] == null) + if (c is not null && foundColumns[c.Ordinal] is null) { // If XmlText Column is set // and we do not have data already @@ -825,7 +825,7 @@ private void LoadTopMostTable(DataTable table) for (int i = foundColumns.Length - 1; i >= 0; --i) { // Check all columns - if (null == foundColumns[i]) + if (foundColumns[i] is null) { // Got data for this column ? c = collection[i]; // No. Get column for this index @@ -872,7 +872,7 @@ private void LoadTable(DataTable table, bool isNested) // ... // - Debug.Assert(table != null, "Table to be loaded is null on LoadTable() entry"); + Debug.Assert(table is not null, "Table to be loaded is null on LoadTable() entry"); DataRow row = null; // Data row we're going to add to this table @@ -903,7 +903,7 @@ private void LoadTable(DataTable table, bool isNested) c = _nodeToSchemaMap.GetColumnSchema(table, _dataReader, FIgnoreNamespace(_dataReader)) as DataColumn; // Try to get column for this attribute - if ((c != null) && (c.ColumnMapping == MappingType.Attribute)) + if ((c is not null) && (c.ColumnMapping == MappingType.Attribute)) { // Yep, it is a column mapped as attribute // Get value from XML and store it in the object array @@ -944,7 +944,7 @@ private void LoadTable(DataTable table, bool isNested) // We have to decode name before we look it up // We could not use XmlToDataSet map as it contains // no hidden columns - if ((c != null) && (c.ColumnMapping == MappingType.Hidden)) + if ((c is not null) && (c.ColumnMapping == MappingType.Hidden)) { // Got column and it is hidden ? foundColumns[c.Ordinal] = c.ConvertXmlToObject(_dataReader.Value); @@ -975,10 +975,10 @@ private void LoadTable(DataTable table, bool isNested) // Get dataset element for this XML element c = o as DataColumn; // Perhaps, it's a column? - if (c != null) + if (c is not null) { // Do we have matched column in this table? // Let's load column data - if (foundColumns[c.Ordinal] == null) + if (foundColumns[c.Ordinal] is null) { // If this column was not found before LoadColumn(c, foundColumns); @@ -993,7 +993,7 @@ private void LoadTable(DataTable table, bool isNested) { DataTable nestedTable = o as DataTable; // Perhaps, it's a nested table ? - if (nestedTable != null) + if (nestedTable is not null) { // Do we have matched nested table in DataSet ? LoadTable(nestedTable, true /* isNested */); // Yes. Load nested table (recursive) @@ -1013,7 +1013,7 @@ private void LoadTable(DataTable table, bool isNested) DataTable misplacedTable = _nodeToSchemaMap.GetTableForNode(_dataReader, FIgnoreNamespace(_dataReader)); // Try to get table for node - if (misplacedTable != null) + if (misplacedTable is not null) { // Got some matching table? LoadTable(misplacedTable, false /* isNested */); // While table's XML element is nested, @@ -1036,7 +1036,7 @@ private void LoadTable(DataTable table, bool isNested) // Get text node value. c = table._xmlText; // Get XML Text column from our table - if (c != null && foundColumns[c.Ordinal] == null) + if (c is not null && foundColumns[c.Ordinal] is null) { // If XmlText Column is set // and we do not have data already @@ -1066,7 +1066,7 @@ private void LoadTable(DataTable table, bool isNested) // Check all columns c = collection[i]; // Get column for this index - c[row._tempRecord] = null != foundColumns[i] ? foundColumns[i] : DBNull.Value; + c[row._tempRecord] = foundColumns[i] is not null ? foundColumns[i] : DBNull.Value; // Set column to loaded value of to // DBNull if value is missing. } @@ -1076,7 +1076,7 @@ private void LoadTable(DataTable table, bool isNested) table.Rows.DiffInsertAt(row, rowOrder); // insert data to specific location // And do some diff processing - if (hasChanges == null) + if (hasChanges is null) { // No changes ? row._oldRecord = row._newRecord; // Restore old record } @@ -1091,7 +1091,7 @@ private void LoadTable(DataTable table, bool isNested) for (int i = foundColumns.Length - 1; i >= 0; --i) { // Check all columns - if (null == foundColumns[i]) + if (foundColumns[i] is null) { // Got data for this column ? c = collection[i]; // No. Get column for this index @@ -1170,22 +1170,22 @@ private void LoadColumn(DataColumn column, object[] foundColumns) // We also need to do that if no polymorphism for this type allowed. bool useXmlSerializer = !column.ImplementsIXMLSerializable && - !((column.DataType == typeof(object)) || (typeName != null) || (xsiTypeString != null)); + !((column.DataType == typeof(object)) || (typeName is not null) || (xsiTypeString is not null)); // Check if we have an attribute telling us value is null. - if ((xsiNilString != null) && XmlConvert.ToBoolean(xsiNilString)) + if ((xsiNilString is not null) && XmlConvert.ToBoolean(xsiNilString)) { if (!useXmlSerializer) { // See if need to set typed null. - if (typeName != null && typeName.Length > 0) + if (typeName is not null && typeName.Length > 0) { // Got type name columnValue = SqlUdtStorage.GetStaticNullForUdtType(DataStorage.GetType(typeName)); } } - if (null == columnValue) + if (columnValue is null) { // If no value, columnValue = DBNull.Value; // change to DBNull; } @@ -1199,7 +1199,7 @@ private void LoadColumn(DataColumn column, object[] foundColumns) { // No NIL attribute. Get value bool skipped = false; - if (column.Table.DataSet != null && column.Table.DataSet._udtIsWrapped) + if (column.Table.DataSet is not null && column.Table.DataSet._udtIsWrapped) { _dataReader.Read(); // if UDT is wrapped, skip the wrapper skipped = true; @@ -1250,7 +1250,7 @@ private void LoadColumn(DataColumn column, object[] foundColumns) StringBuilder builder = null; while (_dataReader.Read() && entryDepth < _dataReader.Depth && IsTextLikeNode(_dataReader.NodeType)) { - if (builder == null) + if (builder is null) { builder = new StringBuilder(text); } @@ -1260,7 +1260,7 @@ private void LoadColumn(DataColumn column, object[] foundColumns) // which would do the same thing but slower. } - if (builder != null) + if (builder is not null) { text = builder.ToString(); } @@ -1285,11 +1285,11 @@ private void LoadColumn(DataColumn column, object[] foundColumns) // Get dataset element for this XML element DataColumn c = o as DataColumn; // Perhaps, it's a column? - if (c != null) + if (c is not null) { // Do we have matched column in this table? // Let's load column data - if (foundColumns[c.Ordinal] == null) + if (foundColumns[c.Ordinal] is null) { // If this column was not found before LoadColumn(c, foundColumns); @@ -1304,7 +1304,7 @@ private void LoadColumn(DataColumn column, object[] foundColumns) { DataTable nestedTable = o as DataTable; // Perhaps, it's a nested table ? - if (nestedTable != null) + if (nestedTable is not null) { // Do we have matched table in DataSet ? LoadTable(nestedTable, true /* isNested */); @@ -1316,7 +1316,7 @@ private void LoadColumn(DataColumn column, object[] foundColumns) DataTable misplacedTable = _nodeToSchemaMap.GetTableForNode(_dataReader, FIgnoreNamespace(_dataReader)); // Try to get table for node - if (misplacedTable != null) + if (misplacedTable is not null) { // Got some table to match? LoadTable(misplacedTable, false /* isNested */); @@ -1342,7 +1342,7 @@ private void LoadColumn(DataColumn column, object[] foundColumns) _dataReader.Read(); // We're done here. To the next element. } - if (0 == text.Length && xsiNilString != null && XmlConvert.ToBoolean(xsiNilString)) + if (0 == text.Length && xsiNilString is not null && XmlConvert.ToBoolean(xsiNilString)) { foundColumns[column.Ordinal] = DBNull.Value; // If no data and NIL attribute is true set value to null diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs index f74bf3799fabd6..2d21ca6f78ad65 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs @@ -106,8 +106,8 @@ public TableSchemaInfo(DataTable tableSchema) public XmlToDatasetMap(DataSet dataSet, XmlNameTable nameTable) { - Debug.Assert(dataSet != null, "DataSet can't be null"); - Debug.Assert(nameTable != null, "NameTable can't be null"); + Debug.Assert(dataSet is not null, "DataSet can't be null"); + Debug.Assert(nameTable is not null, "NameTable can't be null"); BuildIdentityMap(dataSet, nameTable); } @@ -115,8 +115,8 @@ public XmlToDatasetMap(DataSet dataSet, XmlNameTable nameTable) public XmlToDatasetMap(XmlNameTable nameTable, DataSet dataSet) { - Debug.Assert(dataSet != null, "DataSet can't be null"); - Debug.Assert(nameTable != null, "NameTable can't be null"); + Debug.Assert(dataSet is not null, "DataSet can't be null"); + Debug.Assert(nameTable is not null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataSet); } @@ -124,8 +124,8 @@ public XmlToDatasetMap(XmlNameTable nameTable, DataSet dataSet) public XmlToDatasetMap(DataTable dataTable, XmlNameTable nameTable) { - Debug.Assert(dataTable != null, "DataTable can't be null"); - Debug.Assert(nameTable != null, "NameTable can't be null"); + Debug.Assert(dataTable is not null, "DataTable can't be null"); + Debug.Assert(nameTable is not null, "NameTable can't be null"); BuildIdentityMap(dataTable, nameTable); } @@ -133,8 +133,8 @@ public XmlToDatasetMap(DataTable dataTable, XmlNameTable nameTable) public XmlToDatasetMap(XmlNameTable nameTable, DataTable dataTable) { - Debug.Assert(dataTable != null, "DataTable can't be null"); - Debug.Assert(nameTable != null, "NameTable can't be null"); + Debug.Assert(dataTable is not null, "DataTable can't be null"); + Debug.Assert(nameTable is not null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataTable); } internal static bool IsMappedColumn(DataColumn c) @@ -155,7 +155,7 @@ private TableSchemaInfo AddTableSchema(DataTable table, XmlNameTable nameTable) // because it save us time in LoadRows(). We have, as usual, more data them schemas string tableLocalName = nameTable.Get(table.EncodedTableName); string tableNamespace = nameTable.Get(table.Namespace); - if (tableLocalName == null) + if (tableLocalName is null) { // because name of this table isn't present in XML we don't need mapping for it. // Less mapping faster we work. @@ -180,7 +180,7 @@ private TableSchemaInfo AddTableSchema(XmlNameTable nameTable, DataTable table) string tableLocalName = nameTable.Get(_tableLocalName); // Look it up in nametable - if (tableLocalName == null) + if (tableLocalName is null) { // If not found tableLocalName = nameTable.Add(_tableLocalName); // Add it } @@ -189,13 +189,13 @@ private TableSchemaInfo AddTableSchema(XmlNameTable nameTable, DataTable table) string tableNamespace = nameTable.Get(table.Namespace); // Look ip table namespace - if (tableNamespace == null) + if (tableNamespace is null) { // If not found tableNamespace = nameTable.Add(table.Namespace); // Add it } else { - if (table._tableNamespace != null) // Update table namespace + if (table._tableNamespace is not null) // Update table namespace table._tableNamespace = tableNamespace; } @@ -213,7 +213,7 @@ private bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHa { string columnLocalName = nameTable.Get(col.EncodedColumnName); string columnNamespace = nameTable.Get(col.Namespace); - if (columnLocalName == null) + if (columnLocalName is null) { return false; } @@ -235,7 +235,7 @@ private bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHa string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName); string columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table - if (columnLocalName == null) + if (columnLocalName is null) { // Not found? columnLocalName = nameTable.Add(_columnLocalName); // Add it } @@ -244,13 +244,13 @@ private bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHa string columnNamespace = nameTable.Get(col.Namespace); // Get column namespace from nametable - if (columnNamespace == null) + if (columnNamespace is null) { // Not found ? columnNamespace = nameTable.Add(col.Namespace); // Add it } else { - if (col._columnUri != null) // Update namespace + if (col._columnUri is not null) // Update namespace col._columnUri = columnNamespace; } // Create XmlNodeIdentety @@ -273,7 +273,7 @@ private void BuildIdentityMap(DataSet dataSet, XmlNameTable nameTable) foreach (DataTable t in dataSet.Tables) { TableSchemaInfo tableSchemaInfo = AddTableSchema(t, nameTable); - if (tableSchemaInfo != null) + if (tableSchemaInfo is not null) { foreach (DataColumn c in t.Columns) { @@ -301,7 +301,7 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataSet dataSet) string dsNamespace = nameTable.Get(dataSet.Namespace); // Attept to look up DataSet namespace // in the name table - if (dsNamespace == null) + if (dsNamespace is null) { // Found ? dsNamespace = nameTable.Add(dataSet.Namespace); // Nope. Add it } @@ -313,7 +313,7 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataSet dataSet) TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Add table schema info to hash table - if (tableSchemaInfo != null) + if (tableSchemaInfo is not null) { foreach (DataColumn c in t.Columns) { // Add column schema map @@ -337,14 +337,14 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataSet dataSet) string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string tableLocalName = nameTable.Get(_tableLocalName); - if (tableLocalName == null) + if (tableLocalName is null) { tableLocalName = nameTable.Add(_tableLocalName); } string tableNamespace = nameTable.Get(r.ChildTable.Namespace); - if (tableNamespace == null) + if (tableNamespace is null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } @@ -364,7 +364,7 @@ private void BuildIdentityMap(DataTable dataTable, XmlNameTable nameTable) _tableSchemaMap = new XmlNodeIdHashtable(1); TableSchemaInfo tableSchemaInfo = AddTableSchema(dataTable, nameTable); - if (tableSchemaInfo != null) + if (tableSchemaInfo is not null) { foreach (DataColumn c in dataTable.Columns) { @@ -393,7 +393,7 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Create schema info - if (tableSchemaInfo != null) + if (tableSchemaInfo is not null) { foreach (DataColumn c in t.Columns) { // Add column information @@ -415,14 +415,14 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string tableLocalName = nameTable.Get(_tableLocalName); - if (tableLocalName == null) + if (tableLocalName is null) { tableLocalName = nameTable.Add(_tableLocalName); } string tableNamespace = nameTable.Get(r.ChildTable.Namespace); - if (tableNamespace == null) + if (tableNamespace is null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } @@ -457,21 +457,21 @@ private ArrayList GetSelfAndDescendants(DataTable dt) public object GetColumnSchema(XmlNode node, bool fIgnoreNamespace) { - Debug.Assert(node != null, "Argument validation"); + Debug.Assert(node is not null, "Argument validation"); TableSchemaInfo tableSchemaInfo = null; XmlNode nodeRegion = (node.NodeType == XmlNodeType.Attribute) ? ((XmlAttribute)node).OwnerElement : node.ParentNode; do { - if (nodeRegion == null || nodeRegion.NodeType != XmlNodeType.Element) + if (nodeRegion is null || nodeRegion.NodeType != XmlNodeType.Element) { return null; } tableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[nodeRegion.LocalName] : _tableSchemaMap[nodeRegion]); nodeRegion = nodeRegion.ParentNode; - } while (tableSchemaInfo == null); + } while (tableSchemaInfo is null); if (fIgnoreNamespace) return tableSchemaInfo.ColumnsSchemaMap[node.LocalName]; @@ -482,7 +482,7 @@ public object GetColumnSchema(XmlNode node, bool fIgnoreNamespace) public object GetColumnSchema(DataTable table, XmlReader dataReader, bool fIgnoreNamespace) { - if ((_lastTableSchemaInfo == null) || (_lastTableSchemaInfo.TableSchema != table)) + if ((_lastTableSchemaInfo is null) || (_lastTableSchemaInfo.TableSchema != table)) { _lastTableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[table.EncodedTableName] : _tableSchemaMap[table]); } @@ -503,7 +503,7 @@ public object GetSchemaForNode(XmlNode node, bool fIgnoreNamespace) tableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); } // Look up table schema info for it - if (tableSchemaInfo != null) + if (tableSchemaInfo is not null) { // Got info ? return tableSchemaInfo.TableSchema; // Yes, Return table } @@ -514,7 +514,7 @@ public object GetSchemaForNode(XmlNode node, bool fIgnoreNamespace) public DataTable GetTableForNode(XmlReader node, bool fIgnoreNamespace) { TableSchemaInfo tableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); - if (tableSchemaInfo != null) + if (tableSchemaInfo is not null) { _lastTableSchemaInfo = tableSchemaInfo; return _lastTableSchemaInfo.TableSchema; @@ -539,7 +539,7 @@ private void HandleSpecialColumn(DataColumn col, XmlNameTable nameTable, XmlNode tempColumnName = string.Concat(tempColumnName, col.ColumnName.AsSpan(1)); - if (nameTable.Get(tempColumnName) == null) + if (nameTable.Get(tempColumnName) is null) { nameTable.Add(tempColumnName); } 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 7307670eceb503..38b95b7df52ff3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -65,7 +65,7 @@ internal static void AddExtendedProperties(PropertyCollection? props, XmlElement internal static void AddExtendedProperties(PropertyCollection? props, XmlElement node, Type? type) { - if (props != null) + if (props is not null) { foreach (DictionaryEntry entry in props) { @@ -108,7 +108,7 @@ internal static void AddExtendedProperties(PropertyCollection? props, XmlElement internal void AddXdoProperties(object? instance, XmlElement root, XmlDocument xd) { - if (instance == null) + if (instance is null) { return; } @@ -294,7 +294,7 @@ private void GenerateConstraintNames(DataTable table, bool fromTable) string name = constr.ConstraintName; while (_constraintNames!.Contains(name)) { - if (null == builder) + if (builder is null) { builder = new StringBuilder(); } @@ -332,7 +332,7 @@ private void GenerateConstraintNames(DataSet ds) //Does the DS or ANY object in it have ExtendedProperties? private static bool _PropsNotEmpty(PropertyCollection? props) { - return props != null && props.Count != 0; + return props is not null && props.Count != 0; } private bool HaveExtendedProperties(DataSet ds) @@ -371,7 +371,7 @@ private bool HaveExtendedProperties(DataSet ds) internal void WriteSchemaRoot(XmlDocument xd, XmlElement rootSchema, string targetNamespace) { /* - if (_ds != null) + if (_ds is not null) rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName(_ds.DataSetName)); else rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName("NewDataSet")); @@ -388,7 +388,7 @@ internal void WriteSchemaRoot(XmlDocument xd, XmlElement rootSchema, string targ rootSchema.SetAttribute(Keywords.XMLNS, targetNamespace); rootSchema.SetAttribute(Keywords.XMLNS_XSD, Keywords.XSDNS); rootSchema.SetAttribute(Keywords.XMLNS_MSDATA, Keywords.MSDNS); - if ((_ds != null) && (HaveExtendedProperties(_ds))) + if ((_ds is not null) && (HaveExtendedProperties(_ds))) { rootSchema.SetAttribute(Keywords.XMLNS_MSPROP, Keywords.MSPROPNS); } @@ -433,25 +433,25 @@ internal void SetupAutoGenerated(DataTable dt) foreach (Constraint cs in dt.Constraints) { ForeignKeyConstraint? fk = (cs as ForeignKeyConstraint); - if (null != fk) + if (fk is not null) { if (AutoGenerated(fk)) _autogenerated[fk] = fk; else { - if (_autogenerated[fk.Columns[0]] != null) + if (_autogenerated[fk.Columns[0]] is not null) _autogenerated[fk.Columns[0]] = null; - if (_autogenerated[fk.RelatedColumnsReference[0]] != null) + if (_autogenerated[fk.RelatedColumnsReference[0]] is not null) _autogenerated[fk.RelatedColumnsReference[0]] = null; // special case of the ghosted constraints: UniqueConstraint? _constraint = (UniqueConstraint?)fk.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fk.RelatedColumnsReference)); - if (_constraint == null) + if (_constraint is null) continue; - if (_autogenerated[_constraint] != null) + if (_autogenerated[_constraint] is not null) _autogenerated[_constraint] = null; - if (_autogenerated[_constraint.Key.ColumnsReference[0]] != null) + if (_autogenerated[_constraint.Key.ColumnsReference[0]] is not null) _autogenerated[_constraint.Key.ColumnsReference[0]] = null; } } @@ -462,7 +462,7 @@ internal void SetupAutoGenerated(DataTable dt) _autogenerated[unique] = unique; else { - if (_autogenerated[unique.Key.ColumnsReference[0]] != null) + if (_autogenerated[unique.Key.ColumnsReference[0]] is not null) _autogenerated[unique.Key.ColumnsReference[0]] = null; } } @@ -538,7 +538,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT { _constraintNames = new ArrayList(); _autogenerated = new Hashtable(); - bool genSecondary = _filePath != null; //null non-file based streams. + bool genSecondary = _filePath is not null; //null non-file based streams. _dsElement = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); @@ -547,7 +547,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT DataTable _dt = dt!; - if (ds != null) + if (ds is not null) { _ds = ds; foreach (DataTable table in ds.Tables) @@ -557,7 +557,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT } else { - if (dt!.DataSet != null) + if (dt!.DataSet is not null) { // preserve datatable's dataset to use for xml // if null it would write out document element instead of dt.DataSet.DataSetName @@ -580,7 +580,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // Need to writeid attribute on schema, as webservice relys on it for typeddataset deserialization // to get class name - if (_ds != null) + if (_ds is not null) { rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName(_ds.DataSetName)); } @@ -588,7 +588,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT { rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName("NewDataSet")); } - if (_ds != null) + if (_ds is not null) { WriteSchemaRoot(xd, rootSchema, _ds.Namespace); } @@ -600,7 +600,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // register the root element and associated NS if (_schFormat == SchemaFormat.Remoting) { - if (_ds != null) + if (_ds is not null) { _namespaces[_ds.Namespace] = rootSchema; } @@ -612,7 +612,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT if (_schFormat != SchemaFormat.Remoting) { - if (_ds != null) + if (_ds is not null) { _namespaces[_ds.Namespace] = rootSchema; if (_ds.Namespace.Length == 0) @@ -627,7 +627,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT } // Generate all the constraint names - if (ds != null) + if (ds is not null) GenerateConstraintNames(ds); else GenerateConstraintNames(_tables); @@ -635,7 +635,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // Setup AutoGenerated table if (_schFormat != SchemaFormat.Remoting) { - if (ds != null) + if (ds is not null) { SetupAutoGenerated(ds); } @@ -650,7 +650,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // Output all top level elements, which will recursively invoke to other tables. // - top = ((ds != null) ? ds.TopLevelTables(true) : CreateToplevelTables()); + top = ((ds is not null) ? ds.TopLevelTables(true) : CreateToplevelTables()); if (top.Length == 0 || _schFormat == SchemaFormat.WebServiceSkipSchema || _schFormat == SchemaFormat.RemotingSkipSchema) { @@ -678,7 +678,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT _constraintSeparator = xd.CreateElement(Keywords.XSD_PREFIX, "SHOULDNOTBEHERE", Keywords.XSDNS); _dsElement.AppendChild(_constraintSeparator); // DataSet properties - if (_ds != null) + if (_ds is not null) { AddXdoProperties(_ds, _dsElement, xd); AddExtendedProperties(_ds._extendedProperties, _dsElement); @@ -688,11 +688,11 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT for (int i = 0; i < top.Length; i++) { XmlElement el = HandleTable(top[i], xd, rootSchema); - if (((_ds != null) && (_ds.Namespace == top[i].Namespace)) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting)) + if (((_ds is not null) && (_ds.Namespace == top[i].Namespace)) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting)) { bool fNestedInDataset = top[i]._fNestedInDataset; - if (((_ds != null) && (_ds.Namespace.Length != 0)) && string.IsNullOrEmpty(top[i].Namespace)) + if (((_ds is not null) && (_ds.Namespace.Length != 0)) && string.IsNullOrEmpty(top[i].Namespace)) { fNestedInDataset = true; } @@ -728,7 +728,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT { rootSchema.AppendChild(el); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); - if ((_ds != null && _ds.Namespace == top[i].Namespace) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting)) + if ((_ds is not null && _ds.Namespace == top[i].Namespace) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting)) node.SetAttribute(Keywords.REF, top[i].EncodedTableName); else node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]!) + ':' + top[i].EncodedTableName); @@ -754,7 +754,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // Output all non-heirarchical relations without constraints DataRelation[] rels = Array.Empty(); - if (ds != null && _tables.Count > 0) + if (ds is not null && _tables.Count > 0) { // we need to make sure we want to write relation just for tables in list rels = new DataRelation[ds.Relations.Count]; for (int i = 0; i < ds.Relations.Count; i++) @@ -778,9 +778,9 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT if (!rel.Nested || fFlat) { - if (rel.ChildKeyConstraint == null) + if (rel.ChildKeyConstraint is null) { - if (nodeAnn == null) + if (nodeAnn is null) { nodeAnn = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ANNOTATION, Keywords.XSDNS); rootSchema.AppendChild(nodeAnn); @@ -788,7 +788,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT nodeApp = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_APPINFO, Keywords.XSDNS); nodeAnn.AppendChild(nodeApp); } - Debug.Assert(nodeApp != null, "Need to create node first."); + Debug.Assert(nodeApp is not null, "Need to create node first."); nodeApp.AppendChild(HandleRelation(rel, xd)); } } @@ -803,7 +803,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // complete processing of rootSchema foreach (string ns in _namespaces.Keys) { - if (ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace) || string.IsNullOrEmpty(ns)) + if (ns == ((_ds is not null) ? _ds.Namespace : _dt.Namespace) || string.IsNullOrEmpty(ns)) { continue; } @@ -834,7 +834,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT foreach (string ns in _namespaces.Keys) { - if (ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace) || string.IsNullOrEmpty(ns)) + if (ns == ((_ds is not null) ? _ds.Namespace : _dt.Namespace) || string.IsNullOrEmpty(ns)) { continue; } @@ -871,7 +871,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT continue; // don't write out yourself } string? prefix = (string?)_prefixes[imp_ns]; - if (prefix == null) + if (prefix is null) { // only for dataset.Namespace == empty continue; // do nothing } @@ -881,7 +881,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT if (_schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter) { - if (imp_ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace)) + if (imp_ns == ((_ds is not null) ? _ds.Namespace : _dt.Namespace)) _import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, _fileName + _fileExt); // for the dataset namespace don't append anything else _import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, _fileName + "_" + prefix + ".xsd"); @@ -918,7 +918,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT xd.AppendChild(rootSchema); xd.Save(xmlWriter); } - if (comment != null) + if (comment is not null) { rootSchema.PrependChild(comment); } @@ -957,7 +957,7 @@ internal XmlElement SchemaTree(XmlDocument xd, DataTable dt) if (_schFormat != SchemaFormat.Remoting) { - if (_ds != null) + if (_ds is not null) { _namespaces[_ds.Namespace] = rootSchema; if (_ds.Namespace.Length == 0) @@ -1005,15 +1005,15 @@ internal XmlElement SchemaTree(XmlDocument xd, DataTable dt) internal XmlElement FillDataSetElement(XmlDocument xd, DataSet? ds, DataTable? dt) { - Debug.Assert(ds == null || dt == null); - Debug.Assert(_dsElement != null); + Debug.Assert(ds is null || dt is null); + Debug.Assert(_dsElement is not null); - DataSet? dataSet = (ds != null) ? ds : dt!.DataSet; - if (dataSet != null) + DataSet? dataSet = (ds is not null) ? ds : dt!.DataSet; + if (dataSet is not null) { _dsElement.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(dataSet.DataSetName)); _dsElement.SetAttribute(Keywords.MSD_ISDATASET, Keywords.MSDNS, Keywords.TRUE); - if (ds == null) + if (ds is null) _dsElement.SetAttribute(Keywords.MSD_MAINDATATABLE, Keywords.MSDNS, XmlConvert.EncodeLocalName(((dt!.Namespace.Length == 0) ? dt.TableName : (dt.Namespace + ":" + dt.TableName)))); // Add CaseSensitive and locale properties @@ -1032,7 +1032,7 @@ internal XmlElement FillDataSetElement(XmlDocument xd, DataSet? ds, DataTable? d } else { // No DataSet - if (dt != null) + if (dt is not null) { _dsElement.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName("NewDataSet")); _dsElement.SetAttribute(Keywords.MSD_ISDATASET, Keywords.MSDNS, Keywords.TRUE); @@ -1069,15 +1069,15 @@ internal void SetPath(XmlWriter xw) FileStream? fs = null; DataTextWriter? sw = xw as DataTextWriter; - fs = (sw != null) ? sw.BaseStream as FileStream : null; + fs = (sw is not null) ? sw.BaseStream as FileStream : null; - if (fs == null) + if (fs is null) { XmlTextWriter? textw = xw as XmlTextWriter; - if (textw == null) + if (textw is null) return; fs = textw.BaseStream as FileStream; - if (fs == null) + if (fs is null) return; } @@ -1141,10 +1141,10 @@ internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) root.SetAttribute(Keywords.MSD_PARENT, Keywords.MSDNS, rel.ParentKey.Table.EncodedTableName); root.SetAttribute(Keywords.MSD_CHILD, Keywords.MSDNS, rel.ChildKey.Table.EncodedTableName); - if ((_ds == null) || (_ds.Tables.InternalIndexOf(rel.ParentKey.Table.TableName) == -3)) + if ((_ds is null) || (_ds.Tables.InternalIndexOf(rel.ParentKey.Table.TableName) == -3)) root.SetAttribute(Keywords.MSD_PARENTTABLENS, Keywords.MSDNS, rel.ParentKey.Table.Namespace); - if ((_ds == null) || (_ds.Tables.InternalIndexOf(rel.ChildKey.Table.TableName) == -3)) + if ((_ds is null) || (_ds.Tables.InternalIndexOf(rel.ChildKey.Table.TableName) == -3)) root.SetAttribute(Keywords.MSD_CHILDTABLENS, Keywords.MSDNS, rel.ChildKey.Table.Namespace); DataColumn[] key = rel.ParentKey.ColumnsReference; @@ -1167,7 +1167,7 @@ internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) text = key[0].EncodedColumnName; if (1 < key.Length) { - if (null != builder) + if (builder is not null) { builder.Length = 0; } @@ -1189,7 +1189,7 @@ internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) private static XmlElement? FindSimpleType(XmlElement schema, string name) { - for (XmlNode? n = schema.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = schema.FirstChild; n is not null; n = n.NextSibling) { if (n is XmlElement) { @@ -1206,7 +1206,7 @@ internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) internal XmlElement GetSchema(string NamespaceURI) { XmlElement? schemaEl = (XmlElement?)_namespaces![NamespaceURI]; - if (schemaEl == null) + if (schemaEl is null) { schemaEl = _dc!.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); WriteSchemaRoot(_dc, schemaEl, NamespaceURI); @@ -1224,34 +1224,34 @@ internal XmlElement GetSchema(string NamespaceURI) internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, XmlElement schema) { - Debug.Assert(_prefixes != null); + Debug.Assert(_prefixes is not null); string keyword = Keywords.TYPE; if (col.ColumnMapping == MappingType.SimpleContent) keyword = Keywords.BASE; - if (col.SimpleType != null) + if (col.SimpleType is not null) { // generate simpleType node SimpleType? stNode = col.SimpleType; - while (stNode != null) + while (stNode is not null) { // for remoting, set the msdata:targetNamespace for the simpleType. XmlNode type; string? name = stNode.Name; - if (name != null && name.Length != 0) + if (name is not null && name.Length != 0) { // For remoting, always need to work with root schema's namespace string nSpace = (_schFormat != SchemaFormat.Remoting) ? stNode.Namespace : - (col.Table!.DataSet != null ? col.Table.DataSet.Namespace : col.Table.Namespace); + (col.Table!.DataSet is not null ? col.Table.DataSet.Namespace : col.Table.Namespace); // for remoting we need to use columns NS, for other cases it is wrong to get Columns NS, we need to take type's namespace XmlElement schNode = GetSchema(nSpace); //SchNode To Ensure BaseSimpleType Prefix is Generated - if (stNode.BaseSimpleType != null && stNode.BaseSimpleType.Namespace != null && stNode.BaseSimpleType.Namespace.Length > 0) + if (stNode.BaseSimpleType is not null && stNode.BaseSimpleType.Namespace is not null && stNode.BaseSimpleType.Namespace.Length > 0) GetSchema(stNode.BaseSimpleType.Namespace); //it will ensure a prefix has been created for this namespace type = stNode.ToNode(dc, _prefixes, (_schFormat == SchemaFormat.Remoting)); @@ -1260,7 +1260,7 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, { string? prefix = (string?)_prefixes[nSpace]; // set the columns's type - if (prefix != null && prefix.Length > 0) + if (prefix is not null && prefix.Length > 0) { if (_schFormat != SchemaFormat.Remoting) root.SetAttribute(keyword, (prefix + ":" + name)); // look at below,this loop assumes we would be here just oen time: Its Wrong @@ -1273,7 +1273,7 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, } XmlElement? elmSimpeType = FindSimpleType(schNode, name); - if (elmSimpeType == null) + if (elmSimpeType is null) { // if we don't have the defenition for this simpleType yet. Add it schNode.AppendChild(type); @@ -1289,7 +1289,7 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, else { //SchNode To Ensure BaseSimpleType Prefix is Generated - if (stNode.BaseSimpleType != null && stNode.BaseSimpleType.Namespace != null && stNode.BaseSimpleType.Namespace.Length > 0) + if (stNode.BaseSimpleType is not null && stNode.BaseSimpleType.Namespace is not null && stNode.BaseSimpleType.Namespace.Length > 0) GetSchema(stNode.BaseSimpleType.Namespace); //it will ensure a prefix has been created for this namespace type = stNode.ToNode(dc, _prefixes, _schFormat == SchemaFormat.Remoting); root.AppendChild(type); @@ -1298,14 +1298,14 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, stNode = stNode.BaseSimpleType; } } - else if (col.XmlDataType != null && col.XmlDataType.Length != 0 && XSDSchema.IsXsdType(col.XmlDataType)) + else if (col.XmlDataType is not null && col.XmlDataType.Length != 0 && XSDSchema.IsXsdType(col.XmlDataType)) { root.SetAttribute(keyword, XSDSchema.QualifiedName(col.XmlDataType)); } 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 (typeName is null || typeName.Length == 0) { if (col.DataType == typeof(Guid) || col.DataType == typeof(Type)) { @@ -1404,8 +1404,8 @@ private string FindTargetNamespace(DataTable table) internal XmlElement HandleColumn(DataColumn col, XmlDocument dc, XmlElement schema, bool fWriteOrdinal) { - Debug.Assert(_prefixes != null); - Debug.Assert(_dc != null); + Debug.Assert(_prefixes is not null); + Debug.Assert(_dc is not null); XmlElement root; int minOccurs; @@ -1493,7 +1493,7 @@ internal XmlElement HandleColumn(DataColumn col, XmlDocument dc, XmlElement sche if ((col.Namespace != (col.Table!.TypeName.IsEmpty ? col.Table.Namespace : col.Table.TypeName.Namespace)) && (col.Namespace.Length != 0)) { XmlElement schNode = GetSchema(col.Namespace); - if (FindTypeNode(schNode, col.EncodedColumnName) == null) + if (FindTypeNode(schNode, col.EncodedColumnName) is null) schNode.AppendChild(root); root = _dc.CreateElement(Keywords.XSD_PREFIX, refString, Keywords.XSDNS); root.SetAttribute(Keywords.REF, _prefixes[col.Namespace] + ":" + col.EncodedColumnName); @@ -1549,16 +1549,16 @@ internal static string TranslateRule(Rule rule) => internal void AppendChildWithoutRef(XmlElement node, string Namespace, XmlElement el, string refString) { XmlElement schNode = GetSchema(Namespace); - if (FindTypeNode(schNode, el.GetAttribute(Keywords.NAME)) == null) + if (FindTypeNode(schNode, el.GetAttribute(Keywords.NAME)) is null) schNode.AppendChild(el); } internal XmlElement? FindTypeNode(XmlElement node, string strType) { - if (node == null) + if (node is null) return null; - for (XmlNode? n = node.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = node.FirstChild; n is not null; n = n.NextSibling) { if (!(n is XmlElement)) continue; @@ -1672,7 +1672,7 @@ internal static bool AutoGenerated(ForeignKeyConstraint fk, bool checkRelation) DataRelation? rel = fk.FindParentRelation(); if (checkRelation) { - if (rel == null) + if (rel is null) return false; // otherwise roundtrip will create column if (!AutoGenerated(rel)) @@ -1702,21 +1702,21 @@ internal static bool AutoGenerated(ForeignKeyConstraint fk, bool checkRelation) private bool IsAutoGenerated(object o) { if (_schFormat != SchemaFormat.Remoting) - return _autogenerated[o] != null; + return _autogenerated[o] is not null; return false; } internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement schema, bool genNested) { - Debug.Assert(_prefixes != null); - Debug.Assert(_dc != null); - Debug.Assert(_dsElement != null); + Debug.Assert(_prefixes is not null); + Debug.Assert(_dc is not null); + Debug.Assert(_dsElement is not null); XmlElement root = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); bool fWriteOrdinals = false; bool fUnqualified = false; - if (((table.DataSet == null) || (_ds != null && table.Namespace != _ds.Namespace)) && (_schFormat == SchemaFormat.Remoting)) + if (((table.DataSet is null) || (_ds is not null && table.Namespace != _ds.Namespace)) && (_schFormat == SchemaFormat.Remoting)) root.SetAttribute(Keywords.TARGETNAMESPACE, Keywords.MSDNS, table.Namespace); // First add any attributes. @@ -1731,7 +1731,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche DataRelation[] nestedParentRelations = _table.NestedParentRelations; if (nestedParentRelations.Length == 0) { - tgNamespace = (_ds != null) ? _ds.Namespace : ""; + tgNamespace = (_ds is not null) ? _ds.Namespace : ""; break; } int nestedparentPosition = -1; // it is find non-self-nested-parent @@ -1804,7 +1804,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 (_typeName is null || _typeName.Length == 0) { _typeName = Keywords.XSD_ANYTYPE; } @@ -1821,13 +1821,13 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche XmlElement typeSchema = GetSchema(table.TypeName.Namespace); if (string.IsNullOrEmpty(table.TypeName.Namespace)) { - if (_ds == null) + if (_ds is null) typeSchema = GetSchema(table.Namespace); else typeSchema = fUnqualified ? GetSchema(_ds.Namespace) : GetSchema(table.Namespace); } - if (FindTypeNode(typeSchema, table.TypeName.Name) == null) + if (FindTypeNode(typeSchema, table.TypeName.Name) is null) typeSchema.AppendChild(type); type.SetAttribute(Keywords.NAME, table.TypeName.Name); @@ -1847,7 +1847,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche DataColumn? colTxt = table.XmlText; - if (colTxt != null) + if (colTxt is not null) { XmlElement sc = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SIMPLECONTENT, Keywords.XSDNS); @@ -1900,7 +1900,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche } } - if ((table.XmlText == null) && (genNested)) + if ((table.XmlText is null) && (genNested)) { DataRelationCollection childRelations = table.ChildRelations; @@ -1946,7 +1946,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche compositor.AppendChild(NestedTable); } - if (childRelations[j].ChildKeyConstraint != null) + if (childRelations[j].ChildKeyConstraint is not null) continue; // we write the relation using the constraint XmlElement nodeAnn = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ANNOTATION, Keywords.XSDNS); @@ -1959,7 +1959,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche } } - if (compositor != null) + if (compositor is not null) if (!compositor.HasChildNodes) type.RemoveChild(compositor); @@ -1968,7 +1968,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche ConstraintCollection constraints = table.Constraints; XmlElement selector, field; - string xpathprefix = (_ds != null) ? (_ds.Namespace.Length != 0 ? Keywords.MSTNS_PREFIX : string.Empty) : string.Empty; + string xpathprefix = (_ds is not null) ? (_ds.Namespace.Length != 0 ? Keywords.MSTNS_PREFIX : string.Empty) : string.Empty; if (_schFormat != SchemaFormat.Remoting) { GetSchema(table.Namespace); // to ensure prefix handling @@ -1993,7 +1993,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_UNIQUE, Keywords.XSDNS); - if ((_ds == null) || (_ds.Tables.InternalIndexOf(table.TableName) == -3)) + if ((_ds is null) || (_ds.Tables.InternalIndexOf(table.TableName) == -3)) constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, table.Namespace); // convert constraint name to valid xml name constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(unique.SchemaName)); @@ -2070,12 +2070,12 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche UniqueConstraint? _constraint = (UniqueConstraint?)foreign.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fields)); - if (_constraint == null) + if (_constraint is null) { constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_KEY, Keywords.XSDNS); constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(foreign.SchemaName)); - if ((_ds == null) || (_ds.Tables.InternalIndexOf(table.TableName) == -3)) + if ((_ds is null) || (_ds.Tables.InternalIndexOf(table.TableName) == -3)) constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, table.Namespace); selector = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SELECTOR, Keywords.XSDNS); @@ -2121,10 +2121,10 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche // convert constraint name to valid xml name constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(foreign.SchemaName)); - if ((_ds == null) || (_ds.Tables.InternalIndexOf(foreign.RelatedTable.TableName) == -3)) // if there is a conflicting name/namespace only + if ((_ds is null) || (_ds.Tables.InternalIndexOf(foreign.RelatedTable.TableName) == -3)) // if there is a conflicting name/namespace only constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, foreign.Table!.Namespace); - if (_constraint == null) + if (_constraint is null) constraint.SetAttribute(Keywords.REFER, XmlConvert.EncodeLocalName(foreign.SchemaName)); else constraint.SetAttribute(Keywords.REFER, XmlConvert.EncodeLocalName(_constraint.SchemaName)); @@ -2134,7 +2134,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche if (foreign.ConstraintName != foreign.SchemaName) constraint.SetAttribute(Keywords.MSD_CONSTRAINTNAME, Keywords.MSDNS, foreign.ConstraintName); - if (null == rel) + if (rel is null) { constraint.SetAttribute(Keywords.MSD_CONSTRAINTONLY, Keywords.MSDNS, Keywords.TRUE); } @@ -2343,14 +2343,14 @@ internal void Save(XmlWriter xmlw, DataTable? table) if (!EmptyData()) { // write the datapart - if (table != null) + if (table is not null) new XmlDataTreeWriter(table, _writeHierarchy).SaveDiffgramData(_xmlw, _rowsOrder); else new XmlDataTreeWriter(_ds!).SaveDiffgramData(_xmlw, _rowsOrder); // Walk the xd using relational apis and create nodes in nodeRoot appropriately. - if (table == null) + if (table is null) { for (int i = 0; i < _ds!.Tables.Count; ++i) { @@ -2368,7 +2368,7 @@ internal void Save(XmlWriter xmlw, DataTable? table) if (_fBefore) _xmlw.WriteEndElement(); //SQL_BEFORE - if (table == null) + if (table is null) { for (int i = 0; i < _ds!.Tables.Count; ++i) { @@ -2436,7 +2436,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 (error is null || error.Length == 0) { continue; } @@ -2486,7 +2486,7 @@ private void GenerateRow(DataRow row) if ((state == DataRowState.Deleted) && (row.Table.NestedParentRelations.Length != 0)) { DataRow? parentRow = row.GetNestedParentRow(DataRowVersion.Original); - if (parentRow != null) + if (parentRow is not null) { parentId = parentRow.Table.TableName + parentRow.rowID.ToString(CultureInfo.InvariantCulture); } @@ -2503,7 +2503,7 @@ private void GenerateRow(DataRow row) if ((state == DataRowState.Deleted) && XmlDataTreeWriter.RowHasErrors(row)) _xmlw.WriteAttributeString(Keywords.DFF, Keywords.HASERRORS, Keywords.DFFNS, Keywords.TRUE); - if (parentId != null) + if (parentId is not null) _xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFPID, Keywords.DFFNS, parentId); _xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder[row]!.ToString()); @@ -2527,7 +2527,7 @@ private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version) string? value = null; value = col.GetColumnValueAsString(row, version); // this is useless for CTD - if (value == null) + if (value is null) { if (col.ColumnMapping == MappingType.SimpleContent) _xmlw.WriteAttributeString(Keywords.XSI, Keywords.XSI_NIL, Keywords.XSINS, Keywords.TRUE); @@ -2640,7 +2640,7 @@ private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version) internal static string QualifiedName(string prefix, string name) { - if (prefix != null) + if (prefix is not null) return prefix + ":" + name; return name; @@ -2677,7 +2677,7 @@ internal XmlDataTreeWriter(DataTable dt, bool writeHierarchy) { _dt = dt; _fFromTable = true; - if (dt.DataSet == null) + if (dt.DataSet is null) { _dTables.Add(dt); _topLevelTables = new DataTable[] { dt }; @@ -2759,7 +2759,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 (error is null || error.Length == 0) { continue; } @@ -2774,16 +2774,16 @@ internal static bool RowHasErrors(DataRow row) internal void SaveDiffgramData(XmlWriter xw, Hashtable rowsOrder) { - Debug.Assert(_ds != null || _dt != null); + Debug.Assert(_ds is not null || _dt is not null); _xmlw = DataTextWriter.CreateWriter(xw); _isDiffgram = true; _rowsOrder = rowsOrder; - string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); + string prefix = (_ds is not null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); - if (_ds == null || _ds.DataSetName == null || _ds.DataSetName.Length == 0) - _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, (_dt!.Namespace == null) ? "" : _dt.Namespace); + if (_ds is null || _ds.DataSetName is null || _ds.DataSetName.Length == 0) + _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, (_dt!.Namespace is null) ? "" : _dt.Namespace); else _xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace); @@ -2817,16 +2817,16 @@ internal void SaveDiffgramData(XmlWriter xw, Hashtable rowsOrder) internal void Save(XmlWriter xw, bool writeSchema) { - Debug.Assert(_ds != null || _dt != null); + Debug.Assert(_ds is not null || _dt is not null); _xmlw = DataTextWriter.CreateWriter(xw); int countTopTable = _topLevelTables.Length; bool fWriteDSElement = true; - string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); + string prefix = (_ds is not null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); - if (!writeSchema && _ds != null && _ds._fTopLevelTable && countTopTable == 1) + if (!writeSchema && _ds is not null && _ds._fTopLevelTable && countTopTable == 1) { if (_ds.TopLevelTables()[0].Rows.Count == 1) fWriteDSElement = false; @@ -2834,13 +2834,13 @@ internal void Save(XmlWriter xw, bool writeSchema) if (fWriteDSElement) { - if (_ds == null) + if (_ds is null) { _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _dt!.Namespace); } else { - if (_ds.DataSetName == null || _ds.DataSetName.Length == 0) + if (_ds.DataSetName is null || _ds.DataSetName.Length == 0) _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _ds.Namespace); else _xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace); @@ -2848,7 +2848,7 @@ internal void Save(XmlWriter xw, bool writeSchema) for (int i = 0; i < _dTables.Count; i++) { - if (((DataTable)_dTables[i]!)._xmlText != null) + if (((DataTable)_dTables[i]!)._xmlText is not null) { _xmlw.WriteAttributeString(Keywords.XMLNS, Keywords.XSI, Keywords.XSD_XMLNS_NS, Keywords.XSINS); break; @@ -2909,7 +2909,7 @@ private ArrayList GetNestedChildRelations(DataRow row) internal void XmlDataRowWriter(DataRow row, string encodedTableName) { - Debug.Assert(_xmlw != null); + Debug.Assert(_xmlw is not null); object value; string prefix = (row.Table.Namespace.Length == 0) ? "" : row.Table.Prefix; @@ -3062,7 +3062,7 @@ internal void XmlDataRowWriter(DataRow row, string encodedTableName) } } //end foreach - if (_ds != null) + if (_ds is not null) foreach (DataRelation dr in GetNestedChildRelations(row)) { foreach (DataRow r in row.GetChildRows(dr)) @@ -3075,7 +3075,7 @@ internal void XmlDataRowWriter(DataRow row, string encodedTableName) } internal static bool PreserveSpace(object value) { - Debug.Assert(value != null, "Value can not be null"); + Debug.Assert(value is not null, "Value can not be null"); string tempValue = value.ToString()!; if (tempValue.Length == 0) { @@ -3111,7 +3111,7 @@ internal Stream? BaseStream get { XmlTextWriter? textWriter = _xmltextWriter as XmlTextWriter; - if (null != textWriter) + if (textWriter is not null) { return textWriter.BaseStream; } diff --git a/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs index ed8b41d8a8be7b..ac9d327f530482 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs @@ -55,7 +55,7 @@ internal bool NextRightRowElement() [MemberNotNullWhen(true, nameof(CurrentNode))] internal bool OnRowElement() { - return CurrentNode is XmlBoundElement be && be.Row != null; + return CurrentNode is XmlBoundElement be && be.Row is not null; } } } diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs b/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs index 1fc9394dd1253c..84cd86d7f4b1fe 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs @@ -124,10 +124,10 @@ public override bool MoveToFirst() => public override bool MoveTo(XPathNavigator other) { - if (other != null) + if (other is not null) { DataDocumentXPathNavigator? otherDataDocXPathNav = other as DataDocumentXPathNavigator; - if (otherDataDocXPathNav != null && _curNode.MoveTo(otherDataDocXPathNav.CurNode)) + if (otherDataDocXPathNav is not null && _curNode.MoveTo(otherDataDocXPathNav.CurNode)) { _doc = _curNode.Document; return true; @@ -141,10 +141,10 @@ public override bool MoveTo(XPathNavigator other) public override bool IsSamePosition(XPathNavigator other) { - if (other != null) + if (other is not null) { DataDocumentXPathNavigator? otherDataDocXPathNav = other as DataDocumentXPathNavigator; - if (otherDataDocXPathNav != null && + if (otherDataDocXPathNav is not null && _doc == otherDataDocXPathNav.Document && _curNode.IsSamePosition(otherDataDocXPathNav.CurNode)) { return true; @@ -159,14 +159,14 @@ public override bool IsSamePosition(XPathNavigator other) public override XmlNodeOrder ComparePosition(XPathNavigator? other) { - if (other == null) + if (other is null) { return XmlNodeOrder.Unknown; // this is what XPathDocument does. } DataDocumentXPathNavigator? otherDataDocXPathNav = other as DataDocumentXPathNavigator; - return otherDataDocXPathNav == null || otherDataDocXPathNav.Document != _doc ? + return otherDataDocXPathNav is null || otherDataDocXPathNav.Document != _doc ? XmlNodeOrder.Unknown : _curNode.ComparePosition(otherDataDocXPathNav.CurNode); } diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs index d04cd7d46fed03..fb165c728e5f87 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs @@ -45,11 +45,11 @@ internal DataPointer(DataPointer pointer) private XmlBoundElement? GetRowElement() { XmlBoundElement? rowElem; - if (_column != null) + if (_column is not null) { rowElem = _node as XmlBoundElement; - Debug.Assert(rowElem != null); - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem is not null); + Debug.Assert(rowElem.Row is not null); return rowElem; } @@ -62,18 +62,18 @@ private DataRow? Row get { XmlBoundElement? rowElem = GetRowElement(); - if (rowElem == null) + if (rowElem is null) { return null; } - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); return rowElem.Row; } } private static bool IsFoliated(XmlNode node) => - node != null && node is XmlBoundElement ? + node is not null && node is XmlBoundElement ? ((XmlBoundElement)node).IsFoliated : true; internal void MoveTo(DataPointer pointer) @@ -120,7 +120,7 @@ private void MoveTo(XmlNode node, DataColumn? column, bool fOnValue) DataTable table = row.Table; DataColumnCollection columns = table.Columns; - int iColumn = (col != null) ? col.Ordinal + 1 : 0; + int iColumn = (col is not null) ? col.Ordinal + 1 : 0; int cColumns = columns.Count; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; @@ -139,7 +139,7 @@ private void MoveTo(XmlNode node, DataColumn? column, bool fOnValue) private DataColumn? NthColumn(DataRow row, bool fAttribute, int iColumn, bool fNulls) { DataColumn? c = null; - while ((c = NextColumn(row, c, fAttribute, fNulls)) != null) + while ((c = NextColumn(row, c, fAttribute, fNulls)) is not null) { if (iColumn == 0) { @@ -155,7 +155,7 @@ private int ColumnCount(DataRow row, bool fAttribute, bool fNulls) { DataColumn? c = null; int count = 0; - while ((c = NextColumn(row, c, fAttribute, fNulls)) != null) + while ((c = NextColumn(row, c, fAttribute, fNulls)) is not null) { count++; } @@ -166,12 +166,12 @@ internal bool MoveToFirstChild() { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return false; } - if (_column != null) + if (_column is not null) { if (_fOnValue) { @@ -185,7 +185,7 @@ internal bool MoveToFirstChild() { // find virtual column elements first DataColumn? c = NextColumn(Row!, null, false, false); - if (c != null) + if (c is not null) { MoveTo(_node, c, _doc.IsTextOnly(c)); return true; @@ -194,7 +194,7 @@ internal bool MoveToFirstChild() // look for anything XmlNode? n = _doc.SafeFirstChild(_node); - if (n != null) + if (n is not null) { MoveTo(n); return true; @@ -207,9 +207,9 @@ internal bool MoveToNextSibling() { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column != null) + if (_column is not null) { if (_fOnValue && !_doc.IsTextOnly(_column)) { @@ -217,14 +217,14 @@ internal bool MoveToNextSibling() } DataColumn? c = NextColumn(Row!, _column, false, false); - if (c != null) + if (c is not null) { MoveTo(_node, c, false); return true; } XmlNode? n = _doc.SafeFirstChild(_node); - if (n != null) + if (n is not null) { MoveTo(n); return true; @@ -233,7 +233,7 @@ internal bool MoveToNextSibling() else { XmlNode? n = _doc.SafeNextSibling(_node); - if (n != null) + if (n is not null) { MoveTo(n); return true; @@ -248,9 +248,9 @@ internal bool MoveToParent() { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column != null) + if (_column is not null) { if (_fOnValue && !_doc.IsTextOnly(_column)) { @@ -267,7 +267,7 @@ internal bool MoveToParent() else { XmlNode? n = _node.ParentNode; - if (n != null) + if (n is not null) { MoveTo(n); return true; @@ -281,9 +281,9 @@ internal bool MoveToOwnerElement() { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column != null) + if (_column is not null) { if (_fOnValue || _doc.IsTextOnly(_column) || _column.ColumnMapping != MappingType.Attribute) { @@ -296,7 +296,7 @@ internal bool MoveToOwnerElement() else if (_node.NodeType == XmlNodeType.Attribute) { XmlNode? n = ((XmlAttribute)_node).OwnerElement; - if (n != null) + if (n is not null) { MoveTo(n, null, false); return true; @@ -314,9 +314,9 @@ internal int AttributeCount { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column == null && _node.NodeType == XmlNodeType.Element) + if (_column is null && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) { @@ -341,14 +341,14 @@ internal bool MoveToAttribute(int i) return false; } - if (_node != null) + if (_node is not null) { - if ((_column == null || _column.ColumnMapping == MappingType.Attribute) && _node.NodeType == XmlNodeType.Element) + if ((_column is null || _column.ColumnMapping == MappingType.Attribute) && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) { DataColumn? c = NthColumn(Row!, true, i, false); - if (c != null) + if (c is not null) { MoveTo(_node, c, false); return true; @@ -357,7 +357,7 @@ internal bool MoveToAttribute(int i) else { XmlNode? n = _node.Attributes!.Item(i); - if (n != null) + if (n is not null) { MoveTo(n, null, false); return true; @@ -374,11 +374,11 @@ internal XmlNodeType NodeType { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return XmlNodeType.None; } - else if (_column == null) + else if (_column is null) { return _node.NodeType; } @@ -403,14 +403,14 @@ internal string LocalName { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { string name = _node.LocalName; - Debug.Assert(name != null); + Debug.Assert(name is not null); if (IsLocalNameEmpty(_node.NodeType)) { return string.Empty; @@ -435,11 +435,11 @@ internal string NamespaceURI { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { return _node.NamespaceURI; } @@ -460,15 +460,15 @@ internal string Name { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { string name = _node.Name; //Again it could be String.Empty at null position - Debug.Assert(name != null); + Debug.Assert(name is not null); if (IsLocalNameEmpty(_node.NodeType)) { return string.Empty; @@ -479,9 +479,9 @@ internal string Name { string prefix = Prefix; string lname = LocalName; - if (prefix != null && prefix.Length > 0) + if (prefix is not null && prefix.Length > 0) { - if (lname != null && lname.Length > 0) + if (lname is not null && lname.Length > 0) { return _doc.NameTable.Add(prefix + ":" + lname); } @@ -533,11 +533,11 @@ internal string Prefix { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { return _node.Prefix; } @@ -554,11 +554,11 @@ internal string? Value { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return null; } - else if (_column == null) + else if (_column is null) { return _node.Value; } @@ -601,7 +601,7 @@ internal bool IsEmptyElement { RealFoliate(); AssertValid(); - if (_node != null && _column == null) + if (_node is not null && _column is null) { if (_node.NodeType == XmlNodeType.Element) { @@ -618,7 +618,7 @@ internal bool IsDefault { RealFoliate(); AssertValid(); - if (_node != null && _column == null && _node.NodeType == XmlNodeType.Attribute) + if (_node is not null && _column is null && _node.NodeType == XmlNodeType.Attribute) { return !((XmlAttribute)_node).Specified; } @@ -633,7 +633,7 @@ void IXmlDataVirtualNode.OnFoliated(XmlNode foliatedNode) if (_node == foliatedNode) { // if already on this node, nothing to do! - if (_column == null) + if (_column is null) { return; } @@ -662,20 +662,20 @@ internal void RealFoliate() } else { - for (n = _node.FirstChild; n != null; n = n.NextSibling) + for (n = _node.FirstChild; n is not null; n = n.NextSibling) { if (n.LocalName == _column.EncodedColumnName && n.NamespaceURI == _column.Namespace) break; } } - if (n != null && _fOnValue) + if (n is not null && _fOnValue) { n = n.FirstChild; } } - if (n == null) + if (n is null) { throw new InvalidOperationException(SR.DataDom_Foliation); } @@ -689,7 +689,7 @@ internal void RealFoliate() _bNeedFoliate = false; } - //for the 6 properties below, only when the this.column == null that the nodetype could be XmlDeclaration node + //for the 6 properties below, only when the this.column is null that the nodetype could be XmlDeclaration node internal string? PublicId { get @@ -699,17 +699,17 @@ internal string? PublicId { case XmlNodeType.DocumentType: { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlDocumentType)(_node)).PublicId; } case XmlNodeType.Entity: { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlEntity)(_node)).PublicId; } case XmlNodeType.Notation: { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlNotation)(_node)).PublicId; } } @@ -726,17 +726,17 @@ internal string? SystemId { case XmlNodeType.DocumentType: { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlDocumentType)(_node)).SystemId; } case XmlNodeType.Entity: { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlEntity)(_node)).SystemId; } case XmlNodeType.Notation: { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlNotation)(_node)).SystemId; } } @@ -750,7 +750,7 @@ internal string? InternalSubset { if (NodeType == XmlNodeType.DocumentType) { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlDocumentType)(_node)).InternalSubset; } return null; @@ -762,7 +762,7 @@ internal XmlDeclaration? Declaration get { XmlNode? child = _doc.SafeFirstChild(_doc); - if (child != null && child.NodeType == XmlNodeType.XmlDeclaration) + if (child is not null && child.NodeType == XmlNodeType.XmlDeclaration) return (XmlDeclaration)child; return null; } @@ -774,13 +774,13 @@ internal string? Encoding { if (NodeType == XmlNodeType.XmlDeclaration) { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlDeclaration)(_node)).Encoding; } else if (NodeType == XmlNodeType.Document) { XmlDeclaration? dec = Declaration; - if (dec != null) + if (dec is not null) { return dec.Encoding; } @@ -795,13 +795,13 @@ internal string? Standalone { if (NodeType == XmlNodeType.XmlDeclaration) { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlDeclaration)(_node)).Standalone; } else if (NodeType == XmlNodeType.Document) { XmlDeclaration? dec = Declaration; - if (dec != null) + if (dec is not null) { return dec.Standalone; } @@ -816,13 +816,13 @@ internal string? Version { if (NodeType == XmlNodeType.XmlDeclaration) { - Debug.Assert(_column == null); + Debug.Assert(_column is null); return ((XmlDeclaration)(_node)).Version; } else if (NodeType == XmlNodeType.Document) { XmlDeclaration? dec = Declaration; - if (dec != null) + if (dec is not null) return dec.Version; } return null; @@ -833,14 +833,14 @@ internal string? Version private void AssertValid() { // This pointer must be int the document list - if (_column != null) + if (_column is not null) { // We must be on a de-foliated region XmlBoundElement? rowElem = _node as XmlBoundElement; - Debug.Assert(rowElem != null); + Debug.Assert(rowElem is not null); DataRow? row = rowElem.Row; - Debug.Assert(row != null); + Debug.Assert(row is not null); ElementState state = rowElem.ElementState; Debug.Assert(state == ElementState.Defoliated, "Region is accessed using column, but it's state is FOLIATED"); diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs index 55480193f85f2d..a278efcd43784f 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs @@ -14,7 +14,7 @@ namespace System.Xml // Maps XML nodes to schema // // With the exception of some functions (the most important is SearchMatchingTableSchema) all functions expect that each region rowElem is already associated - // w/ it's DataRow (basically the test to determine a rowElem is based on a != null associated DataRow). As a result of this, some functions will NOT work properly + // w/ it's DataRow (basically the test to determine a rowElem is based on a is not null associated DataRow). As a result of this, some functions will NOT work properly // when they are used on a tree for which rowElem's are not associated w/ a DataRow. // @@ -29,7 +29,7 @@ internal sealed class DataSetMapper internal DataSetMapper() { - Debug.Assert(_dataSet == null); + Debug.Assert(_dataSet is null); _tableSchemaMap = new Hashtable(); _columnSchemaMap = new Hashtable(); } @@ -59,7 +59,7 @@ internal void SetupMapping(XmlDataDocument xd, DataSet ds) } } - internal bool IsMapped() => _dataSet != null; + internal bool IsMapped() => _dataSet is not null; internal DataTable SearchMatchingTableSchema(string localName, string namespaceURI) { @@ -86,24 +86,24 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU // internal DataTable? SearchMatchingTableSchema(XmlBoundElement? rowElem, XmlBoundElement elem) { - Debug.Assert(elem != null); + Debug.Assert(elem is not null); DataTable t = SearchMatchingTableSchema(elem.LocalName, elem.NamespaceURI); - if (t == null) + if (t is null) { return null; } - if (rowElem == null) + if (rowElem is null) { return t; } // Currently we expect we map things from top of the tree to the bottom - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); DataColumn? col = GetColumnSchemaForNode(rowElem, elem); - if (col == null) + if (col is null) { return t; } @@ -114,7 +114,7 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU // Some sanity check to catch errors like namespace attributes have the right localName/namespace value, but a wrong atomized namespace value if (a.LocalName == "xmlns") { - Debug.Assert(a.Prefix != null && a.Prefix.Length == 0); + Debug.Assert(a.Prefix is not null && a.Prefix.Length == 0); Debug.Assert(a.NamespaceURI == (object)strReservedXmlns); } if (a.Prefix == "xmlns") @@ -133,7 +133,7 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU } } - for (XmlNode? n = elem.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = elem.FirstChild; n is not null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element) { @@ -148,18 +148,18 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU internal DataColumn? GetColumnSchemaForNode(XmlBoundElement rowElem, XmlNode node) { - Debug.Assert(rowElem != null); + Debug.Assert(rowElem is not null); // The caller must make sure that node is not a row-element - Debug.Assert((node is XmlBoundElement) ? ((XmlBoundElement)node).Row == null : true); + Debug.Assert((node is XmlBoundElement) ? ((XmlBoundElement)node).Row is null : true); object tid = GetIdentity(rowElem.LocalName, rowElem.NamespaceURI); object cid = GetIdentity(node.LocalName, node.NamespaceURI); Hashtable? columns = (Hashtable?)_columnSchemaMap[tid]; - if (columns != null) + if (columns is not null) { DataColumn? col = (DataColumn?)(columns[cid]); - if (col == null) + if (col is null) { return null; } @@ -184,7 +184,7 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU internal DataTable? GetTableSchemaForElement(XmlElement elem) { XmlBoundElement? be = elem as XmlBoundElement; - if (be == null) + if (be is null) { return null; } @@ -211,11 +211,11 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU // This function does not work if the region is not associated w/ a DataRow (it uses DataRow association to know what is the row element associated w/ the region) internal bool GetRegion(XmlNode? node, [NotNullWhen(true)] out XmlBoundElement? rowElem) { - while (node != null) + while (node is not null) { XmlBoundElement? be = node as XmlBoundElement; // Break if found a region - if (be != null && GetRowFromElement(be) != null) + if (be is not null && GetRowFromElement(be) is not null) { rowElem = be; return true; @@ -238,7 +238,7 @@ internal bool GetRegion(XmlNode? node, [NotNullWhen(true)] out XmlBoundElement? internal bool IsRegionRadical(XmlBoundElement rowElem) { // You must pass a row element (which s/b associated w/ a DataRow) - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); if (rowElem.ElementState == ElementState.Defoliated) { @@ -263,7 +263,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) // only mapped attrs are valid DataColumn? schema = GetColumnSchemaForNode(rowElem, attr); - if (schema == null) + if (schema is null) { return false; } @@ -276,7 +276,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) // must have exactly one text node (XmlNodeType.Text) child XmlNode? fc = attr.FirstChild; - if (fc == null || fc.NodeType != XmlNodeType.Text || fc.NextSibling != null) + if (fc is null || fc.NodeType != XmlNodeType.Text || fc.NextSibling is not null) { return false; } @@ -285,7 +285,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) // check column elements iColumn = 0; XmlNode? n = rowElem.FirstChild; - for (; n != null; n = n.NextSibling) + for (; n is not null; n = n.NextSibling) { // only elements can exist in radically structured data if (n.NodeType != XmlNodeType.Element) @@ -295,14 +295,14 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) XmlElement? e = n as XmlElement; // only checking for column mappings in this loop - if (GetRowFromElement(e) != null) + if (GetRowFromElement(e) is not null) { break; } // element's must have schema to be radically structured DataColumn? schema = GetColumnSchemaForNode(rowElem, e!); - if (schema == null) + if (schema is null) { return false; } @@ -321,14 +321,14 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) // must have exactly one text node child XmlNode? fc = e.FirstChild; - if (fc == null || fc.NodeType != XmlNodeType.Text || fc.NextSibling != null) + if (fc is null || fc.NodeType != XmlNodeType.Text || fc.NextSibling is not null) { return false; } } // check for remaining sub-regions - for (; n != null; n = n.NextSibling) + for (; n is not null; n = n.NextSibling) { // only elements can exist in radically structured data if (n.NodeType != XmlNodeType.Element) @@ -338,7 +338,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) // element's must be regions in order to be radially structured DataRow? row = GetRowFromElement((XmlElement?)n); - if (row == null) + if (row is null) { return false; } @@ -359,7 +359,7 @@ private void AddColumnSchema(DataColumn col) object idColumn = GetIdentity(col.EncodedColumnName, col.Namespace); Hashtable? columns = (Hashtable?)_columnSchemaMap[idTable]; - if (columns == null) + if (columns is null) { columns = new Hashtable(); _columnSchemaMap[idTable] = columns; diff --git a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs index 1a6545e1ea6913..081008c4072c42 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs @@ -22,7 +22,7 @@ internal sealed class RegionIterator : BaseRegionIterator internal RegionIterator(XmlBoundElement rowElement) : base(((XmlDataDocument)(rowElement.OwnerDocument)).Mapper) { - Debug.Assert(rowElement != null && rowElement.Row != null); + Debug.Assert(rowElement is not null && rowElement.Row is not null); _rowElement = rowElement; _currentNode = rowElement; } @@ -42,10 +42,10 @@ internal override bool Next() nextNode = _currentNode.FirstChild; // No children, try next sibling - if (nextNode != null) + if (nextNode is not null) { _currentNode = nextNode; - Debug.Assert(CurrentNode != null); + Debug.Assert(CurrentNode is not null); // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation @@ -73,20 +73,20 @@ internal override bool NextRight() XmlNode? nextNode = _currentNode.NextSibling; - if (nextNode != null) + if (nextNode is not null) { _currentNode = nextNode; // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; - Debug.Assert(CurrentNode != null); + Debug.Assert(CurrentNode is not null); return true; } // No next sibling, try the first sibling of from the parent chain nextNode = _currentNode; - while (nextNode != _rowElement && nextNode!.NextSibling == null) + while (nextNode != _rowElement && nextNode!.NextSibling is null) { nextNode = nextNode.ParentNode; } @@ -102,7 +102,7 @@ internal override bool NextRight() return false; } - Debug.Assert(nextNode.NextSibling != null); + Debug.Assert(nextNode.NextSibling is not null); _currentNode = nextNode.NextSibling; // If we have been defoliated, we should have stayed that way @@ -110,7 +110,7 @@ internal override bool NextRight() // Rollback foliation _rowElement.ElementState = oldState; - Debug.Assert(CurrentNode != null); + Debug.Assert(CurrentNode is not null); return true; } @@ -119,11 +119,11 @@ internal override bool NextRight() [MemberNotNullWhen(true, nameof(CurrentNode))] internal bool NextInitialTextLikeNodes(out string value) { - Debug.Assert(CurrentNode != null); + Debug.Assert(CurrentNode is not null); Debug.Assert(CurrentNode.NodeType == XmlNodeType.Element); #if DEBUG // It's not OK to try to read the initial text value for sub-regions, because we do not know how to revert their initial state - if (CurrentNode.NodeType == XmlNodeType.Element && mapper.GetTableSchemaForElement((XmlElement)(CurrentNode)) != null) + if (CurrentNode.NodeType == XmlNodeType.Element && mapper.GetTableSchemaForElement((XmlElement)(CurrentNode)) is not null) { if (CurrentNode != _rowElement) { @@ -139,7 +139,7 @@ internal bool NextInitialTextLikeNodes(out string value) XmlNode? n = CurrentNode.FirstChild; value = GetInitialTextFromNodes(ref n); - if (n == null) + if (n is null) { // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); @@ -163,19 +163,19 @@ private static string GetInitialTextFromNodes(ref XmlNode? n) { string? value = null; - if (n != null) + if (n is not null) { // don't consider whitespace while (n.NodeType == XmlNodeType.Whitespace) { n = n.NextSibling; - if (n == null) + if (n is null) { return string.Empty; } } - if (XmlDataDocument.IsTextLikeNode(n) && (n.NextSibling == null || !XmlDataDocument.IsTextLikeNode(n.NextSibling))) + if (XmlDataDocument.IsTextLikeNode(n) && (n.NextSibling is null || !XmlDataDocument.IsTextLikeNode(n.NextSibling))) { // don't use string builder if only one text node exists value = n.Value; @@ -184,7 +184,7 @@ private static string GetInitialTextFromNodes(ref XmlNode? n) else { StringBuilder sb = new StringBuilder(); - while (n != null && XmlDataDocument.IsTextLikeNode(n)) + while (n is not null && XmlDataDocument.IsTextLikeNode(n)) { // Ignore non-significant whitespace nodes if (n.NodeType != XmlNodeType.Whitespace) diff --git a/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs index 2361b77d884400..e21129897e8a95 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs @@ -15,7 +15,7 @@ internal sealed class TreeIterator : BaseTreeIterator internal TreeIterator(XmlNode nodeTop) : base(((XmlDataDocument)(nodeTop.OwnerDocument!)).Mapper) { - Debug.Assert(nodeTop != null); + Debug.Assert(nodeTop is not null); _nodeTop = nodeTop; _currentNode = nodeTop; } @@ -30,7 +30,7 @@ internal override bool Next() nextNode = _currentNode.FirstChild; // No children, try next sibling - if (nextNode != null) + if (nextNode is not null) { _currentNode = nextNode; return true; @@ -50,7 +50,7 @@ internal override bool NextRight() XmlNode? nextNode = _currentNode.NextSibling; - if (nextNode != null) + if (nextNode is not null) { _currentNode = nextNode; return true; @@ -58,7 +58,7 @@ internal override bool NextRight() // No next sibling, try the first sibling of from the parent chain nextNode = _currentNode; - while (nextNode != _nodeTop && nextNode!.NextSibling == null) + while (nextNode != _nodeTop && nextNode!.NextSibling is null) { nextNode = nextNode.ParentNode; } @@ -69,7 +69,7 @@ internal override bool NextRight() return false; } - Debug.Assert(nextNode.NextSibling != null); + Debug.Assert(nextNode.NextSibling is not null); _currentNode = nextNode.NextSibling; return true; } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs index f7095827dfcd20..35ea9657f4e798 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs @@ -65,7 +65,7 @@ private XPathNodeType DecideXPNodeTypeForTextNodes(XmlNode node) Debug.Assert(XmlDataDocument.IsTextNode(node.NodeType)); XPathNodeType xnt = XPathNodeType.Whitespace; XmlNode? n = node; - while (n != null) + while (n is not null) { switch (n.NodeType) { @@ -118,7 +118,7 @@ internal XPathNodePointer(DataDocumentXPathNavigator owner, XPathNodePointer poi private XPathNodePointer(DataDocumentXPathNavigator owner, XmlDataDocument doc, XmlNode node, DataColumn? c, bool bOnValue, XmlBoundElement? parentOfNS) { - Debug.Assert(owner != null); + Debug.Assert(owner is not null); _owner = new WeakReference(owner); _doc = doc; _node = node; @@ -143,7 +143,7 @@ internal bool IsEmptyElement get { AssertValid(); - if (_node != null && _column == null) + if (_node is not null && _column is null) { if (_node.NodeType == XmlNodeType.Element) { @@ -160,11 +160,11 @@ internal XPathNodeType NodeType { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return XPathNodeType.All; } - else if (_column == null) + else if (_column is null) { return ConvertNodeType(_node); } @@ -195,11 +195,11 @@ internal string LocalName { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { XmlNodeType nt = _node.NodeType; if (IsNamespaceNode(nt, _node.NamespaceURI) && _node.LocalName == StrXmlNS) @@ -224,11 +224,11 @@ internal string Name { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { XmlNodeType nt = _node.NodeType; if (IsNamespaceNode(nt, _node.NamespaceURI)) @@ -260,11 +260,11 @@ internal string NamespaceURI { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { XPathNodeType xnt = ConvertNodeType(_node); if (xnt == XPathNodeType.Element || xnt == XPathNodeType.Root || xnt == XPathNodeType.Attribute) @@ -295,11 +295,11 @@ internal string Prefix { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { if (IsNamespaceNode(_node.NodeType, _node.NamespaceURI)) return string.Empty; @@ -315,19 +315,19 @@ internal string? Value { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) return null; - else if (_column == null) + else if (_column is null) { string? strRet = _node.Value; if (XmlDataDocument.IsTextNode(_node.NodeType)) { //concatenate adjacent textlike nodes XmlNode? parent = _node.ParentNode; - if (parent == null) + if (parent is null) return strRet; XmlNode? n = _doc.SafeNextSibling(_node); - while (n != null && XmlDataDocument.IsTextNode(n.NodeType)) + while (n is not null && XmlDataDocument.IsTextNode(n.NodeType)) { strRet += n.Value; n = _doc.SafeNextSibling(n); @@ -355,17 +355,17 @@ internal string InnerText { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) { return string.Empty; } - else if (_column == null) + else if (_column is null) { if (_node.NodeType == XmlNodeType.Document) { //document node's region should always be uncompressed XmlElement? rootElem = ((XmlDocument)_node).DocumentElement; - if (rootElem != null) + if (rootElem is not null) return rootElem.InnerText; return string.Empty; } @@ -389,7 +389,7 @@ internal string BaseURI get { RealFoliate(); - if (_node != null) + if (_node is not null) return _node.BaseURI; return string.Empty; } @@ -403,10 +403,10 @@ internal string XmlLang XmlNode curNode = _node; XmlBoundElement? curBoundElem = null; object? colVal = null; - while (curNode != null) + while (curNode is not null) { curBoundElem = curNode as XmlBoundElement; - if (curBoundElem != null) + if (curBoundElem is not null) { if (curBoundElem.ElementState == ElementState.Defoliated) { @@ -442,11 +442,11 @@ internal string XmlLang private XmlBoundElement? GetRowElement() { XmlBoundElement? rowElem; - if (_column != null) + if (_column is not null) { rowElem = (XmlBoundElement)_node; - Debug.Assert(rowElem != null); - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem is not null); + Debug.Assert(rowElem.Row is not null); return rowElem; } @@ -459,10 +459,10 @@ private DataRow? Row get { XmlBoundElement? rowElem = GetRowElement(); - if (rowElem == null) + if (rowElem is null) return null; - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); return rowElem.Row; } } @@ -503,7 +503,7 @@ private void MoveTo(XmlNode node, DataColumn? column, bool fOnValue) private bool IsFoliated(XmlNode node) { - if (node != null && node is XmlBoundElement) + if (node is not null && node is XmlBoundElement) return ((XmlBoundElement)node).IsFoliated; return true; } @@ -512,7 +512,7 @@ private int ColumnCount(DataRow row, bool fAttribute) { DataColumn? c = null; int count = 0; - while ((c = NextColumn(row, c, fAttribute)) != null) + while ((c = NextColumn(row, c, fAttribute)) is not null) { if (c.Namespace != StrReservedXmlns) count++; @@ -526,9 +526,9 @@ internal int AttributeCount { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column == null && _node.NodeType == XmlNodeType.Element) + if (_column is null && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) return ColumnCount(Row!, true); @@ -555,7 +555,7 @@ internal int AttributeCount DataTable table = row.Table; DataColumnCollection columns = table.Columns; - int iColumn = (col != null) ? col.Ordinal + 1 : 0; + int iColumn = (col is not null) ? col.Ordinal + 1 : 0; int cColumns = columns.Count; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; @@ -576,7 +576,7 @@ internal int AttributeCount DataTable table = row.Table; DataColumnCollection columns = table.Columns; - int iColumn = (col != null) ? col.Ordinal - 1 : columns.Count - 1; + int iColumn = (col is not null) ? col.Ordinal - 1 : columns.Count - 1; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; for (; iColumn >= 0; iColumn--) @@ -595,16 +595,16 @@ internal bool MoveToAttribute(string localName, string namespaceURI) AssertValid(); if (namespaceURI == StrReservedXmlns) return false; - if (_node != null) + if (_node is not null) { //_column.ColumnMapping checkin below is not really needed since the pointer should be pointing at the node before this // function should even be called ( there is always a call MoveToOwnerElement() before MoveToAttribute(..) - if ((_column == null || _column.ColumnMapping == MappingType.Attribute) && _node.NodeType == XmlNodeType.Element) + if ((_column is null || _column.ColumnMapping == MappingType.Attribute) && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) { DataColumn? c = null; - while ((c = NextColumn(Row!, c, true)) != null) + while ((c = NextColumn(Row!, c, true)) is not null) { if (c.EncodedColumnName == localName && c.Namespace == namespaceURI) { @@ -615,9 +615,9 @@ internal bool MoveToAttribute(string localName, string namespaceURI) } else { - Debug.Assert(_node.Attributes != null); + Debug.Assert(_node.Attributes is not null); XmlNode? n = _node.Attributes.GetNamedItem(localName, namespaceURI); - if (n != null) + if (n is not null) { MoveTo(n, null, false); return true; @@ -632,21 +632,21 @@ internal bool MoveToNextAttribute(bool bFirst) { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (bFirst && (_column != null || _node.NodeType != XmlNodeType.Element)) + if (bFirst && (_column is not null || _node.NodeType != XmlNodeType.Element)) return false; if (!bFirst) { - if (_column != null && _column.ColumnMapping != MappingType.Attribute) + if (_column is not null && _column.ColumnMapping != MappingType.Attribute) return false; - if (_column == null && _node.NodeType != XmlNodeType.Attribute) + if (_column is null && _node.NodeType != XmlNodeType.Attribute) return false; } if (!IsFoliated(_node)) { DataColumn? c = _column; - while ((c = NextColumn(Row!, c, true)) != null) + while ((c = NextColumn(Row!, c, true)) is not null) { if (c.Namespace != StrReservedXmlns) { @@ -732,9 +732,9 @@ internal bool MoveToNextSibling() { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column != null) + if (_column is not null) { if (_fOnValue) { @@ -744,7 +744,7 @@ internal bool MoveToNextSibling() } DataRow curRow = Row!; DataColumn? c = NextColumn(curRow, _column, false); - while (c != null) + while (c is not null) { if (IsValidChild(_node, c)) { @@ -754,7 +754,7 @@ internal bool MoveToNextSibling() c = NextColumn(curRow, c, false); } XmlNode? n = _doc.SafeFirstChild(_node); - if (n != null) + if (n is not null) { MoveTo(n); return true; @@ -764,7 +764,7 @@ internal bool MoveToNextSibling() { XmlNode? n = _node; XmlNode? parent = _node.ParentNode; - if (parent == null) + if (parent is null) return false; bool bTextLike = XmlDataDocument.IsTextNode(_node.NodeType); do @@ -772,9 +772,9 @@ internal bool MoveToNextSibling() do { n = _doc.SafeNextSibling(n); - } while (n != null && bTextLike && XmlDataDocument.IsTextNode(n.NodeType)); - } while (n != null && !IsValidChild(parent, n)); - if (n != null) + } while (n is not null && bTextLike && XmlDataDocument.IsTextNode(n.NodeType)); + } while (n is not null && !IsValidChild(parent, n)); + if (n is not null) { MoveTo(n); return true; @@ -788,15 +788,15 @@ internal bool MoveToPreviousSibling() { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { - if (_column != null) + if (_column is not null) { if (_fOnValue) return false; DataRow curRow = Row!; DataColumn? c = PreviousColumn(curRow, _column, false); - while (c != null) + while (c is not null) { if (IsValidChild(_node, c)) { @@ -810,7 +810,7 @@ internal bool MoveToPreviousSibling() { XmlNode? n = _node; XmlNode? parent = _node.ParentNode; - if (parent == null) + if (parent is null) return false; bool bTextLike = XmlDataDocument.IsTextNode(_node.NodeType); do @@ -818,9 +818,9 @@ internal bool MoveToPreviousSibling() do { n = _doc.SafePreviousSibling(n); - } while (n != null && bTextLike && XmlDataDocument.IsTextNode(n.NodeType)); - } while (n != null && !IsValidChild(parent, n)); - if (n != null) + } while (n is not null && bTextLike && XmlDataDocument.IsTextNode(n.NodeType)); + } while (n is not null && !IsValidChild(parent, n)); + if (n is not null) { MoveTo(n); return true; @@ -828,10 +828,10 @@ internal bool MoveToPreviousSibling() if (!IsFoliated(parent) && (parent is XmlBoundElement)) { DataRow? row = ((XmlBoundElement)parent).Row; - if (row != null) + if (row is not null) { DataColumn? c = PreviousColumn(row, null, false); - if (c != null) + if (c is not null) { MoveTo(parent, c, _doc.IsTextOnly(c)); return true; @@ -847,11 +847,11 @@ internal bool MoveToFirst() { RealFoliate(); AssertValid(); - if (_node != null) + if (_node is not null) { DataRow? curRow = null; XmlNode? parent = null; - if (_column != null) + if (_column is not null) { curRow = Row; parent = _node; @@ -859,16 +859,16 @@ internal bool MoveToFirst() else { parent = _node.ParentNode; - if (parent == null) + if (parent is null) return false; if (!IsFoliated(parent) && (parent is XmlBoundElement)) curRow = ((XmlBoundElement)parent).Row; } //first check with the columns in the row - if (curRow != null) + if (curRow is not null) { DataColumn? c = NextColumn(curRow, null, false); - while (c != null) + while (c is not null) { if (IsValidChild(_node, c)) { @@ -880,7 +880,7 @@ internal bool MoveToFirst() } //didn't find a valid column or maybe already Foliated, go through its children nodes XmlNode? n = _doc.SafeFirstChild(parent); - while (n != null) + while (n is not null) { if (IsValidChild(parent, n)) { @@ -899,10 +899,10 @@ internal bool HasChildren { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) return false; - if (_column != null) + if (_column is not null) { if (_column.ColumnMapping == MappingType.Attribute || _column.ColumnMapping == MappingType.Hidden) return false; @@ -913,7 +913,7 @@ internal bool HasChildren // find virtual column elements first DataRow curRow = Row!; DataColumn? c = NextColumn(curRow, null, false); - while (c != null) + while (c is not null) { if (IsValidChild(_node, c)) return true; @@ -922,7 +922,7 @@ internal bool HasChildren } // look for anything XmlNode? n = _doc.SafeFirstChild(_node); - while (n != null) + while (n is not null) { if (IsValidChild(_node, n)) return true; @@ -937,10 +937,10 @@ internal bool MoveToFirstChild() { RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) return false; - if (_column != null) + if (_column is not null) { if (_column.ColumnMapping == MappingType.Attribute || _column.ColumnMapping == MappingType.Hidden) return false; @@ -954,7 +954,7 @@ internal bool MoveToFirstChild() // find virtual column elements first DataRow curRow = Row!; DataColumn? c = NextColumn(curRow, null, false); - while (c != null) + while (c is not null) { if (IsValidChild(_node, c)) { @@ -966,7 +966,7 @@ internal bool MoveToFirstChild() } // look for anything XmlNode? n = _doc.SafeFirstChild(_node); - while (n != null) + while (n is not null) { if (IsValidChild(_node, n)) { @@ -989,9 +989,9 @@ internal bool MoveToParent() MoveTo(_parentOfNS!); return true; } - if (_node != null) + if (_node is not null) { - if (_column != null) + if (_column is not null) { if (_fOnValue && !_doc.IsTextOnly(_column)) { @@ -1008,7 +1008,7 @@ internal bool MoveToParent() n = ((XmlAttribute)_node).OwnerElement; else n = _node.ParentNode; - if (n != null) + if (n is not null) { MoveTo(n); return true; @@ -1023,7 +1023,7 @@ internal bool MoveToParent() XPathNodeType xnt = ConvertNodeType(node); if (xnt == XPathNodeType.Namespace) { - Debug.Assert(_parentOfNS != null); + Debug.Assert(_parentOfNS is not null); return _parentOfNS; } if (xnt == XPathNodeType.Attribute) @@ -1035,7 +1035,7 @@ internal void MoveToRoot() { XmlNode node = _node; XmlNode? parent = _node; - while (parent != null) + while (parent is not null) { node = parent; parent = GetParent(parent); @@ -1052,7 +1052,7 @@ internal bool IsSamePosition(XPathNodePointer pointer) pointer.RealFoliate(); AssertValid(); pointer.AssertValid(); - if (_column == null && pointer._column == null) + if (_column is null && pointer._column is null) return (pointer._node == _node && pointer._parentOfNS == _parentOfNS); return (pointer._doc == _doc @@ -1079,7 +1079,7 @@ private static XmlNode GetRoot(XmlNode node, ref int depth) depth = 0; XmlNode curNode = node; XmlNode? parent = ((curNode.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode).OwnerElement) : (curNode.ParentNode)); - for (; parent != null; depth++) + for (; parent is not null; depth++) { curNode = parent; parent = curNode.ParentNode; // no need to check for attribute since navigator can't be built on its children or navigate to its children @@ -1111,7 +1111,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) if (_parentOfNS == other._node) { //from the same region, NS nodes come before all other nodes - if (other._column == null) + if (other._column is null) return XmlNodeOrder.After; else return XmlNodeOrder.Before; @@ -1126,7 +1126,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) if (_node == other._parentOfNS) { //from the same region - if (_column == null) + if (_column is null) return XmlNodeOrder.Before; else return XmlNodeOrder.After; @@ -1152,9 +1152,9 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) else { Debug.Assert(Row == other.Row); //in the same row - if (_column == null) + if (_column is null) return XmlNodeOrder.Before; - else if (other._column == null) + else if (other._column is null) return XmlNodeOrder.After; else if (_column.Ordinal < other._column.Ordinal) return XmlNodeOrder.Before; @@ -1166,10 +1166,10 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) curNode2 = other._node; } - Debug.Assert(curNode1 != null); - Debug.Assert(curNode2 != null); + Debug.Assert(curNode1 is not null); + Debug.Assert(curNode2 is not null); - if (curNode1 == null || curNode2 == null) + if (curNode1 is null || curNode2 is null) { return XmlNodeOrder.Unknown; } @@ -1183,7 +1183,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) if (depth1 > depth2) { - while (curNode1 != null && depth1 > depth2) + while (curNode1 is not null && depth1 > depth2) { curNode1 = ((curNode1.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode1).OwnerElement) : (curNode1.ParentNode)); depth1--; @@ -1193,7 +1193,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) } else if (depth2 > depth1) { - while (curNode2 != null && depth2 > depth1) + while (curNode2 is not null && depth2 > depth1) { curNode2 = ((curNode2.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode2).OwnerElement) : (curNode2.ParentNode)); depth2--; @@ -1205,11 +1205,11 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) XmlNode? parent1 = GetParent(curNode1!); XmlNode? parent2 = GetParent(curNode2!); XmlNode? nextNode = null; - while (parent1 != null && parent2 != null) + while (parent1 is not null && parent2 is not null) { if (parent1 == parent2) { - while (curNode1 != null) + while (curNode1 is not null) { nextNode = curNode1.NextSibling; if (nextNode == curNode2) @@ -1235,11 +1235,11 @@ internal XmlNode? Node RealFoliate(); AssertValid(); - if (_node == null) + if (_node is null) return null; XmlBoundElement? rowElem = GetRowElement(); - if (rowElem != null) + if (rowElem is not null) { bool wasFoliationEnabled = _doc.IsFoliationEnabled; _doc.IsFoliationEnabled = true; @@ -1270,7 +1270,7 @@ void IXmlDataVirtualNode.OnFoliated(XmlNode foliatedNode) if (_node == foliatedNode) { // if already on this node, nothing to do! - if (_column == null) + if (_column is null) return; _bNeedFoliate = true; } @@ -1283,7 +1283,7 @@ private void RealFoliate() _bNeedFoliate = false; - Debug.Assert(_column != null); + Debug.Assert(_column is not null); XmlNode? n = null; @@ -1297,18 +1297,18 @@ private void RealFoliate() } else { - for (n = _node.FirstChild; n != null; n = n.NextSibling) + for (n = _node.FirstChild; n is not null; n = n.NextSibling) { if (n.LocalName == _column.EncodedColumnName && n.NamespaceURI == _column.Namespace) break; } } - if (n != null && _fOnValue) + if (n is not null && _fOnValue) n = n.FirstChild; } - if (n == null) + if (n is null) throw new InvalidOperationException(SR.DataDom_Foliation); // Cannot use MoveTo( n ); b/c the initial state for MoveTo is invalid (region is foliated but this is not) @@ -1324,13 +1324,13 @@ private void RealFoliate() //It will not check the ancestor of the given node. private string? GetNamespace(XmlBoundElement be, string name) { - if (be == null) + if (be is null) return null; XmlAttribute? attr = null; if (be.IsFoliated) { attr = be.GetAttributeNode(name, StrReservedXmlns); - if (attr != null) + if (attr is not null) return attr.Value; else return null; @@ -1338,11 +1338,11 @@ private void RealFoliate() else { //defoliated so that we need to search through its column DataRow? curRow = be.Row; - if (curRow == null) + if (curRow is null) return null; //going through its attribute columns DataColumn? curCol = PreviousColumn(curRow, null, true); - while (curCol != null) + while (curCol is not null) { if (curCol.Namespace == StrReservedXmlns) { @@ -1362,16 +1362,16 @@ internal string GetNamespace(string name) return StrReservedXml; if (name == "xmlns") return StrReservedXmlns; - if (name != null && name.Length == 0) + if (name is not null && name.Length == 0) name = "xmlns"; RealFoliate(); XmlNode? node = _node; XmlNodeType nt = node.NodeType; string? retVal = null; - while (node != null) + while (node is not null) { //first identify an element node in the ancestor + itself - while (node != null && ((nt = node.NodeType) != XmlNodeType.Element)) + while (node is not null && ((nt = node.NodeType) != XmlNodeType.Element)) { if (nt == XmlNodeType.Attribute) node = ((XmlAttribute)node).OwnerElement; @@ -1379,11 +1379,11 @@ internal string GetNamespace(string name) node = node.ParentNode; } //found one -- inside if - if (node != null) + if (node is not null) { //must be element node retVal = GetNamespace((XmlBoundElement)node, name!); - if (retVal != null) + if (retVal is not null) return retVal; //didn't find it, try the next parentnode node = node.ParentNode; @@ -1397,27 +1397,27 @@ internal bool MoveToNamespace(string name) { _parentOfNS = _node as XmlBoundElement; //only need to check with _node, even if _column is not null and its mapping type is element, it can't have attributes - if (_parentOfNS == null) + if (_parentOfNS is null) return false; string attrName = name; if (attrName == "xmlns") attrName = "xmlns:xmlns"; - if (attrName != null && attrName.Length == 0) + if (attrName is not null && attrName.Length == 0) attrName = "xmlns"; RealFoliate(); XmlNode? node = _node; XmlAttribute? attr = null; XmlBoundElement? be = null; - while (node != null) + while (node is not null) { //check current element node be = node as XmlBoundElement; - if (be != null) + if (be is not null) { if (be.IsFoliated) { attr = be.GetAttributeNode(name, StrReservedXmlns); - if (attr != null) + if (attr is not null) { MoveTo(attr); return true; @@ -1426,11 +1426,11 @@ internal bool MoveToNamespace(string name) else {//defoliated so that we need to search through its column DataRow? curRow = be.Row; - if (curRow == null) + if (curRow is null) return false; //going through its attribute columns DataColumn? curCol = PreviousColumn(curRow, null, true); - while (curCol != null) + while (curCol is not null) { if (curCol.Namespace == StrReservedXmlns && curCol.ColumnName == name) { @@ -1445,7 +1445,7 @@ internal bool MoveToNamespace(string name) do { node = node.ParentNode; - } while (node != null && node.NodeType != XmlNodeType.Element); + } while (node is not null && node.NodeType != XmlNodeType.Element); } //nothing happens, the name doesn't exist as a namespace node. _parentOfNS = null; @@ -1456,20 +1456,20 @@ internal bool MoveToNamespace(string name) // whether to use column or attribute depends on if the bound element is foliated or not. private bool MoveToNextNamespace(XmlBoundElement? be, DataColumn? col, XmlAttribute? curAttr) { - if (be != null) + if (be is not null) { if (be.IsFoliated) { XmlAttributeCollection attrs = be.Attributes; XmlAttribute? attr = null; bool bFound = false; - if (curAttr == null) + if (curAttr is null) bFound = true; //the first namespace will be the one #if DEBUG - if (curAttr != null) + if (curAttr is not null) Debug.Assert(curAttr.NamespaceURI == StrReservedXmlns); #endif - Debug.Assert(attrs != null); + Debug.Assert(attrs is not null); int attrInd = attrs.Count; while (attrInd > 0) { @@ -1487,11 +1487,11 @@ private bool MoveToNextNamespace(XmlBoundElement? be, DataColumn? col, XmlAttrib else {//defoliated so that we need to search through its column DataRow? curRow = be.Row; - if (curRow == null) + if (curRow is null) return false; //going through its attribute columns DataColumn? curCol = PreviousColumn(curRow, col, true); - while (curCol != null) + while (curCol is not null) { if (curCol.Namespace == StrReservedXmlns && !DuplicateNS(be, curCol.ColumnName)) { @@ -1511,11 +1511,11 @@ internal bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) RealFoliate(); _parentOfNS = _node as XmlBoundElement; //only need to check with _node, even if _column is not null and its mapping type is element, it can't have attributes - if (_parentOfNS == null) + if (_parentOfNS is null) return false; XmlNode? node = _node; XmlBoundElement? be = null; - while (node != null) + while (node is not null) { be = node as XmlBoundElement; if (MoveToNextNamespace(be, null, null)) @@ -1527,7 +1527,7 @@ internal bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) do { node = node.ParentNode; - } while (node != null && node.NodeType != XmlNodeType.Element); + } while (node is not null && node.NodeType != XmlNodeType.Element); } if (namespaceScope == XPathNamespaceScope.All) { @@ -1543,19 +1543,19 @@ internal bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) //endElem is on the path from startElem to root is enforced by the caller private bool DuplicateNS(XmlBoundElement endElem, string lname) { - if (_parentOfNS == null || endElem == null) + if (_parentOfNS is null || endElem is null) return false; XmlBoundElement? be = _parentOfNS; XmlNode? node = null; - while (be != null && be != endElem) + while (be is not null && be != endElem) { - if (GetNamespace(be, lname) != null) + if (GetNamespace(be, lname) is not null) return true; node = be; do { node = node.ParentNode; - } while (node != null && node.NodeType != XmlNodeType.Element); + } while (node is not null && node.NodeType != XmlNodeType.Element); be = node as XmlBoundElement; } return false; @@ -1565,20 +1565,20 @@ private bool DuplicateNS(XmlBoundElement endElem, string lname) internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { RealFoliate(); - Debug.Assert(_parentOfNS != null); + Debug.Assert(_parentOfNS is not null); XmlNode? node = _node; //first check within the same boundelement - if (_column != null) + if (_column is not null) { Debug.Assert(_column.Namespace == StrReservedXmlns); if (namespaceScope == XPathNamespaceScope.Local && _parentOfNS != _node) //already outside scope return false; XmlBoundElement? be = _node as XmlBoundElement; - Debug.Assert(be != null); + Debug.Assert(be is not null); DataRow? curRow = be.Row; - Debug.Assert(curRow != null); + Debug.Assert(curRow is not null); DataColumn? curCol = PreviousColumn(curRow, _column, true); - while (curCol != null) + while (curCol is not null) { if (curCol.Namespace == StrReservedXmlns) { @@ -1594,14 +1594,14 @@ internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) do { node = node.ParentNode; - } while (node != null && node.NodeType != XmlNodeType.Element); + } while (node is not null && node.NodeType != XmlNodeType.Element); } else if (_node.NodeType == XmlNodeType.Attribute) { XmlAttribute attr = (XmlAttribute)(_node); - Debug.Assert(attr != null); + Debug.Assert(attr is not null); node = attr.OwnerElement; - if (node == null) + if (node is null) return false; if (namespaceScope == XPathNamespaceScope.Local && _parentOfNS != node) //already outside scope return false; @@ -1613,10 +1613,10 @@ internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) do { node = node.ParentNode; - } while (node != null && node.NodeType != XmlNodeType.Element); + } while (node is not null && node.NodeType != XmlNodeType.Element); } // till now, node should be the next ancestor (bound) element of the element parent of current namespace node (attribute or data column) - while (node != null) + while (node is not null) { //try the namespace attributes from the same element XmlBoundElement? be = node as XmlBoundElement; @@ -1626,7 +1626,7 @@ internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) do { node = node.ParentNode; - } while (node != null && node.NodeType == XmlNodeType.Element); + } while (node is not null && node.NodeType == XmlNodeType.Element); } //didn't find the next namespace, thus return if (namespaceScope == XPathNamespaceScope.All) @@ -1643,14 +1643,14 @@ private void AssertValid() // This pointer must be int the document list //RealFoliate(); _doc.AssertPointerPresent(this); - if (_column != null) + if (_column is not null) { // We must be on a de-foliated region XmlBoundElement? rowElem = _node as XmlBoundElement; - Debug.Assert(rowElem != null); + Debug.Assert(rowElem is not null); DataRow? row = rowElem.Row; - Debug.Assert(row != null); + Debug.Assert(row is not null); // We cannot be on a column for which the value is DBNull DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; @@ -1659,7 +1659,7 @@ private void AssertValid() // If we are on the Text column, we should always have _fOnValue == true Debug.Assert((_column.ColumnMapping == MappingType.SimpleContent) ? (_fOnValue == true) : true); } - if (_column == null) + if (_column is null) Debug.Assert(!_fOnValue); } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs index ae57ad3186ea90..03e0396bd3a20b 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs @@ -65,10 +65,10 @@ public override XmlNode? PreviousSibling get { XmlNode? prev = base.PreviousSibling; - if (prev == null) + if (prev is null) { XmlBoundElement? parent = ParentNode as XmlBoundElement; - if (parent != null) + if (parent is not null) { parent.AutoFoliate(); return base.PreviousSibling; @@ -85,10 +85,10 @@ public override XmlNode? NextSibling get { XmlNode? next = base.NextSibling; - if (next == null) + if (next is null) { XmlBoundElement? parent = ParentNode as XmlBoundElement; - if (parent != null) + if (parent is not null) { parent.AutoFoliate(); return base.NextSibling; @@ -138,7 +138,7 @@ internal void RemoveAllChildren() XmlNode? child = FirstChild; XmlNode? sibling = null; - while (child != null) + while (child is not null) { sibling = child.NextSibling; RemoveChild(child); @@ -199,7 +199,7 @@ internal ElementState ElementState internal void Foliate(ElementState newState) { XmlDataDocument doc = (XmlDataDocument)OwnerDocument; - if (doc != null) + if (doc is not null) { doc.Foliate(this, newState); } @@ -209,7 +209,7 @@ internal void Foliate(ElementState newState) private void AutoFoliate() { XmlDataDocument doc = (XmlDataDocument)OwnerDocument; - if (doc != null) + if (doc is not null) { doc.Foliate(this, doc.AutoFoliationState); } @@ -381,7 +381,7 @@ private static void WriteTo(DataPointer dp, XmlWriter w) default: Debug.Assert(((IXmlDataVirtualNode)dp).IsOnColumn(null)); - if (dp.GetNode() != null) + if (dp.GetNode() is not null) { dp.GetNode().WriteTo(w); } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index 09d6ee751b9b3c..3ee4031af1b1aa 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -61,7 +61,7 @@ internal void AddPointer(IXmlDataVirtualNode pointer) foreach (DictionaryEntry entry in _pointers) { IXmlDataVirtualNode? temp = (IXmlDataVirtualNode?)(entry.Value); - Debug.Assert(temp != null); + Debug.Assert(temp is not null); if (!temp.IsInUse()) al.Add(temp); } @@ -97,8 +97,8 @@ internal void AssertPointerPresent(IXmlDataVirtualNode pointer) private void AttachDataSet(DataSet ds) { // You should not have already an associated dataset - Debug.Assert(_dataSet == null); - Debug.Assert(ds != null); + Debug.Assert(_dataSet is null); + Debug.Assert(ds is not null); if (ds.FBoundToDocument) throw new ArgumentException(SR.DataDom_MultipleDataSet); ds.FBoundToDocument = true; @@ -112,13 +112,13 @@ private void AttachDataSet(DataSet ds) internal void SyncRows(DataRow? parentRow, XmlNode node, bool fAddRowsToTable) { XmlBoundElement? be = node as XmlBoundElement; - if (be != null) + if (be is not null) { DataRow? r = be.Row; - if (r != null && be.ElementState == ElementState.Defoliated) + if (r is not null && be.ElementState == ElementState.Defoliated) return; //no need of syncRow - if (r != null) + if (r is not null) { // get all field values. SynchronizeRowFromRowElement(be); @@ -127,7 +127,7 @@ internal void SyncRows(DataRow? parentRow, XmlNode node, bool fAddRowsToTable) be.ElementState = ElementState.WeakFoliation; DefoliateRegion(be); - if (parentRow != null) + if (parentRow is not null) SetNestedParentRow(r, parentRow); if (fAddRowsToTable && r.RowState == DataRowState.Detached) r.Table.Rows.Add(r); @@ -136,7 +136,7 @@ internal void SyncRows(DataRow? parentRow, XmlNode node, bool fAddRowsToTable) } // Attach all rows from children nodes - for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child is not null; child = child.NextSibling) SyncRows(parentRow, child, fAddRowsToTable); } @@ -149,13 +149,13 @@ internal void SyncTree(XmlNode node) DataRow? parentRow = null; bool fAddRowsToTable = IsConnected(node); - if (be != null) + if (be is not null) { DataRow? r = be.Row; - if (r != null && be.ElementState == ElementState.Defoliated) + if (r is not null && be.ElementState == ElementState.Defoliated) return; //no need of syncRow - if (r != null) + if (r is not null) { // get all field values. SynchronizeRowFromRowElement(be); @@ -176,7 +176,7 @@ internal void SyncTree(XmlNode node) } // Attach all rows from children nodes - for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child is not null; child = child.NextSibling) SyncRows(parentRow, child, fAddRowsToTable); } @@ -203,7 +203,7 @@ private void BindForLoad() private void Bind(bool fLoadFromDataSet) { // If we have a DocumentElement then it is illegal to call this func to load from data-set - Debug.Assert(DocumentElement == null || !fLoadFromDataSet); + Debug.Assert(DocumentElement is null || !fLoadFromDataSet); _ignoreDataSetEvents = true; _ignoreXmlEvents = true; @@ -211,7 +211,7 @@ private void Bind(bool fLoadFromDataSet) // Do the mapping. This could be a successive mapping in case of this scenario: xd = XmlDataDocument( emptyDataSet ); xd.Load( "file.xml" ); _mapper.SetupMapping(this, _dataSet); - if (DocumentElement != null) + if (DocumentElement is not null) { LoadDataSetFromTree(); BindListeners(); @@ -261,7 +261,7 @@ private void BindToDataSet() // so we must not rebound again to it. if (_fBoundToDataSet) { - Debug.Assert(_dataSet != null); + Debug.Assert(_dataSet is not null); return; } @@ -342,9 +342,9 @@ public override XmlElement CreateElement(string? prefix, string localName, strin // fBoundToDataSet and fBoundToDocument should have the same value Debug.Assert(_fBoundToDataSet ? _fBoundToDocument : (!_fBoundToDocument)); #endif - if (prefix == null) + if (prefix is null) prefix = string.Empty; - if (namespaceURI == null) + if (namespaceURI is null) namespaceURI = string.Empty; if (!_fAssociateDataRow) @@ -360,7 +360,7 @@ public override XmlElement CreateElement(string? prefix, string localName, strin // Loaded state: create a DataRow, this in turn will create and associate the XmlBoundElement, which we will return. DataTable dt = _mapper.SearchMatchingTableSchema(localName, namespaceURI); - if (dt != null) + if (dt is not null) { DataRow row = dt.CreateEmptyRow(); // We need to make sure all fields are DBNull @@ -370,7 +370,7 @@ public override XmlElement CreateElement(string? prefix, string localName, strin SetRowValueToNull(row, col); } XmlBoundElement? be = row.Element; - Debug.Assert(be != null); + Debug.Assert(be is not null); be.Prefix = prefix; return be; } @@ -398,7 +398,7 @@ public DataSet DataSet private void DefoliateRegion(XmlBoundElement rowElem) { // You must pass a row element (which s/b associated w/ a DataRow) - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); if (!_optimizeStorage) return; @@ -422,25 +422,25 @@ private void DefoliateRegion(XmlBoundElement rowElem) rowElem.RemoveAllAttributes(); XmlNode? node = rowElem.FirstChild; - while (node != null) + while (node is not null) { XmlNode? next = node.NextSibling; XmlBoundElement? be = node as XmlBoundElement; - if (be != null && be.Row != null) + if (be is not null && be.Row is not null) break; // The node must be mapped to a column (since the region is radically structured) - Debug.Assert(_mapper.GetColumnSchemaForNode(rowElem, node) != null); + Debug.Assert(_mapper.GetColumnSchemaForNode(rowElem, node) is not null); rowElem.RemoveChild(node); node = next; } #if DEBUG // All subsequent siblings must be sub-regions - for (; node != null; node = node.NextSibling) + for (; node is not null; node = node.NextSibling) { - Debug.Assert((node is XmlBoundElement) && (((XmlBoundElement)node).Row != null)); + Debug.Assert((node is XmlBoundElement) && (((XmlBoundElement)node).Row is not null)); } #endif @@ -455,13 +455,13 @@ private void DefoliateRegion(XmlBoundElement rowElem) private XmlElement EnsureDocumentElement() { XmlElement? docelem = DocumentElement; - if (docelem == null) + if (docelem is null) { string docElemName = XmlConvert.EncodeLocalName(DataSet.DataSetName); - if (docElemName == null || docElemName.Length == 0) + if (docElemName is null || docElemName.Length == 0) docElemName = "Xml"; string ns = DataSet.Namespace; - if (ns == null) + if (ns is null) ns = string.Empty; docelem = new XmlBoundElement(string.Empty, docElemName, ns, this); AppendChild(docelem); @@ -472,11 +472,11 @@ private XmlElement EnsureDocumentElement() private XmlElement EnsureNonRowDocumentElement() { XmlElement? docElem = DocumentElement; - if (docElem == null) + if (docElem is null) return EnsureDocumentElement(); DataRow? rowDocElem = GetRowFromElement(docElem); - if (rowDocElem == null) + if (rowDocElem is null) return docElem; return DemoteDocumentElement(); @@ -486,7 +486,7 @@ private XmlElement DemoteDocumentElement() // Changes of Xml here should not affect ROM Debug.Assert(_ignoreXmlEvents == true); // There should be no reason to call this function if docElem is not a rowElem - Debug.Assert(GetRowFromElement(DocumentElement) != null); + Debug.Assert(GetRowFromElement(DocumentElement) is not null); // Remove the DocumentElement and create a new one XmlElement oldDocElem = DocumentElement!; @@ -546,7 +546,7 @@ private void FixNestedChildren(DataRow row, XmlElement rowElement) XmlElement? childElem = r.Element; // childElem can be null when we create XML from DataSet (XmlDataDocument( DataSet ) is called) and we insert rowElem of the parentRow before // we insert the rowElem of children rows. - if (childElem != null) + if (childElem is not null) { #if DEBUG bool fIsChildConnected = IsConnected(childElem); @@ -575,7 +575,7 @@ internal void Foliate(XmlBoundElement node, ElementState newState) // Do this only when we are not loading if (IsFoliationEnabled) { - if (newState == ElementState.StrongFoliation && node.Row == null) + if (newState == ElementState.StrongFoliation && node.Row is null) { XmlBoundElement? rowElem; ElementState rowElemState = ElementState.None; @@ -602,7 +602,7 @@ internal void Foliate(XmlBoundElement node, ElementState newState) else if (node.ElementState == ElementState.WeakFoliation && newState == ElementState.StrongFoliation) { // Node must be a row-elem - Debug.Assert(node.Row != null); + Debug.Assert(node.Row is not null); node.ElementState = newState; } } @@ -648,7 +648,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) return; // Node must be a row-elem associated w/ a non-deleted row - Debug.Assert(node.Row != null); + Debug.Assert(node.Row is not null); Debug.Assert(node.Row.RowState != DataRowState.Deleted); node.ElementState = ElementState.Foliating; @@ -685,11 +685,11 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) { newNode = new XmlBoundElement(string.Empty, col.EncodedColumnName, col.Namespace, this); newNode.AppendChild(CreateTextNode(col.ConvertObjectToXml(value))); - if (priorNode != null) + if (priorNode is not null) { node.InsertAfter(newNode, priorNode); } - else if (node.FirstChild != null) + else if (node.FirstChild is not null) { node.InsertBefore(newNode, node.FirstChild); } @@ -703,11 +703,11 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) { Debug.Assert(col.ColumnMapping == MappingType.SimpleContent); newNode = CreateTextNode(col.ConvertObjectToXml(value)); - if (node.FirstChild != null) + if (node.FirstChild is not null) node.InsertBefore(newNode, node.FirstChild); else node.AppendChild(newNode); - if (priorNode == null) + if (priorNode is null) priorNode = newNode; } } @@ -746,13 +746,13 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) return null; // insert location must be after free text - for (node = rowElement.FirstChild; node != null; prev = node, node = node.NextSibling) + for (node = rowElement.FirstChild; node is not null; prev = node, node = node.NextSibling) { if (!IsTextLikeNode(node)) break; } - for (; node != null; prev = node, node = node.NextSibling) + for (; node is not null; prev = node, node = node.NextSibling) { // insert location must be before any non-element nodes if (node.NodeType != XmlNodeType.Element) @@ -760,11 +760,11 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) XmlElement? e = node as XmlElement; // insert location must be before any non-mapped elements or separate regions - if (_mapper.GetRowFromElement(e) != null) + if (_mapper.GetRowFromElement(e) is not null) break; object? schema = _mapper.GetColumnSchemaForNode(rowElement, node); - if (schema == null || !(schema is DataColumn)) + if (schema is null || !(schema is DataColumn)) break; // insert location must be before any columns logically after this column @@ -791,7 +791,7 @@ private ArrayList GetNestedChildRelations(DataRow row) private DataRow? GetNestedParent(DataRow row) { DataRelation? relation = GetNestedParentRelation(row); - if (relation != null) + if (relation is not null) return row.GetParentRow(relation); return null; } @@ -823,7 +823,7 @@ private ArrayList GetNestedChildRelations(DataRow row) } Debug.Assert(cTextCols == 0 || cTextCols == 1); if (cTextCols == 0) - Debug.Assert(row.Table.XmlText == null); + Debug.Assert(row.Table.XmlText is null); } #endif return row.Table.XmlText; @@ -871,7 +871,7 @@ private ArrayList GetNestedChildRelations(DataRow row) public XmlElement GetElementFromRow(DataRow r) { XmlBoundElement? be = r.Element; - Debug.Assert(be != null); + Debug.Assert(be is not null); return be; } @@ -887,7 +887,7 @@ internal bool HasPointers(XmlNode node) foreach (DictionaryEntry entry in _pointers) { pointer = entry.Value; - Debug.Assert(pointer != null); + Debug.Assert(pointer is not null); if (((IXmlDataVirtualNode)pointer).IsOnNode(node)) return true; } @@ -959,7 +959,7 @@ internal XmlNode CloneTree(DataPointer other) // Create the diconnected tree based on the other navigator newNode = CloneTreeInternal(other); - Debug.Assert(newNode != null); + Debug.Assert(newNode is not null); // Synchronize DataSet from XML LoadRows(null, newNode); @@ -1020,7 +1020,7 @@ public override XmlNode CloneNode(bool deep) clone.Init(DataSet.Clone()); clone._dataSet.EnforceConstraints = _dataSet.EnforceConstraints; - Debug.Assert(clone.FirstChild == null); + Debug.Assert(clone.FirstChild is null); if (deep) { DataPointer dp = new DataPointer(this, this); @@ -1143,7 +1143,7 @@ public override void Load(TextReader txtReader) /// public override void Load(XmlReader reader) { - if (FirstChild != null) + if (FirstChild is not null) throw new InvalidOperationException(SR.DataDom_MultipleLoad); try @@ -1188,7 +1188,7 @@ private void LoadDataSetFromTree() try { - Debug.Assert(DocumentElement != null); + Debug.Assert(DocumentElement is not null); LoadRows(null, DocumentElement); SyncRows(null, DocumentElement, true); @@ -1225,7 +1225,7 @@ private void LoadTreeFromDataSet(DataSet ds) DataTable t = orderedTables[i]; foreach (DataRow r in t.Rows) { - Debug.Assert(r.Element == null); + Debug.Assert(r.Element is null); AttachBoundElementToDataRow(r); switch (r.RowState) @@ -1260,17 +1260,17 @@ private void LoadTreeFromDataSet(DataSet ds) // load all data from tree structre into datarows private void LoadRows(XmlBoundElement? rowElem, XmlNode node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); XmlBoundElement? be = node as XmlBoundElement; - if (be != null) + if (be is not null) { DataTable? dt = _mapper.SearchMatchingTableSchema(rowElem, be); - if (dt != null) + if (dt is not null) { DataRow? r = GetRowFromElement(be); - Debug.Assert(r == null); + Debug.Assert(r is null); // If the rowElement was just created and has an un-initialized if (be.ElementState == ElementState.None) be.ElementState = ElementState.WeakFoliation; @@ -1278,12 +1278,12 @@ private void LoadRows(XmlBoundElement? rowElem, XmlNode node) Bind(r, be); // the region rowElem is now be - Debug.Assert(be.Row != null); + Debug.Assert(be.Row is not null); rowElem = be; } } // recurse down for children - for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child is not null; child = child.NextSibling) LoadRows(rowElem, child); } @@ -1318,7 +1318,7 @@ internal void OnDataRowCreatedSpecial(object oDataSet, DataRow row) // Called when a new DataRow is created internal void OnNewRow(DataRow row) { - Debug.Assert(row.Element == null); + Debug.Assert(row.Element is null); // Allow New state also because we are calling this function from Debug.Assert(row.RowState == DataRowState.Detached); @@ -1327,7 +1327,7 @@ internal void OnNewRow(DataRow row) private XmlBoundElement AttachBoundElementToDataRow(DataRow row) { - Debug.Assert(row.Element == null); + Debug.Assert(row.Element is null); DataTable table = row.Table; // We shoould NOT call CreateElement here, since CreateElement will create and attach a new DataRow to the element XmlBoundElement rowElement = new XmlBoundElement(string.Empty, table.EncodedTableName, table.Namespace, this); @@ -1340,8 +1340,8 @@ private XmlBoundElement AttachBoundElementToDataRow(DataRow row) private bool NeedXSI_NilAttr(DataRow row) { DataTable tb = row.Table; - Debug.Assert(tb != null); - if (tb._xmlText == null) + Debug.Assert(tb is not null); + if (tb._xmlText is null) return false; object value = row[tb._xmlText]; return (Convert.IsDBNull(value)); @@ -1353,18 +1353,18 @@ private void OnAddRow(DataRow row) Debug.Assert(_ignoreXmlEvents == true); XmlBoundElement rowElement = (XmlBoundElement)(GetElementFromRow(row)); - Debug.Assert(rowElement != null); + Debug.Assert(rowElement is not null); if (NeedXSI_NilAttr(row) && !rowElement.IsFoliated) //we need to foliate it because we need to add one more attribute xsi:nil = true; ForceFoliation(rowElement, AutoFoliationState); - Debug.Assert(rowElement != null); + Debug.Assert(rowElement is not null); DataRow? rowDocElem = GetRowFromElement(DocumentElement); - if (rowDocElem != null) + if (rowDocElem is not null) { DataRow? parentRow = GetNestedParent(row); - if (parentRow == null) + if (parentRow is null) DemoteDocumentElement(); } EnsureDocumentElement().AppendChild(rowElement); @@ -1405,7 +1405,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r foreach (DictionaryEntry entry in _pointers) { pointer = entry.Value; - Debug.Assert((pointer != null) && !((IXmlDataVirtualNode)pointer).IsOnColumn(col)); + Debug.Assert((pointer is not null) && !((IXmlDataVirtualNode)pointer).IsOnColumn(col)); } } } @@ -1426,7 +1426,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r value = string.Empty; //make sure that rowElement has Attribute xsi:nil and its value is true XmlAttribute? attr = rowElement.GetAttributeNode(XSI_NIL); - if (attr == null) + if (attr is null) { attr = CreateAttribute(XSI, Keywords.XSI_NIL, Keywords.XSINS); attr.Value = Keywords.TRUE; @@ -1440,7 +1440,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { //make sure that if rowElement has Attribute xsi:nil, its value is false XmlAttribute? attr = rowElement.GetAttributeNode(XSI_NIL); - if (attr != null) + if (attr is not null) attr.Value = Keywords.FALSE; } ReplaceInitialChildText(rowElement, col.ConvertObjectToXml(value)); @@ -1486,10 +1486,10 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r if (iter.CurrentNode!.NodeType == XmlNodeType.Element) { XmlElement e = (XmlElement)iter.CurrentNode; - Debug.Assert(e != null); + Debug.Assert(e is not null); //we should skip the subregion XmlBoundElement? be = e as XmlBoundElement; - if (be != null && be.Row != null) + if (be is not null && be.Row is not null) { fMore = iter.NextRight(); //skip over the sub-region continue; @@ -1510,7 +1510,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r ReplaceInitialChildText(e, col.ConvertObjectToXml(value)); //make sure that if the Element has Attribute xsi:nil, its value is false XmlAttribute? attr = e.GetAttributeNode(XSI_NIL); - if (attr != null) + if (attr is not null) attr.Value = Keywords.FALSE; // no need to look any further. goto lblDoNestedRelationSync; @@ -1527,11 +1527,11 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r newElem.AppendChild(CreateTextNode(col.ConvertObjectToXml(value))); XmlNode? elemBefore = GetColumnInsertAfterLocation(row, col, rowElement); - if (elemBefore != null) + if (elemBefore is not null) { rowElement.InsertAfter(newElem, elemBefore); } - else if (rowElement.FirstChild != null) + else if (rowElement.FirstChild is not null) { rowElement.InsertBefore(newElem, rowElement.FirstChild); } @@ -1544,7 +1544,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r lblDoNestedRelationSync: // Change the XML to conform to the (potentially) change in parent nested relation DataRelation? relation = GetNestedParentRelation(row); - if (relation != null) + if (relation is not null) { Debug.Assert(relation.ChildTable == row.Table); if (relation.ChildKey.ContainsColumn(col)) @@ -1573,7 +1573,7 @@ private void OnColumnChanged(object sender, DataColumnChangeEventArgs args) if (row.RowState == DataRowState.Detached) { XmlBoundElement? be = row.Element; - Debug.Assert(be != null); + Debug.Assert(be is not null); if (be.IsFoliated) { // Need to sync changes from ROM to DOM @@ -1590,8 +1590,8 @@ private void OnColumnChanged(object sender, DataColumnChangeEventArgs args) private void OnColumnValuesChanged(DataRow row, XmlBoundElement rowElement) { - Debug.Assert(row != null); - Debug.Assert(rowElement != null); + Debug.Assert(row is not null); + Debug.Assert(rowElement is not null); // If user has cascading relationships, then columnChangeList will contains the changed columns only for the last row beeing cascaded // but there will be multiple ROM events @@ -1663,7 +1663,7 @@ private void OnFoliated(XmlNode node) foreach (DictionaryEntry entry in _pointers) { object? pointer = entry.Value; - Debug.Assert(pointer != null); + Debug.Assert(pointer is not null); ((IXmlDataVirtualNode)pointer).OnFoliated(node); } } @@ -1700,7 +1700,7 @@ private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, D bool fChildElementConnected = IsConnected(childElement); #endif DataRow? parentRowInTree; - if (childElement == DocumentElement || childElement.ParentNode == null) + if (childElement == DocumentElement || childElement.ParentNode is null) parentRowInTree = null; else parentRowInTree = GetRowFromElement((XmlElement)childElement.ParentNode); @@ -1708,7 +1708,7 @@ private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, D if (parentRowInTree != parentRowInRelation) { - if (parentRowInRelation != null) + if (parentRowInRelation is not null) { XmlElement newParent = GetElementFromRow(parentRowInRelation); newParent.AppendChild(childElement); @@ -1717,14 +1717,14 @@ private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, D { // no parent? Maybe the parentRow is during changing or childCol is the ID is set to null ( detached from the parent row ). DataRelation? relation = GetNestedParentRelation(child!); - if (childCol == null || relation == null || Convert.IsDBNull(child[childCol])) + if (childCol is null || relation is null || Convert.IsDBNull(child[childCol])) { EnsureNonRowDocumentElement().AppendChild(childElement); } else { DataColumn? colInParent = FindAssociatedParentColumn(relation, childCol); - Debug.Assert(colInParent != null); + Debug.Assert(colInParent is not null); object? comparedValue = colInParent.ConvertValue(child[childCol]); if (parentRowInTree!._tempRecord != -1 && colInParent.CompareValueTo(parentRowInTree._tempRecord, comparedValue) != 0) { @@ -1812,7 +1812,7 @@ private void OnNodeInserted(object sender, XmlNodeChangedEventArgs args) XmlNode? newParent = args.NewParent; // The code bellow assumes a move operation is fired by DOM in 2 steps: a Remvoe followed by an Insert - this is the 2nd part, the Insert. - Debug.Assert(oldParent == null); + Debug.Assert(oldParent is null); if (IsConnected(newParent)) { // Inserting a node to connected tree @@ -1863,7 +1863,7 @@ private void OnNodeRemoved(object sender, XmlNodeChangedEventArgs args) { XmlNode node = args.Node!; XmlNode? oldParent = args.OldParent; - Debug.Assert(args.NewParent == null); + Debug.Assert(args.NewParent is null); if (IsConnected(oldParent)) { @@ -1904,7 +1904,7 @@ private void OnNodeRemovedFromTree(XmlNode node, XmlNode? oldParent) // Disconnect all regions, starting w/ node (if it is a row-elem) XmlBoundElement? rowElem = node as XmlBoundElement; - if (rowElem != null && rowElem.Row != null) + if (rowElem is not null && rowElem.Row is not null) EnsureDisconnectedDataRow(rowElem); TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRowElement()) @@ -1933,7 +1933,7 @@ private void OnNodeRemovedFromFragment(XmlNode node, XmlNode? oldParent) // Need to set nested for the sub-regions (if node is a row-elem, we need to set it just for itself) XmlBoundElement? be = node as XmlBoundElement; - if (be != null && be.Row != null) + if (be is not null && be.Row is not null) { Debug.Assert(!IsRowLive(be.Row)); SetNestedParentRegion(be, null); @@ -1968,7 +1968,7 @@ private void OnRowChanged(object sender, DataRowChangeEventArgs args) DataRow row = args.Row; XmlBoundElement? rowElement = row.Element; // We should have an associated row-elem created when the DataRow was created (or at the load time) - Debug.Assert(rowElement != null); + Debug.Assert(rowElement is not null); switch (args.Action) { @@ -2024,7 +2024,7 @@ private void OnRowChanging(object sender, DataRowChangeEventArgs args) { // We foliate the region each time the assocaited row gets deleted DataRow row = args.Row; - if (args.Action == DataRowAction.Delete && row.Element != null) + if (args.Action == DataRowAction.Delete && row.Element is not null) { OnDeletingRow(row, row.Element); return; @@ -2045,7 +2045,7 @@ private void OnRowChanging(object sender, DataRowChangeEventArgs args) int nRec1 = -1; int nRec2 = -1; - if (rowElement != null) + if (rowElement is not null) { switch (args.Action) { @@ -2175,7 +2175,7 @@ private void OnDataSetRelationsChanging(object oRelationsCollection, CollectionC // Disallow changing the tables collection if there is data loaded and there are nested relationship that are added/refreshed DataRelation rel = (DataRelation)(args.Element); - if (rel != null && rel.Nested) + if (rel is not null && rel.Nested) throw new InvalidOperationException(SR.DataDom_DataSetNestedRelationsChange); // If Add and Remove, we should already been throwing if .Nested == false @@ -2204,19 +2204,19 @@ private void OnUndeleteRow(DataRow row, XmlElement rowElement) XmlElement parent; // make certain we weren't place somewhere else. - if (rowElement.ParentNode != null) + if (rowElement.ParentNode is not null) rowElement.ParentNode.RemoveChild(rowElement); // Find the parent of RowNode to be inserted DataRow? parentRowInRelation = GetNestedParent(row); - if (parentRowInRelation == null) + if (parentRowInRelation is null) { parent = EnsureNonRowDocumentElement(); } else parent = GetElementFromRow(parentRowInRelation); - if ((refRow = GetRowInsertBeforeLocation(row, rowElement, parent)) != null) + if ((refRow = GetRowInsertBeforeLocation(row, rowElement, parent)) is not null) parent.InsertBefore(rowElement, refRow); else parent.AppendChild(rowElement); @@ -2230,23 +2230,23 @@ private void PromoteChild(XmlNode child, XmlNode prevSibling) // It makes no sense to move rowElemChild on the same level Debug.Assert(child.ParentNode != prevSibling.ParentNode); // prevSibling must have a parent, since we want to add a sibling to it - Debug.Assert(prevSibling.ParentNode != null); + Debug.Assert(prevSibling.ParentNode is not null); Debug.Assert(IsFoliationEnabled == false); Debug.Assert(IgnoreXmlEvents == true); // Should not insert after docElem node Debug.Assert(prevSibling != DocumentElement); - if (child.ParentNode != null) + if (child.ParentNode is not null) child.ParentNode.RemoveChild(child); - Debug.Assert(child.ParentNode == null); + Debug.Assert(child.ParentNode is null); prevSibling.ParentNode.InsertAfter(child, prevSibling); } // Promote child regions under parent as next siblings of parent private void PromoteInnerRegions(XmlNode parent) { - Debug.Assert(parent != null); + Debug.Assert(parent is not null); Debug.Assert(parent.NodeType != XmlNodeType.Attribute); // We need to get the grand-parent region Debug.Assert(parent != DocumentElement); // We cannot promote children of the DocumentElement @@ -2258,7 +2258,7 @@ private void PromoteInnerRegions(XmlNode parent) bool fMore = iter.NextRowElement(); while (fMore) { - Debug.Assert(iter.CurrentNode is XmlBoundElement && ((XmlBoundElement)(iter.CurrentNode)).Row != null); + Debug.Assert(iter.CurrentNode is XmlBoundElement && ((XmlBoundElement)(iter.CurrentNode)).Row is not null); XmlBoundElement rowElemChild = (XmlBoundElement)(iter.CurrentNode); fMore = iter.NextRightRowElement(); PromoteChild(rowElemChild, prevSibling); @@ -2268,12 +2268,12 @@ private void PromoteInnerRegions(XmlNode parent) private void PromoteNonValueChildren(XmlNode parent) { - Debug.Assert(parent != null); + Debug.Assert(parent is not null); XmlNode prevSibling = parent; XmlNode? child = parent.FirstChild; bool bTextLikeNode = true; XmlNode? nextSibling = null; - while (child != null) + while (child is not null) { nextSibling = child.NextSibling; if (!bTextLikeNode || !IsTextLikeNode(child)) @@ -2289,7 +2289,7 @@ private void PromoteNonValueChildren(XmlNode parent) private void RemoveInitialTextNodes(XmlNode? node) { - while (node != null && IsTextLikeNode(node)) + while (node is not null && IsTextLikeNode(node)) { XmlNode? sibling = node.NextSibling; node.ParentNode!.RemoveChild(node); @@ -2302,10 +2302,10 @@ private void ReplaceInitialChildText(XmlNode parent, string value) XmlNode? n = parent.FirstChild; // don't consider whitespace when replacing initial text - while (n != null && n.NodeType == XmlNodeType.Whitespace) + while (n is not null && n.NodeType == XmlNodeType.Whitespace) n = n.NextSibling; - if (n != null) + if (n is not null) { if (n.NodeType == XmlNodeType.Text) n.Value = value; @@ -2322,7 +2322,7 @@ private void ReplaceInitialChildText(XmlNode parent, string value) internal XmlNode? SafeFirstChild(XmlNode n) { XmlBoundElement? be = n as XmlBoundElement; - if (be != null) + if (be is not null) return be.SafeFirstChild; else //other type of node should be already foliated. @@ -2332,7 +2332,7 @@ private void ReplaceInitialChildText(XmlNode parent, string value) internal XmlNode? SafeNextSibling(XmlNode n) { XmlBoundElement? be = n as XmlBoundElement; - if (be != null) + if (be is not null) return be.SafeNextSibling; else //other type of node should be already foliated. @@ -2342,7 +2342,7 @@ private void ReplaceInitialChildText(XmlNode parent, string value) internal XmlNode? SafePreviousSibling(XmlNode n) { XmlBoundElement? be = n as XmlBoundElement; - if (be != null) + if (be is not null) return be.SafePreviousSibling; else //other type of node should be already foliated. @@ -2361,14 +2361,14 @@ internal static void SetRowValueToNull(DataRow row, DataColumn col) internal static void SetRowValueFromXmlText(DataRow row, DataColumn col, string xmlText) { - Debug.Assert(xmlText != null); + Debug.Assert(xmlText is not null); Debug.Assert(row.Table.DataSet!.EnforceConstraints == false); object oVal; try { oVal = col.ConvertXmlToObject(xmlText); // This func does not set the field value to null - call SetRowValueToNull in order to do so - Debug.Assert(oVal != null && !(oVal is DBNull)); + Debug.Assert(oVal is not null && !(oVal is DBNull)); } catch (Exception e) when (Data.Common.ADP.IsCatchableExceptionType(e)) { @@ -2386,11 +2386,11 @@ private void SynchronizeRowFromRowElement(XmlBoundElement rowElement) SynchronizeRowFromRowElement(rowElement, null); } // Sync row fields w/ values from rowElem region. - // If rowElemList is != null, all subregions of rowElem are appended to it. + // If rowElemList is is not null, all subregions of rowElem are appended to it. private void SynchronizeRowFromRowElement(XmlBoundElement rowElement, ArrayList? rowElemList) { DataRow? row = rowElement.Row; - Debug.Assert(row != null); + Debug.Assert(row is not null); // No synchronization needed for deleted rows if (row.RowState == DataRowState.Deleted) @@ -2426,12 +2426,12 @@ private void SynchronizeRowFromRowElement(XmlBoundElement rowElement, ArrayList? } private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayList? rowElemList) { - Debug.Assert(rowElement != null); - Debug.Assert(rowElement.Row != null); + Debug.Assert(rowElement is not null); + Debug.Assert(rowElement.Row is not null); Debug.Assert(DataSet.EnforceConstraints == false); DataRow row = rowElement.Row; - Debug.Assert(row != null); + Debug.Assert(row is not null); Hashtable foundColumns = new Hashtable(); string xsi_attrVal = string.Empty; @@ -2440,7 +2440,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis bool fMore; // If present, fill up the TextOnly column DataColumn? column = GetTextOnlyColumn(row); - if (column != null) + if (column is not null) { foundColumns[column] = column; string value; @@ -2457,16 +2457,16 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis while (fMore) { XmlElement? e = iter.CurrentNode as XmlElement; - if (e == null) + if (e is null) { fMore = iter.Next(); continue; } XmlBoundElement? be = e as XmlBoundElement; - if (be != null && be.Row != null) + if (be is not null && be.Row is not null) { - if (rowElemList != null) + if (rowElemList is not null) rowElemList.Add(e); // Skip over sub-regions fMore = iter.NextRight(); @@ -2474,10 +2474,10 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis } DataColumn? c = _mapper.GetColumnSchemaForNode(rowElement, e); - if (c != null) + if (c is not null) { Debug.Assert(c.Table == row.Table); - if (foundColumns[c] == null) + if (foundColumns[c] is null) { foundColumns[c] = c; string value; @@ -2500,9 +2500,9 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis { DataColumn? c = _mapper.GetColumnSchemaForNode(rowElement, attr); - if (c != null) + if (c is not null) { - if (foundColumns[c] == null) + if (foundColumns[c] is null) { foundColumns[c] = c; SetRowValueFromXmlText(row, c, attr.Value); @@ -2513,7 +2513,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis // Null all columns values that aren't represented in the tree foreach (DataColumn c in row.Table.Columns) { - if (foundColumns[c] == null && !IsNotMapped(c)) + if (foundColumns[c] is null && !IsNotMapped(c)) { if (!c.AutoIncrement) SetRowValueToNull(row, c); @@ -2594,7 +2594,7 @@ private void Init() [MemberNotNull(nameof(_dataSet))] private void Init(DataSet ds) { - if (ds == null) + if (ds is null) throw new ArgumentException(SR.DataDom_DataSetNull); Init(); if (ds.FBoundToDocument) @@ -2608,13 +2608,13 @@ private bool IsConnected(XmlNode? node) { while (true) { - if (node == null) + if (node is null) return false; if (node == this) return true; XmlAttribute? attr = node as XmlAttribute; - if (attr != null) + if (attr is not null) node = attr.OwnerElement; else node = node.ParentNode; @@ -2628,9 +2628,9 @@ private static void SetNestedParentRow(DataRow childRow, DataRow? parentRow) { DataRelation? rel = GetNestedParentRelation(childRow); //we should not set this row's parentRow if the table doesn't match. - if (rel != null) + if (rel is not null) { - if (parentRow == null || rel.ParentKey.Table != parentRow.Table) + if (parentRow is null || rel.ParentKey.Table != parentRow.Table) childRow.SetParentRow(null, rel); else childRow.SetParentRow(parentRow, rel); @@ -2664,11 +2664,11 @@ private void OnNodeInsertedInTree(XmlNode node) // Process subregions, so they make transition from disconnected to connected tree while (rowElemList.Count > 0) { - Debug.Assert(rowElemList[0] != null && rowElemList[0] is XmlBoundElement); + Debug.Assert(rowElemList[0] is not null && rowElemList[0] is XmlBoundElement); XmlBoundElement? subRowElem = (XmlBoundElement?)(rowElemList[0]); rowElemList.RemoveAt(0); // Expect rowElem to have a DataTable schema, since it is a sub-region - Debug.Assert(subRowElem != null); + Debug.Assert(subRowElem is not null); OnRowElementInsertedInTree(subRowElem, rowElemList); } @@ -2693,7 +2693,7 @@ private void OnNodeInsertedInFragment(XmlNode node) // Set nested parent for the 1st level subregions (they should already be associated w/ Deleted or Detached rows) while (rowElemList.Count > 0) { - Debug.Assert(rowElemList[0] != null && rowElemList[0] is XmlBoundElement); + Debug.Assert(rowElemList[0] is not null && rowElemList[0] is XmlBoundElement); XmlBoundElement subRowElem = (XmlBoundElement)(rowElemList[0]!); rowElemList.RemoveAt(0); SetNestedParentRegion(subRowElem, be); @@ -2715,7 +2715,7 @@ private void OnNodeInsertedInFragment(XmlNode node) // A row-elem was inserted into the connected tree (connected) from oldParent==null state private void OnRowElementInsertedInTree(XmlBoundElement rowElem, ArrayList rowElemList) { - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); DataRow row = rowElem.Row; DataRowState rowState = row.RowState; @@ -2739,7 +2739,7 @@ private void OnRowElementInsertedInTree(XmlBoundElement rowElem, ArrayList rowEl } #endif // Add all sub-regions to the list if the caller needs this - if (rowElemList != null) + if (rowElemList is not null) { RegionIterator iter = new RegionIterator(rowElem); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRightRowElement()) @@ -2777,7 +2777,7 @@ private void OnRowElementInsertedInTree(XmlBoundElement rowElem, ArrayList rowEl // Disconnect the DataRow associated w/ the rowElem region private void EnsureDisconnectedDataRow(XmlBoundElement rowElem) { - Debug.Assert(rowElem.Row != null); + Debug.Assert(rowElem.Row is not null); DataRow row = rowElem.Row; DataRowState rowState = row.RowState; @@ -2832,9 +2832,9 @@ private void OnNonRowElementInsertedInTree(XmlNode node, XmlBoundElement rowElem // non-row-elem is beeing inserted DataRow? row = rowElement.Row; // Region should already have an associated data row (otherwise how was the original row-elem inserted ?) - Debug.Assert(row != null); + Debug.Assert(row is not null); SynchronizeRowFromRowElement(rowElement); - if (rowElemList != null) + if (rowElemList is not null) { TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRightRowElement()) @@ -2848,8 +2848,8 @@ private void OnNonRowElementInsertedInFragment(XmlNode node, XmlBoundElement row // non-row-elem is beeing inserted DataRow? row = rowElement.Row; // Region should already have an associated data row (otherwise how was the original row-elem inserted ?) - Debug.Assert(row != null); - // Since oldParent == null, the only 2 row states should have been Detached or Deleted + Debug.Assert(row is not null); + // Since oldParent is null, the only 2 row states should have been Detached or Deleted Debug.Assert(row.RowState == DataRowState.Detached || row.RowState == DataRowState.Deleted); if (row.RowState == DataRowState.Detached) @@ -2859,7 +2859,7 @@ private void OnNonRowElementInsertedInFragment(XmlNode node, XmlBoundElement row private void SetNestedParentRegion(XmlBoundElement childRowElem) { - Debug.Assert(childRowElem.Row != null); + Debug.Assert(childRowElem.Row is not null); XmlBoundElement? parentRowElem; _mapper.GetRegion(childRowElem.ParentNode, out parentRowElem); @@ -2868,13 +2868,13 @@ private void SetNestedParentRegion(XmlBoundElement childRowElem) private void SetNestedParentRegion(XmlBoundElement childRowElem, XmlBoundElement? parentRowElem) { DataRow childRow = childRowElem.Row!; - if (parentRowElem == null) + if (parentRowElem is null) { SetNestedParentRow(childRow, null); return; } - Debug.Assert(parentRowElem.Row != null); + Debug.Assert(parentRowElem.Row is not null); DataRow parentRow = parentRowElem.Row; // We should set it only if there is a nested relationship between this child and parent regions DataRelation[] relations = childRow.Table.NestedParentRelations; @@ -2916,7 +2916,7 @@ internal static bool IsWhiteSpace(char ch) { } internal static bool IsOnlyWhitespace( string str ) { - if (str != null) { + if (str is not null) { for (int index = 0; index < str.Length; index ++) { if (! IsWhiteSpace(str[index])) return false; @@ -2934,18 +2934,18 @@ internal static bool IsOnlyWhitespace( string str ) { if (IsTextNode(node.NodeType)) { XmlNode? parent = node.ParentNode; - if (parent != null && parent.NodeType == XmlNodeType.Attribute) + if (parent is not null && parent.NodeType == XmlNodeType.Attribute) return null; else { #if DEBUG //if current node is a text node, its parent node has to be foliated XmlBoundElement? be = node.ParentNode as XmlBoundElement; - if (be != null) + if (be is not null) Debug.Assert(be.IsFoliated); #endif XmlNode? prevSib = node.PreviousSibling; - while (prevSib != null && IsTextNode(prevSib.NodeType)) + while (prevSib is not null && IsTextNode(prevSib.NodeType)) { node = prevSib; prevSib = SafePreviousSibling(node); @@ -2963,13 +2963,13 @@ private void AssertLiveRows(XmlNode node) try { XmlBoundElement? rowElement = node as XmlBoundElement; - if (rowElement != null && rowElement.Row != null) + if (rowElement is not null && rowElement.Row is not null) Debug.Assert(IsRowLive(rowElement.Row)); TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRowElement()) { rowElement = iter.CurrentNode as XmlBoundElement; - Debug.Assert(rowElement!.Row != null); + Debug.Assert(rowElement!.Row is not null); Debug.Assert(IsRowLive(rowElement.Row)); } } @@ -2986,13 +2986,13 @@ private void AssertNonLiveRows(XmlNode node) try { XmlBoundElement? rowElement = node as XmlBoundElement; - if (rowElement != null && rowElement.Row != null) + if (rowElement is not null && rowElement.Row is not null) Debug.Assert(!IsRowLive(rowElement.Row)); TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRowElement()) { rowElement = iter.CurrentNode as XmlBoundElement; - Debug.Assert(rowElement!.Row != null); + Debug.Assert(rowElement!.Row is not null); Debug.Assert(!IsRowLive(rowElement.Row)); } } @@ -3023,7 +3023,7 @@ public override XmlNodeList GetElementsByTagName(string name) private DataTable[] OrderTables(DataSet? ds) { DataTable[]? retValue = null; - if (ds == null || ds.Tables.Count == 0) + if (ds is null || ds.Tables.Count == 0) { retValue = Array.Empty(); } @@ -3035,7 +3035,7 @@ private DataTable[] OrderTables(DataSet? ds) // same as Everett } - if (null == retValue) + if (retValue is null) { retValue = new DataTable[ds!.Tables.Count]; List tableList = new List(); @@ -3059,7 +3059,7 @@ private DataTable[] OrderTables(DataSet? ds) } for (int readPos = 0; readPos < tableList.Count; readPos++) { - Debug.Assert(tableList[readPos] != null, "Temp Array is not supposed to reach to null"); + Debug.Assert(tableList[readPos] is not null, "Temp Array is not supposed to reach to null"); foreach (DataRelation r in tableList[readPos].ChildRelations) { DataTable childTable = r.ChildTable; diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs index 60eda2401f9896..0126a1f33a3ee5 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs @@ -388,8 +388,8 @@ internal static ArgumentException InvalidSizeValue(int value) internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { // WebData 75433 - Debug.Assert(null != value, "null value on conversion failure"); - Debug.Assert(null != inner, "null inner on conversion failure"); + Debug.Assert(value is not null, "null value on conversion failure"); + Debug.Assert(inner is not null, "null inner on conversion failure"); Exception e; string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); @@ -574,7 +574,7 @@ internal static Exception UnsupportedVersion(string collectionName) internal static Delegate? FindBuilder(MulticastDelegate mcd) { // V1.2.3300 - if (null != mcd) + if (mcd is not null) { Delegate[] d = mcd.GetInvocationList(); for (int i = 0; i < d.Length; i++) @@ -653,7 +653,7 @@ internal static string GetFullPath(string filename) internal static int StringLength(string? inputString) { - return ((null != inputString) ? inputString.Length : 0); + return ((inputString is not null) ? inputString.Length : 0); } internal static IntPtr IntPtrOffset(IntPtr pbase, int offset) diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs index dba3fdbbc37e47..dd6d9d40999806 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs @@ -64,7 +64,7 @@ internal DBConnectionString(DbConnectionOptions connectionOptions) private DBConnectionString(DbConnectionOptions connectionOptions, string? restrictions, KeyRestrictionBehavior behavior, Dictionary? synonyms, bool mustCloneDictionary) { // used by DBDataPermission - Debug.Assert(null != connectionOptions, "null connectionOptions"); + Debug.Assert(connectionOptions is not null, "null connectionOptions"); switch (behavior) { case KeyRestrictionBehavior.PreventUsage: @@ -157,10 +157,10 @@ internal string Restrictions get { string? restrictions = _restrictions; - if (null == restrictions) + if (restrictions is null) { string[]? restrictionValues = _restrictionValues; - if ((null != restrictionValues) && (0 < restrictionValues.Length)) + if ((restrictionValues is not null) && (0 < restrictionValues.Length)) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < restrictionValues.Length; ++i) @@ -180,7 +180,7 @@ internal string Restrictions restrictions = builder.ToString(); } } - return ((null != restrictions) ? restrictions : ""); + return ((restrictions is not null) ? restrictions : ""); } } @@ -199,7 +199,7 @@ internal DBConnectionString Intersect(DBConnectionString? entry) KeyRestrictionBehavior behavior = _behavior; string[]? restrictionValues = null; - if (null == entry) + if (entry is null) { //Debug.WriteLine("0 entry AllowNothing"); behavior = KeyRestrictionBehavior.AllowOnly; @@ -284,7 +284,7 @@ internal DBConnectionString Intersect(DBConnectionString? entry) // verify _hasPassword & _parsetable are in [....] between Everett/Whidbey Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this"); - Debug.Assert(null == entry || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry"); + Debug.Assert(entry is null || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry"); DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior); ValidateCombinedSet(this, value); @@ -296,8 +296,8 @@ internal DBConnectionString Intersect(DBConnectionString? entry) [Conditional("DEBUG")] private void ValidateCombinedSet(DBConnectionString? componentSet, DBConnectionString combinedSet) { - Debug.Assert(combinedSet != null, "The combined connection string should not be null"); - if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null)) + Debug.Assert(combinedSet is not null, "The combined connection string should not be null"); + if ((componentSet is not null) && (combinedSet._restrictionValues is not null) && (componentSet._restrictionValues is not null)) { if (componentSet._behavior == KeyRestrictionBehavior.AllowOnly) { @@ -305,7 +305,7 @@ private void ValidateCombinedSet(DBConnectionString? componentSet, DBConnectionS { // Component==Allow, Combined==Allow // All values in the Combined Set should also be in the Component Set - // Combined - Component == null + // Combined - Component is null Debug.Assert(!combinedSet._restrictionValues.Except(componentSet._restrictionValues).Any(), "Combined set allows values not allowed by component set"); } else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage) @@ -324,14 +324,14 @@ private void ValidateCombinedSet(DBConnectionString? componentSet, DBConnectionS { // Component==PreventUsage, Combined==Allow // There shouldn't be any of the values from the Component Set in the Combined Set - // Intersect(Component, Combined) == null + // Intersect(Component, Combined) is null Debug.Assert(!combinedSet._restrictionValues.Intersect(componentSet._restrictionValues).Any(), "Combined values allows values prevented by component set"); } else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage) { // Component==PreventUsage, Combined==PreventUsage // All values in the Component Set should also be in the Combined Set - // Component - Combined == null + // Component - Combined is null Debug.Assert(!componentSet._restrictionValues.Except(combinedSet._restrictionValues).Any(), "Combined values does not prevent all of the values prevented by the component set"); } else @@ -362,7 +362,7 @@ internal bool IsSupersetOf(DBConnectionString entry) case KeyRestrictionBehavior.AllowOnly: // every key must either be in the resticted connection string or in the allowed keywords // keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys - for (NameValuePair? current = entry.KeyChain; null != current; current = current.Next) + for (NameValuePair? current = entry.KeyChain; current is not null; current = current.Next) { if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name)) { @@ -397,7 +397,7 @@ internal bool IsSupersetOf(DBConnectionString entry) { if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal)) { - if (null == newlist) + if (newlist is null) { newlist = new List(); } @@ -405,7 +405,7 @@ internal bool IsSupersetOf(DBConnectionString entry) } } string[]? restrictionValues = null; - if (null != newlist) + if (newlist is not null) { restrictionValues = newlist.ToArray(); } @@ -420,7 +420,7 @@ internal bool IsSupersetOf(DBConnectionString entry) { if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal)) { - if (null == newlist) + if (newlist is null) { newlist = new List(); } @@ -428,7 +428,7 @@ internal bool IsSupersetOf(DBConnectionString entry) } } string[]? restrictionValues = null; - if (newlist != null) + if (newlist is not null) { restrictionValues = newlist.ToArray(); } @@ -439,8 +439,8 @@ internal bool IsSupersetOf(DBConnectionString entry) private static string[] NoDuplicateUnion(string[] a, string[] b) { #if DEBUG - Debug.Assert(null != a && 0 < a.Length, "empty a"); - Debug.Assert(null != b && 0 < b.Length, "empty b"); + Debug.Assert(a is not null && 0 < a.Length, "empty a"); + Debug.Assert(b is not null && 0 < b.Length, "empty b"); Verify(a); Verify(b); #endif @@ -477,7 +477,7 @@ private static string[] NoDuplicateUnion(string[] a, string[] b) nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue); if (!string.IsNullOrEmpty(keyname)) { - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 + string realkeyname = ((synonyms is not null) ? (string)synonyms[keyname] : keyname); // MDAC 85144 if (string.IsNullOrEmpty(realkeyname)) { throw ADP.KeywordNotSupported(keyname); @@ -530,7 +530,7 @@ internal static string[] RemoveDuplicates(string?[] restrictions) [ConditionalAttribute("DEBUG")] private static void Verify(string?[]? restrictionValues) { - if (null != restrictionValues) + if (restrictionValues is not null) { for (int i = 1; i < restrictionValues.Length; ++i) { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs index 893a3e2084a4c6..c4b1db47922442 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs @@ -45,7 +45,7 @@ public DbConnectionOptions(string connectionString, Dictionary? { _useOdbcRules = useOdbcRules; _parsetable = new Dictionary(); - _usersConnectionString = ((null != connectionString) ? connectionString : ""); + _usersConnectionString = ((connectionString is not null) ? connectionString : ""); // first pass on parsing, initial syntax check if (0 < _usersConnectionString.Length) @@ -120,11 +120,11 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); - if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) + if ((keyName is null) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) { throw ADP.InvalidKeyname(keyName); } - if ((null != keyValue) && !IsValueValidInternal(keyValue)) + if ((keyValue is not null) && !IsValueValidInternal(keyValue)) { throw ADP.InvalidValue(keyName); } @@ -144,7 +144,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key } builder.Append('='); - if (null != keyValue) + if (keyValue is not null) { // else =; if (useOdbcRules) { @@ -194,7 +194,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key public bool ConvertValueToIntegratedSecurity() { object? value = _parsetable[KEY.Integrated_Security]; - if (null == value) + if (value is null) { return false; } @@ -224,7 +224,7 @@ internal bool ConvertValueToIntegratedSecurityInternal(string stringValue) public int ConvertValueToInt32(string keyName, int defaultValue) { object? value = _parsetable[keyName]; - if (null == value) + if (value is null) { return defaultValue; } @@ -250,7 +250,7 @@ internal static int ConvertToInt32Internal(string keyname, string stringValue) public string ConvertValueToString(string keyName, string defaultValue) { string? value = _parsetable[keyName]; - return ((null != value) ? value : defaultValue); + return ((value is not null) ? value : defaultValue); } public bool ContainsKey(string keyword) @@ -265,15 +265,15 @@ public bool ContainsKey(string keyword) internal static string? ExpandDataDirectory(string keyword, string? value, ref string? datadir) { string? fullPath = null; - if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) + if ((value is not null) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) { string? rootFolderPath = datadir; - if (null == rootFolderPath) + if (rootFolderPath is null) { // find the replacement path object? rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); rootFolderPath = (rootFolderObject as string); - if ((null != rootFolderObject) && (null == rootFolderPath)) + if ((rootFolderObject is not null) && (rootFolderPath is null)) { throw ADP.InvalidDataDirectory(); } @@ -281,7 +281,7 @@ public bool ContainsKey(string keyword) { rootFolderPath = AppDomain.CurrentDomain.BaseDirectory; } - if (null == rootFolderPath) + if (rootFolderPath is null) { rootFolderPath = ""; } @@ -329,7 +329,7 @@ public bool ContainsKey(string keyword) int copyPosition = 0; bool expanded = false; - for (NameValuePair? current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; current is not null; current = current.Next) { value = current.Value; @@ -372,7 +372,7 @@ public bool ContainsKey(string keyword) break; } } - if (null == value) + if (value is null) { value = current.Value; } @@ -420,7 +420,7 @@ internal string ExpandKeyword(string keyword, string replacementValue) int copyPosition = 0; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair? current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; current is not null; current = current.Next) { if ((current.Name == keyword) && (current.Value == this[keyword])) { @@ -448,11 +448,11 @@ internal string ExpandKeyword(string keyword, string replacementValue) internal static void ValidateKeyValuePair(string keyword, string value) { - if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) + if ((keyword is null) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) { throw ADP.InvalidKeyname(keyword); } - if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value)) + if ((value is not null) && !s_connectionStringValidValueRegex.IsMatch(value)) { throw ADP.InvalidValue(keyword); } diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs index 7c7c32497976d0..8accd03dab5d99 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs @@ -154,9 +154,9 @@ internal static class DbConnectionStringBuilderUtil { internal static bool ConvertToBoolean(object value) { - Debug.Assert(null != value, "ConvertToBoolean(null)"); + Debug.Assert(value is not null, "ConvertToBoolean(null)"); string? svalue = (value as string); - if (null != svalue) + if (svalue is not null) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) { @@ -193,9 +193,9 @@ internal static bool ConvertToBoolean(object value) internal static bool ConvertToIntegratedSecurity(object value) { - Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)"); + Debug.Assert(value is not null, "ConvertToIntegratedSecurity(null)"); string? svalue = (value as string); - if (null != svalue) + if (svalue is not null) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs index 004fcd7832fa7a..0e6bd44eabeab2 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs @@ -43,7 +43,7 @@ private NameValuePermission(NameValuePermission permit) NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[])!; for (int i = 0; i < tree.Length; ++i) { - if (null != tree[i]) + if (tree[i] is not null) { // WebData 98488 tree[i] = tree[i].CopyNameValue(); // deep copy } @@ -59,16 +59,16 @@ int IComparable.CompareTo(object? a) internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBConnectionString entry) { - Debug.Assert(null != entry, "null DBConnectionString"); + Debug.Assert(entry is not null, "null DBConnectionString"); - if (null != entry.KeyChain) + if (entry.KeyChain is not null) { - for (NameValuePair? keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) + for (NameValuePair? keychain = entry.KeyChain; keychain is not null; keychain = keychain.Next) { NameValuePermission? kv; kv = kvtree.CheckKeyForValue(keychain.Name); - if (null == kv) + if (kv is null) { kv = new NameValuePermission(keychain.Name); kvtree.Add(kv); // add directly into live tree @@ -76,19 +76,19 @@ internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC kvtree = kv; kv = kvtree.CheckKeyForValue(keychain.Value); - if (null == kv) + if (kv is null) { - DBConnectionString? insertValue = ((null != keychain.Next) ? null : entry); + DBConnectionString? insertValue = ((keychain.Next is not null) ? null : entry); kv = new NameValuePermission(keychain.Value, insertValue); kvtree.Add(kv); // add directly into live tree - if (null != insertValue) + if (insertValue is not null) { entries.Add(insertValue); } } - else if (null == keychain.Next) + else if (keychain.Next is null) { // shorter chain potential - if (null != kv._entry) + if (kv._entry is not null) { Debug.Assert(entries.Contains(kv._entry), "entries doesn't contain entry"); entries.Remove(kv._entry); @@ -106,7 +106,7 @@ internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC else { // global restrictions, MDAC 84443 DBConnectionString? kentry = kvtree._entry; - if (null != kentry) + if (kentry is not null) { Debug.Assert(entries.Contains(kentry), "entries doesn't contain entry"); entries.Remove(kentry); @@ -122,7 +122,7 @@ internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC internal void Intersect(ArrayList entries, NameValuePermission target) { - if (null == target) + if (target is null) { _tree = null; _entry = null; @@ -135,7 +135,7 @@ internal void Intersect(ArrayList entries, NameValuePermission target) _entry = _entry.Intersect(target._entry); entries.Add(_entry); } - else if (null != target._entry) + else if (target._entry is not null) { _entry = target._entry.Intersect(null); entries.Add(_entry); @@ -147,7 +147,7 @@ internal void Intersect(ArrayList entries, NameValuePermission target) for (int i = 0; i < _tree.Length; ++i) { NameValuePermission? kvtree = target.CheckKeyForValue(_tree[i]._value); - if (null != kvtree) + if (kvtree is not null) { // does target tree contain our value _tree[i].Intersect(entries, kvtree); } @@ -180,7 +180,7 @@ internal void Intersect(ArrayList entries, NameValuePermission target) private void Add(NameValuePermission permit) { NameValuePermission[]? tree = _tree; - int length = ((null != tree) ? tree.Length : 0); + int length = ((tree is not null) ? tree.Length : 0); NameValuePermission[] newtree = new NameValuePermission[1 + length]; for (int i = 0; i < newtree.Length - 1; ++i) { @@ -193,13 +193,13 @@ private void Add(NameValuePermission permit) internal bool CheckValueForKeyPermit(DBConnectionString parsetable) { - if (null == parsetable) + if (parsetable is null) { return false; } bool hasMatch = false; NameValuePermission[]? keytree = _tree; // _tree won't mutate but Add will replace it - if (null != keytree) + if (keytree is not null) { hasMatch = parsetable.IsEmpty; // MDAC 86773 if (!hasMatch) @@ -208,11 +208,11 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) for (int i = 0; i < keytree.Length; ++i) { NameValuePermission permitKey = keytree[i]; - if (null != permitKey) + if (permitKey is not null) { string keyword = permitKey._value!; #if DEBUG - Debug.Assert(null == permitKey._entry, "key member has no restrictions"); + Debug.Assert(permitKey._entry is null, "key member has no restrictions"); #endif if (parsetable.ContainsKey(keyword)) { @@ -220,7 +220,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) // keyword is restricted to certain values NameValuePermission? permitValue = permitKey.CheckKeyForValue(valueInQuestion); - if (null != permitValue) + if (permitValue is not null) { //value does match - continue the chain down that branch if (permitValue.CheckValueForKeyPermit(parsetable)) @@ -249,7 +249,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) } DBConnectionString? entry = _entry; - if (null != entry) + if (entry is not null) { // also checking !hasMatch is tempting, but wrong // user can safetly extend their restrictions for current rule to include missing keyword @@ -264,7 +264,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) private NameValuePermission? CheckKeyForValue(string? keyInQuestion) { NameValuePermission[]? valuetree = _tree; // _tree won't mutate but Add will replace it - if (null != valuetree) + if (valuetree is not null) { for (int i = 0; i < valuetree.Length; ++i) { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs index e885ac9380b67e..c85934f68e92db 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs @@ -145,7 +145,7 @@ internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int le offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -178,7 +178,7 @@ internal char[] ReadChars(int offset, char[] destination, int startIndex, int le offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -237,7 +237,7 @@ internal void ReadInt16Array(int offset, short[] destination, int startIndex, in offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -289,7 +289,7 @@ internal void ReadInt32Array(int offset, int[] destination, int startIndex, int offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -382,7 +382,7 @@ protected override bool ReleaseHandle() private void StructureToPtr(int offset, object structure) { - Debug.Assert(null != structure, "null structure"); + Debug.Assert(structure is not null, "null structure"); offset += BaseOffset; ValidateCheck(offset, Marshal.SizeOf(structure.GetType())); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); @@ -434,7 +434,7 @@ internal void WriteBytes(int offset, byte[] source, int startIndex, int length) offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -460,7 +460,7 @@ internal void WriteCharArray(int offset, char[] source, int startIndex, int leng offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -515,7 +515,7 @@ internal void WriteInt16Array(int offset, short[] source, int startIndex, int le offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -565,7 +565,7 @@ internal void WriteInt32Array(int offset, int[] source, int startIndex, int leng offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs index 5e37564f0710fc..ec70fd371fd23d 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs @@ -12,7 +12,7 @@ internal abstract partial class DbConnectionFactory { internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource? retry, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection, out DbConnectionInternal? connection) { - Debug.Assert(null != owningConnection, "null owningConnection?"); + Debug.Assert(owningConnection is not null, "null owningConnection?"); DbConnectionPoolGroup poolGroup; DbConnectionPool? connectionPool; @@ -35,14 +35,14 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour poolGroup = GetConnectionPoolGroup(owningConnection)!; // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); - if (null == connectionPool) + if (connectionPool is null) { // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool // or have a disabled pool entry. poolGroup = GetConnectionPoolGroup(owningConnection)!; // previous entry have been disabled - if (retry != null) + if (retry is not null) { Task newTask; CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); @@ -53,7 +53,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++) { Task task = s_pendingOpenNonPooled[idx]; - if (task == null) + if (task is null) { s_pendingOpenNonPooled[idx] = GetCompletedTask(); break; @@ -80,7 +80,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) => { var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); - if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open)) + if ((oldConnection is not null) && (oldConnection.State == ConnectionState.Open)) { oldConnection.PrepareForReplaceConnection(); oldConnection.Dispose(); @@ -145,7 +145,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour } //} - if (connection == null) + if (connection is null) { // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) @@ -163,9 +163,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour } } } - } while (connection == null && retriesLeft-- > 0); + } while (connection is null && retriesLeft-- > 0); - if (connection == null) + if (connection is null) { // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs index 09d49bb131d68e..f720ef4fe808de 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs @@ -55,7 +55,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // if the DbConnectionInternal derived class needs to close the connection it should // delegate to the DbConnection if one exists or directly call dispose // DbConnection owningObject = (DbConnection)Owner; - // if (null != owningObject) { + // if (owningObject is not null) { // owningObject.Close(); // force the closed state on the outer object. // } // else { @@ -65,8 +65,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// // DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING! //////////////////////////////////////////////////////////////// - Debug.Assert(null != owningObject, "null owningObject"); - Debug.Assert(null != connectionFactory, "null connectionFactory"); + Debug.Assert(owningObject is not null, "null owningObject"); + Debug.Assert(connectionFactory is not null, "null connectionFactory"); // if an exception occurs after the state change but before the try block @@ -90,7 +90,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // The singleton closed classes won't have owners and // connection pools, and we won't want to put them back // into the pool. - if (null != connectionPool) + if (connectionPool is not null) { connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us... // NOTE: Before we leave the PutObject call, another diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs index ab2d89be6121ac..5a82a23ec44014 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs @@ -137,9 +137,9 @@ internal DbConnectionPool( DbConnectionPoolIdentity identity, DbConnectionPoolProviderInfo? connectionPoolProviderInfo) { - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); + Debug.Assert(connectionPoolGroup is not null, "null connectionPoolGroup"); - if ((null != identity) && identity.IsRestricted) + if ((identity is not null) && identity.IsRestricted) { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken); } @@ -298,7 +298,7 @@ private void CleanupCallback(object? state) if (_stackOld.TryPop(out obj)) { - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); // If we obtained one from the old stack, destroy it. DestroyObject(obj); @@ -328,7 +328,7 @@ private void CleanupCallback(object? state) if (!_stackNew.TryPop(out obj)) break; - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); @@ -356,7 +356,7 @@ internal void Clear() { obj = _objectList[i]; - if (null != obj) + if (obj is not null) { obj.DoNotPoolThisConnection(); } @@ -366,12 +366,12 @@ internal void Clear() // Second, dispose of all the free connections. while (_stackNew.TryPop(out obj)) { - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); DestroyObject(obj); } while (_stackOld.TryPop(out obj)) { - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); DestroyObject(obj); } @@ -394,7 +394,7 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti try { newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions); - if (null == newObj) + if (newObj is null) { throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object } @@ -406,7 +406,7 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti lock (_objectList) { - if ((oldConnection != null) && (oldConnection.Pool == this)) + if ((oldConnection is not null) && (oldConnection.Pool == this)) { _objectList.Remove(oldConnection); } @@ -415,10 +415,10 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti } // If the old connection belonged to another pool, we need to remove it from that - if (oldConnection != null) + if (oldConnection is not null) { var oldConnectionPool = oldConnection.Pool; - if (oldConnectionPool != null && oldConnectionPool != this) + if (oldConnectionPool is not null && oldConnectionPool != this) { Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down"); lock (oldConnectionPool._objectList) @@ -579,7 +579,7 @@ private void ErrorCallback(object? state) // the error state is cleaned, destroy the timer to avoid periodic invocation Timer? t = _errorTimer; _errorTimer = null; - if (t != null) + if (t is not null) { t.Dispose(); // Cancel timer request. } @@ -646,7 +646,7 @@ private void WaitForPendingOpen() caughtException = e; } - if (caughtException != null) + if (caughtException is not null) { next.Completion.TrySetException(caughtException); } @@ -656,7 +656,7 @@ private void WaitForPendingOpen() } else { - Debug.Assert(connection != null, "connection should never be null in success case"); + Debug.Assert(connection is not null, "connection should never be null in success case"); if (!next.Completion.TrySetResult(connection)) { // if the completion was cancelled, lets try and get this connection back for the next try @@ -680,7 +680,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource= 2) + if (ProviderInfo.DriverVersion is not null && ProviderInfo.DriverVersion.Length >= 2) { try { // mdac 89269: driver may return malformatted string @@ -291,7 +291,7 @@ internal string QuoteChar(string method) private void RollbackDeadTransaction() { WeakReference? weak = _weakTransaction; - if ((null != weak) && !weak.IsAlive) + if ((weak is not null) && !weak.IsAlive) { _weakTransaction = null; ConnectionHandle!.CompleteTransaction(ODBC32.SQL_ROLLBACK); @@ -353,17 +353,17 @@ public override void Close() OdbcConnectionHandle? connectionHandle = _connectionHandle; - if (null != connectionHandle) + if (connectionHandle is not null) { _connectionHandle = null; // If there is a pending transaction, automatically rollback. WeakReference? weak = _weakTransaction; - if (null != weak) + if (weak is not null) { _weakTransaction = null; IDisposable? transaction = weak.Target as OdbcTransaction; - if ((null != transaction) && weak.IsAlive) + if ((transaction is not null) && weak.IsAlive) { transaction.Dispose(); } @@ -383,7 +383,7 @@ internal string GetConnectAttrString(ODBC32.SQL_ATTR attribute) int cbActual = 0; byte[] buffer = new byte[100]; OdbcConnectionHandle? connectionHandle = ConnectionHandle; - if (null != connectionHandle) + if (connectionHandle is not null) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); if (buffer.Length + 2 <= cbActual) @@ -416,7 +416,7 @@ internal int GetConnectAttr(ODBC32.SQL_ATTR attribute, ODBC32.HANDLER handler) int cbActual = 0; byte[] buffer = new byte[4]; OdbcConnectionHandle? connectionHandle = ConnectionHandle; - if (null != connectionHandle) + if (connectionHandle is not null) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); @@ -486,7 +486,7 @@ private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) short cbActual = 0; byte[] buffer = new byte[100]; OdbcConnectionHandle? connectionHandle = ConnectionHandle; - if (null != connectionHandle) + if (connectionHandle is not null) { ODBC32.RetCode retcode = connectionHandle.GetInfo2(info, buffer, out cbActual); if (buffer.Length < cbActual - 2) @@ -525,7 +525,7 @@ private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) { //Optimize to only create the event objects and obtain error info if //the user is really interested in retriveing the events... - if (_infoMessageEventHandler != null) + if (_infoMessageEventHandler is not null) { OdbcErrorCollection errors = ODBC32.GetDiagErrors(null, hrHandle, retcode); errors.SetSource(this.Driver); @@ -535,7 +535,7 @@ private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) } default: OdbcException e = OdbcException.CreateException(ODBC32.GetDiagErrors(null, hrHandle, retcode), retcode); - if (e != null) + if (e is not null) { e.Errors.SetSource(this.Driver); } @@ -552,10 +552,10 @@ internal void HandleError(OdbcHandle hrHandle, ODBC32.RetCode retcode) { case ODBC32.RetCode.SUCCESS: case ODBC32.RetCode.SUCCESS_WITH_INFO: - Debug.Assert(null == e, "success exception"); + Debug.Assert(e is null, "success exception"); break; default: - Debug.Assert(null != e, "failure without exception"); + Debug.Assert(e is not null, "failure without exception"); throw e; } } @@ -611,7 +611,7 @@ public static void ReleaseObjectPool() OdbcTransaction? weak = (_weakTransaction.Target as OdbcTransaction); if (transaction != weak) { // transaction doesn't exist - if (null == transaction) + if (transaction is null) { // transaction exists throw ADP.TransactionRequired(method); } @@ -624,9 +624,9 @@ public static void ReleaseObjectPool() transaction = null; // MDAC 69264 } } - else if (null != transaction) + else if (transaction is not null) { // no transaction started - if (null != transaction.Connection) + if (transaction.Connection is not null) { // transaction can't have come from this connection throw ADP.TransactionConnectionMismatch(); @@ -782,7 +782,7 @@ internal bool SQLGetFunctions(ODBC32.SQL_API odbcFunction) short fExists; Debug.Assert((short)odbcFunction != 0, "SQL_API_ALL_FUNCTIONS is not supported"); OdbcConnectionHandle? connectionHandle = ConnectionHandle; - if (null != connectionHandle) + if (connectionHandle is not null) { retcode = connectionHandle.GetFunctions(odbcFunction, out fExists); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs index d9d35950a2e612..9c2f6659f25972 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs @@ -37,7 +37,7 @@ protected override DbConnectionInternal CreateConnection(DbConnectionOptions opt protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions? previous) { Debug.Assert(!string.IsNullOrEmpty(connectionString), "empty connectionString"); - OdbcConnectionString result = new OdbcConnectionString(connectionString, (null != previous)); + OdbcConnectionString result = new OdbcConnectionString(connectionString, (previous is not null)); return result; } @@ -55,16 +55,16 @@ internal override DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory) { - Debug.Assert(internalConnection != null, "internalConnection may not be null."); + Debug.Assert(internalConnection is not null, "internalConnection may not be null."); cacheMetaDataFactory = false; OdbcConnection odbcOuterConnection = ((OdbcConnectionOpen)internalConnection).OuterConnection; - Debug.Assert(odbcOuterConnection != null, "outer connection may not be null."); + Debug.Assert(odbcOuterConnection is not null, "outer connection may not be null."); // get the DBMS Name object? driverName = null; string? stringValue = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); - if (stringValue != null) + if (stringValue is not null) { driverName = stringValue; } @@ -73,7 +73,7 @@ protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal cacheMetaDataFactory = true; - Debug.Assert(XMLStream != null, "XMLstream may not be null."); + Debug.Assert(XMLStream is not null, "XMLstream may not be null."); string versionString = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER)!; @@ -86,7 +86,7 @@ protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internal override DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnection? connection) { OdbcConnection? c = (connection as OdbcConnection); - if (null != c) + if (c is not null) { return c.PoolGroup; } @@ -96,7 +96,7 @@ protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internal override DbConnectionInternal? GetInnerConnection(DbConnection connection) { OdbcConnection? c = (connection as OdbcConnection); - if (null != c) + if (c is not null) { return c.InnerConnection; } @@ -106,7 +106,7 @@ protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internal override void PermissionDemand(DbConnection outerConnection) { OdbcConnection? c = (outerConnection as OdbcConnection); - if (null != c) + if (c is not null) { c.PermissionDemand(); } @@ -115,7 +115,7 @@ internal override void PermissionDemand(DbConnection outerConnection) internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { OdbcConnection? c = (outerConnection as OdbcConnection); - if (null != c) + if (c is not null) { c.PoolGroup = poolGroup; } @@ -124,7 +124,7 @@ internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbCo internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { OdbcConnection? c = (owningObject as OdbcConnection); - if (null != c) + if (c is not null) { c.SetInnerConnectionEvent(to); } @@ -133,7 +133,7 @@ internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConn internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { OdbcConnection? c = (owningObject as OdbcConnection); - if (null != c) + if (c is not null) { return c.SetInnerConnectionFrom(to, from); } @@ -143,7 +143,7 @@ internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConne internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { OdbcConnection? c = (owningObject as OdbcConnection); - if (null != c) + if (c is not null) { c.SetInnerConnectionTo(to); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs index 6cd776f00fa2fc..26fa28cf0d30ef 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs @@ -22,11 +22,11 @@ private enum HandleState internal OdbcConnectionHandle(OdbcConnection connection, OdbcConnectionString constr, OdbcEnvironmentHandle environmentHandle) : base(ODBC32.SQL_HANDLE.DBC, environmentHandle) { - if (null == connection) + if (connection is null) { throw ADP.ArgumentNull(nameof(connection)); } - if (null == constr) + if (constr is null) { throw ADP.ArgumentNull(nameof(constr)); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs index a84658b4b543f5..c39528446f0cea 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs @@ -65,7 +65,7 @@ internal DbConnectionOptions? ConnectionOptions get { System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; - return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + return ((poolGroup is not null) ? poolGroup.ConnectionOptions : null); } } @@ -73,7 +73,7 @@ private string ConnectionString_Get() { bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions? connectionOptions = UserConnectionOptions; - return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); + return ((connectionOptions is not null) ? connectionOptions.UsersConnectionString(hidePassword) : ""); } private void ConnectionString_Set(string? value) @@ -121,7 +121,7 @@ internal System.Data.ProviderBase.DbConnectionPoolGroup? PoolGroup } set { - Debug.Assert(null != value, "null poolGroup"); + Debug.Assert(value is not null, "null poolGroup"); _poolGroup = value; } } @@ -199,13 +199,13 @@ internal void PermissionDemand() { Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; - DbConnectionOptions? connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); - if ((null == connectionOptions) || connectionOptions.IsEmpty) + DbConnectionOptions? connectionOptions = ((poolGroup is not null) ? poolGroup.ConnectionOptions : null); + if ((connectionOptions is null) || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } DbConnectionOptions? userConnectionOptions = UserConnectionOptions; - Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); + Debug.Assert(userConnectionOptions is not null, "null UserConnectionOptions"); } internal void RemoveWeakReference(object value) @@ -216,7 +216,7 @@ internal void RemoveWeakReference(object value) internal void SetInnerConnectionEvent(DbConnectionInternal to) { Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(to is not null, "to null InnerConnection"); ConnectionState originalState = _innerConnection.State & ConnectionState.Open; ConnectionState currentState = to.State & ConnectionState.Open; @@ -247,8 +247,8 @@ internal void SetInnerConnectionEvent(DbConnectionInternal to) internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from) { Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != from, "from null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(from is not null, "from null InnerConnection"); + Debug.Assert(to is not null, "to null InnerConnection"); bool result = (from == Interlocked.CompareExchange(ref _innerConnection, to, from)); return result; } @@ -256,7 +256,7 @@ internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionIntern internal void SetInnerConnectionTo(DbConnectionInternal to) { Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(to is not null, "to null InnerConnection"); _innerConnection = to; } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs index 008facb51311e3..fd3c8465e474f4 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs @@ -21,7 +21,7 @@ internal OdbcConnection OuterConnection { OdbcConnection? outerConnection = (OdbcConnection?)Owner; - if (null == outerConnection) + if (outerConnection is null) throw ODBC.OpenConnectionNoOwner(); return outerConnection; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs index b49f953fecdb81..561f16b3ffb0d3 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs @@ -83,7 +83,7 @@ internal string QuoteChar { get { - Debug.Assert(_quoteChar != null, "QuoteChar getter called but no quote char was set"); + Debug.Assert(_quoteChar is not null, "QuoteChar getter called but no quote char was set"); return _quoteChar; } set diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs index 74790e05ac1f2a..f6d788988d9557 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs @@ -25,7 +25,7 @@ internal OdbcConnectionString(string connectionString, bool validate) : base(con if (validate || (null == _expandedConnectionString)) { // do not check string length if it was expanded because the final result may be shorter than the original - if ((null != connectionString) && (ODBC32.MAX_CONNECTION_STRING_LENGTH < connectionString.Length)) + if ((connectionString is not null) && (ODBC32.MAX_CONNECTION_STRING_LENGTH < connectionString.Length)) { // MDAC 83536 throw ODBC.ConnectionStringTooLong(); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs index ae68e130447fec..a4d8e3e09478e0 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs @@ -67,7 +67,7 @@ public override object this[string keyword] set { ADP.CheckArgumentNull(keyword, nameof(keyword)); - if (null != value) + if (value is not null) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) @@ -122,7 +122,7 @@ public override ICollection Keys get { string[]? knownKeywords = _knownKeywords; - if (null == knownKeywords) + if (knownKeywords is null) { knownKeywords = s_validKeywords; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs index 1af51675e76487..a92fbda295282c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs @@ -118,10 +118,10 @@ public event OdbcRowUpdatingEventHandler? RowUpdating // MDAC 58177, 64513 // prevent someone from registering two different command builders on the adapter by // silently removing the old one - if ((null != handler) && (value!.Target is OdbcCommandBuilder)) + if ((handler is not null) && (value!.Target is OdbcCommandBuilder)) { OdbcRowUpdatingEventHandler? d = (OdbcRowUpdatingEventHandler?)ADP.FindBuilder(handler); - if (null != d) + if (d is not null) { Events.RemoveHandler(s_eventRowUpdating, d); } @@ -153,7 +153,7 @@ protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, protected override void OnRowUpdated(RowUpdatedEventArgs value) { OdbcRowUpdatedEventHandler? handler = (OdbcRowUpdatedEventHandler?)Events[s_eventRowUpdated]; - if ((null != handler) && (value is OdbcRowUpdatedEventArgs)) + if ((handler is not null) && (value is OdbcRowUpdatedEventArgs)) { handler(this, (OdbcRowUpdatedEventArgs)value); } @@ -163,7 +163,7 @@ protected override void OnRowUpdated(RowUpdatedEventArgs value) protected override void OnRowUpdating(RowUpdatingEventArgs value) { OdbcRowUpdatingEventHandler? handler = (OdbcRowUpdatingEventHandler?)Events[s_eventRowUpdating]; - if ((null != handler) && (value is OdbcRowUpdatingEventArgs)) + if ((handler is not null) && (value is OdbcRowUpdatingEventArgs)) { handler(this, (OdbcRowUpdatingEventArgs)value); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index 496e1543d92ee4..ffdc26aaf3ff3d 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -58,7 +58,7 @@ private enum HasRowsStatus internal OdbcDataReader(OdbcCommand command, CMDWrapper cmdWrapper, CommandBehavior commandbehavior) { - Debug.Assert(command != null, "Command null on OdbcDataReader ctor"); + Debug.Assert(command is not null, "Command null on OdbcDataReader ctor"); _command = command; _commandBehavior = commandbehavior; _cmdText = command.CommandText; // get a copy in case the command text on the command is changed ... @@ -70,7 +70,7 @@ private CNativeBuffer Buffer get { CNativeBuffer? value = _cmdWrapper!._dataReaderBuf; - if (null == value) + if (value is null) { Debug.Fail("object is disposed"); throw new ObjectDisposedException(GetType().Name); @@ -128,7 +128,7 @@ internal bool IsCancelingCommand { get { - if (_command != null) + if (_command is not null) { return _command.Canceling; } @@ -140,7 +140,7 @@ internal bool IsNonCancelingCommand { get { - if (_command != null) + if (_command is not null) { return !_command.Canceling; } @@ -320,7 +320,7 @@ private void Close(bool disposing) Exception? error = null; CMDWrapper? wrapper = _cmdWrapper; - if (null != wrapper && wrapper.StatementHandle != null) + if (wrapper is not null && wrapper.StatementHandle is not null) { // disposing // true to release both managed and unmanaged resources; false to release only unmanaged resources. @@ -357,12 +357,12 @@ private void Close(bool disposing) if (IsCommandBehavior(CommandBehavior.CloseConnection)) { - Debug.Assert(null != Connection, "null cmd connection"); + Debug.Assert(Connection is not null, "null cmd connection"); _command.Parameters.RebindCollection = true; Connection.Close(); } } - else if (null != wrapper) + else if (wrapper is not null) { wrapper.Dispose(); } @@ -381,7 +381,7 @@ private void Close(bool disposing) SetCurrentRowColumnInfo(-1, 0); - if ((null != error) && !disposing) + if ((error is not null) && !disposing) { throw error; } @@ -403,7 +403,7 @@ public override string GetDataTypeName(int i) if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); - if (info._typename == null) + if (info._typename is null) { info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!; } @@ -422,7 +422,7 @@ public override Type GetFieldType(int i) if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); - if (info._type == null) + if (info._type is null) { info._type = GetSqlType(i)._type; } @@ -436,10 +436,10 @@ public override string GetName(int i) if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); - if (info._name == null) + if (info._name is null) { info._name = GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW); - if (null == info._name) + if (info._name is null) { // MDAC 66681 info._name = ""; } @@ -545,7 +545,7 @@ internal object GetValue(int i, TypeMap typemap) //will work), and then query for a speicial SQLServer specific attribute. if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { int dummy; bool isNotDbNull = QueryFieldInfo(i, ODBC32.SQL_C.BINARY, out dummy); @@ -573,7 +573,7 @@ public override object GetValue(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { _dataCache[i] = GetValue(i, GetSqlType(i)); } @@ -651,7 +651,7 @@ public override bool IsDBNull(int i) // only in case of SequentialAccess with variable length data types (case 3), we will use GetData with zero length. object? cachedObj = _dataCache![i]; - if (cachedObj != null) + if (cachedObj is not null) { // case 4 - if cached object was created before, use it return Convert.IsDBNull(cachedObj); @@ -686,7 +686,7 @@ private object internalGetByte(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.UTINYINT)) { @@ -706,7 +706,7 @@ private object internalGetChar(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { @@ -726,7 +726,7 @@ private object internalGetInt16(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.SSHORT)) { @@ -746,7 +746,7 @@ private object internalGetInt32(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.SLONG)) { @@ -773,7 +773,7 @@ private object internalGetInt64(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { @@ -794,7 +794,7 @@ private object internalGetBoolean(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.BIT)) { @@ -814,7 +814,7 @@ private object internalGetFloat(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.REAL)) { @@ -835,7 +835,7 @@ private object internalGetDate(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.TYPE_DATE)) { @@ -856,7 +856,7 @@ private object internalGetDateTime(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.TYPE_TIMESTAMP)) { @@ -884,7 +884,7 @@ private object internalGetDecimal(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { @@ -914,7 +914,7 @@ private object internalGetDouble(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.DOUBLE)) { @@ -935,7 +935,7 @@ private object internalGetGuid(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.GUID)) { @@ -956,7 +956,7 @@ private object internalGetString(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { // Obtain _ALL_ the characters // Note: We can bind directly as WCHAR in ODBC and the DM will convert to and @@ -1063,7 +1063,7 @@ private object internalGetTime(int i) { if (_isRead) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { if (GetData(i, ODBC32.SQL_C.TYPE_TIME)) { @@ -1143,7 +1143,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB bool isRandomAccess = !IsCommandBehavior(CommandBehavior.SequentialAccess); - if (isRandomAccess || (cachedObj != null)) + if (isRandomAccess || (cachedObj is not null)) { // random access (cases 1 or 2) and sequential access with cache (case 3) // preserve the original behavior as before the fix @@ -1155,7 +1155,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB throw ADP.ArgumentOutOfRange(nameof(dataIndex)); } - if (cachedObj == null) + if (cachedObj is null) { // case 1, get the value and cache it // internalGetString/internalGetBytes will get the entire value and cache it, @@ -1164,12 +1164,12 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB if (isCharsBuffer) { cachedObj = (string)internalGetString(i); - Debug.Assert((cachedObj != null), "internalGetString should always return non-null or raise exception"); + Debug.Assert((cachedObj is not null), "internalGetString should always return non-null or raise exception"); } else { cachedObj = (byte[])internalGetBytes(i); - Debug.Assert((cachedObj != null), "internalGetBytes should always return non-null or raise exception"); + Debug.Assert((cachedObj is not null), "internalGetBytes should always return non-null or raise exception"); } // continue to case 2 @@ -1180,7 +1180,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB int cachedObjectLength = isCharsBuffer ? ((string)cachedObj).Length : ((byte[])cachedObj).Length; // the user can ask for the length of the field by passing in a null pointer for the buffer - if (buffer == null) + if (buffer is null) { // return the length if that's all what user needs return cachedObjectLength; @@ -1224,7 +1224,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB // regressions // the user can ask for the length of the field by passing in a null pointer for the buffer - if (buffer == null) + if (buffer is null) { // Get len. of remaining data from provider ODBC32.SQL_C sqlctype; @@ -1285,7 +1285,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB } else { - // buffer != null, read the data + // buffer is not null, read the data // check if user tries to read data that was already received // if yes, this violates 'sequential access' @@ -1360,7 +1360,7 @@ private int readBytesOrCharsSequentialAccess(int i, Array? buffer, bool isCharsB Debug.Assert(bytesOrCharsLength >= 0, "Negative number of bytes or chars to read"); // validated by the caller - Debug.Assert(buffer == null || bytesOrCharsLength <= (buffer.Length - bufferIndex), "Not enough space in user's buffer"); + Debug.Assert(buffer is null || bytesOrCharsLength <= (buffer.Length - bufferIndex), "Not enough space in user's buffer"); int totalBytesOrCharsRead = 0; @@ -1448,7 +1448,7 @@ private int readBytesOrCharsSequentialAccess(int i, Array? buffer, bool isCharsB if (isCharsBuffer) { int cchRead = cbRead / 2; - if (buffer != null) + if (buffer is not null) { internalNativeBuffer.ReadChars(0, (char[])buffer, bufferIndex, cchRead); bufferIndex += cchRead; @@ -1457,7 +1457,7 @@ private int readBytesOrCharsSequentialAccess(int i, Array? buffer, bool isCharsB } else { - if (buffer != null) + if (buffer is not null) { internalNativeBuffer.ReadBytes(0, (byte[])buffer, bufferIndex, cbRead); bufferIndex += cbRead; @@ -1477,7 +1477,7 @@ private int readBytesOrCharsSequentialAccess(int i, Array? buffer, bool isCharsB private object internalGetBytes(int i) { - if (_dataCache!.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) is null) { // Obtain _ALL_ the bytes... // The first time GetData returns the true length (so we have to min it). @@ -1555,7 +1555,7 @@ private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQ ODBC32.RetCode retcode; // protect against dead connection, dead or canceling command. - if ((Connection == null) || _cmdWrapper!.Canceling) + if ((Connection is null) || _cmdWrapper!.Canceling) { return -1; } @@ -1612,7 +1612,7 @@ private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQ OdbcStatementHandle? stmt = StatementHandle; // protect against dead connection - if (Connection == null || _cmdWrapper!.Canceling || stmt == null) + if (Connection is null || _cmdWrapper!.Canceling || stmt is null) { return ""; } @@ -1656,7 +1656,7 @@ private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQ int numericAttribute = 0; // protect against dead connection, dead or canceling command. - if ((Connection == null) || _cmdWrapper!.Canceling) + if ((Connection is null) || _cmdWrapper!.Canceling) { return ""; } @@ -1745,10 +1745,10 @@ private bool GetData(int i, ODBC32.SQL_C sqlctype, int cb, out int cbLengthOrInd { throw ADP.DataReaderNoData(); } - Debug.Assert(null != StatementHandle, "Statement handle is null in DateReader"); + Debug.Assert(StatementHandle is not null, "Statement handle is null in DateReader"); // see notes on ODBC32.RetCode.NO_DATA case below. - Debug.Assert(_dataCache == null || !Convert.IsDBNull(_dataCache[i]), "Cannot call GetData without checking for cache first!"); + Debug.Assert(_dataCache is null || !Convert.IsDBNull(_dataCache[i]), "Cannot call GetData without checking for cache first!"); // Never call GetData with anything larger than _buffer.Length-2. // We keep reallocating native buffers and it kills performance!!! @@ -1976,7 +1976,7 @@ private bool NextResult(bool disposing, bool allresults) else if (!disposing && (retcode != ODBC32.RetCode.NO_DATA) && (ODBC32.RetCode.SUCCESS != retcode)) { // allow for building comulative error messages. - if (null == errors) + if (errors is null) { firstRetCode = retcode; errors = new OdbcErrorCollection(); @@ -2007,7 +2007,7 @@ private bool NextResult(bool disposing, bool allresults) _dataCache = null; _noMoreResults = true; } - if (null != errors) + if (errors is not null) { Debug.Assert(!disposing, "errors while disposing"); errors.SetSource(Connection!.Driver); @@ -2172,7 +2172,7 @@ private void BuildMetaDataInfo() // fill in as much as possible. if (IsCommandBehavior(CommandBehavior.KeyInfo)) { - if ((qrytables != null) && (qrytables.Count > 0)) + if ((qrytables is not null) && (qrytables.Count > 0)) { List.Enumerator tablesEnum = qrytables.GetEnumerator(); QualifiedTableName qualifiedTableName = new QualifiedTableName(Connection.QuoteChar(ADP.GetSchemaTable)); @@ -2264,7 +2264,7 @@ private DataTable NewSchemaTable() { return schematable; } - if (_metadata == null) + if (_metadata is null) { BuildMetaDataInfo(); } @@ -2328,7 +2328,7 @@ private DataTable NewSchemaTable() internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTableName, bool quoted) { - Debug.Assert(_metadata != null); + Debug.Assert(_metadata is not null); ODBC32.RetCode retcode; string columnname; @@ -2336,7 +2336,7 @@ internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTable int keyColumns = 0; IntPtr cbActual = IntPtr.Zero; - if (IsClosed || (_cmdWrapper == null)) + if (IsClosed || (_cmdWrapper is null)) { return 0; // Can't do anything without a second handle } @@ -2385,7 +2385,7 @@ internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTable _metadata[ordinal].isNullable = false; _metadata[ordinal].baseTableName = qualifiedTableName.Table; - if (_metadata[ordinal].baseColumnName == null) + if (_metadata[ordinal].baseColumnName is null) { _metadata[ordinal].baseColumnName = columnname; } @@ -2460,7 +2460,7 @@ internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTable if (ordinal != -1) { _metadata[ordinal].isRowVersion = true; - if (_metadata[ordinal].baseColumnName == null) + if (_metadata[ordinal].baseColumnName is null) { _metadata[ordinal].baseColumnName = columnname; } @@ -2498,7 +2498,7 @@ internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTable // Uses SQLStatistics to retrieve key information for a table private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, bool quoted) { - Debug.Assert(_metadata != null); + Debug.Assert(_metadata is not null); ODBC32.RetCode retcode; string columnname = string.Empty; @@ -2663,11 +2663,11 @@ private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, // test test test - we don't know if this is nulalble or not so why do we want to set it to a value? _metadata[indexordinal].isNullable = false; _metadata[indexordinal].isUnique = true; - if (_metadata[indexordinal].baseTableName == null) + if (_metadata[indexordinal].baseTableName is null) { _metadata[indexordinal].baseTableName = qualifiedTableName.Table; } - if (_metadata[indexordinal].baseColumnName == null) + if (_metadata[indexordinal].baseColumnName is null) { _metadata[indexordinal].baseColumnName = columnname; } @@ -2709,12 +2709,12 @@ internal int GetOrdinalFromBaseColName(string? columnname, string? tablename) { return -1; } - if (_metadata != null) + if (_metadata is not null) { int count = FieldCount; for (int i = 0; i < count; i++) { - if ((_metadata[i].baseColumnName != null) && + if ((_metadata[i].baseColumnName is not null) && (columnname == _metadata[i].baseColumnName)) { if (!string.IsNullOrEmpty(tablename)) @@ -2743,7 +2743,7 @@ internal int GetOrdinalFromBaseColName(string? columnname, string? tablename) internal string? GetTableNameFromCommandText() { - if (_command == null) + if (_command is null) { return null; } @@ -2804,7 +2804,7 @@ internal void SetBaseTableNames(QualifiedTableName qualifiedTableName) for (int i = 0; i < count; i++) { - if (_metadata![i].baseTableName == null) + if (_metadata![i].baseTableName is null) { _metadata[i].baseTableName = qualifiedTableName.Table; _metadata[i].baseSchemaName = qualifiedTableName.Schema; @@ -2878,7 +2878,7 @@ internal QualifiedTableName(string quoteChar, string? qualifiedname) private string? UnQuote(string? str) { - if ((str != null) && (str.Length > 0)) + if ((str is not null) && (str.Length > 0)) { char quoteChar = _quoteChar[0]; if (str[0] == quoteChar) @@ -2923,7 +2923,7 @@ internal QualifiedTableName(string quoteChar, string? qualifiedname) // does the part begin with a quotePrefix? if (useQuotes && (name.IndexOf(quotePrefix!, currentPos, quotePrefix!.Length, StringComparison.Ordinal) == currentPos)) { - Debug.Assert(quotePrefix != null && quoteSuffix != null); + Debug.Assert(quotePrefix is not null && quoteSuffix is not null); currentPos += quotePrefix.Length; // move past the quotePrefix diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs index f6c0538764f74f..466e4921de8dac 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs @@ -15,12 +15,12 @@ internal sealed class OdbcEnvironment internal static OdbcEnvironmentHandle GetGlobalEnvironmentHandle() { OdbcEnvironmentHandle? globalEnvironmentHandle = s_globalEnvironmentHandle as OdbcEnvironmentHandle; - if (null == globalEnvironmentHandle) + if (globalEnvironmentHandle is null) { lock (s_globalEnvironmentHandleLock) { globalEnvironmentHandle = s_globalEnvironmentHandle as OdbcEnvironmentHandle; - if (null == globalEnvironmentHandle) + if (globalEnvironmentHandle is null) { globalEnvironmentHandle = new OdbcEnvironmentHandle(); s_globalEnvironmentHandle = globalEnvironmentHandle; @@ -33,7 +33,7 @@ internal static OdbcEnvironmentHandle GetGlobalEnvironmentHandle() internal static void ReleaseObjectPool() { object? globalEnvironmentHandle = Interlocked.Exchange(ref s_globalEnvironmentHandle, null); - if (null != globalEnvironmentHandle) + if (globalEnvironmentHandle is not null) { ((OdbcEnvironmentHandle)globalEnvironmentHandle).Dispose(); // internally refcounted so will happen correctly } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs index 77900ae013f17f..91370bd46bcda9 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs @@ -27,13 +27,13 @@ protected OdbcHandle(ODBC32.SQL_HANDLE handleType, OdbcHandle? parentHandle) : b switch (handleType) { case ODBC32.SQL_HANDLE.ENV: - Debug.Assert(null == parentHandle, "did not expect a parent handle"); + Debug.Assert(parentHandle is null, "did not expect a parent handle"); retcode = Interop.Odbc.SQLAllocHandle(handleType, IntPtr.Zero, out base.handle); break; case ODBC32.SQL_HANDLE.DBC: case ODBC32.SQL_HANDLE.STMT: // must addref before calling native so it won't be released just after - Debug.Assert(null != parentHandle, "expected a parent handle"); // safehandle can't be null + Debug.Assert(parentHandle is not null, "expected a parent handle"); // safehandle can't be null parentHandle.DangerousAddRef(ref mustRelease); retcode = Interop.Odbc.SQLAllocHandle(handleType, parentHandle, out base.handle); @@ -166,7 +166,7 @@ protected override bool ReleaseHandle() // our reference on our parent. OdbcHandle? parentHandle = _parentHandle; _parentHandle = null; - if (null != parentHandle) + if (parentHandle is not null) { parentHandle.DangerousRelease(); parentHandle = null; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs index 33ce321e304862..af157cd22b869c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs @@ -50,7 +50,7 @@ internal OdbcMetaDataFactory(Stream XMLStream, // verify the existance of the table in the data set DataTable? metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - if (metaDataCollectionsTable == null) + if (metaDataCollectionsTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.MetaDataCollections); } @@ -60,7 +60,7 @@ internal OdbcMetaDataFactory(Stream XMLStream, // verify the existance of the table in the data set DataTable? restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; - if (restrictionsTable != null) + if (restrictionsTable is not null) { // copy the table filtering out any rows that don't apply to the current version of the provider restrictionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.Restrictions, null); @@ -75,11 +75,11 @@ internal OdbcMetaDataFactory(Stream XMLStream, DataColumn populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]!; DataColumn collectionName = metaDataCollectionsTable.Columns[_collectionName]!; DataColumn? restrictionCollectionName = null; - if (restrictionsTable != null) + if (restrictionsTable is not null) { restrictionCollectionName = restrictionsTable.Columns[_collectionName]; } - Debug.Assert(restrictionCollectionName != null); + Debug.Assert(restrictionCollectionName is not null); foreach (DataRow collection in metaDataCollectionsTable.Rows) { @@ -106,7 +106,7 @@ internal OdbcMetaDataFactory(Stream XMLStream, if (connection.SQLGetFunctions(_schemaMapping[mapping]._odbcFunction) == false) { // but first delete any related restrictions - if (restrictionsTable != null) + if (restrictionsTable is not null) { foreach (DataRow restriction in restrictionsTable.Rows) { @@ -127,7 +127,7 @@ internal OdbcMetaDataFactory(Stream XMLStream, CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!); CollectionDataSet.Tables.Add(metaDataCollectionsTable); - if (restrictionsTable != null) + if (restrictionsTable is not null) { CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]!); CollectionDataSet.Tables.Add(restrictionsTable); @@ -188,7 +188,7 @@ private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcData schemaTable = dataReader.GetSchemaTable(); // vstfdevdiv:479715 Handle cases where reader is empty - if (null == schemaTable) + if (schemaTable is null) { throw ADP.OdbcNoTypesFromProvider(); } @@ -276,7 +276,7 @@ private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcData } // if we have a type map we can determine the dbType and the CLR type if not leave them null - if (typeMap != null) + if (typeMap is not null) { dataTypesRow[providerDbTypeColumn] = typeMap._odbcType; dataTypesRow[dataTypeColumn] = typeMap._type.FullName; @@ -505,7 +505,7 @@ private void FillOutRestrictions(int restrictionsCount, string?[]? restrictions, int i = 0; // if we have restrictions put them in the restrictions array - if (restrictions != null) + if (restrictions is not null) { if (restrictions.Length > restrictionsCount) { @@ -514,7 +514,7 @@ private void FillOutRestrictions(int restrictionsCount, string?[]? restrictions, for (i = 0; i < restrictions.Length; i++) { - if (restrictions[i] != null) + if (restrictions[i] is not null) { allRestrictions[i] = restrictions[i]; } @@ -549,11 +549,11 @@ private DataTable GetColumnsCollection(string?[]? restrictions, OdbcConnection c finally { - if (dataReader != null) + if (dataReader is not null) { dataReader.Dispose(); }; - if (command != null) + if (command is not null) { command.Dispose(); }; @@ -572,7 +572,7 @@ private DataTable GetDataSourceInformationCollection(string?[]? restrictions, // verify that the data source information table is in the data set DataTable? dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; - if (dataSourceInformationTable == null) + if (dataSourceInformationTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataSourceInformation); } @@ -603,7 +603,7 @@ private DataTable GetDataSourceInformationCollection(string?[]? restrictions, // get the DBMS Name stringValue = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_NAME); - if (stringValue != null) + if (stringValue is not null) { dataSourceInformation[DbMetaDataColumnNames.DataSourceProductName] = stringValue; } @@ -710,7 +710,7 @@ private DataTable GetDataSourceInformationCollection(string?[]? restrictions, // OrderByColumnsInSelect stringValue = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.ORDER_BY_COLUMNS_IN_SELECT); - if (stringValue != null) + if (stringValue is not null) { if (stringValue == "Y") { @@ -726,7 +726,7 @@ private DataTable GetDataSourceInformationCollection(string?[]? restrictions, // assuming that the quote suffix is escaped via repetition (i.e " becomes "") stringValue = connection.QuoteChar(ADP.GetSchema); - if (stringValue != null) + if (stringValue is not null) { // by spec a blank identifier quote char indicates that the provider does not suppport // quoted identifiers @@ -792,7 +792,7 @@ private DataTable GetDataTypesCollection(string?[]? restrictions, OdbcConnection // verify the existance of the table in the data set DataTable? dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; - if (dataTypesTable == null) + if (dataTypesTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes); } @@ -817,11 +817,11 @@ private DataTable GetDataTypesCollection(string?[]? restrictions, OdbcConnection finally { - if (dataReader != null) + if (dataReader is not null) { dataReader.Dispose(); }; - if (command != null) + if (command is not null) { command.Dispose(); }; @@ -846,7 +846,7 @@ private DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection con object[] allRestrictions = new object[nativeRestrictionsCount]; FillOutRestrictions(indexRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Indexes); - if (allRestrictions[indexOfTableName] == null) + if (allRestrictions[indexOfTableName] is null) { throw ODBC.GetSchemaRestrictionRequired(); } @@ -857,7 +857,7 @@ private DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection con dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLSTATISTICS); string? indexName = null; - if (restrictions != null) + if (restrictions is not null) { if (restrictions.Length >= indexOfIndexName + 1) { @@ -872,11 +872,11 @@ private DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection con finally { - if (dataReader != null) + if (dataReader is not null) { dataReader.Dispose(); }; - if (command != null) + if (command is not null) { command.Dispose(); }; @@ -915,11 +915,11 @@ private DataTable GetProcedureColumnsCollection(string?[]? restrictions, OdbcCon finally { - if (dataReader != null) + if (dataReader is not null) { dataReader.Dispose(); }; - if (command != null) + if (command is not null) { command.Dispose(); }; @@ -944,7 +944,7 @@ private DataTable GetProceduresCollection(string?[]? restrictions, OdbcConnectio dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLPROCEDURES); - if (allRestrictions[indexOfProcedureType] == null) + if (allRestrictions[indexOfProcedureType] is null) { resultTable = DataTableFromDataReader(dataReader, OdbcMetaDataCollectionNames.Procedures); } @@ -977,11 +977,11 @@ private DataTable GetProceduresCollection(string?[]? restrictions, OdbcConnectio finally { - if (dataReader != null) + if (dataReader is not null) { dataReader.Dispose(); }; - if (command != null) + if (command is not null) { command.Dispose(); }; @@ -998,7 +998,7 @@ private DataTable GetReservedWordsCollection(string?[]? restrictions, OdbcConnec // verify the existance of the table in the data set DataTable? reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; - if (reservedWordsTable == null) + if (reservedWordsTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } @@ -1007,14 +1007,14 @@ private DataTable GetReservedWordsCollection(string?[]? restrictions, OdbcConnec reservedWordsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.ReservedWords, null); DataColumn? reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; - if (reservedWordColumn == null) + if (reservedWordColumn is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } string? keywords = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.KEYWORDS); - if (null != keywords) + if (keywords is not null) { string[] values = keywords.Split(KeywordSeparatorChar); for (int i = 0; i < values.Length; ++i) @@ -1067,11 +1067,11 @@ private DataTable GetTablesCollection(string?[]? restrictions, OdbcConnection co finally { - if (dataReader != null) + if (dataReader is not null) { dataReader.Dispose(); }; - if (command != null) + if (command is not null) { command.Dispose(); }; @@ -1089,7 +1089,7 @@ private bool IncludeIndexRow(object rowIndexName, return false; } - if ((restrictionIndexName != null) && (restrictionIndexName != (string)rowIndexName)) + if ((restrictionIndexName is not null) && (restrictionIndexName != (string)rowIndexName)) { return false; } @@ -1157,7 +1157,7 @@ protected override DataTable PrepareCollection(string collectionName, string?[]? resultTable = GetReservedWordsCollection(restrictions, odbcConnection); } - if (resultTable == null) + if (resultTable is null) { throw ADP.UnableToBuildCollection(collectionName); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs index 08c95dc69d086f..90619bdb98a458 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs @@ -226,7 +226,7 @@ public override string ParameterName get { string? parameterName = _parameterName; - return ((null != parameterName) ? parameterName : string.Empty); + return ((parameterName is not null) ? parameterName : string.Empty); } set { @@ -339,7 +339,7 @@ private int GetColumnSize(object? value, int offset, int ordinal) { throw ADP.UninitializedParameterSize(ordinal, _bindtype._type); } - if ((null == value) || Convert.IsDBNull(value)) + if ((value is null) || Convert.IsDBNull(value)) { cch = 0; } @@ -478,7 +478,7 @@ private int GetParameterSize(object? value, int offset, int ordinal) { throw ADP.UninitializedParameterSize(ordinal, _bindtype._type); } - if ((null == value) || Convert.IsDBNull(value)) + if ((value is null) || Convert.IsDBNull(value)) { if (_bindtype._sql_c == ODBC32.SQL_C.WCHAR) { @@ -550,7 +550,7 @@ private byte GetParameterPrecision(object? value) } return ADP.DecimalMaxPrecision; } - if ((null == value) || (value is decimal) || Convert.IsDBNull(value)) + if ((value is null) || (value is decimal) || Convert.IsDBNull(value)) { // MDAC 60882 return ADP.DecimalMaxPrecision28; } @@ -620,7 +620,7 @@ internal void ClearBinding() internal void PrepareForBind(OdbcCommand command, short ordinal, ref int parameterBufferSize) { - Debug.Assert(command.Connection != null); + Debug.Assert(command.Connection is not null); // make a snapshot of the current properties. Properties may change while we work on them // @@ -680,7 +680,7 @@ internal void PrepareForBind(OdbcCommand command, short ordinal, ref int paramet // No support for NUMERIC // Change the type _bindtype = TypeMap._VarChar; - if ((null != value) && !Convert.IsDBNull(value)) + if ((value is not null) && !Convert.IsDBNull(value)) { value = ((decimal)value).ToString(CultureInfo.CurrentCulture); size = ((string)value).Length; @@ -694,7 +694,7 @@ internal void PrepareForBind(OdbcCommand command, short ordinal, ref int paramet // No support for BIGINT // Change the type _bindtype = TypeMap._VarChar; - if ((null != value) && !Convert.IsDBNull(value)) + if ((value is not null) && !Convert.IsDBNull(value)) { value = ((long)value).ToString(CultureInfo.CurrentCulture); size = ((string)value).Length; @@ -736,7 +736,7 @@ internal void PrepareForBind(OdbcCommand command, short ordinal, ref int paramet { sql_c_type = ODBC32.SQL_C.CHAR; - if (null != value) + if (value is not null) { if (!Convert.IsDBNull(value) && value is string) { @@ -790,7 +790,7 @@ internal void PrepareForBind(OdbcCommand command, short ordinal, ref int paramet internal void Bind(OdbcStatementHandle hstmt, OdbcCommand command, short ordinal, CNativeBuffer parameterBuffer, bool allowReentrance) { - Debug.Assert(command.Connection != null); + Debug.Assert(command.Connection is not null); ODBC32.RetCode retcode; ODBC32.SQL_C sql_c_type = _prepared_Sql_C_Type; @@ -965,7 +965,7 @@ internal void GetOutputValue(CNativeBuffer parameterBuffer) if (_boundSqlCType == ODBC32.SQL_C.CHAR) { - if ((null != Value) && !Convert.IsDBNull(Value)) + if ((Value is not null) && !Convert.IsDBNull(Value)) { int lcid = System.Globalization.CultureInfo.CurrentCulture.LCID; CultureInfo culInfo = new CultureInfo(lcid); @@ -974,7 +974,7 @@ internal void GetOutputValue(CNativeBuffer parameterBuffer) } } - if ((typemap != _typemap) && (null != Value) && !Convert.IsDBNull(Value) && (Value.GetType() != _typemap!._type)) + if ((typemap != _typemap) && (Value is not null) && !Convert.IsDBNull(Value) && (Value.GetType() != _typemap!._type)) { Debug.Assert(ODBC32.SQL_C.NUMERIC == _typemap._sql_c, "unexpected"); Value = decimal.Parse((string)Value, System.Globalization.CultureInfo.CurrentCulture); @@ -988,7 +988,7 @@ internal void GetOutputValue(CNativeBuffer parameterBuffer) object? value = _internalValue; if (_internalUserSpecifiedType) { - if ((null != value) && !Convert.IsDBNull(value)) + if ((value is not null) && !Convert.IsDBNull(value)) { Type valueType = value.GetType(); if (!valueType.IsArray) @@ -1019,7 +1019,7 @@ internal void GetOutputValue(CNativeBuffer parameterBuffer) } else if (null == _typemap) { - if ((null == value) || Convert.IsDBNull(value)) + if ((value is null) || Convert.IsDBNull(value)) { _typemap = TypeMap._NVarChar; // default type } @@ -1053,7 +1053,7 @@ internal void SetInputValue(object? value, ODBC32.SQL_C sql_c_type, int cbsize, //Note: (lang) "null" means to use the servers default (not DBNull). //We probably should just not have bound this parameter, period, but that //would mess up the users question marks, etc... - if ((null == value)) + if ((value is null)) { parameterBuffer.WriteIntPtr(_preparedIntOffset, (IntPtr)ODBC32.SQL_DEFAULT_PARAM); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs index 671b50959b9e6e..3de1d390b18148 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs @@ -26,7 +26,7 @@ private List InnerList { List? items = _items; - if (null == items) + if (items is null) { items = new List(); _items = items; @@ -79,7 +79,7 @@ public override int Add(object value) public override void AddRange(System.Array values) { OnChange(); - if (null == values) + if (values is null) { throw ADP.ArgumentNull(nameof(values)); } @@ -109,7 +109,7 @@ public override void Clear() OnChange(); List items = InnerList; - if (null != items) + if (items is not null) { foreach (OdbcParameter item in items) { @@ -152,7 +152,7 @@ protected override DbParameter GetParameter(string parameterName) private static int IndexOf(System.Collections.IEnumerable items, string parameterName) { - if (null != items) + if (items is not null) { int i = 0; @@ -185,13 +185,13 @@ public override int IndexOf(string parameterName) public override int IndexOf(object value) { - if (null != value) + if (value is not null) { ValidateType(value); List items = InnerList; - if (null != items) + if (items is not null) { int count = items.Count; @@ -255,7 +255,7 @@ public override void RemoveAt(string parameterName) private void RemoveIndex(int index) { List items = InnerList; - Debug.Assert((null != items) && (0 <= index) && (index < Count), "RemoveIndex, invalid"); + Debug.Assert((items is not null) && (0 <= index) && (index < Count), "RemoveIndex, invalid"); OdbcParameter item = items[index]; items.RemoveAt(index); item.ResetParent(); @@ -264,7 +264,7 @@ private void RemoveIndex(int index) private void Replace(int index, object newValue) { List items = InnerList; - Debug.Assert((null != items) && (0 <= index) && (index < Count), "Replace Index invalid"); + Debug.Assert((items is not null) && (0 <= index) && (index < Count), "Replace Index invalid"); ValidateType(newValue); Validate(index, newValue); OdbcParameter item = items[index]; @@ -292,13 +292,13 @@ protected override void SetParameter(string parameterName, DbParameter value) private void Validate(int index, object value) { - if (null == value) + if (value is null) { throw ADP.ParameterNull(nameof(value), this, s_itemType); } object? parent = ((OdbcParameter)value).CompareExchangeParent(this, null); - if (null != parent) + if (parent is not null) { if (this != parent) { @@ -325,7 +325,7 @@ private void Validate(int index, object value) private void ValidateType(object value) { - if (null == value) + if (value is null) { throw ADP.ParameterNull(nameof(value), this, s_itemType); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs index 60634ace151211..ba0e7926323ad5 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs @@ -140,7 +140,7 @@ public override string SourceColumn get { string? sourceColumn = _sourceColumn; - return ((null != sourceColumn) ? sourceColumn : string.Empty); + return ((sourceColumn is not null) ? sourceColumn : string.Empty); } set { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs index aceee7efbe499a..eb7d8aff5ec064 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs @@ -39,7 +39,7 @@ public override IsolationLevel IsolationLevel get { OdbcConnection? connection = _connection; - if (null == connection) + if (connection is null) { throw ADP.TransactionZombied(this); } @@ -68,7 +68,7 @@ public override IsolationLevel IsolationLevel public override void Commit() { OdbcConnection? connection = _connection; - if (null == connection) + if (connection is null) { throw ADP.TransactionZombied(this); } @@ -102,7 +102,7 @@ protected override void Dispose(bool disposing) { OdbcConnectionHandle? handle = _handle; _handle = null; - if (null != handle) + if (handle is not null) { try { @@ -110,7 +110,7 @@ protected override void Dispose(bool disposing) if (retcode == ODBC32.RetCode.ERROR) { //don't throw an exception here, but trace it so it can be logged - if (_connection != null) + if (_connection is not null) { Exception e = _connection.HandleErrorNoThrow(handle, retcode)!; ADP.TraceExceptionWithoutRethrow(e); @@ -126,7 +126,7 @@ protected override void Dispose(bool disposing) } } } - if (_connection != null) + if (_connection is not null) { if (_connection.IsOpen) { @@ -142,7 +142,7 @@ protected override void Dispose(bool disposing) public override void Rollback() { OdbcConnection? connection = _connection; - if (null == connection) + if (connection is null) { throw ADP.TransactionZombied(this); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs index 370bb9771dc836..1ceb676fb2826c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs @@ -361,7 +361,7 @@ internal CStringTokenizer(string text, char quote, char escape) _quote = quote; _escape = escape; _sqlstatement = text; - if (text != null) + if (text is not null) { int iNul = text.IndexOf('\0'); _len = (0 > iNul) ? text.Length : iNul; diff --git a/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs b/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs index 4ffe04c40f74af..a3ef0e060de2ac 100644 --- a/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs +++ b/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs @@ -16,7 +16,7 @@ internal static TraceSwitch DataSchema get { TraceSwitch? dataSchema = _dataSchema; - if (null == dataSchema) + if (dataSchema is null) { _dataSchema = dataSchema = new TraceSwitch("Data.Schema", "Enable tracing for schema actions."); } diff --git a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs index 34334156e3e1fb..a5be966e00e52c 100644 --- a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs +++ b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs @@ -53,8 +53,8 @@ internal ColumnBinding(OleDbDataReader dataReader, int index, int indexForAccess OleDbParameter? parameter, RowBinding rowbinding, Bindings bindings, tagDBBINDING binding, int offset, bool ifIRowsetElseIRow) { - Debug.Assert(null != rowbinding, "null rowbinding"); - Debug.Assert(null != bindings, "null bindings"); + Debug.Assert(rowbinding is not null, "null rowbinding"); + Debug.Assert(bindings is not null, "null bindings"); Debug.Assert(ODB.SizeOf_tagDBBINDING <= offset, "invalid offset" + offset); _dataReader = dataReader; @@ -64,7 +64,7 @@ internal ColumnBinding(OleDbDataReader dataReader, int index, int indexForAccess _indexForAccessor = indexForAccessor; _indexWithinAccessor = indexWithinAccessor; - if (null != parameter) + if (parameter is not null) { _parameter = parameter; _parameterChangeID = parameter.ChangeID; @@ -163,7 +163,7 @@ private OleDbDataReader DataReader() internal bool IsParameterBindingInvalid(OleDbParameter parameter) { - Debug.Assert((null != _parameter) && (null != parameter), "null parameter"); + Debug.Assert((null != _parameter) && (parameter is not null), "null parameter"); return ((_parameter.ChangeID != _parameterChangeID) || (_parameter != parameter)); } @@ -206,7 +206,7 @@ internal void ResetValue() StringMemHandle? sptr = _sptr; _sptr = null; - if (null != sptr) + if (sptr is not null) { sptr.Dispose(); } @@ -437,7 +437,7 @@ internal object Value() } internal void Value(object? value) { - if (null == value) + if (value is null) { SetValueEmpty(); } @@ -652,7 +652,7 @@ private string Value_BSTR() } private void Value_BSTR(string value) { - Debug.Assert((null != value), "Value_BSTR null"); + Debug.Assert((value is not null), "Value_BSTR null"); Debug.Assert((NativeDBType.BSTR == DbType), "Value_BSTR"); LengthValue(value.Length * 2); /* bytecount*/ StatusValue(DBStatus.S_OK); @@ -684,11 +684,11 @@ private byte[] Value_ByRefBYTES() bindings.DangerousRelease(); } } - return ((null != value) ? value : Array.Empty()); + return ((value is not null) ? value : Array.Empty()); } private void Value_ByRefBYTES(byte[] value) { - Debug.Assert(null != value, "Value_ByRefBYTES null"); + Debug.Assert(value is not null, "Value_ByRefBYTES null"); Debug.Assert((NativeDBType.BYREF | NativeDBType.BYTES) == DbType, "Value_ByRefBYTES"); // we expect the provider/server to apply the silent truncation when binding BY_REF @@ -736,7 +736,7 @@ private string Value_ByRefWSTR() } private void Value_ByRefWSTR(string value) { - Debug.Assert(null != value, "Value_ByRefWSTR null"); + Debug.Assert(value is not null, "Value_ByRefWSTR null"); Debug.Assert((NativeDBType.BYREF | NativeDBType.WSTR) == DbType, "Value_ByRefWSTR"); // we expect the provider/server to apply the silent truncation when binding BY_REF // if (value.Length < ValueBindingOffset) { throw "Offset must refer to a location within the value" } @@ -755,7 +755,7 @@ private void Value_ByRefWSTR(string value) } private void Value_ByRefWSTR(char[] value) { - Debug.Assert(null != value, "Value_ByRefWSTR null"); + Debug.Assert(value is not null, "Value_ByRefWSTR null"); Debug.Assert((NativeDBType.BYREF | NativeDBType.WSTR) == DbType, "Value_ByRefWSTR"); // we expect the provider/server to apply the silent truncation when binding BY_REF // if (value.Length < ValueBindingOffset) { throw "Offset must refer to a location within the value" } @@ -784,7 +784,7 @@ private byte[] Value_BYTES() } private void Value_BYTES(byte[] value) { - Debug.Assert(null != value, "Value_BYTES null"); + Debug.Assert(value is not null, "Value_BYTES null"); // we silently truncate when the user has specified a given Size int bytecount = ((ValueBindingOffset < value.Length) ? Math.Min(value.Length - ValueBindingOffset, ColumnBindingMaxLen) : 0); LengthValue(bytecount); @@ -1041,11 +1041,11 @@ private void Value_IDISPATCH(object value) IntPtr ptr = IntPtr.Zero; // lazy init reflection objects - if (s_getIDispatchForObject == null) + if (s_getIDispatchForObject is null) { object? delegateInstance = null; MethodInfo? mi = typeof(Marshal).GetMethod("GetIDispatchForObject", BindingFlags.Public | BindingFlags.Static); - if (mi == null) + if (mi is null) { throw new NotSupportedException(SR.PlatformNotSupported_GetIDispatchForObject); } @@ -1206,7 +1206,7 @@ private string Value_WSTR() } private void Value_WSTR(string value) { - Debug.Assert(null != value, "Value_BYTES null"); + Debug.Assert(value is not null, "Value_BYTES null"); Debug.Assert(NativeDBType.WSTR == DbType, "Value_WSTR"); // we silently truncate when the user has specified a given Size int charCount = ((ValueBindingOffset < value.Length) ? Math.Min(value.Length - ValueBindingOffset, (ColumnBindingMaxLen - 2) / 2) : 0); @@ -1221,7 +1221,7 @@ private void Value_WSTR(string value) } private void Value_WSTR(char[] value) { - Debug.Assert(null != value, "Value_BYTES null"); + Debug.Assert(value is not null, "Value_BYTES null"); Debug.Assert(NativeDBType.WSTR == DbType, "Value_WSTR"); // we silently truncate when the user has specified a given Size int charCount = ((ValueBindingOffset < value.Length) ? Math.Min(value.Length - ValueBindingOffset, (ColumnBindingMaxLen - 2) / 2) : 0); @@ -1274,7 +1274,7 @@ internal bool ValueBoolean() internal byte[] ValueByteArray() { byte[]? value = (byte[]?)_value; - if (null == value) + if (value is null) { switch (StatusValue()) { @@ -1342,7 +1342,7 @@ internal byte ValueByte() internal OleDbDataReader ValueChapter() { OleDbDataReader? value = (OleDbDataReader?)_value; - if (null == value) + if (value is null) { switch (StatusValue()) { @@ -1607,7 +1607,7 @@ internal double ValueDouble() internal string ValueString() { string? value = (string?)_value; - if (null == value) + if (value is null) { switch (StatusValue()) { @@ -1654,7 +1654,7 @@ internal string ValueString() private object ValueVariant() { object? value = _value; - if (null == value) + if (value is null) { value = Value_VARIANT(); _value = value; diff --git a/src/libraries/System.Data.OleDb/src/DbBindings.cs b/src/libraries/System.Data.OleDb/src/DbBindings.cs index c3802812854454..3ff5c315e66778 100644 --- a/src/libraries/System.Data.OleDb/src/DbBindings.cs +++ b/src/libraries/System.Data.OleDb/src/DbBindings.cs @@ -255,7 +255,7 @@ internal int AllocateForAccessor(OleDbDataReader? dataReader, int indexStart, in _rowBinding = rowBinding; ColumnBinding[] columnBindings = rowBinding.SetBindings(dataReader, this, indexStart, indexForAccessor, _parameters, _dbbindings, _ifIRowsetElseIRow); - Debug.Assert(null != columnBindings, "null column bindings"); + Debug.Assert(columnBindings is not null, "null column bindings"); _columnBindings = columnBindings; if (!_ifIRowsetElseIRow) @@ -318,7 +318,7 @@ internal void ApplyOutputParameters() internal bool AreParameterBindingsInvalid(OleDbParameterCollection collection) { - Debug.Assert(null != collection, "null parameter collection"); + Debug.Assert(collection is not null, "null parameter collection"); Debug.Assert(null != _parameters, "null parameters"); ColumnBinding[] columnBindings = this.ColumnBindings(); @@ -328,7 +328,7 @@ internal bool AreParameterBindingsInvalid(OleDbParameterCollection collection) { ColumnBinding binding = columnBindings[i]; - Debug.Assert(null != binding, "null column binding"); + Debug.Assert(binding is not null, "null column binding"); Debug.Assert(binding.Parameter() == _parameters[i], "parameter mismatch"); if (binding.IsParameterBindingInvalid(collection[i])) { @@ -346,7 +346,7 @@ internal bool AreParameterBindingsInvalid(OleDbParameterCollection collection) internal void CleanupBindings() { RowBinding? rowBinding = this.RowBinding(); - if (null != rowBinding) + if (rowBinding is not null) { rowBinding.ResetValues(); @@ -354,7 +354,7 @@ internal void CleanupBindings() for (int i = 0; i < columnBindings.Length; ++i) { ColumnBinding binding = columnBindings[i]; - if (null != binding) + if (binding is not null) { binding.ResetValue(); } @@ -386,7 +386,7 @@ public void Dispose() RowBinding? rowBinding = _rowBinding; _rowBinding = null; - if (null != rowBinding) + if (rowBinding is not null) { rowBinding.Dispose(); } diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs index 11c5e01bb4b5ff..dc268384958cd0 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs @@ -129,7 +129,7 @@ public DbConnectionOptions(string? connectionString, Hashtable? synonyms, bool u { UseOdbcRules = useOdbcRules; _parsetable = new Hashtable(); - _usersConnectionString = ((null != connectionString) ? connectionString : ""); + _usersConnectionString = ((connectionString is not null) ? connectionString : ""); // first pass on parsing, initial syntax check if (0 < _usersConnectionString.Length) @@ -152,7 +152,7 @@ private string UsersConnectionString(bool hidePassword, bool forceHidePassword) { ReplacePasswordPwd(out connectionString, false); } - return ((null != connectionString) ? connectionString : ""); + return ((connectionString is not null) ? connectionString : ""); } internal bool HasPersistablePassword @@ -169,7 +169,7 @@ internal bool HasPersistablePassword public bool IsEmpty { - get { return (null == KeyChain); } + get { return (KeyChain is null); } } public string? this[string keyword] @@ -182,11 +182,11 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key ADP.CheckArgumentNull(builder, "builder"); ADP.CheckArgumentLength(keyName, "keyName"); - if ((null == keyName) || !ConnectionStringValidKeyRegex.IsMatch(keyName)) + if ((keyName is null) || !ConnectionStringValidKeyRegex.IsMatch(keyName)) { throw ADP.InvalidKeyname(keyName); } - if ((null != keyValue) && !IsValueValidInternal(keyValue)) + if ((keyValue is not null) && !IsValueValidInternal(keyValue)) { throw ADP.InvalidValue(keyName); } @@ -206,7 +206,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key } builder.Append('='); - if (null != keyValue) + if (keyValue is not null) { // else =; if (useOdbcRules) { @@ -253,7 +253,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key public bool ConvertValueToBoolean(string keyName, bool defaultValue) { object? value = _parsetable[keyName]; - if (null == value) + if (value is null) { return defaultValue; } @@ -283,7 +283,7 @@ internal static bool ConvertValueToBooleanInternal(string keyName, string string public int ConvertValueToInt32(string keyName, int defaultValue) { object? value = _parsetable[keyName]; - if (null == value) + if (value is null) { return defaultValue; } @@ -309,7 +309,7 @@ internal static int ConvertToInt32Internal(string keyname, string stringValue) public string? ConvertValueToString(string keyName, string? defaultValue) { string? value = (string?)_parsetable[keyName]; - return ((null != value) ? value : defaultValue); + return ((value is not null) ? value : defaultValue); } private static bool CompareInsensitiveInvariant(string strvalue, string strconst) @@ -334,15 +334,15 @@ protected internal virtual string Expand() internal static string? ExpandDataDirectory(string keyword, string? value, ref string? datadir) { string? fullPath = null; - if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) + if ((value is not null) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) { string? rootFolderPath = datadir; - if (null == rootFolderPath) + if (rootFolderPath is null) { // find the replacement path object? rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); rootFolderPath = (rootFolderObject as string); - if ((null != rootFolderObject) && (null == rootFolderPath)) + if ((rootFolderObject is not null) && (rootFolderPath is null)) { throw ADP.InvalidDataDirectory(); } @@ -350,7 +350,7 @@ protected internal virtual string Expand() { rootFolderPath = AppDomain.CurrentDomain.BaseDirectory; } - if (null == rootFolderPath) + if (rootFolderPath is null) { rootFolderPath = ""; } @@ -398,7 +398,7 @@ protected internal virtual string Expand() int copyPosition = 0; bool expanded = false; - for (NameValuePair? current = KeyChain; null != current; current = current.Next) + for (NameValuePair? current = KeyChain; current is not null; current = current.Next) { value = current.Value; @@ -441,7 +441,7 @@ protected internal virtual string Expand() break; } } - if (null == value) + if (value is null) { value = current.Value; } @@ -486,10 +486,10 @@ private static void DebugTraceKeyValuePair(string keyname, string? keyvalue, Has { Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower"); - string? realkeyname = ((null != synonyms) ? (string)synonyms[keyname]! : keyname); + string? realkeyname = ((synonyms is not null) ? (string)synonyms[keyname]! : keyname); if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! - if (null != keyvalue) + if (keyvalue is not null) { } else @@ -750,7 +750,7 @@ internal static int GetKeyValuePair(string connectionString, int currentPosition private static bool IsValueValidInternal(string? keyvalue) { - if (null != keyvalue) + if (keyvalue is not null) { #if DEBUG bool compValue = ConnectionStringValidValueRegex.IsMatch(keyvalue); @@ -763,7 +763,7 @@ private static bool IsValueValidInternal(string? keyvalue) private static bool IsKeyNameValid([NotNullWhen(true)] string? keyname) { - if (null != keyname) + if (keyname is not null) { #if DEBUG bool compValue = ConnectionStringValidKeyRegex.IsMatch(keyname); @@ -784,7 +784,7 @@ private static Hashtable SplitConnectionString(string connectionString, Hashtabl Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index"); Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index"); - if (null != connectionString) + if (connectionString is not null) { Match match = parser.Match(connectionString); if (!match.Success || (match.Length != connectionString.Length)) @@ -820,7 +820,7 @@ private static Hashtable SplitConnectionString(string connectionString, Hashtabl } DebugTraceKeyValuePair(keyname, keyvalue, synonyms); - string? realkeyname = ((null != synonyms) ? (string)synonyms[keyname]! : keyname); + string? realkeyname = ((synonyms is not null) ? (string)synonyms[keyname]! : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); @@ -851,7 +851,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin } catch (ArgumentException f) { - if (null != e) + if (e is not null) { string msg1 = e.Message; string msg2 = f.Message; @@ -879,7 +879,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin } e = null; } - if (null != e) + if (e is not null) { Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch"); } @@ -887,7 +887,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin #endif private static NameValuePair? ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable? synonyms, bool firstKey) { - Debug.Assert(null != connectionString, "null connectionstring"); + Debug.Assert(connectionString is not null, "null connectionstring"); StringBuilder buffer = new StringBuilder(); NameValuePair? localKeychain = null, keychain = null; #if DEBUG @@ -913,7 +913,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname"); Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue"); #endif - string? realkeyname = ((null != synonyms) ? (string)synonyms[keyname]! : keyname); + string? realkeyname = ((synonyms is not null) ? (string)synonyms[keyname]! : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); @@ -923,7 +923,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } - if (null != localKeychain) + if (localKeychain is not null) { localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); } @@ -950,7 +950,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin int copyPosition = 0; NameValuePair? head = null, tail = null, next = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair? current = KeyChain; null != current; current = current.Next) + for (NameValuePair? current = KeyChain; current is not null; current = current.Next) { if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name)) { @@ -974,7 +974,7 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin if (fakePassword) { - if (null != tail) + if (tail is not null) { tail = tail.Next = next; } diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs b/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs index 9477bb47b6cb11..8cd0ea42286187 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs @@ -19,7 +19,7 @@ internal ReadOnlyCollection(T[] items) #if DEBUG for (int i = 0; i < items.Length; ++i) { - Debug.Assert(null != items[i], "null item"); + Debug.Assert(items[i] is not null, "null item"); } #endif } @@ -131,9 +131,9 @@ internal static class DbConnectionStringBuilderUtil { internal static bool ConvertToBoolean(object value) { - Debug.Assert(null != value, "ConvertToBoolean(null)"); + Debug.Assert(value is not null, "ConvertToBoolean(null)"); string? svalue = (value as string); - if (null != svalue) + if (svalue is not null) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; diff --git a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs index a89572d1f606a0..4f313d1baf1b1f 100644 --- a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs +++ b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs @@ -30,7 +30,7 @@ private OleDbParameter(OleDbParameter source) : this() source.CloneHelper(this); ICloneable? cloneable = (_value as ICloneable); - if (null != cloneable) + if (cloneable is not null) { _value = cloneable.Clone(); } @@ -141,7 +141,7 @@ public override string SourceColumn get { string? sourceColumn = _sourceColumn; - return ((null != sourceColumn) ? sourceColumn : string.Empty); + return ((sourceColumn is not null) ? sourceColumn : string.Empty); } set { @@ -249,17 +249,17 @@ private int ValueSizeCore(object? value) if (!ADP.IsNull(value)) { string? svalue = (value as string); - if (null != svalue) + if (svalue is not null) { return svalue.Length; } byte[]? bvalue = (value as byte[]); - if (null != bvalue) + if (bvalue is not null) { return bvalue.Length; } char[]? cvalue = (value as char[]); - if (null != cvalue) + if (cvalue is not null) { return cvalue.Length; } diff --git a/src/libraries/System.Data.OleDb/src/DbPropSet.cs b/src/libraries/System.Data.OleDb/src/DbPropSet.cs index 30935b1c6f80dd..b56c902018c52d 100644 --- a/src/libraries/System.Data.OleDb/src/DbPropSet.cs +++ b/src/libraries/System.Data.OleDb/src/DbPropSet.cs @@ -44,10 +44,10 @@ internal DBPropSet(int propertysetCount) : this() internal DBPropSet(UnsafeNativeMethods.IDBProperties properties, PropertyIDSet? propidset, out OleDbHResult hr) : this() { - Debug.Assert(null != properties, "null IDBProperties"); + Debug.Assert(properties is not null, "null IDBProperties"); int propidsetcount = 0; - if (null != propidset) + if (propidset is not null) { propidsetcount = propidset.Count; } @@ -62,10 +62,10 @@ internal DBPropSet(UnsafeNativeMethods.IDBProperties properties, PropertyIDSet? internal DBPropSet(UnsafeNativeMethods.IRowsetInfo properties, PropertyIDSet? propidset, out OleDbHResult hr) : this() { - Debug.Assert(null != properties, "null IRowsetInfo"); + Debug.Assert(properties is not null, "null IRowsetInfo"); int propidsetcount = 0; - if (null != propidset) + if (propidset is not null) { propidsetcount = propidset.Count; } @@ -80,10 +80,10 @@ internal DBPropSet(UnsafeNativeMethods.IRowsetInfo properties, PropertyIDSet? pr internal DBPropSet(UnsafeNativeMethods.ICommandProperties properties, PropertyIDSet? propidset, out OleDbHResult hr) : this() { - Debug.Assert(null != properties, "null ICommandProperties"); + Debug.Assert(properties is not null, "null ICommandProperties"); int propidsetcount = 0; - if (null != propidset) + if (propidset is not null) { propidsetcount = propidset.Count; } @@ -103,7 +103,7 @@ private void SetLastErrorInfo(OleDbHResult lastErrorHr) string message = string.Empty; OleDbHResult errorInfoHr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo - if ((errorInfoHr == OleDbHResult.S_OK) && (errorInfo != null)) + if ((errorInfoHr == OleDbHResult.S_OK) && (errorInfo is not null)) { ODB.GetErrorDescription(errorInfo, lastErrorHr, out message); // note that either GetErrorInfo or GetErrorDescription might fail in which case we will have only the HRESULT value in exception message @@ -159,7 +159,7 @@ internal ItagDBPROP[] GetPropertySet(int index, out Guid propertyset) { if ((index < 0) || (PropertySetCount <= index)) { - if (lastErrorFromProvider != null) + if (lastErrorFromProvider is not null) { // add extra error information for CSS/stress troubleshooting. // We need to keep same exception type to avoid breaking change with Orcas RTM/SP1. @@ -205,7 +205,7 @@ internal void SetPropertySet(int index, Guid propertySet, ItagDBPROP[] propertie { if ((index < 0) || (PropertySetCount <= index)) { - if (lastErrorFromProvider != null) + if (lastErrorFromProvider is not null) { // add extra error information for CSS/stress troubleshooting. // We need to keep same exception type to avoid breaking change with Orcas RTM/SP1. @@ -217,7 +217,7 @@ internal void SetPropertySet(int index, Guid propertySet, ItagDBPROP[] propertie } } Debug.Assert(Guid.Empty != propertySet, "invalid propertySet"); - Debug.Assert((null != properties) && (0 < properties.Length), "invalid properties"); + Debug.Assert((properties is not null) && (0 < properties.Length), "invalid properties"); IntPtr countOfBytes = (IntPtr)(properties.Length * ODB.SizeOf_tagDBPROP); tagDBPROPSET propset = new tagDBPROPSET(properties.Length, propertySet); @@ -254,7 +254,7 @@ internal void SetPropertySet(int index, Guid propertySet, ItagDBPROP[] propertie for (int i = 0; i < properties.Length; ++i) { - Debug.Assert(null != properties[i], "null tagDBPROP " + i.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(properties[i] is not null, "null tagDBPROP " + i.ToString(CultureInfo.InvariantCulture)); IntPtr propertyPtr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP); Marshal.StructureToPtr(properties[i], propertyPtr, false/*deleteold*/); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs index a47d9cd6fa444b..0004f9842f08b5 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs @@ -96,7 +96,7 @@ private Bindings? ParameterBindings { Bindings? bindings = _dbBindings; _dbBindings = value; - if ((null != bindings) && (value != bindings)) + if ((bindings is not null) && (value != bindings)) { bindings.Dispose(); } @@ -113,7 +113,7 @@ public override string CommandText get { string? value = _commandText; - return ((null != value) ? value : string.Empty); + return ((value is not null) ? value : string.Empty); } set { @@ -198,7 +198,7 @@ public override CommandType CommandType _connection = value; - if (null != value) + if (value is not null) { _transaction = OleDbTransaction.TransactionUpdate(_transaction); } @@ -209,7 +209,7 @@ public override CommandType CommandType private void ResetConnection() { OleDbConnection? connection = _connection; - if (null != connection) + if (connection is not null) { PropertyChanging(); CloseInternal(); @@ -285,7 +285,7 @@ public override bool DesignTimeVisible get { OleDbParameterCollection? value = _parameters; - if (null == value) + if (value is null) { // delay the creation of the OleDbParameterCollection // until user actually uses the Parameters property @@ -299,7 +299,7 @@ public override bool DesignTimeVisible private bool HasParameters() { OleDbParameterCollection? value = _parameters; - return (null != value) && (0 < value.Count); + return (value is not null) && (0 < value.Count); } [ @@ -313,7 +313,7 @@ private bool HasParameters() // find the last non-zombied local transaction object, but not transactions // that may have been started after the current local transaction OleDbTransaction? transaction = _transaction; - while ((null != transaction) && (null == transaction.Connection)) + while ((transaction is not null) && (transaction.Connection is null)) { transaction = transaction.Parent; _transaction = transaction; @@ -377,7 +377,7 @@ private UnsafeNativeMethods.ICommandWithParameters ICommandWithParameters() { Debug.Assert(null != _icommandText, "ICommandWithParameters: null ICommandText"); UnsafeNativeMethods.ICommandWithParameters? value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters); - if (null == value) + if (value is null) { throw ODB.NoProviderSupportForParameters(_connection!.Provider, null); } @@ -463,7 +463,7 @@ public override void Cancel() { _changeID++; } UnsafeNativeMethods.ICommandText? icmdtxt = _icommandText; - if (null != icmdtxt) + if (icmdtxt is not null) { OleDbHResult hr = OleDbHResult.S_OK; @@ -526,7 +526,7 @@ internal void CloseInternal() // via OleDbCommand.Dispose or OleDbConnection.Close internal void CloseFromDataReader(Bindings? bindings) { - if (null != bindings) + if (bindings is not null) { if (canceling) { @@ -550,7 +550,7 @@ private void CloseInternalCommand() _isPrepared = false; UnsafeNativeMethods.ICommandText? ict = Interlocked.Exchange(ref _icommandText, null); - if (null != ict) + if (ict is not null) { lock (ict) { @@ -564,7 +564,7 @@ private void CloseInternalParameters() Debug.Assert(null != _connection, "no connection, CloseInternalParameters"); Bindings? bindings = _dbBindings; _dbBindings = null; - if (null != bindings) + if (bindings is not null) { bindings.Dispose(); } @@ -706,14 +706,14 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) if (ODB.InternalStateOpen != state) { this.canceling = true; - if (null != dataReader) + if (dataReader is not null) { ((IDisposable)dataReader).Dispose(); dataReader = null; } } } - Debug.Assert(null != dataReader, "ExecuteReader should never return a null DataReader"); + Debug.Assert(dataReader is not null, "ExecuteReader should never return a null DataReader"); } else { // optimized code path for ExecuteNonQuery to not create a OleDbDataReader object @@ -731,7 +731,7 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { try { - if (null != executeResult) + if (executeResult is not null) { Marshal.ReleaseComObject(executeResult); executeResult = null; @@ -745,7 +745,7 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { throw; } - if (null != nextResultsFailure) + if (nextResultsFailure is not null) { nextResultsFailure = new OleDbException(nextResultsFailure, e); } @@ -761,7 +761,7 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { // finally clear executing state try { - if ((null == dataReader) && (ODB.InternalStateOpen != state)) + if ((dataReader is null) && (ODB.InternalStateOpen != state)) { ParameterCleanup(); } @@ -773,7 +773,7 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { throw; } - if (null != nextResultsFailure) + if (nextResultsFailure is not null) { nextResultsFailure = new OleDbException(nextResultsFailure, e); } @@ -782,7 +782,7 @@ protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) throw; } } - if (null != nextResultsFailure) + if (nextResultsFailure is not null) { throw nextResultsFailure; } @@ -819,7 +819,7 @@ private int ExecuteCommandText(out object executeResult) try { // TODO-NULLABLE: Code below seems to assume that bindings will always be non-null - if (null != bindings) + if (bindings is not null) { // parameters may be suppressed rowbinding = bindings.RowBinding(); @@ -917,7 +917,7 @@ private int ExecuteCommandTextForSingleRow(tagDBPARAMS dbParams, out object exec private void ExecuteCommandTextErrorHandling(OleDbHResult hr) { Exception? e = OleDbConnection.ProcessResults(hr, _connection, this); - if (null != e) + if (e is not null) { e = ExecuteCommandTextSpecialErrorHandling(hr, e); throw e; @@ -933,7 +933,7 @@ private Exception ExecuteCommandTextSpecialErrorHandling(OleDbHResult hr, Except // of invalid parameter types being passed to a provider that doesn't understand // the user specified parameter OleDbType - Debug.Assert(null != e, "missing inner exception"); + Debug.Assert(e is not null, "missing inner exception"); StringBuilder builder = new StringBuilder(); ParameterBindings!.ParameterStatus(builder); @@ -991,7 +991,7 @@ private int ExecuteTableDirect(CommandBehavior behavior, out object? executeResu { using (DBPropSet? propSet = CommandPropertySets()) { - if (null != propSet) + if (propSet is not null) { bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1128,7 +1128,7 @@ private string ExpandStoredProcedureToText(string sproctext) private void ParameterCleanup() { Bindings? bindings = ParameterBindings; - if (null != bindings) + if (bindings is not null) { bindings.CleanupBindings(); } @@ -1209,7 +1209,7 @@ public override void Prepare() private void PrepareCommandText(int expectedExecutionCount) { OleDbParameterCollection? parameters = _parameters; - if (null != parameters) + if (parameters is not null) { foreach (OleDbParameter parameter in parameters) { @@ -1223,7 +1223,7 @@ private void PrepareCommandText(int expectedExecutionCount) } } UnsafeNativeMethods.ICommandPrepare? icommandPrepare = ICommandPrepare(); - if (null != icommandPrepare) + if (icommandPrepare is not null) { OleDbHResult hr; hr = icommandPrepare.Prepare(expectedExecutionCount); @@ -1238,14 +1238,14 @@ private void PrepareCommandText(int expectedExecutionCount) private void ProcessResults(OleDbHResult hr) { Exception? e = OleDbConnection.ProcessResults(hr, _connection, this); - if (null != e) + if (e is not null) { throw e; } } private void ProcessResultsNoReset(OleDbHResult hr) { Exception? e = OleDbConnection.ProcessResults(hr, null, this); - if (null != e) + if (e is not null) { throw e; } } @@ -1281,7 +1281,7 @@ private void ProcessResultsNoReset(OleDbHResult hr) private bool PropertiesOnCommand(bool throwNotSupported) { - Debug.Assert(_connection != null); + Debug.Assert(_connection is not null); if (null != _icommandText) { @@ -1309,7 +1309,7 @@ private bool PropertiesOnCommand(bool throwNotSupported) using (DBPropSet? propSet = CommandPropertySets()) { - if (null != propSet) + if (propSet is not null) { UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties(); OleDbHResult hr = icommandProperties.SetProperties(propSet.PropertySetCount, propSet); diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs index 7eeabb87487d03..25a4eb037721fc 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs @@ -102,7 +102,7 @@ protected override void ApplyParameterInfo(DbParameter parameter, DataRow dataro public static void DeriveParameters(OleDbCommand command) { - if (null == command) + if (command is null) { throw ADP.ArgumentNull("command"); } @@ -123,7 +123,7 @@ public static void DeriveParameters(OleDbCommand command) throw ADP.CommandTextRequired(ADP.DeriveParameters); } OleDbConnection? connection = command.Connection; - if (null == connection) + if (connection is null) { throw ADP.ConnectionRequired(ADP.DeriveParameters); } @@ -156,7 +156,7 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect connection.GetLiteralQuotes(ADP.DeriveParameters, out quotePrefix, out quoteSuffix); object?[] parsed = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quotePrefix, quoteSuffix, '.', 4, true, SR.OLEDB_OLEDBCommandText, false); - if (null == parsed[3]) + if (parsed[3] is null) { throw ADP.NoStoredProcedureExists(command.CommandText); } @@ -184,7 +184,7 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect //} DataTable? table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters, restrictions); - if (null != table) + if (table is not null) { DataColumnCollection columns = table.Columns; @@ -232,23 +232,23 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect OleDbParameter parameter = new OleDbParameter(); - if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default)) + if ((parameterName is not null) && !dataRow.IsNull(parameterName, DataRowVersion.Default)) { // $CONSIDER - not trimming the @ from the beginning but to left the designer do that parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(new char[] { '@', ' ', ':' }); } - if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default)) + if ((parameterDirection is not null) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default)) { short direction = Convert.ToInt16(dataRow[parameterDirection, DataRowVersion.Default], CultureInfo.InvariantCulture); parameter.Direction = ConvertToParameterDirection(direction); } - if ((null != dataType) && !dataRow.IsNull(dataType, DataRowVersion.Default)) + if ((dataType is not null) && !dataRow.IsNull(dataType, DataRowVersion.Default)) { // need to ping FromDBType, otherwise WChar->WChar when the user really wants VarWChar short wType = Convert.ToInt16(dataRow[dataType, DataRowVersion.Default], CultureInfo.InvariantCulture); parameter.OleDbType = NativeDBType.FromDBType(wType, false, false).enumOleDbType; } - if ((null != maxLen) && !dataRow.IsNull(maxLen, DataRowVersion.Default)) + if ((maxLen is not null) && !dataRow.IsNull(maxLen, DataRowVersion.Default)) { parameter.Size = Convert.ToInt32(dataRow[maxLen, DataRowVersion.Default], CultureInfo.InvariantCulture); } @@ -257,12 +257,12 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect case OleDbType.Decimal: case OleDbType.Numeric: case OleDbType.VarNumeric: - if ((null != numericPrecision) && !dataRow.IsNull(numericPrecision, DataRowVersion.Default)) + if ((numericPrecision is not null) && !dataRow.IsNull(numericPrecision, DataRowVersion.Default)) { // @devnote: unguarded cast from Int16 to Byte parameter.PrecisionInternal = (byte)Convert.ToInt16(dataRow[numericPrecision], CultureInfo.InvariantCulture); } - if ((null != numericScale) && !dataRow.IsNull(numericScale, DataRowVersion.Default)) + if ((numericScale is not null) && !dataRow.IsNull(numericScale, DataRowVersion.Default)) { // @devnote: unguarded cast from Int16 to Byte parameter.ScaleInternal = (byte)Convert.ToInt16(dataRow[numericScale], CultureInfo.InvariantCulture); @@ -366,12 +366,12 @@ public string QuoteIdentifier(string unquotedIdentifier, OleDbConnection? connec string quoteSuffix = QuoteSuffix; if (ADP.IsEmpty(quotePrefix) == true) { - if (connection == null) + if (connection is null) { // Use the adapter's connection if QuoteIdentifier was called from // DbCommandBuilder instance (which does not have an overload that gets connection object) connection = DataAdapter?.SelectCommand?.Connection; - if (connection == null) + if (connection is null) { throw ADP.QuotePrefixNotSet(ADP.QuoteIdentifier); } @@ -379,7 +379,7 @@ public string QuoteIdentifier(string unquotedIdentifier, OleDbConnection? connec connection.GetLiteralQuotes(ADP.QuoteIdentifier, out quotePrefix, out quoteSuffix); // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) - if (quoteSuffix == null) + if (quoteSuffix is null) { quoteSuffix = quotePrefix; } @@ -416,12 +416,12 @@ public string UnquoteIdentifier(string quotedIdentifier, OleDbConnection? connec string quoteSuffix = QuoteSuffix; if (ADP.IsEmpty(quotePrefix) == true) { - if (connection == null) + if (connection is null) { // Use the adapter's connection if UnquoteIdentifier was called from // DbCommandBuilder instance (which does not have an overload that gets connection object) connection = DataAdapter?.SelectCommand?.Connection; - if (connection == null) + if (connection is null) { throw ADP.QuotePrefixNotSet(ADP.UnquoteIdentifier); } @@ -429,7 +429,7 @@ public string UnquoteIdentifier(string quotedIdentifier, OleDbConnection? connec connection.GetLiteralQuotes(ADP.UnquoteIdentifier, out quotePrefix, out quoteSuffix); // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) - if (quoteSuffix == null) + if (quoteSuffix is null) { quoteSuffix = quotePrefix; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 6417087aa62302..a40ed794b37f67 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -78,9 +78,9 @@ public override int ConnectionTimeout else { OleDbConnectionString? constr = this.OleDbConnectionStringValue; - value = (null != constr) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout; + value = (constr is not null) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout; } - if (null != value) + if (value is not null) { return Convert.ToInt32(value, CultureInfo.InvariantCulture); } @@ -97,11 +97,11 @@ public override string Database get { OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; - object? value = (null != constr) ? constr.InitialCatalog : string.Empty; - if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) + object? value = (constr is not null) ? constr.InitialCatalog : string.Empty; + if ((value is not null) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { OleDbConnectionInternal connection = GetOpenConnection(); - if (null != connection) + if (connection is not null) { if (connection.HasSession) { @@ -115,7 +115,7 @@ public override string Database else { constr = this.OleDbConnectionStringValue; - value = (null != constr) ? constr.InitialCatalog : string.Empty; + value = (constr is not null) ? constr.InitialCatalog : string.Empty; } } return Convert.ToString(value, CultureInfo.InvariantCulture)!; @@ -130,13 +130,13 @@ public override string DataSource get { OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; - object? value = (null != constr) ? constr.DataSource : string.Empty; - if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) + object? value = (constr is not null) ? constr.DataSource : string.Empty; + if ((value is not null) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_DATASOURCE); - if ((null == value) || ((value is string) && (0 == (value as string)!.Length))) + if ((value is null) || ((value is string) && (0 == (value as string)!.Length))) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DATASOURCENAME); } @@ -144,7 +144,7 @@ public override string DataSource else { constr = this.OleDbConnectionStringValue; - value = (null != constr) ? constr.DataSource : string.Empty; + value = (constr is not null) ? constr.DataSource : string.Empty; } } return Convert.ToString(value, CultureInfo.InvariantCulture)!; @@ -153,7 +153,7 @@ public override string DataSource internal bool IsOpen { - get { return (null != GetOpenConnection()); } + get { return (GetOpenConnection() is not null); } } internal OleDbTransaction? LocalTransaction @@ -162,7 +162,7 @@ internal OleDbTransaction? LocalTransaction { OleDbConnectionInternal openConnection = GetOpenConnection(); - if (null != openConnection) + if (openConnection is not null) { openConnection.LocalTransaction = value; } @@ -178,8 +178,8 @@ public string Provider get { OleDbConnectionString? constr = this.OleDbConnectionStringValue; - string? value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null); - return ((null != value) ? value : string.Empty); + string? value = ((constr is not null) ? constr.ConvertValueToString(ODB.Provider, null) : null); + return ((value is not null) ? value : string.Empty); } } @@ -187,7 +187,7 @@ internal OleDbConnectionPoolGroupProviderInfo ProviderInfo { get { - Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); + Debug.Assert(this.PoolGroup is not null, "PoolGroup must never be null when accessing ProviderInfo"); return (OleDbConnectionPoolGroupProviderInfo)PoolGroup!.ProviderInfo!; } } @@ -256,43 +256,43 @@ public event OleDbInfoMessageEventHandler? InfoMessage internal UnsafeNativeMethods.ICommandText? ICommandText() { - Debug.Assert(null != GetOpenConnection(), "ICommandText closed"); + Debug.Assert(GetOpenConnection() is not null, "ICommandText closed"); return GetOpenConnection().ICommandText(); } private IDBPropertiesWrapper IDBProperties() { - Debug.Assert(null != GetOpenConnection(), "IDBProperties closed"); + Debug.Assert(GetOpenConnection() is not null, "IDBProperties closed"); return GetOpenConnection().IDBProperties(); } internal IOpenRowsetWrapper IOpenRowset() { - Debug.Assert(null != GetOpenConnection(), "IOpenRowset closed"); + Debug.Assert(GetOpenConnection() is not null, "IOpenRowset closed"); return GetOpenConnection().IOpenRowset(); } internal int SqlSupport() { - Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SqlSupport"); + Debug.Assert(this.OleDbConnectionStringValue is not null, "no OleDbConnectionString SqlSupport"); return this.OleDbConnectionStringValue.GetSqlSupport(this); } internal bool SupportMultipleResults() { - Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportMultipleResults"); + Debug.Assert(this.OleDbConnectionStringValue is not null, "no OleDbConnectionString SupportMultipleResults"); return this.OleDbConnectionStringValue.GetSupportMultipleResults(this); } internal bool SupportIRow(OleDbCommand cmd) { - Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportIRow"); + Debug.Assert(this.OleDbConnectionStringValue is not null, "no OleDbConnectionString SupportIRow"); return this.OleDbConnectionStringValue.GetSupportIRow(this, cmd); } internal int QuotedIdentifierCase() { - Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString QuotedIdentifierCase"); + Debug.Assert(this.OleDbConnectionStringValue is not null, "no OleDbConnectionString QuotedIdentifierCase"); int quotedIdentifierCase; object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); @@ -430,7 +430,7 @@ internal void GetLiteralQuotes(string method, out string quotePrefix, out string if (OleDbSchemaGuid.DbInfoLiterals == schema) { - if ((null == restrictions) || (0 == restrictions.Length)) + if ((restrictions is null) || (0 == restrictions.Length)) { return connection.BuildInfoLiterals(); } @@ -438,7 +438,7 @@ internal void GetLiteralQuotes(string method, out string quotePrefix, out string } else if (OleDbSchemaGuid.SchemaGuids == schema) { - if ((null == restrictions) || (0 == restrictions.Length)) + if ((restrictions is null) || (0 == restrictions.Length)) { return connection.BuildSchemaGuids(); } @@ -446,7 +446,7 @@ internal void GetLiteralQuotes(string method, out string quotePrefix, out string } else if (OleDbSchemaGuid.DbInfoKeywords == schema) { - if ((null == restrictions) || (0 == restrictions.Length)) + if ((restrictions is null) || (0 == restrictions.Length)) { return connection.BuildInfoKeywords(); } @@ -461,7 +461,7 @@ internal void GetLiteralQuotes(string method, out string quotePrefix, out string { using (IDBSchemaRowsetWrapper wrapper = connection.IDBSchemaRowset()) { - if (null == wrapper.Value) + if (wrapper.Value is null) { throw ODB.SchemaRowsetsNotSupported(Provider); } @@ -472,7 +472,7 @@ internal void GetLiteralQuotes(string method, out string quotePrefix, out string internal DataTable? GetSchemaRowset(Guid schema, object?[] restrictions) { - Debug.Assert(null != GetOpenConnection(), "GetSchemaRowset closed"); + Debug.Assert(GetOpenConnection() is not null, "GetSchemaRowset closed"); return GetOpenConnection().GetSchemaRowset(schema, restrictions); } @@ -481,7 +481,7 @@ internal bool HasLiveReader(OleDbCommand cmd) bool result = false; OleDbConnectionInternal openConnection = GetOpenConnection(); - if (null != openConnection) + if (openConnection is not null) { result = openConnection.HasLiveReader(cmd); } @@ -491,7 +491,7 @@ internal bool HasLiveReader(OleDbCommand cmd) internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode) { OleDbInfoMessageEventHandler? handler = (OleDbInfoMessageEventHandler?)Events[EventInfoMessage]; - if (null != handler) + if (handler is not null) { try { @@ -550,7 +550,7 @@ internal void SetDataSourcePropertyValue(Guid propertySet, int propertyID, strin e = ODB.PropsetSetFailure(builder.ToString(), e!); } - if (null != e) + if (e is not null) { throw e; } @@ -575,7 +575,7 @@ internal bool SupportSchemaRowset(Guid schema) internal static Exception? ProcessResults(OleDbHResult hresult, OleDbConnection? connection, object? src) { - if ((0 <= (int)hresult) && ((null == connection) || (null == connection.Events[EventInfoMessage]))) + if ((0 <= (int)hresult) && ((connection is null) || (null == connection.Events[EventInfoMessage]))) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return null; @@ -585,7 +585,7 @@ internal bool SupportSchemaRowset(Guid schema) Exception? e = null; UnsafeNativeMethods.IErrorInfo? errorInfo = null; OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo - if ((OleDbHResult.S_OK == hr) && (null != errorInfo)) + if ((OleDbHResult.S_OK == hr) && (errorInfo is not null)) { if (hresult < 0) { @@ -605,7 +605,7 @@ internal bool SupportSchemaRowset(Guid schema) ResetState(connection); } - else if (null != connection) + else if (connection is not null) { connection.OnInfoMessage(errorInfo, hresult); } @@ -620,11 +620,11 @@ internal bool SupportSchemaRowset(Guid schema) } else if ((int)hresult < 0) { - e = ODB.NoErrorInformation((null != connection) ? connection.Provider : null, hresult, null); // OleDbException + e = ODB.NoErrorInformation((connection is not null) ? connection.Provider : null, hresult, null); // OleDbException ResetState(connection); } - if (null != e) + if (e is not null) { ADP.TraceExceptionAsReturnValue(e); } @@ -641,7 +641,7 @@ public static void ReleaseObjectPool() private static void ResetState(OleDbConnection? connection) { - if (null != connection) + if (connection is not null) { connection.ResetState(); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs index 9b1a7cd366424a..960a374b018e22 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs @@ -41,24 +41,24 @@ protected override DbConnectionInternal CreateConnection(DbConnectionOptions opt protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions? previous) { Debug.Assert(!ADP.IsEmpty(connectionString), "null connectionString"); - OleDbConnectionString result = new OleDbConnectionString(connectionString, (null != previous)); + OleDbConnectionString result = new OleDbConnectionString(connectionString, (previous is not null)); return result; } protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory) { - Debug.Assert(internalConnection != null, "internalConnection may not be null."); + Debug.Assert(internalConnection is not null, "internalConnection may not be null."); cacheMetaDataFactory = false; OleDbConnectionInternal oleDbInternalConnection = (OleDbConnectionInternal)internalConnection; OleDbConnection? oleDbOuterConnection = oleDbInternalConnection.Connection; - Debug.Assert(oleDbOuterConnection != null, "outer connection may not be null."); + Debug.Assert(oleDbOuterConnection is not null, "outer connection may not be null."); NameValueCollection settings = (NameValueCollection)ConfigurationManager.GetSection("system.data.oledb"); Stream? XMLStream = null; string? providerFileName = oleDbOuterConnection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_PROVIDERFILENAME) as string; - if (settings != null) + if (settings is not null) { string[]? values = null; string? metaDataXML = null; @@ -66,34 +66,34 @@ protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal // if providerfilename is not supported we can't build the settings key needed to // get the provider specific XML path - if (providerFileName != null) + if (providerFileName is not null) { metaDataXML = providerFileName + _metaDataXml; values = settings.GetValues(metaDataXML); } // if we did not find provider specific xml see if there is new default xml - if (values == null) + if (values is null) { metaDataXML = _defaultMetaDataXml; values = settings.GetValues(metaDataXML); } // If there is new XML get it - if (values != null) + if (values is not null) { XMLStream = ADP.GetXmlStreamFromValues(values, metaDataXML!); } } // if the xml was not obtained from machine.config use the embedded XML resource - if (XMLStream == null) + if (XMLStream is null) { XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.OleDb.OleDbMetaData.xml"); cacheMetaDataFactory = true; } - Debug.Assert(XMLStream != null, "XMLstream may not be null."); + Debug.Assert(XMLStream is not null, "XMLstream may not be null."); // using the ServerVersion as the NormalizedServerVersion. Doing this for two reasons // 1) The Spec for DBPROP_DBMSVER normalizes the ServerVersion @@ -117,7 +117,7 @@ internal override DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro internal override DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnection connection) { OleDbConnection? c = (connection as OleDbConnection); - if (null != c) + if (c is not null) { return c.PoolGroup; } @@ -127,7 +127,7 @@ internal override DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro internal override void PermissionDemand(DbConnection outerConnection) { OleDbConnection? c = (outerConnection as OleDbConnection); - if (null != c) + if (c is not null) { c.PermissionDemand(); } @@ -136,7 +136,7 @@ internal override void PermissionDemand(DbConnection outerConnection) internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { OleDbConnection? c = (outerConnection as OleDbConnection); - if (null != c) + if (c is not null) { c.PoolGroup = poolGroup; } @@ -145,7 +145,7 @@ internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbCo internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { OleDbConnection? c = (owningObject as OleDbConnection); - if (null != c) + if (c is not null) { c.SetInnerConnectionEvent(to); } @@ -154,7 +154,7 @@ internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConn internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { OleDbConnection? c = (owningObject as OleDbConnection); - if (null != c) + if (c is not null) { return c.SetInnerConnectionFrom(to, from); } @@ -164,7 +164,7 @@ internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConne internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { OleDbConnection? c = (owningObject as OleDbConnection); - if (null != c) + if (c is not null) { c.SetInnerConnectionTo(to); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs index 09ab6982105b5e..7e5ffd0f331d52 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs @@ -63,7 +63,7 @@ internal sealed class OleDbConnectionInternal : DbConnectionInternal, IDisposabl internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection? connection) : base() { - Debug.Assert((null != constr) && !constr.IsEmpty, "empty connectionstring"); + Debug.Assert((constr is not null) && !constr.IsEmpty, "empty connectionstring"); ConnectionString = constr; if (constr.PossiblePrompt && !System.Environment.UserInteractive) @@ -84,7 +84,7 @@ internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection? // initialization is delayed because of OleDbConnectionStringBuilder only wants // pre-Initialize IDBPropertyInfo & IDBProperties on the data source - if (null != connection) + if (connection is not null) { _sessionwrp = new SessionWrapper(); @@ -101,7 +101,7 @@ internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection? else { Exception? e = OleDbConnection.ProcessResults(hr, null, null); - Debug.Assert(null != e, "CreateSessionError"); + Debug.Assert(e is not null, "CreateSessionError"); throw e; } Debug.Assert(!_sessionwrp.IsInvalid, "bad Session"); @@ -144,7 +144,7 @@ internal OleDbTransaction? LocalTransaction get { OleDbTransaction? result = null; - if (null != weakTransaction) + if (weakTransaction is not null) { result = ((OleDbTransaction?)weakTransaction.Target); } @@ -154,7 +154,7 @@ internal OleDbTransaction? LocalTransaction { weakTransaction = null; - if (null != value) + if (value is not null) { weakTransaction = new WeakReference((OleDbTransaction)value); } @@ -226,7 +226,7 @@ internal ITransactionJoinWrapper ITransactionJoin() object? icommandText = null; OleDbHResult hr = _sessionwrp.CreateCommand(ref icommandText); - Debug.Assert((0 <= hr) || (null == icommandText), "CreateICommandText: error with ICommandText"); + Debug.Assert((0 <= hr) || (icommandText is null), "CreateICommandText: error with ICommandText"); if (hr < 0) { if (OleDbHResult.E_NOINTERFACE != hr) @@ -249,7 +249,7 @@ protected override void Activate(SysTx.Transaction? transaction) public override DbTransaction BeginTransaction(IsolationLevel isolationLevel) { OleDbConnection outerConnection = Connection!; - if (null != LocalTransaction) + if (LocalTransaction is not null) { throw ADP.ParallelTransactionsNotSupported(outerConnection); } @@ -263,7 +263,7 @@ public override DbTransaction BeginTransaction(IsolationLevel isolationLevel) Debug.Assert(null != _sessionwrp, "ITransactionLocal: null session"); unknown = _sessionwrp.ComWrapper(); UnsafeNativeMethods.ITransactionLocal? value = (unknown as UnsafeNativeMethods.ITransactionLocal); - if (null == value) + if (value is null) { throw ODB.TransactionsNotSupported(Provider, null); } @@ -271,7 +271,7 @@ public override DbTransaction BeginTransaction(IsolationLevel isolationLevel) } finally { - if (null != unknown) + if (unknown is not null) { Marshal.ReleaseComObject(unknown); } @@ -295,7 +295,7 @@ protected override void Deactivate() EnlistTransactionInternal(null); } OleDbTransaction? transaction = LocalTransaction; - if (null != transaction) + if (transaction is not null) { LocalTransaction = null; // required to rollback any transactions on this connection @@ -306,7 +306,7 @@ protected override void Deactivate() public override void Dispose() { - Debug.Assert(null == LocalTransaction, "why was Deactivate not called first"); + Debug.Assert(LocalTransaction is null, "why was Deactivate not called first"); if (null != _sessionwrp) { _sessionwrp.Dispose(); @@ -320,7 +320,7 @@ public override void Dispose() public override void EnlistTransaction(SysTx.Transaction? transaction) { - if (null != LocalTransaction) + if (LocalTransaction is not null) { throw ADP.LocalTransactionPresent(); } @@ -333,12 +333,12 @@ internal void EnlistTransactionInternal(SysTx.Transaction? transaction) using (ITransactionJoinWrapper transactionJoin = ITransactionJoin()) { - if (null == transactionJoin.Value) + if (transactionJoin.Value is null) { throw ODB.TransactionsNotSupported(Provider, null); } transactionJoin.Value.JoinTransaction(oleTxTransaction, (int)IsolationLevel.Unspecified, 0, IntPtr.Zero); - _unEnlistDuringDeactivate = (null != transaction); + _unEnlistDuringDeactivate = (transaction is not null); } EnlistedTransaction = transaction; } @@ -386,7 +386,7 @@ internal void EnlistTransactionInternal(SysTx.Transaction? transaction) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; // TODO-NULLABLE: check may not be necessary (and thus method may return non-nullable) - if (null == dbInfo) + if (dbInfo is null) { return null; } @@ -466,7 +466,7 @@ internal bool AddInfoKeywordsToTable(DataTable table, DataColumn keyword) using (IDBInfoWrapper wrapper = IDBInfo()) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; - if (null == dbInfo) + if (dbInfo is null) { return false; } @@ -480,7 +480,7 @@ internal bool AddInfoKeywordsToTable(DataTable table, DataColumn keyword) ProcessResults(hr); } - if (null != keywords) + if (keywords is not null) { string[] values = keywords.Split(new char[1] { ',' }); for (int i = 0; i < values.Length; ++i) @@ -509,7 +509,7 @@ internal DataTable BuildSchemaGuids() SchemaSupport[]? supportedSchemas = GetSchemaRowsetInformation(); - if (null != supportedSchemas) + if (supportedSchemas is not null) { object[] values = new object[2]; table.BeginLoadData(); @@ -529,7 +529,7 @@ internal DataTable BuildSchemaGuids() using (IDBInfoWrapper wrapper = IDBInfo()) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; - if (null == dbInfo) + if (dbInfo is null) { return null; } @@ -565,14 +565,14 @@ internal DataTable BuildSchemaGuids() { OleDbConnectionString constr = ConnectionString; SchemaSupport[]? supportedSchemas = constr.SchemaSupport; - if (null != supportedSchemas) + if (supportedSchemas is not null) { return supportedSchemas; } using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) { UnsafeNativeMethods.IDBSchemaRowset? dbSchemaRowset = wrapper.Value; - if (null == dbSchemaRowset) + if (dbSchemaRowset is null) { return null; // IDBSchemaRowset not supported } @@ -614,7 +614,7 @@ internal DataTable BuildSchemaGuids() internal DataTable? GetSchemaRowset(Guid schema, object?[]? restrictions) { - if (null == restrictions) + if (restrictions is null) { restrictions = Array.Empty(); } @@ -622,7 +622,7 @@ internal DataTable BuildSchemaGuids() using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) { UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value; - if (null == dbSchemaRowset) + if (dbSchemaRowset is null) { throw ODB.SchemaRowsetsNotSupported(Provider); } @@ -636,7 +636,7 @@ internal DataTable BuildSchemaGuids() ProcessResults(hr); } - if (null != rowset) + if (rowset is not null) { using (OleDbDataReader dataReader = new OleDbDataReader(Connection, null, 0, CommandBehavior.Default)) { @@ -659,26 +659,26 @@ internal bool HasLiveReader(OleDbCommand cmd) { OleDbDataReader? reader = null; - if (null != ReferenceCollection) + if (ReferenceCollection is not null) { reader = ReferenceCollection.FindItem(OleDbReferenceCollection.DataReaderTag, (dataReader) => cmd == dataReader.Command); } - return (reader != null); + return (reader is not null); } private void ProcessResults(OleDbHResult hr) { OleDbConnection? connection = Connection; // get value from weakref only once Exception? e = OleDbConnection.ProcessResults(hr, connection, connection); - if (null != e) + if (e is not null) { throw e; } } internal bool SupportSchemaRowset(Guid schema) { SchemaSupport[]? schemaSupport = GetSchemaRowsetInformation(); - if (null != schemaSupport) + if (schemaSupport is not null) { for (int i = 0; i < schemaSupport.Length; ++i) { @@ -703,12 +703,12 @@ private static object CreateInstanceDataLinks() private static OleDbServicesWrapper GetObjectPool() { OleDbServicesWrapper? wrapper = OleDbConnectionInternal.idataInitialize; - if (null == wrapper) + if (wrapper is null) { lock (dataInitializeLock) { wrapper = OleDbConnectionInternal.idataInitialize; - if (null == wrapper) + if (wrapper is null) { VersionCheck(); @@ -727,7 +727,7 @@ private static OleDbServicesWrapper GetObjectPool() throw ODB.MDACNotAvailable(e); } - if (null == datalinks) + if (datalinks is null) { throw ODB.MDACNotAvailable(null); } @@ -736,7 +736,7 @@ private static OleDbServicesWrapper GetObjectPool() } } } - Debug.Assert(null != wrapper, "GetObjectPool: null dataInitialize"); + Debug.Assert(wrapper is not null, "GetObjectPool: null dataInitialize"); return wrapper; } @@ -767,21 +767,21 @@ public static void ReleaseObjectPool() internal OleDbTransaction? ValidateTransaction(OleDbTransaction? transaction, string method) { - if (null != this.weakTransaction) + if (this.weakTransaction is not null) { OleDbTransaction? head = (OleDbTransaction?)this.weakTransaction.Target; - if ((null != head) && this.weakTransaction.IsAlive) + if ((head is not null) && this.weakTransaction.IsAlive) { head = OleDbTransaction.TransactionUpdate(head); // either we are wrong or finalize was called and object still alive - Debug.Assert(null != head, "unexcpted Transaction state"); + Debug.Assert(head is not null, "unexcpted Transaction state"); } // else transaction has finalized on user - if (null != head) + if (head is not null) { - if (null == transaction) + if (transaction is null) { // valid transaction exists and cmd doesn't have it throw ADP.TransactionRequired(method); @@ -807,7 +807,7 @@ public static void ReleaseObjectPool() this.weakTransaction = null; } } - else if ((null != transaction) && (null != transaction.Connection)) + else if ((transaction is not null) && (null != transaction.Connection)) { throw ADP.TransactionConnectionMismatch(); } @@ -822,7 +822,7 @@ public static void ReleaseObjectPool() { Dictionary? properties = null; - if (null == propertySets) + if (propertySets is null) { propertySets = Array.Empty(); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs index 7f3946291684b3..cfe9b25248d3b5 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs @@ -106,7 +106,7 @@ internal OleDbConnectionString(string connectionString, bool validate) : base(co { // fail via new FileStream vs. GetFullPath udlFileName = ADP.GetFullPath(udlFileName); } - if (null != udlFileName) + if (udlFileName is not null) { udlConnectionString = LoadStringFromStorage(udlFileName); @@ -246,10 +246,10 @@ private static int UdlPoolSize string? udlConnectionString = null; Dictionary? udlcache = UDL._Pool; - if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString)) + if ((udlcache is null) || !udlcache.TryGetValue(udlfilename, out udlConnectionString)) { udlConnectionString = LoadStringFromFileStorage(udlfilename); - if (null != udlConnectionString) + if (udlConnectionString is not null) { Debug.Assert(!ADP.IsEmpty(udlfilename), "empty filename didn't fail"); @@ -257,14 +257,14 @@ private static int UdlPoolSize { Debug.Assert(udlfilename == ADP.GetFullPath(udlfilename), "only cache full path filenames"); - if (null == udlcache) + if (udlcache is null) { udlcache = new Dictionary(); udlcache[udlfilename] = udlConnectionString; lock (UDL._PoolLock) { - if (null != UDL._Pool) + if (UDL._Pool is not null) { udlcache = UDL._Pool; } @@ -275,7 +275,7 @@ private static int UdlPoolSize } } } - if (null != udlcache) + if (udlcache is not null) { lock (udlcache) { @@ -338,7 +338,7 @@ private static string LoadStringFromFileStorage(string udlfilename) throw ADP.UdlFileError(e); } - if (null != failure) + if (failure is not null) { throw failure; } @@ -359,7 +359,7 @@ private string ValidateConnectionString(string connectionString) } string? progid = ConvertValueToString(KEY.Data_Provider, null); - if (null != progid) + if (progid is not null) { progid = progid.Trim(); if (0 < progid.Length) @@ -368,7 +368,7 @@ private string ValidateConnectionString(string connectionString) } } progid = ConvertValueToString(KEY.RemoteProvider, null); - if (null != progid) + if (progid is not null) { progid = progid.Trim(); if (0 < progid.Length) @@ -389,7 +389,7 @@ private string ValidateConnectionString(string connectionString) if (!hasOleDBServices) { // don't touch registry if they have OLE DB Services string? classid = (string?)ADP.ClassesRootRegistryValue(progid + "\\CLSID", string.Empty); - if ((null != classid) && (0 < classid.Length)) + if ((classid is not null) && (0 < classid.Length)) { // CLSID detection of 'Microsoft OLE DB Provider for ODBC Drivers' Guid classidProvider = new Guid(classid); @@ -398,7 +398,7 @@ private string ValidateConnectionString(string connectionString) throw ODB.MSDASQLNotSupported(); } object? tmp = ADP.ClassesRootRegistryValue("CLSID\\{" + classidProvider.ToString("D", CultureInfo.InvariantCulture) + "}", ODB.OLEDB_SERVICES); - if (null != tmp) + if (tmp is not null) { // @devnote: some providers like MSDataShape don't have the OLEDB_SERVICES value // the MSDataShape provider doesn't support the 'Ole Db Services' keyword diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs index 67737585e1ea27..d90263c2ff85d2 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs @@ -89,7 +89,7 @@ public override object this[string keyword] } set { - if (null != value) + if (value is not null) { ADP.CheckArgumentNull(keyword, "keyword"); Keywords index; @@ -204,7 +204,7 @@ public override ICollection Keys get { string[]? knownKeywords = _knownKeywords; - if (null == knownKeywords) + if (knownKeywords is null) { Dictionary dynamic = GetProviderInfo(Provider); if (0 < dynamic.Count) @@ -411,7 +411,7 @@ public override bool TryGetValue(string keyword, [NotNullWhen(true)] out object? private Dictionary GetProviderInfo(string provider) { Dictionary? providerInfo = _propertyInfo; - if (null == providerInfo) + if (providerInfo is null) { providerInfo = new Dictionary(StringComparer.OrdinalIgnoreCase); if (!ADP.IsEmpty(provider)) @@ -485,7 +485,7 @@ private Dictionary GetProviderInfo(string provider) { info._defaultValue = prop.vValue; - if (null == info._defaultValue) + if (info._defaultValue is null) { if (typeof(string) == info._type) { @@ -617,7 +617,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string? svalue = (value as string); - if (null != svalue) + if (svalue is not null) { int services; if (int.TryParse(svalue, out services)) @@ -653,7 +653,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { - if ((typeof(string) == destinationType) && (null != value) && (typeof(int) == value.GetType())) + if ((typeof(string) == destinationType) && (value is not null) && (typeof(int) == value.GetType())) { return Enum.Format(typeof(OleDbServiceValues), ((OleDbServiceValues)(int)value), "G"); } @@ -673,7 +673,7 @@ public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { StandardValuesCollection? standardValues = _standardValues; - if (null == standardValues) + if (standardValues is null) { Array objValues = Enum.GetValues(typeof(OleDbServiceValues)); Array.Sort(objValues, 0, objValues.Length); @@ -708,14 +708,14 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw ADP.ArgumentNull("destinationType"); } if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) { OleDbConnectionStringBuilder? obj = (value as OleDbConnectionStringBuilder); - if (null != obj) + if (obj is not null) { return ConvertToInstanceDescriptor(obj); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs index a9aa7d1d56b334..bdbca3ecfc63cd 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs @@ -117,10 +117,10 @@ public event OleDbRowUpdatingEventHandler? RowUpdating // prevent someone from registering two different command builders on the adapter by // silently removing the old one - if ((null != handler) && (value.Target is DbCommandBuilder)) + if ((handler is not null) && (value.Target is DbCommandBuilder)) { OleDbRowUpdatingEventHandler? d = (OleDbRowUpdatingEventHandler?)ADP.FindBuilder(handler); - if (null != d) + if (d is not null) { Events.RemoveHandler(EventRowUpdating, d); } @@ -153,11 +153,11 @@ internal static void FillDataTable(OleDbDataReader dataReader, params DataTable[ public int Fill(DataTable dataTable, object ADODBRecordSet) { - if (null == dataTable) + if (dataTable is null) { throw ADP.ArgumentNull("dataTable"); } - if (null == ADODBRecordSet) + if (ADODBRecordSet is null) { throw ADP.ArgumentNull("adodb"); } @@ -166,11 +166,11 @@ public int Fill(DataTable dataTable, object ADODBRecordSet) public int Fill(DataSet dataSet, object ADODBRecordSet, string srcTable) { - if (null == dataSet) + if (dataSet is null) { throw ADP.ArgumentNull("dataSet"); } - if (null == ADODBRecordSet) + if (ADODBRecordSet is null) { throw ADP.ArgumentNull("adodb"); } @@ -183,8 +183,8 @@ public int Fill(DataSet dataSet, object ADODBRecordSet, string srcTable) private int FillFromADODB(object data, object adodb, string? srcTable, bool multipleResults) { - Debug.Assert(null != data, "FillFromADODB: null data object"); - Debug.Assert(null != adodb, "FillFromADODB: null ADODB"); + Debug.Assert(data is not null, "FillFromADODB: null data object"); + Debug.Assert(adodb is not null, "FillFromADODB: null ADODB"); Debug.Assert(!(adodb is DataTable), "call Fill( (DataTable) value)"); Debug.Assert(!(adodb is DataSet), "call Fill( (DataSet) value)"); @@ -205,7 +205,7 @@ private int FillFromADODB(object data, object adodb, string? srcTable, bool mult UnsafeNativeMethods.ADORecordsetConstruction? recordset = (adodb as UnsafeNativeMethods.ADORecordsetConstruction); UnsafeNativeMethods.ADORecordConstruction? record = null; - if (null != recordset) + if (recordset is not null) { if (multipleResults) { @@ -213,7 +213,7 @@ private int FillFromADODB(object data, object adodb, string? srcTable, bool mult object activeConnection; activeConnection = ((UnsafeNativeMethods.Recordset15)adodb).get_ActiveConnection(); - if (null == activeConnection) + if (activeConnection is null) { multipleResults = false; } @@ -223,7 +223,7 @@ private int FillFromADODB(object data, object adodb, string? srcTable, bool mult { record = (adodb as UnsafeNativeMethods.ADORecordConstruction); - if (null != record) + if (record is not null) { multipleResults = false; // IRow implies CommandBehavior.SingleRow which implies CommandBehavior.SingleResult } @@ -231,7 +231,7 @@ record = (adodb as UnsafeNativeMethods.ADORecordConstruction); // else throw ODB.Fill_NotADODB("adodb"); /* throw later, less code here*/ int results = 0; - if (null != recordset) + if (recordset is not null) { int resultCount = 0; bool incrementResultCount; @@ -268,7 +268,7 @@ record = (adodb as UnsafeNativeMethods.ADORecordConstruction); break; } adodb = nextresult; - if (null != adodb) + if (adodb is not null) { recordset = (UnsafeNativeMethods.ADORecordsetConstruction)adodb; @@ -280,14 +280,14 @@ record = (adodb as UnsafeNativeMethods.ADORecordConstruction); } } break; - } while (null != recordset); + } while (recordset is not null); - if ((null != recordset) && (closeRecordset || (null == adodb))) + if ((recordset is not null) && (closeRecordset || (adodb is null))) { FillClose(true, recordset); } } - else if (null != record) + else if (record is not null) { results = FillFromRecord(data, record, srcTable!); if (closeRecordset) @@ -328,7 +328,7 @@ private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConst throw ODB.Fill_EmptyRecordSet("ADODBRecordSet", e); } - if (null != result) + if (result is not null) { CommandBehavior behavior = (MissingSchemaAction.AddWithKey != MissingSchemaAction) ? 0 : CommandBehavior.KeyInfo; behavior |= CommandBehavior.SequentialAccess; @@ -358,7 +358,7 @@ private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConst } finally { - if (null != dataReader) + if (dataReader is not null) { dataReader.Close(); } @@ -385,7 +385,7 @@ private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstructio throw ODB.Fill_EmptyRecord("adodb", e); } - if (null != result) + if (result is not null) { CommandBehavior behavior = (MissingSchemaAction.AddWithKey != MissingSchemaAction) ? 0 : CommandBehavior.KeyInfo; behavior |= CommandBehavior.SequentialAccess | CommandBehavior.SingleRow; @@ -408,7 +408,7 @@ private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstructio } finally { - if (null != dataReader) + if (dataReader is not null) { dataReader.Close(); } @@ -440,7 +440,7 @@ private void FillClose(bool isrecordset, object value) protected override void OnRowUpdated(RowUpdatedEventArgs value) { OleDbRowUpdatedEventHandler? handler = (OleDbRowUpdatedEventHandler?)Events[EventRowUpdated]; - if ((null != handler) && (value is OleDbRowUpdatedEventArgs)) + if ((handler is not null) && (value is OleDbRowUpdatedEventArgs)) { handler(this, (OleDbRowUpdatedEventArgs)value); } @@ -450,7 +450,7 @@ protected override void OnRowUpdated(RowUpdatedEventArgs value) protected override void OnRowUpdating(RowUpdatingEventArgs value) { OleDbRowUpdatingEventHandler? handler = (OleDbRowUpdatingEventHandler?)Events[EventRowUpdating]; - if ((null != handler) && (value is OleDbRowUpdatingEventArgs)) + if ((handler is not null) && (value is OleDbRowUpdatingEventArgs)) { handler(this, (OleDbRowUpdatingEventArgs)value); } @@ -459,7 +459,7 @@ protected override void OnRowUpdating(RowUpdatingEventArgs value) private static string GetSourceTableName(string srcTable, int index) { - //if ((null != srcTable) && (0 <= index) && (index < srcTable.Length)) { + //if ((srcTable is not null) && (0 <= index) && (index < srcTable.Length)) { if (0 == index) { return srcTable; //[index]; diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 98846eab53ae15..cb10a896e0beca 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -74,7 +74,7 @@ internal OleDbDataReader(OleDbConnection? connection, OleDbCommand? command, int _command = command; _commandBehavior = commandBehavior; - if ((null != command) && (0 == _depth)) + if ((command is not null) && (0 == _depth)) { _parameterBindings = command.TakeBindingOwnerShip(); } @@ -150,7 +150,7 @@ public override int FieldCount throw ADP.DataReaderClosed("FieldCount"); } MetaData[]? metadata = MetaData; - return ((null != metadata) ? metadata.Length : 0); + return ((metadata is not null) ? metadata.Length : 0); } } @@ -233,7 +233,7 @@ private UnsafeNativeMethods.IRowsetInfo IRowsetInfo() private UnsafeNativeMethods.IRowset IRowset() { UnsafeNativeMethods.IRowset? irowset = _irowset; - if (null == irowset) + if (irowset is null) { Debug.Assert(false, "object is disposed"); throw new ObjectDisposedException(GetType().Name); @@ -244,7 +244,7 @@ private UnsafeNativeMethods.IRowset IRowset() private UnsafeNativeMethods.IRow IRow() { UnsafeNativeMethods.IRow? irow = _irow; - if (null == irow) + if (irow is null) { Debug.Assert(false, "object is disposed"); throw new ObjectDisposedException(GetType().Name); @@ -255,10 +255,10 @@ private UnsafeNativeMethods.IRow IRow() public override DataTable? GetSchemaTable() { DataTable? schemaTable = _dbSchemaTable; - if (null == schemaTable) + if (schemaTable is null) { MetaData[]? metadata = MetaData; - if ((null != metadata) && (0 < metadata.Length)) + if ((metadata is not null) && (0 < metadata.Length)) { if ((0 < metadata.Length) && _useIColumnsRowset && (null != _connection)) { @@ -317,7 +317,7 @@ internal void BuildMetaInfo() private DataTable BuildSchemaTable(MetaData[] metadata) { Debug.Assert(null == _dbSchemaTable, "BuildSchemaTable: schema table already exists"); - Debug.Assert(null != metadata, "BuildSchemaTable: no _metadata"); + Debug.Assert(metadata is not null, "BuildSchemaTable: no _metadata"); DataTable schemaTable = new DataTable("SchemaTable"); schemaTable.Locale = CultureInfo.InvariantCulture; @@ -414,19 +414,19 @@ private DataTable BuildSchemaTable(MetaData[] metadata) newRow[isHidden] = info.isHidden; } - if (null != info.baseSchemaName) + if (info.baseSchemaName is not null) { newRow[baseSchemaName] = info.baseSchemaName; } - if (null != info.baseCatalogName) + if (info.baseCatalogName is not null) { newRow[baseCatalogName] = info.baseCatalogName; } - if (null != info.baseTableName) + if (info.baseTableName is not null) { newRow[baseTableName] = info.baseTableName; } - if (null != info.baseColumnName) + if (info.baseColumnName is not null) { newRow[baseColumnName] = info.baseColumnName; } @@ -450,9 +450,9 @@ private void BuildSchemaTableInfo(object handle, bool filterITypeInfo, bool filt { Debug.Assert(null == _dbSchemaTable, "non-null SchemaTable"); Debug.Assert(null == _metadata, "non-null metadata"); - Debug.Assert(null != handle, "unexpected null rowset"); + Debug.Assert(handle is not null, "unexpected null rowset"); UnsafeNativeMethods.IColumnsInfo? icolumnsInfo = (handle as UnsafeNativeMethods.IColumnsInfo); - if (null == icolumnsInfo) + if (icolumnsInfo is null) { _dbSchemaTable = null; #if DEBUG @@ -510,7 +510,7 @@ private void BuildSchemaTableInfoTable(int columnCount, IntPtr columnInfos, bool continue; } - if (null == dbColumnInfo.pwszName) + if (dbColumnInfo.pwszName is null) { dbColumnInfo.pwszName = ""; } @@ -605,10 +605,10 @@ private void BuildSchemaTableInfoTable(int columnCount, IntPtr columnInfos, bool private void BuildSchemaTableRowset(object handle) { Debug.Assert(null == _dbSchemaTable, "BuildSchemaTableRowset - non-null SchemaTable"); - Debug.Assert(null != handle, "BuildSchemaTableRowset(object) - unexpected null handle"); + Debug.Assert(handle is not null, "BuildSchemaTableRowset(object) - unexpected null handle"); UnsafeNativeMethods.IColumnsRowset? icolumnsRowset = (handle as UnsafeNativeMethods.IColumnsRowset); - if (null != icolumnsRowset) + if (icolumnsRowset is not null) { UnsafeNativeMethods.IRowset? rowset = null; IntPtr cOptColumns; @@ -620,7 +620,7 @@ private void BuildSchemaTableRowset(object handle) hr = icolumnsRowset.GetColumnsRowset(ADP.PtrZero, cOptColumns, prgOptColumns, ref ODB.IID_IRowset, 0, ADP.PtrZero, out rowset); } - Debug.Assert((0 <= hr) || (null == rowset), "if GetColumnsRowset failed, rowset should be null"); + Debug.Assert((0 <= hr) || (rowset is null), "if GetColumnsRowset failed, rowset should be null"); if (hr < 0) { ProcessResults(hr); @@ -629,7 +629,7 @@ private void BuildSchemaTableRowset(object handle) // release the rowset to avoid race condition between the GC and the user code causing // "Connection is busy with results for another command" exception - if (null != rowset) + if (rowset is not null) { Marshal.ReleaseComObject(rowset); } @@ -655,11 +655,11 @@ public override void Close() DisposeOpenResults(); _hasRows = false; - if ((null != cmd) && cmd.canceling) + if ((cmd is not null) && cmd.canceling) { DisposeNativeMultipleResults(); - if (null != bindings) + if (bindings is not null) { bindings.CloseFromConnection(); bindings = null; @@ -670,7 +670,7 @@ public override void Close() UnsafeNativeMethods.IMultipleResults? multipleResults = _imultipleResults; _imultipleResults = null; - if (null != multipleResults) + if (multipleResults is not null) { // if we don't have a cmd, same as a cancel (don't call NextResults) which is ADODB behavior @@ -679,12 +679,12 @@ public override void Close() // tricky code path is an exception is thrown // causing connection to do a ResetState and connection.Close // resulting in OleDbCommand.CloseFromConnection - if ((null != cmd) && !cmd.canceling) + if ((cmd is not null) && !cmd.canceling) { IntPtr affected = IntPtr.Zero; OleDbException? nextResultsFailure = NextResults(multipleResults, null, cmd, out affected); _recordsAffected = AddRecordsAffected(_recordsAffected, affected); - if (null != nextResultsFailure) + if (nextResultsFailure is not null) { throw nextResultsFailure; } @@ -692,7 +692,7 @@ public override void Close() } finally { - if (null != multipleResults) + if (multipleResults is not null) { Marshal.ReleaseComObject(multipleResults); } @@ -700,13 +700,13 @@ public override void Close() } } - if ((null != cmd) && (0 == _depth)) + if ((cmd is not null) && (0 == _depth)) { // return bindings back to the cmd after closure of root DataReader cmd.CloseFromDataReader(bindings); } - if (null != con) + if (con is not null) { con.RemoveWeakReference(this); @@ -720,7 +720,7 @@ public override void Close() // release unmanaged objects RowHandleBuffer? rowHandleNativeBuffer = _rowHandleNativeBuffer; _rowHandleNativeBuffer = null; - if (null != rowHandleNativeBuffer) + if (rowHandleNativeBuffer is not null) { rowHandleNativeBuffer.Dispose(); } @@ -757,7 +757,7 @@ private void DisposeManagedRowset() Bindings?[]? bindings = _bindings; _bindings = null; - if (null != bindings) + if (bindings is not null) { for (int i = 0; i < bindings.Length; ++i) { @@ -782,7 +782,7 @@ private void DisposeNativeMultipleResults() UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults; _imultipleResults = null; - if (null != imultipleResults) + if (imultipleResults is not null) { Marshal.ReleaseComObject(imultipleResults); } @@ -801,7 +801,7 @@ private void DisposeNativeRowset() chapter.Dispose(); } - if (null != irowset) + if (irowset is not null) { Marshal.ReleaseComObject(irowset); } @@ -812,7 +812,7 @@ private void DisposeNativeRow() UnsafeNativeMethods.IRow? irow = _irow; _irow = null; - if (null != irow) + if (irow is not null) { Marshal.ReleaseComObject(irow); } @@ -865,7 +865,7 @@ public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int b ColumnBinding binding = DoSequentialCheck(ordinal, dataIndex, ADP.GetBytes); byte[] value = binding.ValueByteArray(); - if (null == buffer) + if (buffer is null) { return value.Length; } @@ -901,7 +901,7 @@ public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int b ColumnBinding binding = DoSequentialCheck(ordinal, dataIndex, ADP.GetChars); string value = binding.ValueString(); - if (null == buffer) + if (buffer is null) { return value.Length; } @@ -967,7 +967,7 @@ protected override DbDataReader GetDbDataReader(int ordinal) OleDbDataReader? reader = null; // TODO: Not sure if GetReferenceRowset above actually returns null, calling code seems to assume it doesn't - if (null != result) + if (result is not null) { // only when the first datareader is closed will the connection close ChapterHandle chapterHandle = ChapterHandle.CreateChapterHandle(result, rowbinding, valueOffset); @@ -1117,7 +1117,7 @@ private ColumnBinding GetColumnBinding(int ordinal) private ColumnBinding GetValueBinding(MetaData info) { ColumnBinding binding = info.columnBinding; - Debug.Assert(null != binding, "null binding"); + Debug.Assert(binding is not null, "null binding"); // do we need to jump to the next accessor for (int i = _nextAccessorForRetrieval; i <= binding.IndexForAccessor; ++i) @@ -1162,7 +1162,7 @@ public override object GetValue(int ordinal) public override int GetValues(object[] values) { - if (null == values) + if (values is null) { throw ADP.ArgumentNull("values"); } @@ -1198,7 +1198,7 @@ private void ProcessResults(OleDbHResult hr) { e = OleDbConnection.ProcessResults(hr, _connection, _connection); } - if (null != e) + if (e is not null) { throw e; } } @@ -1255,7 +1255,7 @@ internal void HasRowsRead() { recordsAffected = ADP.RecordsUnaffected; List? exceptions = null; - if (null != imultipleResults) + if (imultipleResults is not null) { object result; IntPtr affected; @@ -1265,7 +1265,7 @@ internal void HasRowsRead() // we want to break out of that infinite loop for ExecuteNonQuery and the multiple result Close scenarios for (int loop = 0; ; ++loop) { - if ((null != command) && command.canceling) + if ((command is not null) && command.canceling) { break; } @@ -1278,15 +1278,15 @@ internal void HasRowsRead() { break; } - if (null != connection) + if (connection is not null) { Exception? e = OleDbConnection.ProcessResults(hr, connection, command); - if (null != e) + if (e is not null) { OleDbException? excep = (e as OleDbException); - if (null != excep) + if (excep is not null) { - if (null == exceptions) + if (exceptions is null) { exceptions = new List(); } @@ -1317,7 +1317,7 @@ internal void HasRowsRead() } } } - if (null != exceptions) + if (exceptions is not null) { return OleDbException.CombineExceptions(exceptions); } @@ -1341,7 +1341,7 @@ public override bool NextResult() OleDbCommand? command = _command; UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults; - if (null != imultipleResults) + if (imultipleResults is not null) { DisposeOpenResults(); _hasRows = false; @@ -1355,14 +1355,14 @@ public override bool NextResult() OleDbHResult hr; IntPtr affected; - if ((null != command) && command.canceling) + if ((command is not null) && command.canceling) { Close(); break; } hr = imultipleResults.GetResult(ADP.PtrZero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_IRowset, out affected, out result); - if ((0 <= hr) && (null != result)) + if ((0 <= hr) && (result is not null)) { _irowset = (UnsafeNativeMethods.IRowset)result; } @@ -1397,7 +1397,7 @@ public override bool Read() { bool retflag = false; OleDbCommand? command = _command; - if ((null != command) && command.canceling) + if ((command is not null) && command.canceling) { DisposeOpenResults(); } @@ -1457,7 +1457,7 @@ private bool ReadRowset() _sequentialOrdinal = -1; // sequentialBytesRead will reset when used - // making the check if (null != irowset) unnecessary + // making the check if (irowset is not null) unnecessary // if necessary, get next group of row handles if (IntPtr.Zero == _rowFetchedCount) { // starts at (-1 <= 0) @@ -1480,7 +1480,7 @@ private void ReleaseCurrentRow() { // release the data in the current row Bindings?[]? bindings = _bindings; - Debug.Assert(null != bindings, "ReleaseCurrentRow: null dbBindings"); + Debug.Assert(bindings is not null, "ReleaseCurrentRow: null dbBindings"); for (int i = 0; (i < bindings.Length) && (i < _nextAccessorForRetrieval); ++i) { bindings[i]!.CleanupBindings(); @@ -1613,7 +1613,7 @@ private Bindings[] CreateBindingsFromMetaData(bool allowMultipleAccessor) { Debug.Assert(indexToBinding[index] < dbbindings.Length, "bad indexToAccessor"); bindings = dbbindings[indexToBinding[index]]; - if (null == bindings) + if (bindings is null) { bindingCount = 0; for (int i = index; (i < metadata.Length) && (bindingCount == indexWithinBinding[i]); ++i) @@ -1643,8 +1643,8 @@ private Bindings[] CreateBindingsFromMetaData(bool allowMultipleAccessor) else if (-1 == maxLen) { // @devnote: not using provider owned memory for PDC, no one really supports it anyway. - /*if (((null != connection) && connection.PropertyGetProviderOwnedMemory()) - || ((null != command) && command.Connection.PropertyGetProviderOwnedMemory())) { + /*if (((connection is not null) && connection.PropertyGetProviderOwnedMemory()) + || ((command is not null) && command.Connection.PropertyGetProviderOwnedMemory())) { bindings.MemOwner = DBMemOwner.ProviderOwned; bindings.MaxLen = ADP.PtrSize; @@ -1670,8 +1670,8 @@ private Bindings[] CreateBindingsFromMetaData(bool allowMultipleAccessor) else if (maxLen < 0) { // if variable length and no defined size we require this to be byref at this time - /*if (((null != connection) && connection.PropertyGetProviderOwnedMemory()) - || ((null != command) && command.Connection.PropertyGetProviderOwnedMemory())) { + /*if (((connection is not null) && connection.PropertyGetProviderOwnedMemory()) + || ((command is not null) && command.Connection.PropertyGetProviderOwnedMemory())) { bindings.MemOwner = DBMemOwner.ProviderOwned; }*/ maxLen = ADP.PtrSize; @@ -1896,7 +1896,7 @@ private void GetRowValue() sptr[i]!.DangerousAddRef(ref mustRelease[i]); - IntPtr ulPropid = ((null != sptr[i]) ? sptr[i]!.DangerousGetHandle() : info.propid); + IntPtr ulPropid = ((sptr[i] is not null) ? sptr[i]!.DangerousGetHandle() : info.propid); bindings.GuidKindName(info.guid, info.kind, ulPropid); } @@ -1930,7 +1930,7 @@ private int IndexOf(Hashtable hash, string name) { // via case sensitive search, first match with lowest ordinal matches object? index = hash[name]; - if (null != index) + if (index is not null) { return (int)index; // match via case-insensitive or by chance lowercase } @@ -1938,7 +1938,7 @@ private int IndexOf(Hashtable hash, string name) // via case insensitive search, first match with lowest ordinal matches string tmp = name.ToLowerInvariant(); index = hash[tmp]; // match via lowercase - return ((null != index) ? (int)index : -1); + return ((index is not null) ? (int)index : -1); } private void AppendSchemaInfo() @@ -1969,11 +1969,11 @@ private void AppendSchemaInfo() for (int i = 0; i < _metadata.Length; ++i) { MetaData info = _metadata[i]; - if ((null != info.baseTableName) && (0 < info.baseTableName.Length)) + if ((info.baseTableName is not null) && (0 < info.baseTableName.Length)) { - catalogName = ((null != info.baseCatalogName) ? info.baseCatalogName : ""); - schemaName = ((null != info.baseSchemaName) ? info.baseSchemaName : ""); - if (null == baseTableName) + catalogName = ((info.baseCatalogName is not null) ? info.baseCatalogName : ""); + schemaName = ((info.baseSchemaName is not null) ? info.baseSchemaName : ""); + if (baseTableName is null) { baseSchemaName = schemaName; baseCatalogName = catalogName; @@ -1996,7 +1996,7 @@ private void AppendSchemaInfo() } } } - if (null == baseTableName) + if (baseTableName is null) { return; } @@ -2009,11 +2009,11 @@ private void AppendSchemaInfo() { string? p = null, s = null; _connection.GetLiteralQuotes(ADP.GetSchemaTable, out s, out p); - if (null == s) + if (s is null) { s = ""; } - if (null == p) + if (p is null) { p = ""; } @@ -2082,7 +2082,7 @@ private int AppendSchemaPrimaryKey(Hashtable baseColumnNames, object?[] restrict ADP.TraceExceptionWithoutRethrow(e); } - if (null != table) + if (table is not null) { DataColumnCollection dataColumns = table.Columns; int nameColumnIndex = dataColumns.IndexOf(ODB.COLUMN_NAME); @@ -2145,7 +2145,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r ADP.TraceExceptionWithoutRethrow(e); } - if (null != table) + if (table is not null) { DataColumnCollection dataColumns = table.Columns; @@ -2184,12 +2184,12 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r { keys[metaindex] = true; } - if (isUniq && (null != uniq)) + if (isUniq && (uniq is not null)) { uniq[metaindex] = true; string indexname = (string)dataRow[indxColumn, DataRowVersion.Default]; - if (null == uniqueIndexName) + if (uniqueIndexName is null) { uniqueIndexName = indexname; } @@ -2216,7 +2216,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r partialPrimaryKey = true; break; } - else if (null != uniqueIndexName) + else if (uniqueIndexName is not null) { string indexname = (string)dataRow[indxColumn, DataRowVersion.Default]; @@ -2241,7 +2241,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r } return; } - else if (null != uniq) + else if (uniq is not null) { #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) @@ -2282,7 +2282,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) return; } - Debug.Assert(null == dataReader._fieldNameLookup, "lookup already exists"); + Debug.Assert(dataReader._fieldNameLookup is null, "lookup already exists"); FieldNameLookup lookup = new FieldNameLookup(dataReader, -1); dataReader._fieldNameLookup = lookup; @@ -2389,7 +2389,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.type = dbType; - if (null != isautoincrement) + if (isautoincrement is not null) { binding = isautoincrement.columnBinding; if (!binding.IsValueNull()) @@ -2397,7 +2397,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.isAutoIncrement = binding.Value_BOOL(); } } - if (null != isunique) + if (isunique is not null) { binding = isunique.columnBinding; if (!binding.IsValueNull()) @@ -2405,7 +2405,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.isUnique = binding.Value_BOOL(); } } - if (null != iskeycolumn) + if (iskeycolumn is not null) { binding = iskeycolumn.columnBinding; if (!binding.IsValueNull()) @@ -2413,7 +2413,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.isKeyColumn = binding.Value_BOOL(); } } - if (null != baseschemaname) + if (baseschemaname is not null) { binding = baseschemaname.columnBinding; if (!binding.IsValueNull()) @@ -2421,7 +2421,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.baseSchemaName = binding.ValueString(); } } - if (null != basecatalogname) + if (basecatalogname is not null) { binding = basecatalogname.columnBinding; if (!binding.IsValueNull()) @@ -2429,7 +2429,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.baseCatalogName = binding.ValueString(); } } - if (null != basetablename) + if (basetablename is not null) { binding = basetablename.columnBinding; if (!binding.IsValueNull()) @@ -2437,7 +2437,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) info.baseTableName = binding.ValueString(); } } - if (null != basecolumnname) + if (basecolumnname is not null) { binding = basecolumnname.columnBinding; if (!binding.IsValueNull()) @@ -2546,7 +2546,7 @@ internal static void GenerateSchemaTable(OleDbDataReader dataReader, object hand dataReader.BuildSchemaTableInfo(handle, false, false); // only tries IColumnsInfo } MetaData[]? metadata = dataReader.MetaData; - if ((null != metadata) && (0 < metadata.Length)) + if ((metadata is not null) && (0 < metadata.Length)) { dataReader.BuildSchemaTable(metadata); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs b/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs index 03ddf25741551c..403c77d7cede26 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs @@ -44,7 +44,7 @@ private static OleDbDataReader GetEnumeratorReader(object? value) { throw ODB.ISourcesRowsetNotSupported(); } - if (null == srcrowset) + if (srcrowset is null) { throw ODB.ISourcesRowsetNotSupported(); } @@ -55,7 +55,7 @@ private static OleDbDataReader GetEnumeratorReader(object? value) OleDbHResult hr = srcrowset.GetSourcesRowset(ADP.PtrZero, ODB.IID_IRowset, propCount, propSets, out value); Exception? f = OleDbConnection.ProcessResults(hr, null, null); - if (null != f) + if (f is not null) { throw f; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbError.cs b/src/libraries/System.Data.OleDb/src/OleDbError.cs index 333cdb3128a795..dac18ab27c7782 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbError.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbError.cs @@ -18,7 +18,7 @@ internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) OleDbHResult hr; int lcid = System.Globalization.CultureInfo.CurrentCulture.LCID; UnsafeNativeMethods.IErrorInfo errorInfo = errorRecords.GetErrorInfo(index, lcid); - if (null != errorInfo) + if (errorInfo is not null) { hr = errorInfo.GetDescription(out this.message); @@ -28,7 +28,7 @@ internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) lcid = SafeNativeMethods.GetUserDefaultLCID(); errorInfo = errorRecords.GetErrorInfo(index, lcid); - if (null != errorInfo) + if (errorInfo is not null) { hr = errorInfo.GetDescription(out this.message); } @@ -37,7 +37,7 @@ internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) { this.message = ODB.FailedGetDescription(hr); } - if (null != errorInfo) + if (errorInfo is not null) { hr = errorInfo.GetSource(out this.source); @@ -47,7 +47,7 @@ internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) lcid = SafeNativeMethods.GetUserDefaultLCID(); errorInfo = errorRecords.GetErrorInfo(index, lcid); - if (null != errorInfo) + if (errorInfo is not null) { hr = errorInfo.GetSource(out this.source); } @@ -63,7 +63,7 @@ internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) UnsafeNativeMethods.ISQLErrorInfo sqlErrorInfo; hr = errorRecords.GetCustomErrorObject(index, ref ODB.IID_ISQLErrorInfo, out sqlErrorInfo); - if (null != sqlErrorInfo) + if (sqlErrorInfo is not null) { this.nativeError = sqlErrorInfo.GetSQLInfo(out this.sqlState); Marshal.ReleaseComObject(sqlErrorInfo); @@ -75,7 +75,7 @@ public string Message get { string? message = this.message; - return ((null != message) ? message : string.Empty); + return ((message is not null) ? message : string.Empty); } } @@ -92,7 +92,7 @@ public string Source get { string? source = this.source; - return ((null != source) ? source : string.Empty); + return ((source is not null) ? source : string.Empty); } } @@ -101,7 +101,7 @@ public string SQLState get { string? sqlState = this.sqlState; - return ((null != sqlState) ? sqlState : string.Empty); + return ((sqlState is not null) ? sqlState : string.Empty); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs b/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs index d6a16448755966..86ad4f2199904f 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs @@ -16,7 +16,7 @@ internal OleDbErrorCollection(UnsafeNativeMethods.IErrorInfo? errorInfo) { ArrayList items = new ArrayList(); UnsafeNativeMethods.IErrorRecords? errorRecords = (errorInfo as UnsafeNativeMethods.IErrorRecords); - if (null != errorRecords) + if (errorRecords is not null) { int recordCount = errorRecords.GetRecordCount(); @@ -44,7 +44,7 @@ public int Count get { ArrayList items = this.items; - return ((null != items) ? items.Count : 0); + return ((items is not null) ? items.Count : 0); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbException.cs b/src/libraries/System.Data.OleDb/src/OleDbException.cs index 410e9cb33da820..22c1de6c422a4e 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbException.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbException.cs @@ -29,7 +29,7 @@ internal OleDbException(OleDbException previous, Exception? inner) : base(previo private OleDbException(string? message, Exception? inner, string? source, OleDbHResult errorCode, OleDbErrorCollection errors) : base(message, inner) { - Debug.Assert(null != errors, "OleDbException without OleDbErrorCollection"); + Debug.Assert(errors is not null, "OleDbException without OleDbErrorCollection"); Source = source; HResult = (int)errorCode; this.oledbErrors = errors; @@ -37,7 +37,7 @@ private OleDbException(string? message, Exception? inner, string? source, OleDbH public override void GetObjectData(SerializationInfo si, StreamingContext context) { - if (null == si) + if (si is null) { throw new ArgumentNullException(nameof(si)); } @@ -60,7 +60,7 @@ public OleDbErrorCollection Errors get { OleDbErrorCollection errors = this.oledbErrors; - return ((null != errors) ? errors : new OleDbErrorCollection(null)); + return ((errors is not null) ? errors : new OleDbErrorCollection(null)); } } @@ -71,7 +71,7 @@ internal static OleDbException CreateException(UnsafeNativeMethods.IErrorInfo er string? source = null; OleDbHResult hr = 0; - if (null != errorInfo) + if (errorInfo is not null) { hr = errorInfo.GetDescription(out message); @@ -83,7 +83,7 @@ internal static OleDbException CreateException(UnsafeNativeMethods.IErrorInfo er { StringBuilder builder = new StringBuilder(); - if ((null != message) && (message != errors[0].Message)) + if ((message is not null) && (message != errors[0].Message)) { builder.Append(message.TrimEnd(ODB.ErrorTrimCharacters)); if (1 < count) @@ -139,11 +139,11 @@ public ErrorCodeConverter() public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw ADP.ArgumentNull("destinationType"); } - if ((destinationType == typeof(string)) && (value != null) && (value is int)) + if ((destinationType == typeof(string)) && (value is not null) && (value is int)) { return ODB.ELookup((OleDbHResult)value); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs b/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs index e082c8f5c53c1c..970f686ec342d5 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs @@ -11,7 +11,7 @@ public sealed class OleDbInfoMessageEventArgs : System.EventArgs internal OleDbInfoMessageEventArgs(OleDbException exception) { - Debug.Assert(null != exception, "OleDbInfoMessageEventArgs without OleDbException"); + Debug.Assert(exception is not null, "OleDbInfoMessageEventArgs without OleDbException"); this.exception = exception; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs index e978419c2f8369..eb7033d4d5bf83 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs @@ -51,7 +51,7 @@ internal OleDbMetaDataFactory(Stream XMLStream, // verify the existance of the table in the data set DataTable? metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - if (metaDataCollectionsTable == null) + if (metaDataCollectionsTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.MetaDataCollections); } @@ -61,7 +61,7 @@ internal OleDbMetaDataFactory(Stream XMLStream, // verify the existance of the table in the data set DataTable? restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; - if (restrictionsTable != null) + if (restrictionsTable is not null) { // copy the table filtering out any rows that don't apply to the current version of the provider restrictionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.Restrictions, null); @@ -73,20 +73,20 @@ internal OleDbMetaDataFactory(Stream XMLStream, // 3) the provider does not support the necessary schema rowset DataColumn? populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]; - if ((null == populationMechanism) || (typeof(string) != populationMechanism.DataType)) + if ((populationMechanism is null) || (typeof(string) != populationMechanism.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, _populationMechanism); } DataColumn? collectionName = metaDataCollectionsTable.Columns[_collectionName]; - if ((null == collectionName) || (typeof(string) != collectionName.DataType)) + if ((collectionName is null) || (typeof(string) != collectionName.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, _collectionName); } DataColumn? restrictionCollectionName = null; - if (restrictionsTable != null) + if (restrictionsTable is not null) { restrictionCollectionName = restrictionsTable.Columns[_collectionName]; - if ((null == restrictionCollectionName) || (typeof(string) != restrictionCollectionName.DataType)) + if ((restrictionCollectionName is null) || (typeof(string) != restrictionCollectionName.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.Restrictions, _collectionName); } @@ -125,7 +125,7 @@ internal OleDbMetaDataFactory(Stream XMLStream, // does the provider support the necessary schema rowset bool isSchemaRowsetSupported = false; - if (schemaSupport != null) + if (schemaSupport is not null) { for (int i = 0; i < schemaSupport.Length; i++) { @@ -140,7 +140,7 @@ internal OleDbMetaDataFactory(Stream XMLStream, if (isSchemaRowsetSupported == false) { // but first delete any related restrictions - if (restrictionsTable != null) + if (restrictionsTable is not null) { foreach (DataRow restriction in restrictionsTable.Rows) { @@ -167,7 +167,7 @@ internal OleDbMetaDataFactory(Stream XMLStream, CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!); CollectionDataSet.Tables.Add(metaDataCollectionsTable); - if (restrictionsTable != null) + if (restrictionsTable is not null) { CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]!); CollectionDataSet.Tables.Add(restrictionsTable); @@ -190,7 +190,7 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD { // verify that the data source information table is in the data set DataTable? dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; - if (dataSourceInformationTable == null) + if (dataSourceInformationTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataSourceInformation); } @@ -209,13 +209,13 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD string? catalogSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_CATALOG_SEPARATOR); string? schemaSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_SCHEMA_SEPARATOR); - if (catalogSeparatorPattern != null) + if (catalogSeparatorPattern is not null) { StringBuilder compositeSeparatorPattern = new StringBuilder(); StringBuilder patternEscaped = new StringBuilder(); ADP.EscapeSpecialCharacters(catalogSeparatorPattern, patternEscaped); compositeSeparatorPattern.Append(patternEscaped.ToString()); - if ((schemaSeparatorPattern != null) && (schemaSeparatorPattern != catalogSeparatorPattern)) + if ((schemaSeparatorPattern is not null) && (schemaSeparatorPattern != catalogSeparatorPattern)) { compositeSeparatorPattern.Append('|'); patternEscaped.Length = 0; @@ -224,7 +224,7 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD } dataSourceInformation[DbMetaDataColumnNames.CompositeIdentifierSeparatorPattern] = compositeSeparatorPattern.ToString(); } - else if (schemaSeparatorPattern != null) + else if (schemaSeparatorPattern is not null) { StringBuilder patternEscaped = new StringBuilder(); ADP.EscapeSpecialCharacters(schemaSeparatorPattern, patternEscaped); @@ -235,7 +235,7 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD // update the DataSourceProductName object? property; property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSNAME); - if (property != null) + if (property is not null) { dataSourceInformation[DbMetaDataColumnNames.DataSourceProductName] = (string)property; } @@ -251,7 +251,7 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_GROUPBY); GroupByBehavior groupByBehavior = GroupByBehavior.Unknown; - if (property != null) + if (property is not null) { switch ((int)property) { @@ -278,16 +278,16 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD SetIdentifierCase(DbMetaDataColumnNames.QuotedIdentifierCase, ODB.DBPROP_QUOTEDIDENTIFIERCASE, dataSourceInformation, connection); property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_ORDERBYCOLUNSINSELECT); - if (property != null) + if (property is not null) { dataSourceInformation[DbMetaDataColumnNames.OrderByColumnsInSelect] = (bool)property; } DataTable? infoLiterals = internalConnection.BuildInfoLiterals(); - if (infoLiterals != null) + if (infoLiterals is not null) { DataRow[] tableNameRow = infoLiterals.Select("Literal = " + ODB.DBLITERAL_TABLE_NAME.ToString(CultureInfo.InvariantCulture)); - if (tableNameRow != null) + if (tableNameRow is not null) { object invalidCharsObject = tableNameRow[0]["InvalidChars"]; if (invalidCharsObject.GetType() == typeof(string)) @@ -315,11 +315,11 @@ private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleD string quoteSuffix; connection.GetLiteralQuotes(ADP.GetSchema, out quotePrefix, out quoteSuffix); - if (quotePrefix != null) + if (quotePrefix is not null) { // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) - if (quoteSuffix == null) + if (quoteSuffix is null) { quoteSuffix = quotePrefix; } @@ -354,7 +354,7 @@ private DataTable GetDataTypesTable(OleDbConnection connection) { // verify the existance of the table in the data set DataTable? dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; - if (dataTypesTable == null) + if (dataTypesTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes); } @@ -428,7 +428,7 @@ private DataTable GetDataTypesTable(OleDbConnection connection) newRow[providerDbType] = nativeType.enumOleDbType; // searchable has to be special cased becasue it is not an eaxct mapping - if ((isSearchable != null) && (isSearchableWithLike != null) && (searchable != null)) + if ((isSearchable is not null) && (isSearchableWithLike is not null) && (searchable is not null)) { newRow[isSearchable] = DBNull.Value; newRow[isSearchableWithLike] = DBNull.Value; @@ -473,7 +473,7 @@ private DataTable GetReservedWordsTable(OleDbConnectionInternal internalConnecti { // verify the existance of the table in the data set DataTable? reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; - if (null == reservedWordsTable) + if (reservedWordsTable is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } @@ -482,7 +482,7 @@ private DataTable GetReservedWordsTable(OleDbConnectionInternal internalConnecti reservedWordsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.ReservedWords, null); DataColumn? reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; - if (null == reservedWordColumn) + if (reservedWordColumn is null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } @@ -534,7 +534,7 @@ protected override DataTable PrepareCollection(string collectionName, string?[]? // string tpyes object?[]? mungedRestrictions = restrictions; ; - if (restrictions != null) + if (restrictions is not null) { //verify that there are not too many restrictions DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; @@ -563,7 +563,7 @@ protected override DataTable PrepareCollection(string collectionName, string?[]? if ((collectionName == OleDbMetaDataCollectionNames.Indexes) && (restrictions.Length >= indexRestrictionTypeSlot + 1) && - (restrictions[indexRestrictionTypeSlot] != null)) + (restrictions[indexRestrictionTypeSlot] is not null)) { mungedRestrictions = new object[restrictions.Length]; for (int j = 0; j < restrictions.Length; j++) @@ -607,7 +607,7 @@ protected override DataTable PrepareCollection(string collectionName, string?[]? if ((collectionName == OleDbMetaDataCollectionNames.Procedures) && (restrictions.Length >= procedureRestrictionTypeSlot + 1) && - (restrictions[procedureRestrictionTypeSlot] != null)) + (restrictions[procedureRestrictionTypeSlot] is not null)) { mungedRestrictions = new object[restrictions.Length]; for (int j = 0; j < restrictions.Length; j++) @@ -648,7 +648,7 @@ protected override DataTable PrepareCollection(string collectionName, string?[]? } } - if (resultTable == null) + if (resultTable is null) { throw ADP.UnableToBuildCollection(collectionName); } @@ -660,7 +660,7 @@ private void SetIdentifierCase(string columnName, int propertyID, DataRow row, O { object? property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, propertyID); IdentifierCase identifierCase = IdentifierCase.Unknown; - if (property != null) + if (property is not null) { int propertyValue = (int)property; switch (propertyValue) diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs index 61053ad7c31908..de0518cc5959c6 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs @@ -113,7 +113,7 @@ public override DbType DbType set { NativeDBType? dbtype = _metaType; - if ((null == dbtype) || (dbtype.enumDbType != value)) + if ((dbtype is null) || (dbtype.enumDbType != value)) { PropertyTypeChanging(); _metaType = NativeDBType.FromDbType(value); @@ -139,7 +139,7 @@ public OleDbType OleDbType set { NativeDBType? dbtype = _metaType; - if ((null == dbtype) || (dbtype.enumOleDbType != value)) + if ((dbtype is null) || (dbtype.enumOleDbType != value)) { PropertyTypeChanging(); _metaType = NativeDBType.FromDataType(value); @@ -167,7 +167,7 @@ public override string ParameterName get { string? parameterName = _parameterName; - return ((null != parameterName) ? parameterName : string.Empty); + return ((parameterName is not null) ? parameterName : string.Empty); } set { @@ -464,8 +464,8 @@ internal bool BindParameter(int index, Bindings bindings) private static object? CoerceValue(object? value, NativeDBType destinationType) { - Debug.Assert(null != destinationType, "null destinationType"); - if ((null != value) && (DBNull.Value != value) && (typeof(object) != destinationType.dataType)) + Debug.Assert(destinationType is not null, "null destinationType"); + if ((value is not null) && (DBNull.Value != value) && (typeof(object) != destinationType.dataType)) { Type currentType = value.GetType(); if (currentType != destinationType.dataType) @@ -502,7 +502,7 @@ internal bool BindParameter(int index, Bindings bindings) private NativeDBType GetBindType(object? value) { NativeDBType? dbtype = _metaType; - if (null == dbtype) + if (dbtype is null) { if (ADP.IsNull(value)) { @@ -519,7 +519,7 @@ private NativeDBType GetBindType(object? value) internal object? GetCoercedValue() { object? value = CoercedValue; // will also be set during binding, will rebind everytime if _metaType not set - if (null == value) + if (value is null) { value = CoerceValue(Value, _coerceMetaType!); CoercedValue = value; @@ -530,7 +530,7 @@ private NativeDBType GetBindType(object? value) internal bool IsParameterComputed() { NativeDBType? metaType = _metaType; - return ((null == metaType) + return ((metaType is null) || (!ShouldSerializeSize() && metaType.IsVariableLength) || ((NativeDBType.DECIMAL == metaType.dbType) || (NativeDBType.NUMERIC == metaType.dbType) && (!ShouldSerializeScale() || !ShouldSerializePrecision()) @@ -639,7 +639,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (null == destinationType) + if (destinationType is null) { throw ADP.ArgumentNull("destinationType"); } @@ -666,7 +666,7 @@ private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToI { flags |= 4; } - if (null != p.Value) + if (p.Value is not null) { flags |= 8; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs b/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs index 9f0f898c5c300f..3e457749699050 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs @@ -27,7 +27,7 @@ private List InnerList { List? items = _items; - if (null == items) + if (items is null) { items = new List(); _items = items; @@ -80,7 +80,7 @@ public override int Add(object value) public override void AddRange(System.Array values) { OnChange(); - if (null == values) + if (values is null) { throw ADP.ArgumentNull(nameof(values)); } @@ -110,7 +110,7 @@ public override void Clear() OnChange(); List items = InnerList; - if (null != items) + if (items is not null) { foreach (OleDbParameter item in items) { @@ -153,7 +153,7 @@ protected override DbParameter GetParameter(string parameterName) private static int IndexOf(System.Collections.IEnumerable items, string parameterName) { - if (null != items) + if (items is not null) { int i = 0; @@ -186,13 +186,13 @@ public override int IndexOf(string parameterName) public override int IndexOf(object value) { - if (null != value) + if (value is not null) { ValidateType(value); List items = InnerList; - if (null != items) + if (items is not null) { int count = items.Count; @@ -256,7 +256,7 @@ public override void RemoveAt(string parameterName) private void RemoveIndex(int index) { List items = InnerList; - Debug.Assert((null != items) && (0 <= index) && (index < Count), "RemoveIndex, invalid"); + Debug.Assert((items is not null) && (0 <= index) && (index < Count), "RemoveIndex, invalid"); OleDbParameter item = items[index]; items.RemoveAt(index); item.ResetParent(); @@ -265,7 +265,7 @@ private void RemoveIndex(int index) private void Replace(int index, object newValue) { List items = InnerList; - Debug.Assert((null != items) && (0 <= index) && (index < Count), "Replace Index invalid"); + Debug.Assert((items is not null) && (0 <= index) && (index < Count), "Replace Index invalid"); ValidateType(newValue); Validate(index, newValue); OleDbParameter item = items[index]; @@ -293,13 +293,13 @@ protected override void SetParameter(string parameterName, DbParameter value) private void Validate(int index, object value) { - if (null == value) + if (value is null) { throw ADP.ParameterNull(nameof(value), this, s_itemType); } object? parent = ((OleDbParameter)value).CompareExchangeParent(this, null); - if (null != parent) + if (parent is not null) { if (this != parent) { @@ -326,7 +326,7 @@ private void Validate(int index, object value) private void ValidateType(object value) { - if (null == value) + if (value is null) { throw ADP.ParameterNull(nameof(value), this, s_itemType); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbPropertySetGuid.cs b/src/libraries/System.Data.OleDb/src/OleDbPropertySetGuid.cs index 43ba7d228f8eab..d926b1eff96756 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbPropertySetGuid.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbPropertySetGuid.cs @@ -38,7 +38,7 @@ private OleDbPropertySetGuid() /* internal static string GetTextFromValue(Guid guid) { string value = ConvertToString(guid); - if (null == value) { + if (value is null) { value = "{" + guid.ToString("D", CultureInfo.InvariantCulture) + "}"; } return value; diff --git a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs index 26a20357af16bb..a8af5c92520207 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs @@ -196,7 +196,7 @@ public OleDbTransaction Begin(IsolationLevel isolevel) } finally { - if (null != wrapper) + if (wrapper is not null) { Marshal.ReleaseComObject(wrapper); } @@ -239,7 +239,7 @@ private void CommitInternal() if (null != _nestedTransaction) { OleDbTransaction? transaction = (OleDbTransaction?)_nestedTransaction.Target; - if ((null != transaction) && _nestedTransaction.IsAlive) + if ((transaction is not null) && _nestedTransaction.IsAlive) { transaction.CommitInternal(); } @@ -297,7 +297,7 @@ private void DisposeManaged() private void ProcessResults(OleDbHResult hr) { Exception? e = OleDbConnection.ProcessResults(hr, _parentConnection, this); - if (null != e) + if (e is not null) { throw e; } } @@ -320,7 +320,7 @@ internal OleDbHResult RollbackInternal(bool exceptionHandling) if (null != _nestedTransaction) { OleDbTransaction? transaction = (OleDbTransaction?)_nestedTransaction.Target; - if ((null != transaction) && _nestedTransaction.IsAlive) + if ((transaction is not null) && _nestedTransaction.IsAlive) { hr = transaction.RollbackInternal(exceptionHandling); if (exceptionHandling && (hr < 0)) @@ -351,10 +351,10 @@ internal OleDbHResult RollbackInternal(bool exceptionHandling) internal static OleDbTransaction TransactionLast(OleDbTransaction head) { - if (null != head._nestedTransaction) + if (head._nestedTransaction is not null) { OleDbTransaction? current = (OleDbTransaction?)head._nestedTransaction.Target; - if ((null != current) && head._nestedTransaction.IsAlive) + if ((current is not null) && head._nestedTransaction.IsAlive) { return TransactionLast(current); } @@ -364,7 +364,7 @@ internal static OleDbTransaction TransactionLast(OleDbTransaction head) internal static OleDbTransaction? TransactionUpdate(OleDbTransaction? transaction) { - if ((null != transaction) && (null == transaction._transaction)) + if ((transaction is not null) && (transaction._transaction is null)) { return null; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs b/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs index 23ef6c6b0d4954..15e08aea255a40 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs @@ -22,7 +22,7 @@ internal sealed class OleDbServicesWrapper : WrappedIUnknown // DataLinks (the unknown parameter) is created via Activator.CreateInstance outside of the SafeHandle internal OleDbServicesWrapper(object? unknown) : base() { - if (null != unknown) + if (unknown is not null) { RuntimeHelpers.PrepareConstrainedRegions(); try @@ -73,7 +73,7 @@ internal void GetDataSource(OleDbConnectionString constr, ref DataSourceWrapper throw ODB.ProviderUnavailable(constr.Provider, null); } Exception? e = OleDbConnection.ProcessResults(hr, null, null); - Debug.Assert(null != e, "CreateProviderError"); + Debug.Assert(e is not null, "CreateProviderError"); throw e; } else if (datasrcWrapper.IsInvalid) @@ -117,7 +117,7 @@ internal OleDbHResult InitializeAndCreateSession(OleDbConnectionString constr, r // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer - if ((null == QueryInterface) || (method != Marshal.GetFunctionPointerForDelegate(QueryInterface))) + if ((QueryInterface is null) || (method != Marshal.GetFunctionPointerForDelegate(QueryInterface))) { QueryInterface = (UnsafeNativeMethods.IUnknownQueryInterface)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IUnknownQueryInterface)); constr.DangerousDataSourceIUnknownQueryInterface = QueryInterface; @@ -134,7 +134,7 @@ internal OleDbHResult InitializeAndCreateSession(OleDbConnectionString constr, r // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer - if ((null == Initialize) || (method != Marshal.GetFunctionPointerForDelegate(Initialize))) + if ((Initialize is null) || (method != Marshal.GetFunctionPointerForDelegate(Initialize))) { Initialize = (UnsafeNativeMethods.IDBInitializeInitialize)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IDBInitializeInitialize)); constr.DangerousIDBInitializeInitialize = Initialize; @@ -160,14 +160,14 @@ internal OleDbHResult InitializeAndCreateSession(OleDbConnectionString constr, r // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer - if ((null == CreateSession) || (method != Marshal.GetFunctionPointerForDelegate(CreateSession))) + if ((CreateSession is null) || (method != Marshal.GetFunctionPointerForDelegate(CreateSession))) { CreateSession = (UnsafeNativeMethods.IDBCreateSessionCreateSession)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IDBCreateSessionCreateSession)); constr.DangerousIDBCreateSessionCreateSession = CreateSession; } // if I have a delegate for CreateCommand directly ask for IDBCreateCommand - if (null != constr.DangerousIDBCreateCommandCreateCommand) + if (constr.DangerousIDBCreateCommandCreateCommand is not null) { // call IDBCreateSession::CreateSession via the delegate directly for IDBCreateCommand hr = CreateSession(idbCreateSession, IntPtr.Zero, ref ODB.IID_IDBCreateCommand, ref sessionWrapper); @@ -251,7 +251,7 @@ internal void QueryInterfaceIDBCreateCommand(OleDbConnectionString constr) // If constr.HaveQueriedForCreateCommand is true and constr.DangerousIDBCreateCommandCreateCommand is not null, that means that another thread has set it after we // determined we needed to call QueryInterfaceIDBCreateCommand -- otherwise we would have called VerifyIDBCreateCommand instead // In that case, we still need to set our local DangerousIDBCreateCommandCreateCommand, so we want to go through the if block even though the cache has been set on constr already - if (!constr.HaveQueriedForCreateCommand || (null != constr.DangerousIDBCreateCommandCreateCommand)) + if (!constr.HaveQueriedForCreateCommand || (constr.DangerousIDBCreateCommandCreateCommand is not null)) { IntPtr idbCreateCommand = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); @@ -296,7 +296,7 @@ internal void VerifyIDBCreateCommand(OleDbConnectionString constr) // only used from within OleDbConnectionInternal.ctor->DataSourceWrapper.InitializeAndCreateSession Debug.Assert(constr.HaveQueriedForCreateCommand, "expected HaveQueriedForCreateCommand"); - Debug.Assert(null != constr.DangerousIDBCreateCommandCreateCommand, "expected DangerousIDBCreateCommandCreateCommand"); + Debug.Assert(constr.DangerousIDBCreateCommandCreateCommand is not null, "expected DangerousIDBCreateCommandCreateCommand"); // native COM rules are the QI result is the 'this' pointer // the pointer stored at that location is the vtable @@ -309,7 +309,7 @@ internal void VerifyIDBCreateCommand(OleDbConnectionString constr) // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer - if ((null == CreateCommand) || (method != Marshal.GetFunctionPointerForDelegate(CreateCommand))) + if ((CreateCommand is null) || (method != Marshal.GetFunctionPointerForDelegate(CreateCommand))) { CreateCommand = (UnsafeNativeMethods.IDBCreateCommandCreateCommand)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IDBCreateCommandCreateCommand)); constr.DangerousIDBCreateCommandCreateCommand = CreateCommand; @@ -321,10 +321,10 @@ internal void VerifyIDBCreateCommand(OleDbConnectionString constr) internal OleDbHResult CreateCommand(ref object? icommandText) { - // if (null == CreateCommand), the IDBCreateCommand isn't supported - aka E_NOINTERFACE + // if (CreateCommand is null), the IDBCreateCommand isn't supported - aka E_NOINTERFACE OleDbHResult hr = OleDbHResult.E_NOINTERFACE; UnsafeNativeMethods.IDBCreateCommandCreateCommand? CreateCommand = DangerousIDBCreateCommandCreateCommand; - if (null != CreateCommand) + if (CreateCommand is not null) { bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -389,7 +389,7 @@ public void Dispose() object unknown = _unknown; _unknown = null!; _value = null!; - if (null != unknown) + if (unknown is not null) { Marshal.ReleaseComObject(unknown); } @@ -422,7 +422,7 @@ public void Dispose() object unknown = _unknown; _unknown = null!; _value = null!; - if (null != unknown) + if (unknown is not null) { Marshal.ReleaseComObject(unknown); } @@ -453,7 +453,7 @@ public void Dispose() object unknown = _unknown; _unknown = null!; _value = null!; - if (null != unknown) + if (unknown is not null) { Marshal.ReleaseComObject(unknown); } @@ -486,7 +486,7 @@ public void Dispose() object unknown = _unknown; _unknown = null!; _value = null!; - if (null != unknown) + if (unknown is not null) { Marshal.ReleaseComObject(unknown); } @@ -517,7 +517,7 @@ public void Dispose() object unknown = _unknown; _unknown = null!; _value = null!; - if (null != unknown) + if (unknown is not null) { Marshal.ReleaseComObject(unknown); } diff --git a/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs b/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs index b1c7664c3c58e5..6a243a55907fbe 100644 --- a/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs +++ b/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs @@ -266,7 +266,7 @@ internal static NativeDBType FromDataType(OleDbType enumOleDbType) => internal static NativeDBType FromSystemType(object value) { IConvertible? ic = (value as IConvertible); - if (null != ic) + if (ic is not null) { return ic.GetTypeCode() switch { diff --git a/src/libraries/System.Data.OleDb/src/OleDb_Util.cs b/src/libraries/System.Data.OleDb/src/OleDb_Util.cs index b0a39dea96c734..6bd1fb135a8ad2 100644 --- a/src/libraries/System.Data.OleDb/src/OleDb_Util.cs +++ b/src/libraries/System.Data.OleDb/src/OleDb_Util.cs @@ -708,7 +708,7 @@ internal static string ELookup(OleDbHResult hr) internal static string WLookup(short id) { string? value = (string?)g_wlookpup[id]; - if (null == value) + if (value is null) { value = "0x" + ((short)id).ToString("X2", CultureInfo.InvariantCulture) + " " + ((short)id); value += " " + ((DBTypeEnum)id).ToString(); diff --git a/src/libraries/System.Data.OleDb/src/RowBinding.cs b/src/libraries/System.Data.OleDb/src/RowBinding.cs index 7f94bf563d5f13..5dfd719551f59c 100644 --- a/src/libraries/System.Data.OleDb/src/RowBinding.cs +++ b/src/libraries/System.Data.OleDb/src/RowBinding.cs @@ -121,7 +121,7 @@ internal ColumnBinding[] SetBindings(OleDbDataReader? dataReader, Bindings bindi int indexStart, int indexForAccessor, OleDbParameter[]? parameters, tagDBBINDING[] dbbindings, bool ifIRowsetElseIRow) { - Debug.Assert(null != bindings, "null bindings"); + Debug.Assert(bindings is not null, "null bindings"); Debug.Assert(dbbindings.Length == BindingCount(), "count mismatch"); bool mustRelease = false; @@ -150,7 +150,7 @@ internal ColumnBinding[] SetBindings(OleDbDataReader? dataReader, Bindings bindi for (int indexWithinAccessor = 0; indexWithinAccessor < columns.Length; ++indexWithinAccessor) { int index = indexStart + indexWithinAccessor; - OleDbParameter? parameter = ((null != parameters) ? parameters[index] : null); + OleDbParameter? parameter = ((parameters is not null) ? parameters[index] : null); columns[indexWithinAccessor] = new ColumnBinding( dataReader!, index, indexForAccessor, indexWithinAccessor, parameter, this, bindings, dbbindings[indexWithinAccessor], _headerLength, @@ -190,7 +190,7 @@ internal object GetVariantValue(int offset) } } - return ((null != value) ? value : DBNull.Value); + return ((value is not null) ? value : DBNull.Value); } // translate to native @@ -326,7 +326,7 @@ internal void CloseFromConnection() _iaccessor = null; _accessorHandle = ODB.DB_INVALID_HACCESSOR; - if ((ODB.DB_INVALID_HACCESSOR != accessorHandle) && (null != iaccessor)) + if ((ODB.DB_INVALID_HACCESSOR != accessorHandle) && (iaccessor is not null)) { OleDbHResult hr; int refcount; @@ -423,7 +423,7 @@ private unsafe void ResetValues(IntPtr buffer, object? iaccessor) FreeBstr(buffer, valueOffset); break; case NativeDBType.HCHAPTER: - if (null != iaccessor) + if (iaccessor is not null) { // iaccessor will always be null when from ReleaseHandle FreeChapter(buffer, valueOffset, iaccessor); diff --git a/src/libraries/System.Data.OleDb/src/SafeHandles.cs b/src/libraries/System.Data.OleDb/src/SafeHandles.cs index 185712be565c7b..69d11bc41e8fe1 100644 --- a/src/libraries/System.Data.OleDb/src/SafeHandles.cs +++ b/src/libraries/System.Data.OleDb/src/SafeHandles.cs @@ -23,7 +23,7 @@ private DualCoTaskMem() : base(IntPtr.Zero, true) // IDBInfo.GetLiteralInfo internal DualCoTaskMem(UnsafeNativeMethods.IDBInfo dbInfo, int[]? literals, out int literalCount, out IntPtr literalInfo, out OleDbHResult hr) : this() { - int count = (null != literals) ? literals.Length : 0; + int count = (literals is not null) ? literals.Length : 0; hr = dbInfo.GetLiteralInfo(count, literals, out literalCount, out base.handle, out this.handle2); literalInfo = base.handle; } @@ -93,9 +93,9 @@ internal IntPtr GetRowHandle(int index) internal sealed class StringMemHandle : DbBuffer { - internal StringMemHandle(string? value) : base((null != value) ? checked(2 + 2 * value.Length) : 0) + internal StringMemHandle(string? value) : base((value is not null) ? checked(2 + 2 * value.Length) : 0) { - if (null != value) + if (value is not null) { // null-termination exists because of the extra 2+ which is zero'd during on allocation WriteCharArray(0, value.ToCharArray(), 0, value.Length); @@ -110,7 +110,7 @@ internal sealed class ChapterHandle : WrappedIUnknown internal static ChapterHandle CreateChapterHandle(object chapteredRowset, RowBinding binding, int valueOffset) { - if ((null == chapteredRowset) || (IntPtr.Zero == binding.ReadIntPtr(valueOffset))) + if ((chapteredRowset is null) || (IntPtr.Zero == binding.ReadIntPtr(valueOffset))) { return ChapterHandle.DB_NULL_HCHAPTER; } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs index f5bacfd6239170..17478443e02f2a 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs @@ -36,8 +36,8 @@ internal static Exception ExceptionWithStackTrace(Exception e) private static void TraceException(string trace, Exception e) { - Debug.Assert(e != null, "TraceException: null Exception"); - if (e != null) + Debug.Assert(e is not null, "TraceException: null Exception"); + if (e is not null) { DataCommonEventSource.Log.Trace(trace, e); } @@ -203,7 +203,7 @@ internal static void CheckArgumentLength(string value, string parameterName) internal static void CheckArgumentNull(object value, string parameterName) { - if (null == value) + if (value is null) { throw ArgumentNull(parameterName); } @@ -220,7 +220,7 @@ internal static void CheckArgumentNull(object value, string parameterName) internal static bool IsCatchableExceptionType(Exception e) { // a 'catchable' exception is defined by what it is not. - Debug.Assert(e != null, "Unexpected null exception!"); + Debug.Assert(e is not null, "Unexpected null exception!"); Type type = e.GetType(); return ((type != StackOverflowType) && @@ -240,7 +240,7 @@ internal static bool IsCatchableOrSecurityExceptionType(Exception e) // the other way to write this method is, but then SecurityException is checked twice // return ((e is SecurityException) || IsCatchableExceptionType(e)); - Debug.Assert(e != null, "Unexpected null exception!"); + Debug.Assert(e is not null, "Unexpected null exception!"); Type type = e.GetType(); return ((type != StackOverflowType) && @@ -711,8 +711,8 @@ internal static ArgumentException InvalidSizeValue(int value) } internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { - Debug.Assert(null != value, "null value on conversion failure"); - Debug.Assert(null != inner, "null inner on conversion failure"); + Debug.Assert(value is not null, "null value on conversion failure"); + Debug.Assert(inner is not null, "null inner on conversion failure"); Exception e; string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); @@ -912,7 +912,7 @@ internal static bool CompareInsensitiveInvariant(string strvalue, string strcons internal static Delegate? FindBuilder(MulticastDelegate? mcd) { // V1.2.3300 - if (null != mcd) + if (mcd is not null) { Delegate[] d = mcd.GetInvocationList(); for (int i = 0; i < d.Length; i++) @@ -943,7 +943,7 @@ internal static void SetCurrentTransaction(SysTx.Transaction? transaction) { SysTx.IDtcTransaction? oleTxTransaction = null; - if (null != transaction) + if (transaction is not null) { oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction); } @@ -1059,7 +1059,7 @@ internal static Stream GetXmlStream(string value, string errorString) const string config = "config\\"; // get location of config directory string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); - if (rootPath == null) + if (rootPath is null) { throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString); } @@ -1099,7 +1099,7 @@ internal static Stream GetXmlStream(string value, string errorString) { using (RegistryKey? key = Registry.ClassesRoot.OpenSubKey(subkey, false)) { - return ((null != key) ? key.GetValue(queryvalue) : null); + return ((key is not null) ? key.GetValue(queryvalue) : null); } } catch (SecurityException e) @@ -1117,7 +1117,7 @@ internal static Stream GetXmlStream(string value, string errorString) { using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(subkey, false)) { - return ((null != key) ? key.GetValue(queryvalue) : null); + return ((key is not null) ? key.GetValue(queryvalue) : null); } } catch (SecurityException e) @@ -1187,7 +1187,7 @@ internal static void CheckVersionMDAC(bool ifodbcelseoledb) internal static bool RemoveStringQuotes(string? quotePrefix, string? quoteSuffix, string? quotedString, out string? unquotedString) { int prefixLength; - if (quotePrefix == null) + if (quotePrefix is null) { prefixLength = 0; } @@ -1197,7 +1197,7 @@ internal static bool RemoveStringQuotes(string? quotePrefix, string? quoteSuffix } int suffixLength; - if (quoteSuffix == null) + if (quoteSuffix is null) { suffixLength = 0; } @@ -1212,7 +1212,7 @@ internal static bool RemoveStringQuotes(string? quotePrefix, string? quoteSuffix return true; } - if (quotedString == null) + if (quotedString is null) { unquotedString = quotedString; return false; @@ -1315,22 +1315,22 @@ private static void IsDirectionValid(ParameterDirection value) internal static bool IsEmpty([NotNullWhen(false)] string? str) { - return ((null == str) || (0 == str.Length)); + return ((str is null) || (0 == str.Length)); } internal static bool IsEmptyArray([NotNullWhen(false)] string?[]? array) { - return ((null == array) || (0 == array.Length)); + return ((array is null) || (0 == array.Length)); } internal static bool IsNull([NotNullWhen(false)] object? value) { - if ((null == value) || (DBNull.Value == value)) + if ((value is null) || (DBNull.Value == value)) { return true; } INullable? nullable = (value as INullable); - return ((null != nullable) && nullable.IsNull); + return ((nullable is not null) && nullable.IsNull); } } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs index 80252bde49e876..19af333c5e5c05 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs @@ -42,19 +42,19 @@ internal virtual string? ConnectionString public override bool Equals(object? obj) { - if (obj == null || obj.GetType() != typeof(DbConnectionPoolKey)) + if (obj is null || obj.GetType() != typeof(DbConnectionPoolKey)) { return false; } DbConnectionPoolKey? key = obj as DbConnectionPoolKey; - return (key != null && _connectionString == key._connectionString); + return (key is not null && _connectionString == key._connectionString); } public override int GetHashCode() { - return _connectionString == null ? 0 : _connectionString.GetHashCode(); + return _connectionString is null ? 0 : _connectionString.GetHashCode(); } } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs index 918c3304fe6090..005da322cea800 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs @@ -30,7 +30,7 @@ public FieldNameLookup(IDataRecord reader, int defaultLocaleID) for (int i = 0; i < length; ++i) { fieldNames[i] = reader.GetName(i); - Debug.Assert(null != fieldNames[i]); + Debug.Assert(fieldNames[i] is not null); } _fieldNames = fieldNames; _defaultLocaleID = defaultLocaleID; @@ -38,7 +38,7 @@ public FieldNameLookup(IDataRecord reader, int defaultLocaleID) public int GetOrdinal(string fieldName) { // V1.2.3300 - if (null == fieldName) + if (fieldName is null) { throw ADP.ArgumentNull("fieldName"); } @@ -58,7 +58,7 @@ public int IndexOfName(string fieldName) } // via case sensitive search, first match with lowest ordinal matches object? value = _fieldNameLookup![fieldName]; - return ((null != value) ? (int)value : -1); + return ((value is not null) ? (int)value : -1); } public int IndexOf(string fieldName) @@ -69,7 +69,7 @@ public int IndexOf(string fieldName) } int index; object? value = _fieldNameLookup![fieldName]; - if (null != value) + if (value is not null) { // via case sensitive search, first match with lowest ordinal matches index = (int)value; @@ -90,13 +90,13 @@ public int IndexOf(string fieldName) private int LinearIndexOf(string fieldName, CompareOptions compareOptions) { CompareInfo? compareInfo = _compareInfo; - if (null == compareInfo) + if (compareInfo is null) { if (-1 != _defaultLocaleID) { compareInfo = CompareInfo.GetCompareInfo(_defaultLocaleID); } - if (null == compareInfo) + if (compareInfo is null) { compareInfo = CultureInfo.InvariantCulture.CompareInfo; } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs index 09ec22615fca61..46048aaac7c3b0 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs @@ -37,7 +37,7 @@ internal NameValuePair? Next get { return _next; } set { - if ((null != _next) || (null == value)) + if ((null != _next) || (value is null)) { throw ADP.InternalError(ADP.InternalErrorCode.NameValuePairNext); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs index dc0db72fa5c6cd..c5b448d4d409a1 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs @@ -128,7 +128,7 @@ internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int le offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -161,7 +161,7 @@ internal char[] ReadChars(int offset, char[] destination, int startIndex, int le offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -220,7 +220,7 @@ internal void ReadInt16Array(int offset, short[] destination, int startIndex, in offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -272,7 +272,7 @@ internal void ReadInt32Array(int offset, int[] destination, int startIndex, int offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination is not null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -365,7 +365,7 @@ protected override bool ReleaseHandle() private void StructureToPtr(int offset, object structure) { - Debug.Assert(null != structure, "null structure"); + Debug.Assert(structure is not null, "null structure"); offset += BaseOffset; ValidateCheck(offset, Marshal.SizeOf(structure.GetType())); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); @@ -417,7 +417,7 @@ internal void WriteBytes(int offset, byte[] source, int startIndex, int length) offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -443,7 +443,7 @@ internal void WriteCharArray(int offset, char[] source, int startIndex, int leng offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -498,7 +498,7 @@ internal void WriteInt16Array(int offset, short[] source, int startIndex, int le offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -548,7 +548,7 @@ internal void WriteInt32Array(int offset, int[] source, int startIndex, int leng offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source is not null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs index 0d89234d92bc34..cd6dd5a2a98aa8 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs @@ -113,7 +113,7 @@ internal override void CloseConnection(DbConnection owningObject, DbConnectionFa internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { - if (retry == null || !retry.Task.IsCompleted) + if (retry is null || !retry.Task.IsCompleted) { // retry is null if this is a synchronous call @@ -126,7 +126,7 @@ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnect // we are completing an asynchronous open Debug.Assert(retry.Task.Status == TaskStatus.RanToCompletion, "retry task must be completed successfully"); DbConnectionInternal openConnection = retry.Task.Result; - if (null == openConnection) + if (openConnection is null) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs index d096b432bc808d..a096cb3138180e 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -53,7 +53,7 @@ public void ClearAllPools() foreach (KeyValuePair entry in connectionPoolGroups) { DbConnectionPoolGroup poolGroup = entry.Value; - if (null != poolGroup) + if (poolGroup is not null) { poolGroup.Clear(); } @@ -70,15 +70,15 @@ protected virtual DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal i internal DbConnectionInternal? CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions? userOptions) { - Debug.Assert(null != owningConnection, "null owningConnection?"); - Debug.Assert(null != poolGroup, "null poolGroup?"); + Debug.Assert(owningConnection is not null, "null owningConnection?"); + Debug.Assert(poolGroup is not null, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo!; DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); - if (null != newConnection) + if (newConnection is not null) { PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); @@ -88,11 +88,11 @@ protected virtual DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal i internal DbConnectionInternal? CreatePooledConnection(DbConnectionPool pool, DbConnection? owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions? userOptions) { - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool is not null, "null pool?"); DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo!; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); - if (null != newConnection) + if (newConnection is not null) { PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); @@ -114,7 +114,7 @@ private Timer CreatePruningTimer() // GetCompletedTask must be called from within s_pendingOpenPooled lock private static Task GetCompletedTask() { - if (s_completedTask == null) + if (s_completedTask is null) { TaskCompletionSource source = new TaskCompletionSource(); source.SetResult(null); @@ -125,7 +125,7 @@ private Timer CreatePruningTimer() internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource? retry, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection, out DbConnectionInternal? connection) { - Debug.Assert(null != owningConnection, "null owningConnection?"); + Debug.Assert(owningConnection is not null, "null owningConnection?"); DbConnectionPoolGroup poolGroup; DbConnectionPool? connectionPool; @@ -148,14 +148,14 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour poolGroup = GetConnectionPoolGroup(owningConnection)!; // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); - if (null == connectionPool) + if (connectionPool is null) { // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool // or have a disabled pool entry. poolGroup = GetConnectionPoolGroup(owningConnection)!; // previous entry have been disabled - if (retry != null) + if (retry is not null) { Task newTask; CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); @@ -166,7 +166,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++) { Task task = s_pendingOpenNonPooled[idx]; - if (task == null) + if (task is null) { s_pendingOpenNonPooled[idx] = GetCompletedTask(); break; @@ -195,7 +195,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour { ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction); var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); - if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open)) + if ((oldConnection is not null) && (oldConnection.State == ConnectionState.Open)) { oldConnection.PrepareForReplaceConnection(); oldConnection.Dispose(); @@ -269,7 +269,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour } } - if (connection == null) + if (connection is null) { // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) @@ -287,9 +287,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour } } } - } while (connection == null && retriesLeft-- > 0); + } while (connection is null && retriesLeft-- > 0); - if (connection == null) + if (connection is null) { // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); @@ -302,8 +302,8 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour { // if poolgroup is disabled, it will be replaced with a new entry - Debug.Assert(null != owningObject, "null owningObject?"); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); + Debug.Assert(owningObject is not null, "null owningObject?"); + Debug.Assert(connectionPoolGroup is not null, "null connectionPoolGroup?"); // It is possible that while the outer connection object has // been sitting around in a closed and unused state in some long @@ -314,17 +314,17 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // re-create the pool entry whenever it's disabled. // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work - if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) + if (connectionPoolGroup.IsDisabled && (connectionPoolGroup.PoolGroupOptions is not null)) { // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; // get the string to hash on again DbConnectionOptions? connectionOptions = connectionPoolGroup.ConnectionOptions; - Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); + Debug.Assert(connectionOptions is not null, "prevent expansion of connectionString"); connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions)!; - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); + Debug.Assert(connectionPoolGroup is not null, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } DbConnectionPool? connectionPool = connectionPoolGroup.GetConnectionPool(this); @@ -340,20 +340,20 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour DbConnectionPoolGroup? connectionPoolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; - if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) + if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (connectionPoolGroup.PoolGroupOptions is not null))) { // If we can't find an entry for the connection string in // our collection of pool entries, then we need to create a // new pool entry and add it to our collection. DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); - if (null == connectionOptions) + if (connectionOptions is null) { throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); } string expandedConnectionString = key.ConnectionString; - if (null == userConnectionOptions) + if (userConnectionOptions is null) { // we only allow one expansion on the connection string userConnectionOptions = connectionOptions; @@ -370,9 +370,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour } // We don't support connection pooling on Win9x; it lacks too many of the APIs we require. - if ((null == poolOptions) && ADP.IsWindowsNT) + if ((poolOptions is null) && ADP.IsWindowsNT) { - if (null != connectionPoolGroup) + if (connectionPoolGroup is not null) { // reusing existing pool option in case user originally used SetConnectionPoolOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -410,10 +410,10 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered"); } } - Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?"); - Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?"); + Debug.Assert(connectionPoolGroup is not null, "how did we not create a pool entry?"); + Debug.Assert(userConnectionOptions is not null, "how did we not have user connection options?"); } - else if (null == userConnectionOptions) + else if (userConnectionOptions is null) { userConnectionOptions = connectionPoolGroup.ConnectionOptions; } @@ -422,7 +422,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPoolGroup, DbConnectionInternal internalConnection) { - Debug.Assert(connectionPoolGroup != null, "connectionPoolGroup may not be null."); + Debug.Assert(connectionPoolGroup is not null, "connectionPoolGroup may not be null."); // get the matadatafactory from the pool entry. If it does not already have one // create one and save it on the pool entry @@ -430,7 +430,7 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo // consider serializing this so we don't construct multiple metadata factories // if two threads happen to hit this at the same time. One will be GC'd - if (metaDataFactory == null) + if (metaDataFactory is null) { bool allowCache = false; metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache); @@ -456,7 +456,7 @@ private void PruneConnectionPoolGroups(object? state) DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray(); foreach (DbConnectionPool pool in poolsToRelease) { - if (null != pool) + if (pool is not null) { pool.Clear(); @@ -480,7 +480,7 @@ private void PruneConnectionPoolGroups(object? state) DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray(); foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease) { - if (null != poolGroup) + if (poolGroup is not null) { int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease @@ -504,7 +504,7 @@ private void PruneConnectionPoolGroups(object? state) foreach (KeyValuePair entry in connectionPoolGroups) { - if (null != entry.Value) + if (entry.Value is not null) { Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered"); @@ -531,7 +531,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) // Queue the pool up for release -- we'll clear it out and dispose // of it as the last part of the pruning timer callback so we don't // do it with the pool entry or the pool collection locked. - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool is not null, "null pool?"); // set the pool to the shutdown state to force all active // connections to be automatically disposed when they @@ -551,7 +551,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { - Debug.Assert(null != poolGroup, "null poolGroup?"); + Debug.Assert(poolGroup is not null, "null poolGroup?"); lock (_poolGroupsToRelease) { _poolGroupsToRelease.Add(poolGroup); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs index c7cacdaf6cabbb..3242e6aff3a8f7 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs @@ -57,7 +57,7 @@ internal DbConnectionOptions? ConnectionOptions get { System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; - return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + return ((poolGroup is not null) ? poolGroup.ConnectionOptions : null); } } @@ -65,7 +65,7 @@ private string ConnectionString_Get() { bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions? connectionOptions = UserConnectionOptions; - return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); + return ((connectionOptions is not null) ? connectionOptions.UsersConnectionString(hidePassword) : ""); } private void ConnectionString_Set(string? value) @@ -124,7 +124,7 @@ internal System.Data.ProviderBase.DbConnectionPoolGroup? PoolGroup set { // when a poolgroup expires and the connection eventually activates, the pool entry will be replaced - Debug.Assert(null != value, "null poolGroup"); + Debug.Assert(value is not null, "null poolGroup"); _poolGroup = value; } } @@ -172,7 +172,7 @@ protected override void Dispose(bool disposing) //private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITransaction transaction) { // SysTx.Transaction indigoTransaction = null; - // if (null != transaction) { + // if (transaction is not null) { // indigoTransaction = SysTx.TransactionInterop.GetTransactionFromDtcTransaction((SysTx.IDtcTransaction)transaction); // } @@ -201,7 +201,7 @@ public override void EnlistTransaction(SysTx.Transaction? transaction) // server, we don't want to lock here, we'll handle the race conditions // elsewhere. SysTx.Transaction? enlistedTransaction = innerConnection.EnlistedTransaction; - if (enlistedTransaction != null) + if (enlistedTransaction is not null) { // Allow calling enlist if already enlisted (no-op) if (enlistedTransaction.Equals(transaction)) @@ -252,14 +252,14 @@ internal void PermissionDemand() Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; - DbConnectionOptions? connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); - if ((null == connectionOptions) || connectionOptions.IsEmpty) + DbConnectionOptions? connectionOptions = ((poolGroup is not null) ? poolGroup.ConnectionOptions : null); + if ((connectionOptions is null) || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } DbConnectionOptions? userConnectionOptions = UserConnectionOptions; - Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); + Debug.Assert(userConnectionOptions is not null, "null UserConnectionOptions"); } internal void RemoveWeakReference(object value) @@ -273,7 +273,7 @@ internal void SetInnerConnectionEvent(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(to is not null, "to null InnerConnection"); ConnectionState originalState = _innerConnection.State & ConnectionState.Open; ConnectionState currentState = to.State & ConnectionState.Open; @@ -312,8 +312,8 @@ internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionIntern { // Set's the internal connection, verifying that it's a specific value before doing so. Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != from, "from null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(from is not null, "from null InnerConnection"); + Debug.Assert(to is not null, "to null InnerConnection"); bool result = (from == Interlocked.CompareExchange(ref _innerConnection, to, from)); return result; @@ -325,7 +325,7 @@ internal void SetInnerConnectionTo(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(to is not null, "to null InnerConnection"); _innerConnection = to; } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs index 7aa55a95e73d61..2ac9ecef0e687f 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs @@ -81,8 +81,8 @@ protected internal SysTx.Transaction? EnlistedTransaction set { SysTx.Transaction? currentEnlistedTransaction = _enlistedTransaction; - if (((null == currentEnlistedTransaction) && (null != value)) - || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) + if (((currentEnlistedTransaction is null) && (value is not null)) + || ((currentEnlistedTransaction is not null) && !currentEnlistedTransaction.Equals(value))) { // Pay attention to the order here: // 1) defect from any notifications @@ -96,7 +96,7 @@ protected internal SysTx.Transaction? EnlistedTransaction SysTx.Transaction? previousTransactionClone = null; try { - if (null != value) + if (value is not null) { valueClone = value.Clone(); } @@ -131,12 +131,12 @@ protected internal SysTx.Transaction? EnlistedTransaction // we really need to dispose our clones; they may have // native resources and GC may not happen soon enough. // don't dispose if still holding reference in _enlistedTransaction - if (null != previousTransactionClone && + if (previousTransactionClone is not null && !object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) { previousTransactionClone.Dispose(); } - if (null != valueClone && !object.ReferenceEquals(valueClone, _enlistedTransaction)) + if (valueClone is not null && !object.ReferenceEquals(valueClone, _enlistedTransaction)) { valueClone.Dispose(); } @@ -338,7 +338,7 @@ internal void DeactivateConnection() Debug.Assert(0 == activateCount, "activated multiple times?"); #endif // DEBUG - if (PerformanceCounters != null) + if (PerformanceCounters is not null) { // Pool.Clear will DestroyObject that will clean performanceCounters before going here PerformanceCounters.NumberOfActiveConnections.Decrement(); } @@ -379,7 +379,7 @@ internal virtual void DelegatedTransactionEnded() DbConnectionPool? pool = Pool; - if (null == pool) + if (pool is null) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool } @@ -423,10 +423,10 @@ protected internal void DoomThisConnection() protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string?[]? restrictions) { - Debug.Assert(outerConnection != null, "outerConnection may not be null."); + Debug.Assert(outerConnection is not null, "outerConnection may not be null."); DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this); - Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null."); + Debug.Assert(metaDataFactory is not null, "metaDataFactory may not be null."); return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions); } @@ -457,7 +457,7 @@ internal void MakePooledConnection(DbConnectionPool connectionPool) internal void NotifyWeakReference(int message) { DbReferenceCollection? referenceCollection = ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection is not null) { referenceCollection.Notify(message); } @@ -501,7 +501,7 @@ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnect connectionFactory.SetInnerConnectionTo(outerConnection, this); throw; } - if (null == openConnection) + if (openConnection is null) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); @@ -522,7 +522,7 @@ internal void PrePush(object? expectedOwner) // ReclaimEmancipatedObjects. //3 // The following tests are retail assertions of things we can't allow to happen. - if (null == expectedOwner) + if (expectedOwner is null) { if (null != _owningObject.Target) { @@ -566,7 +566,7 @@ internal void PostPop(object newOwner) _owningObject.Target = newOwner; _pooledCount--; //3 // The following tests are retail assertions of things we can't allow to happen. - if (null != Pool) + if (Pool is not null) { if (0 != _pooledCount) { @@ -582,7 +582,7 @@ internal void PostPop(object newOwner) internal void RemoveWeakReference(object value) { DbReferenceCollection? referenceCollection = ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection is not null) { referenceCollection.Remove(value); } @@ -591,7 +591,7 @@ internal void RemoveWeakReference(object value) internal void DetachCurrentTransactionIfEnded() { SysTx.Transaction? enlistedTransaction = EnlistedTransaction; - if (enlistedTransaction != null) + if (enlistedTransaction is not null) { bool transactionIsDead; try @@ -620,10 +620,10 @@ internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitly { // Detach if detach-on-end behavior, or if outer connection was closed DbConnection? owner = (DbConnection?)Owner; - if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) + if (isExplicitlyReleasing || UnbindOnTransactionCompletion || owner is null) { SysTx.Transaction? currentEnlistedTransaction = _enlistedTransaction; - if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) + if (currentEnlistedTransaction is not null && transaction.Equals(currentEnlistedTransaction)) { EnlistedTransaction = null; diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs index f98d94b4ba044e..b6e12e53f46522 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs @@ -53,7 +53,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // if the DbConnectionInternal derived class needs to close the connection it should // delegate to the DbConnection if one exists or directly call dispose // DbConnection owningObject = (DbConnection)Owner; - // if (null != owningObject) { + // if (owningObject is not null) { // owningObject.Close(); // force the closed state on the outer object. // } // else { @@ -63,8 +63,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// // DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING! //////////////////////////////////////////////////////////////// - Debug.Assert(null != owningObject, "null owningObject"); - Debug.Assert(null != connectionFactory, "null connectionFactory"); + Debug.Assert(owningObject is not null, "null owningObject"); + Debug.Assert(connectionFactory is not null, "null connectionFactory"); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -89,7 +89,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // The singleton closed classes won't have owners and // connection pools, and we won't want to put them back // into the pool. - if (null != connectionPool) + if (connectionPool is not null) { connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us... // NOTE: Before we leave the PutObject call, another @@ -144,7 +144,7 @@ public virtual void Dispose() // of the original reference. // _enlistedTransaction can be changed by another thread (TX end event) SysTx.Transaction? enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null); - if (enlistedTransaction != null) + if (enlistedTransaction is not null) { enlistedTransaction.Dispose(); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs index e411fc550101fb..3447ef33b54f6e 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs @@ -67,7 +67,7 @@ private sealed class TransactedConnectionPool internal TransactedConnectionPool(DbConnectionPool pool) { - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool is not null, "null pool?"); _pool = pool; _transactedCxns = new Dictionary(); @@ -83,7 +83,7 @@ internal DbConnectionPool Pool internal DbConnectionInternal? GetTransactedObject(SysTx.Transaction transaction) { - Debug.Assert(null != transaction, "null transaction?"); + Debug.Assert(transaction is not null, "null transaction?"); DbConnectionInternal? transactedObject = null; @@ -104,7 +104,7 @@ internal DbConnectionPool Pool // connection is probably better than unnecessarily locking if (txnFound) { - Debug.Assert(connections != null); + Debug.Assert(connections is not null); // synchronize multi-threaded access with PutTransactedObject (TransactionEnded should // not be a concern, see comments above) @@ -123,8 +123,8 @@ internal DbConnectionPool Pool internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - Debug.Assert(null != transaction, "null transaction?"); - Debug.Assert(null != transactedObject, "null transactedObject?"); + Debug.Assert(transaction is not null, "null transaction?"); + Debug.Assert(transactedObject is not null, "null transactedObject?"); TransactedConnectionList? connections; bool txnFound = false; @@ -137,7 +137,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt // Check if a transacted pool has been created for this transaction if (txnFound = _transactedCxns.TryGetValue(transaction, out connections)) { - Debug.Assert(connections != null); + Debug.Assert(connections is not null); // synchronize multi-threaded access with GetTransactedObject lock (connections) @@ -172,7 +172,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt // transacted pool while threadA was processing the above instructions. if (txnFound = _transactedCxns.TryGetValue(transaction, out connections)) { - Debug.Assert(connections != null); + Debug.Assert(connections is not null); // synchronize multi-threaded access with GetTransactedObject lock (connections) @@ -194,9 +194,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } finally { - if (null != transactionClone) + if (transactionClone is not null) { - if (newConnections != null) + if (newConnections is not null) { // another thread created the transaction pool and thus the new // TransactedConnectionList was not used, so dispose of it and @@ -377,9 +377,9 @@ internal DbConnectionPool( DbConnectionPoolIdentity identity) { Debug.Assert(ADP.IsWindowsNT, "Attempting to construct a connection pool on Win9x?"); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); + Debug.Assert(connectionPoolGroup is not null, "null connectionPoolGroup"); - if ((null != identity) && identity.IsRestricted) + if ((identity is not null) && identity.IsRestricted) { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken); } @@ -540,7 +540,7 @@ private void CleanupCallback(object? state) if (_stackOld.TryPop(out obj)) { - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); // If we obtained one from the old stack, destroy it. PerformanceCounters.NumberOfFreeConnections.Decrement(); @@ -600,7 +600,7 @@ private void CleanupCallback(object? state) if (!_stackNew.TryPop(out obj)) break; - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -627,7 +627,7 @@ internal void Clear() { obj = _objectList[i]; - if (null != obj) + if (obj is not null) { obj.DoNotPoolThisConnection(); } @@ -637,13 +637,13 @@ internal void Clear() // Second, dispose of all the free connections. while (_stackNew.TryPop(out obj)) { - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); PerformanceCounters.NumberOfFreeConnections.Decrement(); DestroyObject(obj); } while (_stackOld.TryPop(out obj)) { - Debug.Assert(obj != null, "null connection is not expected"); + Debug.Assert(obj is not null, "null connection is not expected"); PerformanceCounters.NumberOfFreeConnections.Decrement(); DestroyObject(obj); } @@ -667,7 +667,7 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti try { newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions); - if (null == newObj) + if (newObj is null) { throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object } @@ -679,7 +679,7 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti lock (_objectList) { - if ((oldConnection != null) && (oldConnection.Pool == this)) + if ((oldConnection is not null) && (oldConnection.Pool == this)) { _objectList.Remove(oldConnection); } @@ -689,10 +689,10 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti } // If the old connection belonged to another pool, we need to remove it from that - if (oldConnection != null) + if (oldConnection is not null) { var oldConnectionPool = oldConnection.Pool; - if (oldConnectionPool != null && oldConnectionPool != this) + if (oldConnectionPool is not null && oldConnectionPool != this) { Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down"); lock (oldConnectionPool._objectList) @@ -822,14 +822,14 @@ private void DeactivateObject(DbConnectionInternal obj) // thread. SysTx.Transaction? transaction = obj.EnlistedTransaction; - if (null != transaction) + if (transaction is not null) { // NOTE: we're not locking on _state, so it's possible that its // value could change between the conditional check and here. // Although perhaps not ideal, this is OK because the // DelegatedTransactionEnded event will clean up the // connection appropriately regardless of the pool state. - Debug.Assert(_transactedConnectionPool != null, "Transacted connection pool was not expected to be null."); + Debug.Assert(_transactedConnectionPool is not null, "Transacted connection pool was not expected to be null."); _transactedConnectionPool.PutTransactedObject(transaction, obj); rootTxn = true; } @@ -929,7 +929,7 @@ private void ErrorCallback(object? state) // the error state is cleaned, destroy the timer to avoid periodic invocation Timer? t = _errorTimer; _errorTimer = null; - if (t != null) + if (t is not null) { t.Dispose(); // Cancel timer request. } @@ -999,19 +999,19 @@ private void WaitForPendingOpen() } catch (System.OutOfMemoryException) { - if (connection != null) + if (connection is not null) { connection.DoomThisConnection(); } throw; } catch (System.StackOverflowException) { - if (connection != null) + if (connection is not null) { connection.DoomThisConnection(); } throw; } catch (System.Threading.ThreadAbortException) { - if (connection != null) + if (connection is not null) { connection.DoomThisConnection(); } throw; } @@ -1020,7 +1020,7 @@ private void WaitForPendingOpen() caughtException = e; } - if (caughtException != null) + if (caughtException is not null) { next.Completion.TrySetException(caughtException); } @@ -1030,7 +1030,7 @@ private void WaitForPendingOpen() } else { - Debug.Assert(connection != null, "connection should never be null in success case"); + Debug.Assert(connection is not null, "connection should never be null in success case"); if (!next.Completion.TrySetResult(connection)) { // if the completion was cancelled, lets try and get this connection back for the next try @@ -1055,7 +1055,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource numberOfRestrictions)) + if ((restrictions is not null) && (restrictions.Length > numberOfRestrictions)) { throw ADP.TooManyRestrictions(collectionName); } @@ -152,7 +152,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest { DbParameter restrictionParameter = command.CreateParameter(); - if ((restrictions != null) && (restrictions.Length > i) && (restrictions[i] != null)) + if ((restrictions is not null) && (restrictions.Length > i) && (restrictions[i] is not null)) { restrictionParameter.Value = restrictions[i]; } @@ -204,7 +204,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest } finally { - if (reader != null) + if (reader is not null) { reader.Dispose(); reader = null; @@ -257,14 +257,14 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) string? candidateCollectionName; DataTable? metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - if (metaDataCollectionsTable == null) + if (metaDataCollectionsTable is null) { throw ADP.InvalidXml(); } DataColumn? collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; - if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType)) + if ((collectionNameColumn is null) || (typeof(string) != collectionNameColumn.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName); } @@ -306,7 +306,7 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) else { // have an inexact match - ok only if it is the only one - if (exactCollectionName != null) + if (exactCollectionName is not null) { // can't fail here becasue we may still find an exact match haveMultipleInexactMatches = true; @@ -318,7 +318,7 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) } } - if (requestedCollectionRow == null) + if (requestedCollectionRow is null) { if (versionFailure == false) { @@ -345,7 +345,7 @@ private void FixUpVersion(DataTable dataSourceInfoTable) DataColumn? versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion]; DataColumn? normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized]; - if ((versionColumn == null) || (normalizedVersionColumn == null)) + if ((versionColumn is null) || (normalizedVersionColumn is null)) { throw ADP.MissingDataSourceInformationColumn(); } @@ -374,10 +374,10 @@ private string GetParameterName(string neededCollectionName, int neededRestricti string? result = null; restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; - if (restrictionsTable != null) + if (restrictionsTable is not null) { restrictionColumns = restrictionsTable.Columns; - if (restrictionColumns != null) + if (restrictionColumns is not null) { collectionName = restrictionColumns[_collectionName]; parameterName = restrictionColumns[_parameterName]; @@ -386,7 +386,7 @@ private string GetParameterName(string neededCollectionName, int neededRestricti } } - if ((parameterName == null) || (collectionName == null) || (restrictionName == null) || (restrictionNumber == null)) + if ((parameterName is null) || (collectionName is null) || (restrictionName is null) || (restrictionNumber is null)) { throw ADP.MissingRestrictionColumn(); } @@ -402,7 +402,7 @@ private string GetParameterName(string neededCollectionName, int neededRestricti } } - if (result == null) + if (result is null) { throw ADP.MissingRestrictionRow(); } @@ -413,7 +413,7 @@ private string GetParameterName(string neededCollectionName, int neededRestricti public virtual DataTable GetSchema(DbConnection connection, string collectionName, string?[]? restrictions) { - Debug.Assert(_metaDataCollectionsDataSet != null); + Debug.Assert(_metaDataCollectionsDataSet is not null); DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]!; @@ -499,7 +499,7 @@ private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNa break; default: - if (hiddenColumnNames == null) + if (hiddenColumnNames is null) { break; } @@ -531,10 +531,10 @@ private bool SupportedByCurrentVersion(DataRow requestedCollectionRow) // check the minimum version first versionColumn = tableColumns[_minimumVersion]; - if (versionColumn != null) + if (versionColumn is not null) { version = requestedCollectionRow[versionColumn]; - if (version != null) + if (version is not null) { if (version != DBNull.Value) { @@ -550,10 +550,10 @@ private bool SupportedByCurrentVersion(DataRow requestedCollectionRow) if (result == true) { versionColumn = tableColumns[_maximumVersion]; - if (versionColumn != null) + if (versionColumn is not null) { version = requestedCollectionRow[versionColumn]; - if (version != null) + if (version is not null) { if (version != DBNull.Value) { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs index 02e526676ca374..88fd8f34e5a9ef 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs @@ -18,9 +18,9 @@ public void NewTarget(int tag, object target) { Debug.Assert(!HasTarget, "Entry already has a valid target"); Debug.Assert(tag != 0, "Bad tag"); - Debug.Assert(target != null, "Invalid target"); + Debug.Assert(target is not null, "Invalid target"); - if (_weak == null) + if (_weak is null) { _weak = new WeakReference(target, false); } @@ -81,7 +81,7 @@ protected DbReferenceCollection() protected void AddItem(object value, int tag) { - Debug.Assert(null != value && 0 != tag, "AddItem with null value or 0 tag"); + Debug.Assert(value is not null && 0 != tag, "AddItem with null value or 0 tag"); bool itemAdded = false; lock (_itemLock) @@ -152,11 +152,11 @@ protected void AddItem(object value, int tag) // NOTE: Check if the returned value is null twice may seem wasteful, but this if for performance // Since checking for null twice is cheaper than calling both HasTarget and Target OR always attempting to typecast object? value = _items[counter].Target; - if (value != null) + if (value is not null) { // Make sure the item has the correct type and passes the filtering T? tempItem = value as T; - if ((tempItem != null) && (filterMethod(tempItem))) + if ((tempItem is not null) && (filterMethod(tempItem))) { return tempItem; } @@ -193,7 +193,7 @@ public void Notify(int message) for (int index = 0; index <= _lastItemIndex; ++index) { object? value = _items[index].Target; // checks tag & gets target - if (null != value) + if (value is not null) { NotifyItem(message, _items[index].Tag, value); _items[index].RemoveTarget(); @@ -228,7 +228,7 @@ public void Notify(int message) protected void RemoveItem(object value) { - Debug.Assert(null != value, "RemoveItem with null"); + Debug.Assert(value is not null, "RemoveItem with null"); bool lockObtained = false; try diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs index a45f38e06111aa..de68e3bb034427 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs @@ -20,7 +20,7 @@ internal WrappedIUnknown() : base(IntPtr.Zero, true) internal WrappedIUnknown(object? unknown) : this() { - if (null != unknown) + if (unknown is not null) { RuntimeHelpers.PrepareConstrainedRegions(); try diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs index 3ee6a7c65440b3..cf62b954f93676 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs @@ -23,7 +23,7 @@ public static Activity Current ObjectHandle activityHandle = (ObjectHandle)CallContext.LogicalGetData(FieldKey); // Unwrap the Activity if it was set in the same AppDomain (as FieldKey is AppDomain-specific). - if (activityHandle != null) + if (activityHandle is not null) { return (Activity)activityHandle.Unwrap(); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs index 74c061c89ccfee..c207abf48a937b 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs @@ -159,7 +159,7 @@ public string? Id { // if we represented it as a traceId-spanId, convert it to a string. // We can do this concatenation with a stackalloced Span if we actually used Id a lot. - if (_id == null && _spanId != null) + if (_id is null && _spanId is not null) { // Convert flags to binary. Span flagsChars = stackalloc char[2]; @@ -186,14 +186,14 @@ public string? ParentId get { // if we represented it as a traceId-spanId, convert it to a string. - if (_parentId == null) + if (_parentId is null) { - if (_parentSpanId != null) + if (_parentSpanId is not null) { string parentId = "00-" + _traceId + "-" + _parentSpanId + "-00"; Interlocked.CompareExchange(ref _parentId, parentId, null); } - else if (Parent != null) + else if (Parent is not null) { Interlocked.CompareExchange(ref _parentId, Parent.Id, null); } @@ -216,19 +216,19 @@ public string? RootId //we expect RootId to be requested at any time after activity is created, //possibly even before it was started for sampling or logging purposes //Presumably, it will be called by logging systems for every log record, so we cache it. - if (_rootId == null) + if (_rootId is null) { string? rootId = null; - if (Id != null) + if (Id is not null) { rootId = GetRootId(Id); } - else if (ParentId != null) + else if (ParentId is not null) { rootId = GetRootId(ParentId); } - if (rootId != null) + if (rootId is not null) { Interlocked.CompareExchange(ref _rootId, rootId, null); } @@ -288,9 +288,9 @@ public IEnumerable Links { get { - for (Activity? activity = this; activity != null; activity = activity.Parent) + for (Activity? activity = this; activity is not null; activity = activity.Parent) { - if (activity._baggage != null) + if (activity._baggage is not null) { return Iterate(activity); } @@ -300,19 +300,19 @@ public IEnumerable Links static IEnumerable> Iterate(Activity? activity) { - Debug.Assert(activity != null); + Debug.Assert(activity is not null); do { - if (activity._baggage != null) + if (activity._baggage is not null) { - for (LinkedListNode>? current = activity._baggage.First; current != null; current = current.Next) + for (LinkedListNode>? current = activity._baggage.First; current is not null; current = current.Next) { yield return current.Value; } } activity = activity.Parent; - } while (activity != null); + } while (activity is not null); } } } @@ -372,7 +372,7 @@ public Activity AddTag(string key, object? value) { KeyValuePair kvp = new KeyValuePair(key, value); - if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp), null) != null) + if (_tags is not null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp), null) is not null) { _tags.Add(kvp); } @@ -396,7 +396,7 @@ public Activity SetTag(string key, object? value) { KeyValuePair kvp = new KeyValuePair(key, value); - if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp, set: true), null) != null) + if (_tags is not null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp, set: true), null) is not null) { _tags.Set(kvp); } @@ -411,7 +411,7 @@ public Activity SetTag(string key, object? value) /// 'this' for convenient chaining public Activity AddEvent(ActivityEvent e) { - if (_events != null || Interlocked.CompareExchange(ref _events, new LinkedList(e), null) != null) + if (_events is not null || Interlocked.CompareExchange(ref _events, new LinkedList(e), null) is not null) { _events.Add(e); } @@ -432,7 +432,7 @@ public Activity AddBaggage(string key, string? value) { KeyValuePair kvp = new KeyValuePair(key, value); - if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new LinkedList>(kvp), null) != null) + if (_baggage is not null || Interlocked.CompareExchange(ref _baggage, new LinkedList>(kvp), null) is not null) { _baggage.AddFront(kvp); } @@ -451,11 +451,11 @@ public Activity AddBaggage(string key, string? value) /// The id of the parent operation. public Activity SetParentId(string parentId) { - if (Parent != null) + if (Parent is not null) { NotifyError(new InvalidOperationException(SR.SetParentIdOnActivityWithParent)); } - else if (ParentId != null || _parentSpanId != null) + else if (ParentId is not null || _parentSpanId is not null) { NotifyError(new InvalidOperationException(SR.ParentIdAlreadySet)); } @@ -476,11 +476,11 @@ public Activity SetParentId(string parentId) /// public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None) { - if (Parent != null) + if (Parent is not null) { NotifyError(new InvalidOperationException(SR.SetParentIdOnActivityWithParent)); } - else if (ParentId != null || _parentSpanId != null) + else if (ParentId is not null || _parentSpanId is not null) { NotifyError(new InvalidOperationException(SR.ParentIdAlreadySet)); } @@ -554,16 +554,16 @@ public Activity SetEndTime(DateTime endTimeUtc) public Activity Start() { // Has the ID already been set (have we called Start()). - if (_id != null || _spanId != null) + if (_id is not null || _spanId is not null) { NotifyError(new InvalidOperationException(SR.ActivityStartAlreadyStarted)); } else { - if (_parentId == null && _parentSpanId is null) + if (_parentId is null && _parentSpanId is null) { Activity? parent = Current; - if (parent != null) + if (parent is not null) { // The parent change should not form a loop. We are actually guaranteed this because // 1. Un-started activities can't be 'Current' (thus can't be 'parent'), we throw if you try. @@ -580,9 +580,9 @@ public Activity Start() // Figure out what format to use. IdFormat = ForceDefaultIdFormat ? DefaultIdFormat : - Parent != null ? Parent.IdFormat : - _parentSpanId != null ? ActivityIdFormat.W3C : - _parentId == null ? DefaultIdFormat : + Parent is not null ? Parent.IdFormat : + _parentSpanId is not null ? ActivityIdFormat.W3C : + _parentId is null ? DefaultIdFormat : IsW3CId(_parentId) ? ActivityIdFormat.W3C : ActivityIdFormat.Hierarchical; } @@ -609,7 +609,7 @@ public Activity Start() /// public void Stop() { - if (Id == null) + if (Id is null) { NotifyError(new InvalidOperationException(SR.ActivityNotStarted)); return; @@ -649,10 +649,10 @@ public string? TraceStateString { get { - for (Activity? activity = this; activity != null; activity = activity.Parent) + for (Activity? activity = this; activity is not null; activity = activity.Parent) { string? val = activity._traceState; - if (val != null) + if (val is not null) return val; } return null; @@ -676,7 +676,7 @@ public ActivitySpanId SpanId { if (_spanId is null) { - if (_id != null && IdFormat == ActivityIdFormat.W3C) + if (_id is not null && IdFormat == ActivityIdFormat.W3C) { ActivitySpanId activitySpanId = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16)); string spanId = activitySpanId.ToHexString(); @@ -749,7 +749,7 @@ public ActivitySpanId ParentSpanId if (_parentSpanId is null) { string? parentSpanId = null; - if (_parentId != null && IsW3CId(_parentId)) + if (_parentId is not null && IsW3CId(_parentId)) { try { @@ -757,12 +757,12 @@ public ActivitySpanId ParentSpanId } catch { } } - else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) + else if (Parent is not null && Parent.IdFormat == ActivityIdFormat.W3C) { parentSpanId = Parent.SpanId.ToHexString(); } - if (parentSpanId != null) + if (parentSpanId is not null) { Interlocked.CompareExchange(ref _parentSpanId, parentSpanId, null); } @@ -805,7 +805,7 @@ public static ActivityIdFormat DefaultIdFormat /// public Activity SetIdFormat(ActivityIdFormat format) { - if (_id != null || _spanId != null) + if (_id is not null || _spanId is not null) { NotifyError(new InvalidOperationException(SR.SetFormatOnStartedActivity)); } @@ -892,14 +892,14 @@ protected virtual void Dispose(bool disposing) /// The object to attach and map to the property name. public void SetCustomProperty(string propertyName, object? propertyValue) { - if (_customProperties == null) + if (_customProperties is null) { Interlocked.CompareExchange(ref _customProperties, new Dictionary(), null); } lock (_customProperties) { - if (propertyValue == null) + if (propertyValue is null) { _customProperties.Remove(propertyName); } @@ -919,7 +919,7 @@ public void SetCustomProperty(string propertyName, object? propertyValue) { // We don't check null name here as the dictionary is performing this check anyway. - if (_customProperties == null) + if (_customProperties is null) { return null; } @@ -942,7 +942,7 @@ internal static Activity CreateAndStart(ActivitySource source, string name, Acti activity.Source = source; activity.Kind = kind; - if (parentId != null) + if (parentId is not null) { activity._parentId = parentId; } @@ -961,7 +961,7 @@ internal static Activity CreateAndStart(ActivitySource source, string name, Acti else { Activity? parent = Current; - if (parent != null) + if (parent is not null) { // The parent change should not form a loop. We are actually guaranteed this because // 1. Un-started activities can't be 'Current' (thus can't be 'parent'), we throw if you try. @@ -972,9 +972,9 @@ internal static Activity CreateAndStart(ActivitySource source, string name, Acti activity.IdFormat = ForceDefaultIdFormat ? DefaultIdFormat : - activity.Parent != null ? activity.Parent.IdFormat : - activity._parentSpanId != null ? ActivityIdFormat.W3C : - activity._parentId == null ? DefaultIdFormat : + activity.Parent is not null ? activity.Parent.IdFormat : + activity._parentSpanId is not null ? ActivityIdFormat.W3C : + activity._parentId is null ? DefaultIdFormat : IsW3CId(activity._parentId) ? ActivityIdFormat.W3C : ActivityIdFormat.Hierarchical; @@ -983,7 +983,7 @@ internal static Activity CreateAndStart(ActivitySource source, string name, Acti else activity._id = activity.GenerateHierarchicalId(); - if (links != null) + if (links is not null) { using (IEnumerator enumerator = links.GetEnumerator()) { @@ -994,7 +994,7 @@ internal static Activity CreateAndStart(ActivitySource source, string name, Acti } } - if (tags != null) + if (tags is not null) { using (IEnumerator> enumerator = tags.GetEnumerator()) { @@ -1005,9 +1005,9 @@ internal static Activity CreateAndStart(ActivitySource source, string name, Acti } } - if (samplerTags != null) + if (samplerTags is not null) { - if (activity._tags == null) + if (activity._tags is null) { activity._tags = new TagsLinkedList(samplerTags!); } @@ -1078,13 +1078,13 @@ private string GenerateHierarchicalId() { // Called from .Start() string ret; - if (Parent != null) + if (Parent is not null) { // Normal start within the process Debug.Assert(!string.IsNullOrEmpty(Parent.Id)); ret = AppendSuffix(Parent.Id, Interlocked.Increment(ref Parent._currentChildId).ToString(), '.'); } - else if (ParentId != null) + else if (ParentId is not null) { // Start from outside the process (e.g. incoming HTTP) Debug.Assert(ParentId.Length != 0); @@ -1165,7 +1165,7 @@ private static unsafe long GetRandomNumber() private static bool ValidateSetCurrent(Activity? activity) { - bool canSet = activity == null || (activity.Id != null && !activity.IsFinished); + bool canSet = activity is null || (activity.Id is not null && !activity.IsFinished); if (!canSet) { NotifyError(new InvalidOperationException(SR.ActivityNotRunning)); @@ -1181,11 +1181,11 @@ private bool TrySetTraceIdFromParent() { Debug.Assert(_traceId is null); - if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) + if (Parent is not null && Parent.IdFormat == ActivityIdFormat.W3C) { _traceId = Parent.TraceId.ToHexString(); } - else if (_parentId != null && IsW3CId(_parentId)) + else if (_parentId is not null && IsW3CId(_parentId)) { try { @@ -1196,7 +1196,7 @@ private bool TrySetTraceIdFromParent() } } - return _traceId != null; + return _traceId is not null; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS @@ -1208,11 +1208,11 @@ private void TrySetTraceFlagsFromParent() if (!W3CIdFlagsSet) { - if (Parent != null) + if (Parent is not null) { ActivityTraceFlags = Parent.ActivityTraceFlags; } - else if (_parentId != null && IsW3CId(_parentId)) + else if (_parentId is not null && IsW3CId(_parentId)) { if (HexConverter.IsHexLowerChar(_parentId[53]) && HexConverter.IsHexLowerChar(_parentId[54])) { @@ -1317,7 +1317,7 @@ private class TagsLinkedList : IEnumerable> private LinkedListNode>? _first; private LinkedListNode>? _last; - public TagsLinkedList(KeyValuePair firstValue, bool set = false) => _last = _first = ((set && firstValue.Value == null) ? null : new LinkedListNode>(firstValue)); + public TagsLinkedList(KeyValuePair firstValue, bool set = false) => _last = _first = ((set && firstValue.Value is null) ? null : new LinkedListNode>(firstValue)); public TagsLinkedList(IEnumerator> e) { @@ -1341,7 +1341,7 @@ public void Add(IEnumerable> list) return; } - if (_first == null) + if (_first is null) { _last = _first = new LinkedListNode>(e.Current); } @@ -1364,13 +1364,13 @@ public void Add(KeyValuePair value) lock (this) { - if (_first == null) + if (_first is null) { _first = _last = newNode; return; } - Debug.Assert(_last != null); + Debug.Assert(_last is not null); _last!.Next = newNode; _last = newNode; @@ -1379,7 +1379,7 @@ public void Add(KeyValuePair value) public void Remove(string key) { - if (_first == null) + if (_first is null) { return; } @@ -1394,7 +1394,7 @@ public void Remove(string key) LinkedListNode> previous = _first; - while (previous.Next != null) + while (previous.Next is not null) { if (previous.Next.Value.Key == key) { @@ -1408,7 +1408,7 @@ public void Remove(string key) public void Set(KeyValuePair value) { - if (value.Value == null) + if (value.Value is null) { Remove(value.Key); return; @@ -1417,7 +1417,7 @@ public void Set(KeyValuePair value) lock (this) { LinkedListNode>? current = _first; - while (current != null) + while (current is not null) { if (current.Value.Key == value.Key) { @@ -1429,13 +1429,13 @@ public void Set(KeyValuePair value) } LinkedListNode> newNode = new LinkedListNode>(value); - if (_first == null) + if (_first is null) { _first = _last = newNode; return; } - Debug.Assert(_last != null); + Debug.Assert(_last is not null); _last!.Next = newNode; _last = newNode; @@ -1451,9 +1451,9 @@ public void Set(KeyValuePair value) { LinkedListNode>? current = _first; - while (current != null) + while (current is not null) { - if (current.Value.Value is string || current.Value.Value == null) + if (current.Value.Value is string || current.Value.Value is null) { yield return new KeyValuePair(current.Value.Key, (string?)current.Value.Value); } @@ -1481,7 +1481,7 @@ public Enumerator(LinkedListNode? head) public bool MoveNext() { - if (_nextNode == null) + if (_nextNode is null) { _currentItem = default; return false; diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs index 0522cbfb7dce89..062f3a85dc789f 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs @@ -67,7 +67,7 @@ public ActivityContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityT /// The ActivityContext object created from the parsing operation. public static bool TryParse(string traceParent, string? traceState, out ActivityContext context) { - if (traceParent == null) + if (traceParent is null) { throw new ArgumentNullException(nameof(traceParent)); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.netfx.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.netfx.cs index 610c35f3a5605b..39ad9c6067e15b 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.netfx.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.netfx.cs @@ -21,7 +21,7 @@ public override int GetHashCode() hash = ((hash << 5) + hash) + TraceId.GetHashCode(); hash = ((hash << 5) + hash) + SpanId.GetHashCode(); hash = ((hash << 5) + hash) + (int) TraceFlags; - hash = ((hash << 5) + hash) + (TraceState == null ? 0 : TraceState.GetHashCode()); + hash = ((hash << 5) + hash) + (TraceState is null ? 0 : TraceState.GetHashCode()); return hash; } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityCreationOptions.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityCreationOptions.cs index a57854261f41d1..ebb43739279f84 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityCreationOptions.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityCreationOptions.cs @@ -38,7 +38,7 @@ internal ActivityCreationOptions(ActivitySource source, string name, T parent, A { _context = ac; } - else if (parent is string p && p != null) + else if (parent is string p && p is not null) { // We don't care about the return value. we care if _context is initialized accordingly. ActivityContext.TryParse(p, null, out _context); @@ -86,7 +86,7 @@ public ActivityTagsCollection SamplingTags #endif get { - if (_samplerTags == null) + if (_samplerTags is null) { // Because the struct is readonly, we cannot directly assign _samplerTags. We have to workaround it by calling Unsafe.AsRef Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection(); diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netcoreapp.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netcoreapp.cs index 513b89da99f525..9be6d627d581f1 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netcoreapp.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netcoreapp.cs @@ -17,7 +17,7 @@ public override int GetHashCode() { HashCode hashCode = default; hashCode.Add(Context); - if (Tags != null) + if (Tags is not null) { foreach (KeyValuePair kvp in Tags) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netfx.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netfx.cs index 93501800ed9d80..681a90ede2ce0a 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netfx.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityLink.netfx.cs @@ -23,12 +23,12 @@ public override int GetHashCode() // the hashing manually. int hash = 5381; hash = ((hash << 5) + hash) + this.Context.GetHashCode(); - if (Tags != null) + if (Tags is not null) { foreach (KeyValuePair kvp in Tags) { hash = ((hash << 5) + hash) + kvp.Key.GetHashCode(); - if (kvp.Value != null) + if (kvp.Value is not null) { hash = ((hash << 5) + hash) + kvp.Value.GetHashCode(); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs index 781e9ddca63d66..f6be7bc9a8d41d 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs @@ -19,7 +19,7 @@ public sealed class ActivitySource : IDisposable /// The version of the component publishing the tracing info. public ActivitySource(string name, string? version = "") { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -34,7 +34,7 @@ public ActivitySource(string name, string? version = "") s_allListeners.EnumWithAction((listener, source) => { Func? shouldListenTo = listener.ShouldListenTo; - if (shouldListenTo != null) + if (shouldListenTo is not null) { var activitySource = (ActivitySource)source; if (shouldListenTo(activitySource)) @@ -67,7 +67,7 @@ public ActivitySource(string name, string? version = "") public bool HasListeners() { SynchronizedList? listeners = _listeners; - return listeners != null && listeners.Count > 0; + return listeners is not null && listeners.Count > 0; } /// @@ -109,7 +109,7 @@ public bool HasListeners() { // _listeners can get assigned to null in Dispose. SynchronizedList? listeners = _listeners; - if (listeners == null || listeners.Count == 0) + if (listeners is null || listeners.Count == 0) { return null; } @@ -119,14 +119,14 @@ public bool HasListeners() ActivitySamplingResult samplingResult = ActivitySamplingResult.None; - if (parentId != null) + if (parentId is not null) { var aco = new ActivityCreationOptions(this, name, parentId, kind, tags, links); var acoContext = new ActivityCreationOptions(this, name, aco.GetContext(), kind, tags, links); listeners.EnumWithFunc((ActivityListener listener, ref ActivityCreationOptions data, ref ActivitySamplingResult result, ref ActivityCreationOptions dataWithContext) => { SampleActivity? sampleUsingParentId = listener.SampleUsingParentId; - if (sampleUsingParentId != null) + if (sampleUsingParentId is not null) { ActivitySamplingResult sr = sampleUsingParentId(ref data); if (sr > result) @@ -141,7 +141,7 @@ public bool HasListeners() // - Can convert the parent Id to a Context. ActivityCreationOptions.TraceId != default means parent id converted to a valid context. // Then we can call the listener Sample callback with the constructed context. SampleActivity? sample = listener.Sample; - if (sample != null && data.GetContext() != default) // data.GetContext() != default means parent Id parsed correctly to a context + if (sample is not null && data.GetContext() != default) // data.GetContext() != default means parent Id parsed correctly to a context { ActivitySamplingResult sr = sample(ref dataWithContext); if (sr > result) @@ -160,9 +160,9 @@ public bool HasListeners() samplerTags = aco.GetSamplingTags(); ActivityTagsCollection? atc = acoContext.GetSamplingTags(); - if (atc != null) + if (atc is not null) { - if (samplerTags == null) + if (samplerTags is null) { samplerTags = atc; } @@ -177,11 +177,11 @@ public bool HasListeners() } else { - bool useCurrentActivityContext = context == default && Activity.Current != null; + bool useCurrentActivityContext = context == default && Activity.Current is not null; var aco = new ActivityCreationOptions(this, name, useCurrentActivityContext ? Activity.Current!.Context : context, kind, tags, links); listeners.EnumWithFunc((ActivityListener listener, ref ActivityCreationOptions data, ref ActivitySamplingResult result, ref ActivityCreationOptions unused) => { SampleActivity? sample = listener.Sample; - if (sample != null) + if (sample is not null) { ActivitySamplingResult dr = sample(ref data); if (dr > result) @@ -226,7 +226,7 @@ public void Dispose() /// The object to use for listeneing to the events. public static void AddActivityListener(ActivityListener listener) { - if (listener == null) + if (listener is null) { throw new ArgumentNullException(nameof(listener)); } @@ -235,7 +235,7 @@ public static void AddActivityListener(ActivityListener listener) { s_activeSources.EnumWithAction((source, obj) => { var shouldListenTo = ((ActivityListener)obj).ShouldListenTo; - if (shouldListenTo != null && shouldListenTo(source)) + if (shouldListenTo is not null && shouldListenTo(source)) { source.AddListener((ActivityListener)obj); } @@ -247,7 +247,7 @@ public static void AddActivityListener(ActivityListener listener) internal void AddListener(ActivityListener listener) { - if (_listeners == null) + if (_listeners is null) { Interlocked.CompareExchange(ref _listeners, new SynchronizedList(), null); } @@ -263,11 +263,11 @@ internal static void DetachListener(ActivityListener listener) internal void NotifyActivityStart(Activity activity) { - Debug.Assert(activity != null); + Debug.Assert(activity is not null); // _listeners can get assigned to null in Dispose. SynchronizedList? listeners = _listeners; - if (listeners != null && listeners.Count > 0) + if (listeners is not null && listeners.Count > 0) { listeners.EnumWithAction((listener, obj) => listener.ActivityStarted?.Invoke((Activity) obj), activity); } @@ -275,11 +275,11 @@ internal void NotifyActivityStart(Activity activity) internal void NotifyActivityStop(Activity activity) { - Debug.Assert(activity != null); + Debug.Assert(activity is not null); // _listeners can get assigned to null in Dispose. SynchronizedList? listeners = _listeners; - if (listeners != null && listeners.Count > 0) + if (listeners is not null && listeners.Count > 0) { listeners.EnumWithAction((listener, obj) => listener.ActivityStopped?.Invoke((Activity) obj), activity); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs index 55accdb5ed463b..7eff84d89fb781 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs @@ -36,14 +36,14 @@ public ActivityTagsCollection() /// Initial list to store in the collection. public ActivityTagsCollection(IEnumerable> list) { - if (list == null) + if (list is null) { throw new ArgumentNullException(nameof(list)); } foreach (KeyValuePair kvp in list) { - if (kvp.Key != null) + if (kvp.Key is not null) { this[kvp.Key] = kvp.Value; } @@ -68,13 +68,13 @@ public object? this[string key] set { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } int index = FindIndex(key); - if (value == null) + if (value is null) { if (index >= 0) { @@ -144,7 +144,7 @@ public ICollection Values /// The tag value. public void Add(string key, object? value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -164,7 +164,7 @@ public void Add(string key, object? value) /// Key and value pair of the tag to add to the collection. public void Add(KeyValuePair item) { - if (item.Key == null) + if (item.Key is null) { throw new ArgumentNullException(nameof(item)); } @@ -221,7 +221,7 @@ public void Add(KeyValuePair item) /// True if the item existed and removed. False otherwise. public bool Remove(string key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticListener.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticListener.cs index 99e7f138c6d5c9..94b999f601106a 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticListener.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticListener.cs @@ -39,7 +39,7 @@ public static IObservable AllListeners GC.KeepAlive(HttpHandlerDiagnosticListener.s_instance); #endif - if (s_allListenerObservable == null) + if (s_allListenerObservable is null) { s_allListenerObservable = new AllListenerObservable(); } @@ -65,7 +65,7 @@ public static IObservable AllListeners public virtual IDisposable Subscribe(IObserver> observer, Predicate? isEnabled) { IDisposable subscription; - if (isEnabled == null) + if (isEnabled is null) { subscription = SubscribeInternal(observer, null, null, null, null); } @@ -108,7 +108,7 @@ public virtual IDisposable Subscribe(IObserver> ob /// public virtual IDisposable Subscribe(IObserver> observer, Func? isEnabled) { - return isEnabled == null ? + return isEnabled is null ? SubscribeInternal(observer, null, null, null, null) : SubscribeInternal(observer, name => IsEnabled(name, null, null), isEnabled, null, null); } @@ -137,7 +137,7 @@ public DiagnosticListener(string name) { // Issue the callback for this new diagnostic listener. var allListenerObservable = s_allListenerObservable; - if (allListenerObservable != null) + if (allListenerObservable is not null) allListenerObservable.OnNewDiagnosticListener(this); // And add it to the list of all past listeners. @@ -171,7 +171,7 @@ public virtual void Dispose() else { var cur = s_allListeners; - while (cur != null) + while (cur is not null) { if (cur._next == this) { @@ -187,7 +187,7 @@ public virtual void Dispose() // Indicate completion to all subscribers. DiagnosticSubscription? subscriber = null; Interlocked.Exchange(ref subscriber, _subscriptions); - while (subscriber != null) + while (subscriber is not null) { subscriber.Observer.OnCompleted(); subscriber = subscriber.Next; @@ -222,7 +222,7 @@ public override string ToString() /// to ensure somebody listens to the DiagnosticListener at all. public bool IsEnabled() { - return _subscriptions != null; + return _subscriptions is not null; } /// @@ -230,9 +230,9 @@ public bool IsEnabled() /// public override bool IsEnabled(string name) { - for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) + for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription is not null; curSubscription = curSubscription.Next) { - if (curSubscription.IsEnabled1Arg == null || curSubscription.IsEnabled1Arg(name)) + if (curSubscription.IsEnabled1Arg is null || curSubscription.IsEnabled1Arg(name)) return true; } return false; @@ -244,9 +244,9 @@ public override bool IsEnabled(string name) /// public override bool IsEnabled(string name, object? arg1, object? arg2 = null) { - for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) + for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription is not null; curSubscription = curSubscription.Next) { - if (curSubscription.IsEnabled3Arg == null || curSubscription.IsEnabled3Arg(name, arg1, arg2)) + if (curSubscription.IsEnabled3Arg is null || curSubscription.IsEnabled3Arg(name, arg1, arg2)) return true; } return false; @@ -257,7 +257,7 @@ public override bool IsEnabled(string name, object? arg1, object? arg2 = null) /// public override void Write(string name, object? value) { - for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) + for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription is not null; curSubscription = curSubscription.Next) curSubscription.Observer.OnNext(new KeyValuePair(name, value)); } @@ -306,7 +306,7 @@ public void Dispose() { #if DEBUG var cur = newSubscriptions; - while (cur != null) + while (cur is not null) { Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled1Arg == IsEnabled1Arg && cur.IsEnabled3Arg == IsEnabled3Arg), "Did not remove subscription!"); cur = cur.Next; @@ -320,7 +320,7 @@ public void Dispose() // Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'. private static DiagnosticSubscription? Remove(DiagnosticSubscription? subscriptions, DiagnosticSubscription subscription) { - if (subscriptions == null) + if (subscriptions is null) { // May happen if the IDisposable returned from Subscribe is Dispose'd again return null; @@ -352,7 +352,7 @@ public IDisposable Subscribe(IObserver observer) lock (s_allListenersLock) { // Call back for each existing listener on the new callback (catch-up). - for (DiagnosticListener? cur = s_allListeners; cur != null; cur = cur._next) + for (DiagnosticListener? cur = s_allListeners; cur is not null; cur = cur._next) observer.OnNext(cur); // Add the observer to the list of subscribers. @@ -370,7 +370,7 @@ internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener) Debug.Assert(Monitor.IsEntered(s_allListenersLock)); // We should only be called when we hold this lock // Simply send a callback to every subscriber that we have a new listener - for (var cur = _subscriptions; cur != null; cur = cur.Next) + for (var cur = _subscriptions; cur is not null; cur = cur.Next) cur.Subscriber.OnNext(diagnosticListener); } @@ -388,9 +388,9 @@ private bool Remove(AllListenerSubscription subscription) _subscriptions = subscription.Next; return true; } - else if (_subscriptions != null) + else if (_subscriptions is not null) { - for (var cur = _subscriptions; cur.Next != null; cur = cur.Next) + for (var cur = _subscriptions; cur.Next is not null; cur = cur.Next) { if (cur.Next == subscription) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceActivity.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceActivity.cs index 549c4a8274cb20..fc2481c7e5a095 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceActivity.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceActivity.cs @@ -108,13 +108,13 @@ public partial class DiagnosticListener { public override void OnActivityImport(Activity activity, object? payload) { - for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) + for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription is not null; curSubscription = curSubscription.Next) curSubscription.OnActivityImport?.Invoke(activity, payload); } public override void OnActivityExport(Activity activity, object? payload) { - for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next) + for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription is not null; curSubscription = curSubscription.Next) curSubscription.OnActivityExport?.Invoke(activity, payload); } @@ -128,7 +128,7 @@ public override void OnActivityExport(Activity activity, object? payload) public virtual IDisposable Subscribe(IObserver> observer, Func? isEnabled, Action? onActivityImport = null, Action? onActivityExport = null) { - return isEnabled == null ? + return isEnabled is null ? SubscribeInternal(observer, null, null, onActivityImport, onActivityExport) : SubscribeInternal(observer, name => IsEnabled(name, null, null), isEnabled, onActivityImport, onActivityExport); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs index b38829b6ad0cb7..b40f819c52655f 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs @@ -424,7 +424,7 @@ protected override void OnEventCommand(EventCommandEventArgs command) // trivial helper to allow you to join two strings the first of which can be null. private static string NewLineSeparate(string? str1, string str2) { - Debug.Assert(str2 != null); + Debug.Assert(str2 is not null); if (string.IsNullOrEmpty(str1)) return str2; return str1 + "\n" + str2; @@ -492,7 +492,7 @@ internal class FilterAndTransform public static void CreateFilterAndTransformList(ref FilterAndTransform? specList, string? filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) { DestroyFilterAndTransformList(ref specList, eventSource); // Stop anything that was on before. - if (filterAndPayloadSpecs == null) + if (filterAndPayloadSpecs is null) filterAndPayloadSpecs = ""; // Points just beyond the last point in the string that has yet to be parsed. Thus we start with the whole string. @@ -528,7 +528,7 @@ public static void CreateFilterAndTransformList(ref FilterAndTransform? specList break; } #if EVENTSOURCE_ACTIVITY_SUPPORT - if (eventSource._activitySourceSpecs != null) + if (eventSource._activitySourceSpecs is not null) { NormalizeActivitySourceSpecsList(eventSource); CreateActivityListener(eventSource); @@ -551,7 +551,7 @@ public static void DestroyFilterAndTransformList(ref FilterAndTransform? specLis var curSpec = specList; specList = null; // Null out the list - while (curSpec != null) // Dispose everything in the list. + while (curSpec is not null) // Dispose everything in the list. { curSpec.Dispose(); curSpec = curSpec.Next; @@ -565,7 +565,7 @@ public static void DestroyFilterAndTransformList(ref FilterAndTransform? specLis /// public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform? next) { - Debug.Assert(filterAndPayloadSpec != null && startIdx >= 0 && startIdx <= endIdx && endIdx <= filterAndPayloadSpec.Length); + Debug.Assert(filterAndPayloadSpec is not null && startIdx >= 0 && startIdx <= endIdx && endIdx <= filterAndPayloadSpec.Length); Next = next; _eventSource = eventSource; @@ -639,7 +639,7 @@ public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, } Action>>? writeEvent = null; - if (activityName != null && activityName.Contains("Activity")) + if (activityName is not null && activityName.Contains("Activity")) { #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT writeEvent = activityName switch @@ -654,11 +654,11 @@ public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, }; #endif - if (writeEvent == null) + if (writeEvent is null) _eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + activityName); } - if (writeEvent == null) + if (writeEvent is null) { #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT writeEvent = _eventSource.Event; @@ -674,18 +674,18 @@ public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, // to the EventSource. _diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver(delegate (DiagnosticListener newListener) { - if (listenerNameFilter == null || listenerNameFilter == newListener.Name) + if (listenerNameFilter is null || listenerNameFilter == newListener.Name) { _eventSource.NewDiagnosticListener(newListener.Name); Predicate? eventNameFilterPredicate = null; - if (eventNameFilter != null) + if (eventNameFilter is not null) eventNameFilterPredicate = (string eventName) => eventNameFilter == eventName; var subscription = newListener.Subscribe(new CallbackObserver>(delegate (KeyValuePair evnt) { // The filter given to the DiagnosticSource may not work if users don't is 'IsEnabled' as expected. // Thus we look for any events that may have snuck through and filter them out before forwarding. - if (eventNameFilter != null && eventNameFilter != evnt.Key) + if (eventNameFilter is not null && eventNameFilter != evnt.Key) return; var outputArgs = this.Morph(evnt.Value); @@ -847,9 +847,9 @@ private static ActivitySamplingResult Sample(string activitySourceName, string a ActivitySamplingResult specificResult = ActivitySamplingResult.None; ActivitySamplingResult wildResult = ActivitySamplingResult.None; - while (list != null) + while (list is not null) { - if (list.ActivityName == null || list.ActivityName == activityName) + if (list.ActivityName is null || list.ActivityName == activityName) { if (activitySourceName == list.SourceName) { @@ -888,8 +888,8 @@ private static ActivitySamplingResult Sample(string activitySourceName, string a internal static void CreateActivityListener(DiagnosticSourceEventSource eventSource) { - Debug.Assert(eventSource._activityListener == null); - Debug.Assert(eventSource._activitySourceSpecs != null); + Debug.Assert(eventSource._activityListener is null); + Debug.Assert(eventSource._activitySourceSpecs is not null); eventSource._activityListener = new ActivityListener(); @@ -899,7 +899,7 @@ internal static void CreateActivityListener(DiagnosticSourceEventSource eventSou eventSource._activityListener.ShouldListenTo = (activitySource) => { FilterAndTransform? list = eventSource._activitySourceSpecs; - while (list != null) + while (list is not null) { if (activitySource.Name == list.SourceName || list.SourceName == "*") { @@ -915,11 +915,11 @@ internal static void CreateActivityListener(DiagnosticSourceEventSource eventSou eventSource._activityListener.ActivityStarted = activity => { FilterAndTransform? list = eventSource._activitySourceSpecs; - while (list != null) + while (list is not null) { if ((list.Events & ActivityEvents.ActivityStart) != 0 && (activity.Source.Name == list.SourceName || list.SourceName == "*") && - (list.ActivityName == null || list.ActivityName == activity.OperationName)) + (list.ActivityName is null || list.ActivityName == activity.OperationName)) { eventSource.ActivityStart(activity.Source.Name, activity.OperationName, list.Morph(activity)); return; @@ -932,11 +932,11 @@ internal static void CreateActivityListener(DiagnosticSourceEventSource eventSou eventSource._activityListener.ActivityStopped = activity => { FilterAndTransform? list = eventSource._activitySourceSpecs; - while (list != null) + while (list is not null) { if ((list.Events & ActivityEvents.ActivityStop) != 0 && (activity.Source.Name == list.SourceName || list.SourceName == "*") && - (list.ActivityName == null || list.ActivityName == activity.OperationName)) + (list.ActivityName is null || list.ActivityName == activity.OperationName)) { eventSource.ActivityStop(activity.Source.Name, activity.OperationName, list.Morph(activity)); return; @@ -953,8 +953,8 @@ internal static void CreateActivityListener(DiagnosticSourceEventSource eventSou // This will give more priority to the specific nodes over the wildcards. internal static void NormalizeActivitySourceSpecsList(DiagnosticSourceEventSource eventSource) { - Debug.Assert(eventSource._activityListener == null); - Debug.Assert(eventSource._activitySourceSpecs != null); + Debug.Assert(eventSource._activityListener is null); + Debug.Assert(eventSource._activitySourceSpecs is not null); FilterAndTransform? list = eventSource._activitySourceSpecs; @@ -964,30 +964,30 @@ internal static void NormalizeActivitySourceSpecsList(DiagnosticSourceEventSourc FilterAndTransform? firstWildcardList = null; FilterAndTransform? lastWildcardList = null; - while (list != null) + while (list is not null) { if (list.SourceName == "*") { - if (firstWildcardList == null) + if (firstWildcardList is null) { firstWildcardList = lastWildcardList = list; } else { - Debug.Assert(lastWildcardList != null); + Debug.Assert(lastWildcardList is not null); lastWildcardList.Next = list; lastWildcardList = list; } } else { - if (firstSpecificList == null) + if (firstSpecificList is null) { firstSpecificList = lastSpecificList = list; } else { - Debug.Assert(lastSpecificList != null); + Debug.Assert(lastSpecificList is not null); lastSpecificList.Next = list; lastSpecificList = list; } @@ -996,13 +996,13 @@ internal static void NormalizeActivitySourceSpecsList(DiagnosticSourceEventSourc list = list.Next; } - if (firstSpecificList == null || firstWildcardList == null) + if (firstSpecificList is null || firstWildcardList is null) { - Debug.Assert(firstSpecificList != null || firstWildcardList != null); + Debug.Assert(firstSpecificList is not null || firstWildcardList is not null); return; // list shouldn't be chanaged. } - Debug.Assert(lastWildcardList != null && lastSpecificList != null); + Debug.Assert(lastWildcardList is not null && lastSpecificList is not null); lastSpecificList.Next = firstWildcardList; lastWildcardList.Next = null; @@ -1013,17 +1013,17 @@ internal static void NormalizeActivitySourceSpecsList(DiagnosticSourceEventSourc private void Dispose() { - if (_diagnosticsListenersSubscription != null) + if (_diagnosticsListenersSubscription is not null) { _diagnosticsListenersSubscription.Dispose(); _diagnosticsListenersSubscription = null; } - if (_liveSubscriptions != null) + if (_liveSubscriptions is not null) { Subscriptions? subscr = _liveSubscriptions; _liveSubscriptions = null; - while (subscr != null) + while (subscr is not null) { subscr.Subscription.Dispose(); subscr = subscr.Next; @@ -1035,7 +1035,7 @@ private void Dispose() { // Transform the args into a bag of key-value strings. var outputArgs = new List>(); - if (args != null) + if (args is not null) { if (!_noImplicitTransforms) { @@ -1045,11 +1045,11 @@ private void Dispose() // First check the one-element cache _firstImplicitTransformsEntry ImplicitTransformEntry? cacheEntry = _firstImplicitTransformsEntry; - if (cacheEntry != null && cacheEntry.Type == argType) + if (cacheEntry is not null && cacheEntry.Type == argType) { implicitTransforms = cacheEntry.Transforms; // Yeah we hit the cache. } - else if (cacheEntry == null) + else if (cacheEntry is null) { // _firstImplicitTransformsEntry is empty, we should fill it. // Note that it is OK that two threads may race and both call MakeImplicitTransforms on their own @@ -1064,7 +1064,7 @@ private void Dispose() // In that case you will probably need many types // Note currently we don't limit the cache size, but it is limited by the number of // distinct types of objects passed to DiagnosticSource.Write. - if (_implicitTransformsTable == null) + if (_implicitTransformsTable is null) { Interlocked.CompareExchange(ref _implicitTransformsTable, new ConcurrentDictionary(1, 8), null); @@ -1073,19 +1073,19 @@ private void Dispose() } // implicitTransformas now fetched from cache or constructed, use it to Fetch all the implicit fields. - if (implicitTransforms != null) + if (implicitTransforms is not null) { - for (TransformSpec? serializableArg = implicitTransforms; serializableArg != null; serializableArg = serializableArg.Next) + for (TransformSpec? serializableArg = implicitTransforms; serializableArg is not null; serializableArg = serializableArg.Next) outputArgs.Add(serializableArg.Morph(args)); } } - if (_explicitTransforms != null) + if (_explicitTransforms is not null) { - for (TransformSpec? explicitTransform = _explicitTransforms; explicitTransform != null; explicitTransform = explicitTransform.Next) + for (TransformSpec? explicitTransform = _explicitTransforms; explicitTransform is not null; explicitTransform = explicitTransform.Next) { var keyValue = explicitTransform.Morph(args); - if (keyValue.Value != null) + if (keyValue.Value is not null) outputArgs.Add(keyValue); } } @@ -1116,7 +1116,7 @@ private void Dispose() foreach (PropertyInfo property in curTypeInfo.DeclaredProperties) { // prevent TransformSpec from attempting to implicitly transform index properties - if (property.GetMethod == null || property.GetMethod!.GetParameters().Length > 0) + if (property.GetMethod is null || property.GetMethod!.GetParameters().Length > 0) continue; newSerializableArgs = new TransformSpec(property.Name, 0, property.Name.Length, newSerializableArgs); } @@ -1127,7 +1127,7 @@ private void Dispose() private static TransformSpec? Reverse(TransformSpec? list) { TransformSpec? ret = null; - while (list != null) + while (list is not null) { var next = list.Next; list.Next = ret; @@ -1168,7 +1168,7 @@ internal class TransformSpec /// public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSpec? next = null) { - Debug.Assert(transformSpec != null && startIdx >= 0 && startIdx < endIdx && endIdx <= transformSpec.Length); + Debug.Assert(transformSpec is not null && startIdx >= 0 && startIdx < endIdx && endIdx <= transformSpec.Length); Next = next; // Pick off the Var= @@ -1191,7 +1191,7 @@ public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSp _fetches = new PropertySpec(propertName, _fetches); // If the user did not explicitly set a name, it is the last one (first to be processed from the end). - if (_outputName == null) + if (_outputName is null) _outputName = propertName; endIdx = dotIdx; // This works even when LastIndexOf return -1. @@ -1205,9 +1205,9 @@ public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSp /// public KeyValuePair Morph(object? obj) { - for (PropertySpec? cur = _fetches; cur != null; cur = cur.Next) + for (PropertySpec? cur = _fetches; cur is not null; cur = cur.Next) { - if (obj != null || cur.IsStatic) + if (obj is not null || cur.IsStatic) obj = cur.Fetch(obj); } @@ -1256,9 +1256,9 @@ public PropertySpec(string propertyName, PropertySpec? next) public object? Fetch(object? obj) { PropertyFetch? fetch = _fetchForExpectedType; - Debug.Assert(obj != null || IsStatic); + Debug.Assert(obj is not null || IsStatic); Type? objType = obj?.GetType(); - if (fetch == null || fetch.Type != objType) + if (fetch is null || fetch.Type != objType) { _fetchForExpectedType = fetch = PropertyFetch.FetcherForProperty( objType, _propertyName); @@ -1298,7 +1298,7 @@ public PropertyFetch(Type? type) [DynamicDependency("#ctor(System.Type,System.Reflection.PropertyInfo)", typeof(ValueTypedFetchProperty<,>))] public static PropertyFetch FetcherForProperty(Type? type, string propertyName) { - if (propertyName == null) + if (propertyName is null) return new PropertyFetch(type); // returns null on any fetch. if (propertyName == CurrentActivityPropertyName) { @@ -1311,7 +1311,7 @@ public static PropertyFetch FetcherForProperty(Type? type, string propertyName) #endif } - Debug.Assert(type != null, "Type should only be null for the well-known static fetchers already checked"); + Debug.Assert(type is not null, "Type should only be null for the well-known static fetchers already checked"); TypeInfo typeInfo = type.GetTypeInfo(); if (propertyName == EnumeratePropertyName) { @@ -1345,7 +1345,7 @@ public static PropertyFetch FetcherForProperty(Type? type, string propertyName) else { PropertyInfo? propertyInfo = typeInfo.GetDeclaredProperty(propertyName); - if (propertyInfo == null) + if (propertyInfo is null) { Logger.Message($"Property {propertyName} not found on {type}"); return new PropertyFetch(type); diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs index de84e67c0509ec..c050574014877a 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs @@ -217,10 +217,10 @@ public override object this[object key] set { WeakReference weakRef = value as WeakReference; - if (weakRef != null && weakRef.IsAlive) + if (weakRef is not null && weakRef.IsAlive) { ServicePoint servicePoint = weakRef.Target as ServicePoint; - if (servicePoint != null) + if (servicePoint is not null) { // Replace the ConnectionGroup hashtable inside this ServicePoint object, // which allows us to intercept each new ConnectionGroup object added under @@ -520,7 +520,7 @@ public HttpWebRequestArrayList(ArrayList list) : base(list) public override int Add(object value) { HttpWebRequest request = value as HttpWebRequest; - if (request != null) + if (request is not null) { s_instance.RaiseRequestEvent(request); } @@ -531,10 +531,10 @@ public override int Add(object value) public override void RemoveAt(int index) { HttpWebRequest request = base[index] as HttpWebRequest; - if (request != null) + if (request is not null) { HttpWebResponse response = s_httpResponseAccessor(request); - if (response != null) + if (response is not null) { s_instance.RaiseResponseEvent(request, response); } @@ -548,7 +548,7 @@ public override void RemoveAt(int index) // or the internal HTTP reponse representation having status, content and headers var coreResponse = s_coreResponseAccessor(request); - if (coreResponse != null && s_coreResponseDataType.IsInstanceOfType(coreResponse)) + if (coreResponse is not null && s_coreResponseDataType.IsInstanceOfType(coreResponse)) { HttpStatusCode status = s_coreStatusCodeAccessor(coreResponse); WebHeaderCollection headers = s_coreHeadersAccessor(coreResponse); @@ -582,7 +582,7 @@ private HttpHandlerDiagnosticListener() : base(DiagnosticListenerName) private void RaiseRequestEvent(HttpWebRequest request) { - if (request.Headers.Get(RequestIdHeaderName) != null) + if (request.Headers.Get(RequestIdHeaderName) is not null) { // this request was instrumented by previous RaiseRequestEvent return; @@ -606,12 +606,12 @@ private void RaiseRequestEvent(HttpWebRequest request) { // do not inject header if it was injected already // perhaps tracing systems wants to override it - if (request.Headers.Get(TraceParentHeaderName) == null) + if (request.Headers.Get(TraceParentHeaderName) is null) { request.Headers.Add(TraceParentHeaderName, activity.Id); var traceState = activity.TraceStateString; - if (traceState != null) + if (traceState is not null) { request.Headers.Add(TraceStateHeaderName, traceState); } @@ -621,13 +621,13 @@ private void RaiseRequestEvent(HttpWebRequest request) { // do not inject header if it was injected already // perhaps tracing systems wants to override it - if (request.Headers.Get(RequestIdHeaderName) == null) + if (request.Headers.Get(RequestIdHeaderName) is null) { request.Headers.Add(RequestIdHeaderName, activity.Id); } } - if (request.Headers.Get(CorrelationContextHeaderName) == null) + if (request.Headers.Get(CorrelationContextHeaderName) is null) { // we expect baggage to be empty or contain a few items using (IEnumerator> e = activity.Baggage.GetEnumerator()) @@ -657,7 +657,7 @@ private void RaiseResponseEvent(HttpWebRequest request, HttpWebResponse response // Response event could be received several times for the same request in case it was redirected // IsLastResponse checks if response is the last one (no more redirects will happen) // based on response StatusCode and number or redirects done so far - bool wasRequestInstrumented = request.Headers.Get(TraceParentHeaderName) != null || request.Headers.Get(RequestIdHeaderName) != null; + bool wasRequestInstrumented = request.Headers.Get(TraceParentHeaderName) is not null || request.Headers.Get(RequestIdHeaderName) is not null; if (wasRequestInstrumented && IsLastResponse(request, response.StatusCode)) { // only send Stop if request was instrumented @@ -670,7 +670,7 @@ private void RaiseResponseEvent(HttpWebRequest request, HttpStatusCode statusCod // Response event could be received several times for the same request in case it was redirected // IsLastResponse checks if response is the last one (no more redirects will happen) // based on response StatusCode and number or redirects done so far - if (request.Headers.Get(RequestIdHeaderName) != null && IsLastResponse(request, statusCode)) + if (request.Headers.Get(RequestIdHeaderName) is not null && IsLastResponse(request, statusCode)) { this.Write(RequestStopExName, new { Request = request, StatusCode = statusCode, Headers = headers }); } @@ -711,22 +711,22 @@ private static void PrepareReflectionObjects() s_coreResponseAccessor = CreateFieldGetter("_CoreResponse", BindingFlags.NonPublic | BindingFlags.Instance); s_coreResponseDataType = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData"); - if (s_coreResponseDataType != null) + if (s_coreResponseDataType is not null) { s_coreStatusCodeAccessor = CreateFieldGetter(s_coreResponseDataType, "m_StatusCode", BindingFlags.Public | BindingFlags.Instance); s_coreHeadersAccessor = CreateFieldGetter(s_coreResponseDataType, "m_ResponseHeaders", BindingFlags.Public | BindingFlags.Instance); } // Double checking to make sure we have all the pieces initialized - if (s_connectionGroupListField == null || - s_connectionGroupType == null || - s_connectionListField == null || - s_connectionType == null || - s_writeListField == null || - s_httpResponseAccessor == null || - s_autoRedirectsAccessor == null || - s_coreResponseDataType == null || - s_coreStatusCodeAccessor == null || - s_coreHeadersAccessor == null) + if (s_connectionGroupListField is null || + s_connectionGroupType is null || + s_connectionListField is null || + s_connectionType is null || + s_writeListField is null || + s_httpResponseAccessor is null || + s_autoRedirectsAccessor is null || + s_coreResponseDataType is null || + s_coreStatusCodeAccessor is null || + s_coreHeadersAccessor is null) { // If anything went wrong here, just return false. There is nothing we can do. throw new InvalidOperationException("Unable to initialize all required reflection objects"); @@ -736,7 +736,7 @@ private static void PrepareReflectionObjects() private static void PerformInjection() { FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic); - if (servicePointTableField == null) + if (servicePointTableField is null) { // If anything went wrong here, just return false. There is nothing we can do. throw new InvalidOperationException("Unable to access the ServicePointTable field"); @@ -751,7 +751,7 @@ private static void PerformInjection() private static Func CreateFieldGetter(string fieldName, BindingFlags flags) where TClass : class { FieldInfo field = typeof(TClass).GetField(fieldName, flags); - if (field != null) + if (field is not null) { string methodName = field.ReflectedType.FullName + ".get_" + field.Name; DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(TClass) }, true); @@ -773,7 +773,7 @@ private static Func CreateFieldGetter(string fie private static Func CreateFieldGetter(Type classType, string fieldName, BindingFlags flags) { FieldInfo field = classType.GetField(fieldName, flags); - if (field != null) + if (field is not null) { string methodName = classType.FullName + ".get_" + field.Name; DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(object) }, true); diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/LocalAppContextSwitches.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/LocalAppContextSwitches.cs index 1da5480d9d70ef..b184b34e6d0c85 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/LocalAppContextSwitches.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/LocalAppContextSwitches.cs @@ -16,7 +16,7 @@ private static bool InitializeDefaultActivityIdFormat() if (!LocalAppContextSwitches.GetSwitchValue("System.Diagnostics.DefaultActivityIdFormatIsHierarchial", ref defaultActivityIdFormatIsHierarchial)) { string? switchValue = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_DIAGNOSTICS_DEFAULTACTIVITYIDFORMATISHIERARCHIAL"); - if (switchValue != null) + if (switchValue is not null) { defaultActivityIdFormatIsHierarchial = IsTrueStringIgnoreCase(switchValue) || switchValue.Equals("1"); } diff --git a/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Unix.cs b/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Unix.cs index bf7eb505001380..6fb86bad0e7b16 100644 --- a/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Unix.cs +++ b/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Unix.cs @@ -195,7 +195,7 @@ private static void ParseVersion(string? versionString, out int major, out int m major = minor = build = priv = 0; - if (versionString != null) + if (versionString is not null) { string[] parts = versionString.Split('.'); if (parts.Length <= 4 && parts.Length > 0) diff --git a/src/libraries/System.Diagnostics.Process/src/Microsoft/Win32/SafeHandles/SafeProcessHandle.Unix.cs b/src/libraries/System.Diagnostics.Process/src/Microsoft/Win32/SafeHandles/SafeProcessHandle.Unix.cs index 5b66e92e708baf..d341c2d3315285 100644 --- a/src/libraries/System.Diagnostics.Process/src/Microsoft/Win32/SafeHandles/SafeProcessHandle.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/Microsoft/Win32/SafeHandles/SafeProcessHandle.Unix.cs @@ -41,7 +41,7 @@ protected override bool ReleaseHandle() { if (_releaseRef) { - Debug.Assert(_handle != null); + Debug.Assert(_handle is not null); _handle.DangerousRelease(); } return true; diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/AsyncStreamReader.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/AsyncStreamReader.cs index 83640ff93c1b67..0f86e6804d5ca8 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/AsyncStreamReader.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/AsyncStreamReader.cs @@ -47,7 +47,7 @@ internal sealed class AsyncStreamReader : IDisposable // in number of 16-bit characters, is set by bufferSize. internal AsyncStreamReader(Stream stream, Action callback, Encoding encoding) { - Debug.Assert(stream != null && encoding != null && callback != null, "Invalid arguments!"); + Debug.Assert(stream is not null && encoding is not null && callback is not null, "Invalid arguments!"); Debug.Assert(stream.CanRead, "Stream must be readable!"); _stream = stream; @@ -69,7 +69,7 @@ internal void BeginReadLine() { _cancelOperation = false; - if (_sb == null) + if (_sb is null) { _sb = new StringBuilder(DefaultBufferSize); _readToBufferTask = Task.Run((Func)ReadBufferAsync); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs index 08ff0741e0e1a8..7d01ba4619c3fb 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs @@ -42,11 +42,11 @@ internal Dictionary NameTable { get { - if (_nameTable == null) + if (_nameTable is null) { lock (_nameTableLock) { - if (_nameTable == null) + if (_nameTable is null) _nameTable = GetStringTable(false); } } @@ -76,11 +76,11 @@ internal static PerformanceCounterLib GetPerformanceCounterLib(string machineNam internal byte[]? GetPerformanceData(string item) { - if (_performanceMonitor == null) + if (_performanceMonitor is null) { lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject)) { - if (_performanceMonitor == null) + if (_performanceMonitor is null) _performanceMonitor = new PerformanceMonitor(_machineName); } } @@ -117,7 +117,7 @@ private Dictionary GetStringTable(bool isHelp) else names = (string[]?)libraryKey.GetValue("Explain " + _perfLcid); - if ((names == null) || (names.Length == 0)) + if ((names is null) || (names.Length == 0)) { --waitRetries; if (waitSleep == 0) @@ -147,7 +147,7 @@ private Dictionary GetStringTable(bool isHelp) } } - if (names == null) + if (names is null) stringTable = new Dictionary(); else { @@ -156,7 +156,7 @@ private Dictionary GetStringTable(bool isHelp) for (int index = 0; index < (names.Length / 2); ++index) { string nameString = names[(index * 2) + 1]; - if (nameString == null) + if (nameString is null) nameString = string.Empty; int key; diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs index ec2e319bb80965..98e6b41aa5083d 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs @@ -14,7 +14,7 @@ public partial class Process /// public static Process[] GetProcessesByName(string? processName, string machineName) { - if (processName == null) + if (processName is null) { processName = string.Empty; } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs index 775c170da1d1ef..3d86aedf71738e 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs @@ -20,7 +20,7 @@ public partial class Process : IDisposable public static Process[] GetProcessesByName(string? processName, string machineName) { ProcessManager.ThrowIfRemoteMachine(machineName); - if (processName == null) + if (processName is null) { processName = string.Empty; } @@ -276,7 +276,7 @@ internal static string GetUntruncatedProcessName(ref Interop.procfs.ParsedStat s buffer.CopyTo(tmp); byte[]? toReturn = rentedArray; buffer = rentedArray = tmp; - if (toReturn != null) + if (toReturn is not null) { ArrayPool.Shared.Return(toReturn); } @@ -296,7 +296,7 @@ internal static string GetUntruncatedProcessName(ref Interop.procfs.ParsedStat s { // Check if argv[0] has the process name. string? name = GetUntruncatedNameFromArg(argRemainder.Slice(0, argEnd), prefix: stat.comm); - if (name != null) + if (name is not null) { return name; } @@ -324,7 +324,7 @@ internal static string GetUntruncatedProcessName(ref Interop.procfs.ParsedStat s } finally { - if (rentedArray != null) + if (rentedArray is not null) { ArrayPool.Shared.Return(rentedArray); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.NonUap.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.NonUap.cs index be09b7bb146ef0..f1711f16ca6831 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.NonUap.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.NonUap.cs @@ -23,7 +23,7 @@ public void Kill(bool entireProcessTree) List? result = KillTree(); - if (result != null && result.Count != 0) + if (result is not null && result.Count != 0) throw new AggregateException(SR.KillEntireProcessTree_TerminationIncomplete, result); } } @@ -67,7 +67,7 @@ private bool IsSelfOrDescendantOf(Process processOfInterest) /// private IReadOnlyList GetChildProcesses(Process[]? processes = null) { - bool internallyInitializedProcesses = processes == null; + bool internallyInitializedProcesses = processes is null; processes = processes ?? GetProcesses(); List childProcesses = new List(); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs index c06f622880ddd7..bd7c82649684bc 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs @@ -31,7 +31,7 @@ internal DateTime StartTimeCore EnsureState(State.HaveNonExitedId); Interop.libproc.proc_taskallinfo? info = Interop.libproc.GetProcessInfoById(Id); - if (info == null) + if (info is null) throw new Win32Exception(SR.ProcessInformationUnavailable); DateTime startTime = DateTime.UnixEpoch + TimeSpan.FromSeconds(info.Value.pbsd.pbi_start_tvsec + info.Value.pbsd.pbi_start_tvusec / (double)MicrosecondsToSecondsFactor); @@ -84,7 +84,7 @@ private int ParentProcessId EnsureState(State.HaveNonExitedId); Interop.libproc.proc_taskallinfo? info = Interop.libproc.GetProcessInfoById(Id); - if (info == null) + if (info is null) throw new Win32Exception(SR.ProcessInformationUnavailable); return Convert.ToInt32(info.Value.pbsd.pbi_ppid); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index d9ed6c43db6519..47c75169c0196d 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -145,7 +145,7 @@ private void RefreshCore() /// Additional logic invoked when the Process is closed. private void CloseCore() { - if (_waitStateHolder != null) + if (_waitStateHolder is not null) { _waitStateHolder.Dispose(); _waitStateHolder = null; @@ -173,8 +173,8 @@ private void EnsureWatchingForExit() { if (!_watchingForExit) { - Debug.Assert(_waitHandle == null); - Debug.Assert(_registeredWaitHandle == null); + Debug.Assert(_waitHandle is null); + Debug.Assert(_registeredWaitHandle is null); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try @@ -205,11 +205,11 @@ private bool WaitForExitCore(int milliseconds) if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams { - if (_output != null) + if (_output is not null) { _output.WaitUntilEOF(); } - if (_error != null) + if (_error is not null) { _error.WaitUntilEOF(); } @@ -233,7 +233,7 @@ private void UpdateHasExited() { int? exitCode; _exited = GetWaitState().GetExited(out exitCode, refresh: true); - if (_exited && exitCode != null) + if (_exited && exitCode is not null) { _exitCode = exitCode.Value; } @@ -318,7 +318,7 @@ private bool Equals(Process process) => partial void ThrowIfExited(bool refresh) { // Don't allocate a ProcessWaitState.Holder unless we're refreshing. - if (_waitStateHolder == null && !refresh) + if (_waitStateHolder is null && !refresh) { return; } @@ -403,7 +403,7 @@ private bool StartCore(ProcessStartInfo startInfo) // when exec returns ENOEXEC (file format cannot be executed). bool isExecuting = false; filename = ResolveExecutableForShellExecute(startInfo.FileName, cwd); - if (filename != null) + if (filename is not null) { argv = ParseArgv(startInfo); @@ -532,7 +532,7 @@ private bool ForkAndExecProcess( { s_processStartLock.ExitReadLock(); - if (_waitStateHolder == null && usesTerminal) + if (_waitStateHolder is null && usesTerminal) { // We failed to launch a child that could use the terminal. s_processStartLock.EnterWriteLock(); @@ -628,7 +628,7 @@ private static string[] CreateEnvp(ProcessStartInfo psi) { // The WorkingDirectory property specifies the location of the executable. // If WorkingDirectory is an empty string, the current directory is understood to contain the executable. - workingDirectory = workingDirectory != null ? Path.GetFullPath(workingDirectory) : + workingDirectory = workingDirectory is not null ? Path.GetFullPath(workingDirectory) : Directory.GetCurrentDirectory(); string filenameInWorkingDirectory = Path.Combine(workingDirectory, filename); // filename is a relative path in the working directory @@ -643,7 +643,7 @@ private static string[] CreateEnvp(ProcessStartInfo psi) } } - if (resolvedFilename == null) + if (resolvedFilename is null) { return null; } @@ -681,7 +681,7 @@ private static string[] CreateEnvp(ProcessStartInfo psi) // Then check the executable's directory string? path = Environment.ProcessPath; - if (path != null) + if (path is not null) { try { @@ -714,7 +714,7 @@ private static string[] CreateEnvp(ProcessStartInfo psi) { string path; string? pathEnvVar = Environment.GetEnvironmentVariable("PATH"); - if (pathEnvVar != null) + if (pathEnvVar is not null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) @@ -885,7 +885,7 @@ private static string GetNextArgument(string arguments, ref int i) /// Gets the wait state for this Process object. private ProcessWaitState GetWaitState() { - if (_waitStateHolder == null) + if (_waitStateHolder is null) { EnsureState(State.HaveId); _waitStateHolder = new ProcessWaitState.Holder(_processId); @@ -909,7 +909,7 @@ private static (uint userId, uint groupId, uint[] groups) GetUserAndGroupIds(Pro } uint[]? groups = Interop.Sys.GetGroupList(startInfo.UserName, groupId!.Value); - if (groups == null) + if (groups is null) { throw new Win32Exception(SR.Format(SR.UserGroupsCannotBeDetermined, startInfo.UserName)); } @@ -927,7 +927,7 @@ private static unsafe (uint? userId, uint? groupId) GetUserAndGroupIds(string us byte* stackBuf = stackalloc byte[BufLen]; if (TryGetPasswd(userName, stackBuf, BufLen, out passwd)) { - if (passwd == null) + if (passwd is null) { return (null, null); } @@ -945,7 +945,7 @@ private static unsafe (uint? userId, uint? groupId) GetUserAndGroupIds(string us { if (TryGetPasswd(userName, buf, heapBuf.Length, out passwd)) { - if (passwd == null) + if (passwd is null) { return (null, null); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs index 76419e195cee14..d579d1de74372d 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs @@ -28,22 +28,22 @@ private bool StartCore(ProcessStartInfo startInfo) private unsafe bool StartWithShellExecuteEx(ProcessStartInfo startInfo) { - if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null) + if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password is not null) throw new InvalidOperationException(SR.CantStartAsUser); if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) throw new InvalidOperationException(SR.CantRedirectStreams); - if (startInfo.StandardInputEncoding != null) + if (startInfo.StandardInputEncoding is not null) throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed); - if (startInfo.StandardErrorEncoding != null) + if (startInfo.StandardErrorEncoding is not null) throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); - if (startInfo.StandardOutputEncoding != null) + if (startInfo.StandardOutputEncoding is not null) throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); - if (startInfo._environmentVariables != null) + if (startInfo._environmentVariables is not null) throw new InvalidOperationException(SR.CantUseEnvVars); string arguments = startInfo.BuildArguments(); @@ -263,7 +263,7 @@ public string MainWindowTitle { get { - if (_mainWindowTitle == null) + if (_mainWindowTitle is null) { _mainWindowTitle = GetMainWindowTitle(); } @@ -391,7 +391,7 @@ private bool Equals(Process process) => foreach ((Process Process, SafeProcessHandle Handle) child in children) { List? exceptionsFromChild = child.Process.KillTree(child.Handle); - if (exceptionsFromChild != null) + if (exceptionsFromChild is not null) { (exceptions ??= new List()).AddRange(exceptionsFromChild); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs index 44323f9ef7111e..f2a66ca43915e1 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs @@ -23,7 +23,7 @@ public partial class Process : IDisposable /// public static Process[] GetProcessesByName(string? processName, string machineName) { - if (processName == null) + if (processName is null) { processName = string.Empty; } @@ -179,10 +179,10 @@ private bool WaitForExitCore(int milliseconds) finally { // If we have a hard timeout, we cannot wait for the streams - if (_output != null && milliseconds == Timeout.Infinite) + if (_output is not null && milliseconds == Timeout.Infinite) _output.WaitUntilEOF(); - if (_error != null && milliseconds == Timeout.Infinite) + if (_error is not null && milliseconds == Timeout.Infinite) _error.WaitUntilEOF(); handle?.Dispose(); @@ -419,7 +419,7 @@ private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr if ((long)min > (long)max) { - if (newMin != null) + if (newMin is not null) { throw new ArgumentException(SR.BadMinWorkset); } @@ -527,7 +527,7 @@ private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo) // set up the environment block parameter string? environmentBlock = null; - if (startInfo._environmentVariables != null) + if (startInfo._environmentVariables is not null) { creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT; environmentBlock = GetEnvironmentVariablesBlock(startInfo._environmentVariables!); @@ -541,7 +541,7 @@ private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo) if (startInfo.UserName.Length != 0) { - if (startInfo.Password != null && startInfo.PasswordInClearText != null) + if (startInfo.Password is not null && startInfo.PasswordInClearText is not null) { throw new ArgumentException(SR.CantSetDuplicatePassword); } @@ -555,7 +555,7 @@ private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo) fixed (char* passwordInClearTextPtr = startInfo.PasswordInClearText ?? string.Empty) fixed (char* environmentBlockPtr = environmentBlock) { - IntPtr passwordPtr = (startInfo.Password != null) ? + IntPtr passwordPtr = (startInfo.Password is not null) ? Marshal.SecureStringToGlobalAllocUnicode(startInfo.Password) : IntPtr.Zero; try @@ -747,7 +747,7 @@ private static unsafe void SetPrivilege(string privilegeName, int attrib) } finally { - if (hToken != null) + if (hToken is not null) { hToken.Dispose(); } @@ -866,7 +866,7 @@ private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle chil } finally { - if (hTmp != null && !hTmp.IsInvalid) + if (hTmp is not null && !hTmp.IsInvalid) { hTmp.Dispose(); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs index ab5e7be8c278aa..57dfb2f61666e3 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs @@ -298,7 +298,7 @@ public ProcessModuleCollection Modules { get { - if (_modules == null) + if (_modules is null) { EnsureState(State.HaveNonExitedId | State.IsLocal); _modules = ProcessManager.GetModules(_processId); @@ -557,7 +557,7 @@ public ProcessStartInfo StartInfo { get { - if (_startInfo == null) + if (_startInfo is null) { if (Associated) { @@ -570,7 +570,7 @@ public ProcessStartInfo StartInfo } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -594,7 +594,7 @@ public ProcessThreadCollection Threads { get { - if (_threads == null) + if (_threads is null) { EnsureState(State.HaveProcessInfo); int count = _processInfo!._threadInfoList.Count; @@ -683,7 +683,7 @@ public StreamWriter StandardInput { get { - if (_standardInput == null) + if (_standardInput is null) { throw new InvalidOperationException(SR.CantGetStandardIn); } @@ -700,7 +700,7 @@ public StreamReader StandardOutput { get { - if (_standardOutput == null) + if (_standardOutput is null) { throw new InvalidOperationException(SR.CantGetStandardOut); } @@ -725,7 +725,7 @@ public StreamReader StandardError { get { - if (_standardError == null) + if (_standardError is null) { throw new InvalidOperationException(SR.CantGetStandardError); } @@ -780,7 +780,7 @@ public event EventHandler Exited /// private void CompletionCallback(object? waitHandleContext, bool wasSignaled) { - Debug.Assert(waitHandleContext != null, "Process.CompletionCallback called with no waitHandleContext"); + Debug.Assert(waitHandleContext is not null, "Process.CompletionCallback called with no waitHandleContext"); lock (this) { // Check the exited event that we get from the threadpool @@ -863,7 +863,7 @@ public void Close() // If they are referenced it is the user's responsibility to dispose of them. try { - if (_standardOutput != null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined)) + if (_standardOutput is not null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined)) { if (_outputStreamReadMode == StreamReadMode.AsyncMode) { @@ -873,7 +873,7 @@ public void Close() _standardOutput.Close(); } - if (_standardError != null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined)) + if (_standardError is not null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined)) { if (_errorStreamReadMode == StreamReadMode.AsyncMode) { @@ -883,7 +883,7 @@ public void Close() _standardError.Close(); } - if (_standardInput != null && !_standardInputAccessed) + if (_standardInput is not null && !_standardInputAccessed) { _standardInput.Close(); } @@ -944,14 +944,14 @@ private void EnsureState(State state) if ((state & State.HaveProcessInfo) != (State)0) { - if (_processInfo == null) + if (_processInfo is null) { if ((state & State.HaveNonExitedId) != State.HaveNonExitedId) { EnsureState(State.HaveNonExitedId); } _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName); - if (_processInfo == null) + if (_processInfo is null) { throw new InvalidOperationException(SR.NoProcessInfo); } @@ -1085,7 +1085,7 @@ public static Process GetCurrentProcess() protected void OnExited() { EventHandler? exited = _onExited; - if (exited != null) + if (exited is not null) { if (SynchronizingObject is ISynchronizeInvoke syncObj && syncObj.InvokeRequired) { @@ -1206,15 +1206,15 @@ public bool Start() { throw new InvalidOperationException(SR.FileNameMissing); } - if (startInfo.StandardInputEncoding != null && !startInfo.RedirectStandardInput) + if (startInfo.StandardInputEncoding is not null && !startInfo.RedirectStandardInput) { throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed); } - if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) + if (startInfo.StandardOutputEncoding is not null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); } - if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) + if (startInfo.StandardErrorEncoding is not null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); } @@ -1270,9 +1270,9 @@ public static Process Start(string fileName, string arguments) /// public static Process Start(string fileName, IEnumerable arguments) { - if (fileName == null) + if (fileName is null) throw new ArgumentNullException(nameof(fileName)); - if (arguments == null) + if (arguments is null) throw new ArgumentNullException(nameof(arguments)); var startInfo = new ProcessStartInfo(fileName); @@ -1295,7 +1295,7 @@ public static Process Start(string fileName, IEnumerable arguments) public static Process? Start(ProcessStartInfo startInfo) { Process process = new Process(); - if (startInfo == null) + if (startInfo is null) throw new ArgumentNullException(nameof(startInfo)); process.StartInfo = startInfo; @@ -1329,12 +1329,12 @@ private void StopWatchingForExit() } } - if (rwh != null) + if (rwh is not null) { rwh.Unregister(null); } - if (wh != null) + if (wh is not null) { wh.Dispose(); } @@ -1489,12 +1489,12 @@ public async Task WaitForExitAsync(CancellationToken cancellationToken = default async ValueTask WaitUntilOutputEOF() { - if (_output != null) + if (_output is not null) { await _output.WaitUntilEOFAsync(cancellationToken).ConfigureAwait(false); } - if (_error != null) + if (_error is not null) { await _error.WaitUntilEOFAsync(cancellationToken).ConfigureAwait(false); } @@ -1525,9 +1525,9 @@ public void BeginOutputReadLine() _pendingOutputRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. - if (_output == null) + if (_output is null) { - if (_standardOutput == null) + if (_standardOutput is null) { throw new InvalidOperationException(SR.CantGetStandardOut); } @@ -1565,9 +1565,9 @@ public void BeginErrorReadLine() _pendingErrorRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. - if (_error == null) + if (_error is null) { - if (_standardError == null) + if (_standardError is null) { throw new InvalidOperationException(SR.CantGetStandardError); } @@ -1586,7 +1586,7 @@ public void BeginErrorReadLine() /// public void CancelOutputRead() { - if (_output != null) + if (_output is not null) { _output.CancelOperation(); } @@ -1606,7 +1606,7 @@ public void CancelOutputRead() /// public void CancelErrorRead() { - if (_error != null) + if (_error is not null) { _error.CancelOperation(); } @@ -1622,7 +1622,7 @@ internal void OutputReadNotifyUser(string? data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler? outputDataReceived = OutputDataReceived; - if (outputDataReceived != null) + if (outputDataReceived is not null) { // Call back to user informing data is available DataReceivedEventArgs e = new DataReceivedEventArgs(data); @@ -1641,7 +1641,7 @@ internal void ErrorReadNotifyUser(string? data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler? errorDataReceived = ErrorDataReceived; - if (errorDataReceived != null) + if (errorDataReceived is not null) { // Call back to user informing data is available. DataReceivedEventArgs e = new DataReceivedEventArgs(data); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.BSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.BSD.cs index c6c43dd36a91c5..9c301668820467 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.BSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.BSD.cs @@ -22,7 +22,7 @@ public static ProcessInfo[] GetProcessInfos(string machineName) foreach (int pid in procIds) { ProcessInfo pi = CreateProcessInfo(pid); - if (pi != null) + if (pi is not null) { processes.Add(pi); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs index cc514764fa4d8a..b43d1aebeb3adf 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs @@ -30,7 +30,7 @@ public static ProcessInfo[] GetProcessInfos(string machineName) foreach (int pid in procIds) { ProcessInfo? pi = CreateProcessInfo(pid); - if (pi != null) + if (pi is not null) { processes.Add(pi); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs index fa17d76ef2bf07..be68864765feda 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs @@ -267,7 +267,7 @@ internal static ProcessInfo[] GetProcessInfos(Predicate? processIdFilter = { while (true) { - if (buffer == null) + if (buffer is null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; @@ -357,7 +357,7 @@ private static unsafe ProcessInfo[] GetProcessInfos(ReadOnlySpan data, Pre // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. int processInfoProcessId = pi.UniqueProcessId.ToInt32(); - if (processIdFilter == null || processIdFilter(processInfoProcessId)) + if (processIdFilter is null || processIdFilter(processInfoProcessId)) { // get information for a process ProcessInfo processInfo = new ProcessInfo((int)pi.NumberOfThreads) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs index 98075165c63ae0..b258b88d957dbf 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs @@ -165,7 +165,7 @@ static unsafe ProcessManager() } finally { - if (tokenHandle != null) + if (tokenHandle is not null) { tokenHandle.Dispose(); } @@ -589,7 +589,7 @@ private static ProcessInfo GetProcessInfo(ReadOnlySpan instanceData, PERF_ private static ValueId GetValueId(string counterName) { - if (counterName != null) + if (counterName is not null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.cs index 85525bbe3e8a59..f0946eb6b454fc 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.cs @@ -10,7 +10,7 @@ internal static partial class ProcessManager /// true if the machine is remote; false if it's local. public static bool IsRemoteMachine(string machineName) { - if (machineName == null) + if (machineName is null) throw new ArgumentNullException(nameof(machineName)); if (machineName.Length == 0) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs index 6b3503675d0be3..3fb0c3c1d500c8 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs @@ -19,7 +19,7 @@ public string[] Verbs using (RegistryKey? key = Registry.ClassesRoot.OpenSubKey(extension)) { - if (key == null) + if (key is null) return Array.Empty(); string? value = key.GetValue(string.Empty) as string; @@ -28,7 +28,7 @@ public string[] Verbs using (RegistryKey? subKey = Registry.ClassesRoot.OpenSubKey(value + "\\shell")) { - if (subKey == null) + if (subKey is null) return Array.Empty(); string[] names = subKey.GetSubKeyNames(); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs index 050afb547972f2..8a135fea6c217a 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs @@ -67,7 +67,7 @@ public Collection ArgumentList { get { - if (_argumentList == null) + if (_argumentList is null) { _argumentList = new Collection(); } @@ -85,7 +85,7 @@ public Collection ArgumentList { get { - if (_environmentVariables == null) + if (_environmentVariables is null) { IDictionary envVars = System.Environment.GetEnvironmentVariables(); @@ -176,7 +176,7 @@ public ProcessWindowStyle WindowStyle internal string BuildArguments() { - if (_argumentList == null || _argumentList.Count == 0) + if (_argumentList is null || _argumentList.Count == 0) { return Arguments; } @@ -190,7 +190,7 @@ internal string BuildArguments() internal void AppendArgumentsTo(StringBuilder stringBuilder) { - if (_argumentList != null && _argumentList.Count > 0) + if (_argumentList is not null && _argumentList.Count > 0) { foreach (string argument in _argumentList) { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs index 03e93a725c4b7e..f6c9b75effa465 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs @@ -63,7 +63,7 @@ internal Holder(int processId, bool isNewChild = false, bool usesTerminal = fals { // Don't try to Dispose resources (like ManualResetEvents) if // the process is shutting down. - if (_state != null && !Environment.HasShutdownStarted) + if (_state is not null && !Environment.HasShutdownStarted) { _state.ReleaseRef(); } @@ -71,7 +71,7 @@ internal Holder(int processId, bool isNewChild = false, bool usesTerminal = fals public void Dispose() { - if (_state != null) + if (_state is not null) { GC.SuppressFinalize(this); _state.ReleaseRef(); @@ -142,7 +142,7 @@ internal static ProcessWaitState AddRef(int processId, bool isNewChild, bool use pws = null; } } - if (pws == null) + if (pws is null) { pws = new ProcessWaitState(processId, isChild: false, usesTerminal: false, exitTime); s_processWaitStates.Add(processId, pws); @@ -238,7 +238,7 @@ public void Dispose() lock (_gate) { - if (_exitedEvent != null) + if (_exitedEvent is not null) { _exitedEvent.Dispose(); _exitedEvent = null; @@ -268,7 +268,7 @@ internal ManualResetEvent EnsureExitedEvent() lock (_gate) { // If we already have an initialized event, just return it. - if (_exitedEvent == null) + if (_exitedEvent is null) { // If we don't, create one, and if the process hasn't yet exited, // make sure we have a task that's actively monitoring the completion state. @@ -280,7 +280,7 @@ internal ManualResetEvent EnsureExitedEvent() // If we haven't exited, we need to spin up an asynchronous operation that // will completed the exitedEvent when the other process exits. If there's already // another operation underway, then we'll just tack ours onto the end of it. - _waitInProgress = _waitInProgress == null ? + _waitInProgress = _waitInProgress is null ? WaitForExitAsync() : _waitInProgress.ContinueWith((_, state) => ((ProcessWaitState)state!).WaitForExitAsync(), this, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap(); @@ -325,7 +325,7 @@ internal bool GetExited(out int? exitCode, bool refresh) // Is another wait operation in progress? If so, then we haven't exited, // and that task owns the right to call CheckForNonChildExit. - if (_waitInProgress != null) + if (_waitInProgress is not null) { exitCode = null; return false; @@ -442,7 +442,7 @@ internal bool WaitForExit(int millisecondsTimeout) { // If there's currently a wait-in-progress, then we know the other process // hasn't exited (barring races and the polling interval). - if (_waitInProgress != null) + if (_waitInProgress is not null) { return false; } @@ -459,7 +459,7 @@ internal bool WaitForExit(int millisecondsTimeout) // If there's already a wait in progress, we'll do so later // by waiting on that existing task. Otherwise, we'll spin up // such a task. - if (_waitInProgress != null) + if (_waitInProgress is not null) { waitTask = _waitInProgress; } @@ -503,7 +503,7 @@ internal bool WaitForExit(int millisecondsTimeout) private Task WaitForExitAsync(CancellationToken cancellationToken = default) { Debug.Assert(Monitor.IsEntered(_gate)); - Debug.Assert(_waitInProgress == null); + Debug.Assert(_waitInProgress is null); Debug.Assert(!_isChild); return _waitInProgress = Task.Run(async delegate // Task.Run used because of potential blocking in CheckForNonChildExit @@ -647,13 +647,13 @@ internal static void CheckChildren(bool reapAll) ProcessWaitState pws = kv.Value; if (pws.TryReapChild()) { - if (firstToRemove == null) + if (firstToRemove is null) { firstToRemove = pws; } else { - if (additionalToRemove == null) + if (additionalToRemove is null) { additionalToRemove = new List(); } @@ -662,10 +662,10 @@ internal static void CheckChildren(bool reapAll) } } - if (firstToRemove != null) + if (firstToRemove is not null) { firstToRemove.ReleaseRef(); - if (additionalToRemove != null) + if (additionalToRemove is not null) { foreach (ProcessWaitState pws in additionalToRemove) { diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs index 4397987761b293..6e1beb8c08de67 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs @@ -63,7 +63,7 @@ public string Delimiter } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(Delimiter)); if (value.Length == 0) @@ -88,12 +88,12 @@ public string Delimiter public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string format, params object?[]? args) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) return; WriteHeader(source, eventType, id); - if (args != null) + if (args is not null) WriteEscaped(string.Format(CultureInfo.InvariantCulture, format, args)); else WriteEscaped(format); @@ -107,7 +107,7 @@ public override void TraceEvent(TraceEventCache? eventCache, string source, Trac public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string? message) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) return; WriteHeader(source, eventType, id); @@ -123,7 +123,7 @@ public override void TraceEvent(TraceEventCache? eventCache, string source, Trac public override void TraceData(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, object? data) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) return; WriteHeader(source, eventType, id); @@ -139,7 +139,7 @@ public override void TraceData(TraceEventCache? eventCache, string source, Trace public override void TraceData(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, params object?[]? data) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id); @@ -147,7 +147,7 @@ public override void TraceData(TraceEventCache? eventCache, string source, Trace // first a delimiter for the message Write(Delimiter); // Use get_Delimiter - if (data != null) + if (data is not null) { for (int i = 0; i < data.Length; i++) { @@ -175,7 +175,7 @@ private void WriteHeader(string source, TraceEventType eventType, int id) private void WriteFooter(TraceEventCache? eventCache) { - if (eventCache != null) + if (eventCache is not null) { if (IsEnabled(TraceOptions.ProcessId)) Write(eventCache.ProcessId.ToString(CultureInfo.InvariantCulture)); diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs index 9c4015842b11d8..d91f225f6eb3c9 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs @@ -41,7 +41,7 @@ public TextWriterTraceListener(Stream stream) public TextWriterTraceListener(Stream stream, string? name) : base(name) { - if (stream == null) throw new ArgumentNullException(nameof(stream)); + if (stream is null) throw new ArgumentNullException(nameof(stream)); _writer = new StreamWriter(stream); } @@ -63,7 +63,7 @@ public TextWriterTraceListener(TextWriter writer) public TextWriterTraceListener(TextWriter writer, string? name) : base(name) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); + if (writer is null) throw new ArgumentNullException(nameof(writer)); _writer = writer; } @@ -110,7 +110,7 @@ public TextWriter? Writer /// public override void Close() { - if (_writer != null) + if (_writer is not null) { try { @@ -132,7 +132,7 @@ protected override void Dispose(bool disposing) { try { - if (disposing && _writer != null) + if (disposing && _writer is not null) { _writer.Dispose(); } @@ -163,7 +163,7 @@ public override void Flush() public override void Write(string? message) { EnsureWriter(); - if (_writer != null) + if (_writer is not null) { if (NeedIndent) WriteIndent(); try @@ -182,7 +182,7 @@ public override void Write(string? message) public override void WriteLine(string? message) { EnsureWriter(); - if (_writer != null) + if (_writer is not null) { if (NeedIndent) WriteIndent(); try @@ -206,11 +206,11 @@ private static Encoding GetEncodingWithFallback(Encoding encoding) internal void EnsureWriter() { - if (_writer == null) + if (_writer is null) { bool success = false; - if (_fileName == null) + if (_fileName is null) return; // StreamWriter by default uses UTF8Encoding which will throw on invalid encoding errors. diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs index bf97f5fe8418c0..08da6b78c2ee9d 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs @@ -67,14 +67,14 @@ public override void WriteLine(string? message) public override void Fail(string? message, string? detailMessage) { message ??= string.Empty; - int length = detailMessage != null ? message.Length + 1 + detailMessage.Length : message.Length; + int length = detailMessage is not null ? message.Length + 1 + detailMessage.Length : message.Length; TraceEvent(null, SR.TraceAsTraceSource, TraceEventType.Error, 0, string.Create(length, (message, detailMessage), (dst, v) => { ReadOnlySpan prefix = v.message; prefix.CopyTo(dst); - if (v.detailMessage != null) + if (v.detailMessage is not null) { dst[prefix.Length] = ' '; @@ -86,17 +86,17 @@ public override void Fail(string? message, string? detailMessage) public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string format, params object?[]? args) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) return; WriteHeader(source, eventType, id, eventCache); - WriteEscaped(args != null && args.Length != 0 ? string.Format(CultureInfo.InvariantCulture, format, args) : format); + WriteEscaped(args is not null && args.Length != 0 ? string.Format(CultureInfo.InvariantCulture, format, args) : format); WriteFooter(eventCache); } public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string? message) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) return; WriteHeader(source, eventType, id, eventCache); @@ -106,13 +106,13 @@ public override void TraceEvent(TraceEventCache? eventCache, string source, Trac public override void TraceData(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, object? data) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) return; WriteHeader(source, eventType, id, eventCache); InternalWrite(""); - if (data != null) + if (data is not null) { InternalWrite(""); WriteData(data); @@ -125,17 +125,17 @@ public override void TraceData(TraceEventCache? eventCache, string source, Trace public override void TraceData(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, params object?[]? data) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id, eventCache); InternalWrite(""); - if (data != null) + if (data is not null) { for (int i = 0; i < data.Length; i++) { InternalWrite(""); - if (data[i] != null) + if (data[i] is not null) WriteData(data[i]!); InternalWrite(""); } @@ -154,7 +154,7 @@ private void WriteData(object data) } else { - if (_strBldr == null) + if (_strBldr is null) { _strBldr = new StringBuilder(); _xmlBlobWriter = new XmlTextWriter(new StringWriter(_strBldr, CultureInfo.CurrentCulture)); @@ -188,7 +188,7 @@ public override void Close() public override void TraceTransfer(TraceEventCache? eventCache, string source, int id, string? message, Guid relatedActivityId) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, TraceEventType.Transfer, id, message, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, TraceEventType.Transfer, id, message, null, null, null)) return; WriteHeader(source, TraceEventType.Transfer, id, eventCache, relatedActivityId); @@ -234,7 +234,7 @@ private void WriteStartHeader(string source, TraceEventType eventType, int id, T InternalWrite(""); InternalWrite(""); InternalWrite(""); diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs index c5f67fc2139b96..60b1aaa4c54ed2 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs @@ -29,7 +29,7 @@ internal CorrelationManager() public void StartLogicalOperation(object operationId) { - if (operationId == null) + if (operationId is null) { throw new ArgumentNullException(nameof(operationId)); } @@ -43,7 +43,7 @@ internal StackNode(object? value, StackNode? prev = null) { Value = value; Prev = prev; - Count = prev != null ? prev.Count + 1 : 1; + Count = prev is not null ? prev.Count + 1 : 1; } internal int Count { get; } @@ -57,7 +57,7 @@ private sealed class AsyncLocalStackWrapper : Stack internal AsyncLocalStackWrapper(AsyncLocal stack) { - Debug.Assert(stack != null); + Debug.Assert(stack is not null); _stack = stack; } @@ -73,11 +73,11 @@ internal AsyncLocalStackWrapper(AsyncLocal stack) public override bool Contains(object? obj) { - for (StackNode? n = _stack.Value; n != null; n = n.Prev) + for (StackNode? n = _stack.Value; n is not null; n = n.Prev) { - if (obj == null) + if (obj is null) { - if (n.Value == null) return true; + if (n.Value is null) return true; } else if (obj.Equals(n.Value)) { @@ -89,7 +89,7 @@ public override bool Contains(object? obj) public override void CopyTo(Array array, int index) { - for (StackNode? n = _stack.Value; n != null; n = n.Prev) + for (StackNode? n = _stack.Value; n is not null; n = n.Prev) { array.SetValue(n.Value, index++); } @@ -97,7 +97,7 @@ public override void CopyTo(Array array, int index) private IEnumerator GetEnumerator(StackNode? n) { - while (n != null) + while (n is not null) { yield return n.Value; n = n.Prev; @@ -107,7 +107,7 @@ private IEnumerator GetEnumerator(StackNode? n) public override object? Pop() { StackNode? n = _stack.Value; - if (n == null) + if (n is null) { base.Pop(); // used to throw proper exception } @@ -123,7 +123,7 @@ public override void Push(object? obj) public override object?[] ToArray() { StackNode? n = _stack.Value; - if (n == null) + if (n is null) { return Array.Empty(); } @@ -134,7 +134,7 @@ public override void Push(object? obj) results.Add(n.Value); n = n.Prev; } - while (n != null); + while (n is not null); return results.ToArray(); } } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs index 4af317f3f2cfc8..4a6168bec35f20 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs @@ -145,7 +145,7 @@ private void WriteLine(string? message, bool useLogFile) private void Write(string? message, bool useLogFile) { - if (message == null) + if (message is null) { message = string.Empty; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs index e792cd846b762a..a739eb15376451 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs @@ -19,7 +19,7 @@ public SourceFilter(string source) public override bool ShouldTrace(TraceEventCache? cache, string source, TraceEventType eventType, int id, string? formatOrMessage, object?[]? args, object? data1, object?[]? data) { - if (source == null) + if (source is null) throw new ArgumentNullException(nameof(source)); return string.Equals(_src, source); @@ -34,7 +34,7 @@ public string Source [MemberNotNull(nameof(_src))] set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(Source)); _src = value; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs index e61fad92429510..d44100f731a7f7 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs @@ -35,7 +35,7 @@ private object InitializedLock { get { - if (_initializedLock == null) + if (_initializedLock is null) { object o = new object(); Interlocked.CompareExchange(ref _initializedLock, o, null); @@ -57,7 +57,7 @@ protected Switch(string displayName, string? description, string? defaultSwitchV { // displayName is used as a hashtable key, so it can never // be null. - if (displayName == null) displayName = string.Empty; + if (displayName is null) displayName = string.Empty; _displayName = displayName; _description = description; @@ -82,7 +82,7 @@ private static void _pruneCachedSwitches() for (int i = 0; i < s_switches.Count; i++) { Switch? s = ((Switch?)s_switches[i].Target); - if (s != null) + if (s is not null) { buffer.Add(s_switches[i]); } @@ -116,7 +116,7 @@ public string Description { get { - return (_description == null) ? string.Empty : _description; + return (_description is null) ? string.Empty : _description; } } @@ -125,7 +125,7 @@ public StringDictionary Attributes get { Initialize(); - if (_attributes == null) + if (_attributes is null) _attributes = new StringDictionary(); return _attributes; } @@ -237,7 +237,7 @@ internal static void RefreshAll() for (int i = 0; i < s_switches.Count; i++) { Switch? swtch = ((Switch?)s_switches[i].Target); - if (swtch != null) + if (swtch is not null) { swtch.Refresh(); } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs index 0a65152e23af5e..40955b98169bf6 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs @@ -26,7 +26,7 @@ public string SwitchName [MemberNotNull(nameof(_name))] set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(value)), nameof(value)); @@ -41,7 +41,7 @@ public Type SwitchType [MemberNotNull(nameof(_type))] set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _type = value; } @@ -51,7 +51,7 @@ public Type SwitchType public static SwitchAttribute[] GetAll(Assembly assembly) { - if (assembly == null) + if (assembly is null) throw new ArgumentNullException(nameof(assembly)); List switchAttribs = new List(); diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchLevelAttribute.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchLevelAttribute.cs index 6fd36334e4c5dc..7123f5366a46a7 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchLevelAttribute.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchLevelAttribute.cs @@ -21,7 +21,7 @@ public Type SwitchLevelType [MemberNotNull(nameof(_type))] set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _type = value; diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs index 31af00ab0accc5..ba6778e95e6c2a 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs @@ -23,7 +23,7 @@ public static CorrelationManager CorrelationManager { get { - if (s_correlationManager == null) + if (s_correlationManager is null) { s_correlationManager = new CorrelationManager(); } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs index cdc431dfe527db..f1c13e5a2094fa 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs @@ -55,7 +55,7 @@ public string Callstack { get { - if (_stackTrace == null) + if (_stackTrace is null) { _stackTrace = Environment.StackTrace; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs index 469b6464149a56..e5c6345a495fae 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs @@ -57,11 +57,11 @@ public static TraceListenerCollection Listeners get { InitializeSettings(); - if (s_listeners == null) + if (s_listeners is null) { lock (critSec) { - if (s_listeners == null) + if (s_listeners is null) { // This is where we override default DebugProvider because we know // for sure that we have some Listeners to write to. @@ -84,7 +84,7 @@ internal static string AppName { get { - if (s_appName == null) + if (s_appName is null) { s_appName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty; } @@ -157,7 +157,7 @@ public static void Unindent() public static void Flush() { - if (s_listeners != null) + if (s_listeners is not null) { if (UseGlobalLock) { @@ -191,7 +191,7 @@ public static void Flush() public static void Close() { - if (s_listeners != null) + if (s_listeners is not null) { // Use global lock lock (critSec) @@ -329,7 +329,7 @@ public static void TraceEvent(TraceEventType eventType, int id, string? format, { lock (critSec) { - if (args == null) + if (args is null) { foreach (TraceListener listener in Listeners) { @@ -349,7 +349,7 @@ public static void TraceEvent(TraceEventType eventType, int id, string? format, } else { - if (args == null) + if (args is null) { foreach (TraceListener listener in Listeners) { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs index b19d1aa333abfc..c6e2b1382b50cb 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs @@ -46,7 +46,7 @@ public StringDictionary Attributes { get { - if (_attributes == null) + if (_attributes is null) _attributes = new StringDictionary(); return _attributes; } @@ -204,7 +204,7 @@ public virtual void Fail(string? message, string? detailMessage) failMessage.Append(SR.TraceListenerFail); failMessage.Append(' '); failMessage.Append(message); - if (detailMessage != null) + if (detailMessage is not null) { failMessage.Append(' '); failMessage.Append(detailMessage); @@ -225,10 +225,10 @@ public virtual void Fail(string? message, string? detailMessage) /// public virtual void Write(object? o) { - if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) + if (Filter is not null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; - if (o == null) return; + if (o is null) return; Write(o.ToString()); } @@ -239,13 +239,13 @@ public virtual void Write(object? o) /// public virtual void Write(string? message, string? category) { - if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) + if (Filter is not null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; - if (category == null) + if (category is null) Write(message); else - Write(category + ": " + ((message == null) ? string.Empty : message)); + Write(category + ": " + ((message is null) ? string.Empty : message)); } /// @@ -255,13 +255,13 @@ public virtual void Write(string? message, string? category) /// public virtual void Write(object? o, string? category) { - if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) + if (Filter is not null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; - if (category == null) + if (category is null) Write(o); else - Write(o == null ? "" : o.ToString(), category); + Write(o is null ? "" : o.ToString(), category); } /// @@ -300,10 +300,10 @@ protected virtual void WriteIndent() /// public virtual void WriteLine(object? o) { - if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) + if (Filter is not null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; - WriteLine(o == null ? "" : o.ToString()); + WriteLine(o is null ? "" : o.ToString()); } /// @@ -313,12 +313,12 @@ public virtual void WriteLine(object? o) /// public virtual void WriteLine(string? message, string? category) { - if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) + if (Filter is not null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; - if (category == null) + if (category is null) WriteLine(message); else - WriteLine(category + ": " + ((message == null) ? string.Empty : message)); + WriteLine(category + ": " + ((message is null) ? string.Empty : message)); } /// @@ -330,10 +330,10 @@ public virtual void WriteLine(string? message, string? category) /// public virtual void WriteLine(object? o, string? category) { - if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) + if (Filter is not null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; - WriteLine(o == null ? "" : o.ToString(), category); + WriteLine(o is null ? "" : o.ToString(), category); } @@ -341,12 +341,12 @@ public virtual void WriteLine(object? o, string? category) public virtual void TraceData(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, object? data) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data)) return; WriteHeader(source, eventType, id); string? datastring = string.Empty; - if (data != null) + if (data is not null) datastring = data.ToString(); WriteLine(datastring); @@ -355,20 +355,20 @@ public virtual void TraceData(TraceEventCache? eventCache, string source, TraceE public virtual void TraceData(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, params object?[]? data) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id); StringBuilder sb = new StringBuilder(); - if (data != null) + if (data is not null) { for (int i = 0; i < data.Length; i++) { if (i != 0) sb.Append(", "); - if (data[i] != null) + if (data[i] is not null) sb.Append(data[i]!.ToString()); } } @@ -385,7 +385,7 @@ public virtual void TraceEvent(TraceEventCache? eventCache, string source, Trace // All other TraceEvent methods come through this one. public virtual void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string? message) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, message)) return; WriteHeader(source, eventType, id); @@ -396,11 +396,11 @@ public virtual void TraceEvent(TraceEventCache? eventCache, string source, Trace public virtual void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string format, params object?[]? args) { - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args)) return; WriteHeader(source, eventType, id); - if (args != null) + if (args is not null) WriteLine(string.Format(CultureInfo.InvariantCulture, format, args)); else WriteLine(format); @@ -415,7 +415,7 @@ private void WriteHeader(string source, TraceEventType eventType, int id) private void WriteFooter(TraceEventCache? eventCache) { - if (eventCache == null) + if (eventCache is null) return; _indentLevel++; diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs index 09d2ce791e48a8..8208b90d489b66 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs @@ -85,7 +85,7 @@ public int Add(TraceListener listener) /// public void AddRange(TraceListener[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -100,7 +100,7 @@ public void AddRange(TraceListener[] value) /// public void AddRange(TraceListenerCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -152,7 +152,7 @@ public IEnumerator GetEnumerator() internal void InitializeListener(TraceListener listener) { - if (listener == null) + if (listener is null) throw new ArgumentNullException(nameof(listener)); listener.IndentSize = TraceInternal.IndentSize; @@ -196,7 +196,7 @@ public void Remove(TraceListener? listener) public void Remove(string name) { TraceListener? listener = this[name]; - if (listener != null) + if (listener is not null) ((IList)this).Remove(listener); } @@ -222,7 +222,7 @@ public void RemoveAt(int index) set { TraceListener? listener = value as TraceListener; - if (listener == null) + if (listener is null) throw new ArgumentException(SR.MustAddListener, nameof(value)); InitializeListener(listener); _list[index] = listener; @@ -251,7 +251,7 @@ bool IList.IsFixedSize int IList.Add(object? value) { TraceListener? listener = value as TraceListener; - if (listener == null) + if (listener is null) throw new ArgumentException(SR.MustAddListener, nameof(value)); InitializeListener(listener); @@ -278,7 +278,7 @@ int IList.IndexOf(object? value) void IList.Insert(int index, object? value) { TraceListener? listener = value as TraceListener; - if (listener == null) + if (listener is null) throw new ArgumentException(SR.MustAddListener, nameof(value)); InitializeListener(listener); diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs index 5dd7accb977553..7c3633e01a2118 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs @@ -28,7 +28,7 @@ public TraceSource(string name) public TraceSource(string name, SourceLevels defaultLevel) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(name)), nameof(name)); @@ -54,7 +54,7 @@ private static void _pruneCachedTraceSources() for (int i = 0; i < s_tracesources.Count; i++) { TraceSource? tracesource = ((TraceSource?)s_tracesources[i].Target); - if (tracesource != null) + if (tracesource is not null) { buffer.Add(s_tracesources[i]); } @@ -96,7 +96,7 @@ private void NoConfigInit() public void Close() { // No need to call Initialize() - if (_listeners != null) + if (_listeners is not null) { // Use global lock lock (TraceInternal.critSec) @@ -112,7 +112,7 @@ public void Close() public void Flush() { // No need to call Initialize() - if (_listeners != null) + if (_listeners is not null) { if (TraceInternal.UseGlobalLock) { @@ -154,7 +154,7 @@ internal static void RefreshAll() for (int i = 0; i < s_tracesources.Count; i++) { TraceSource? tracesource = ((TraceSource?)s_tracesources[i].Target); - if (tracesource != null) + if (tracesource is not null) { tracesource.Refresh(); } @@ -176,7 +176,7 @@ public void TraceEvent(TraceEventType eventType, int id) { Initialize(); - if (_internalSwitch!.ShouldTrace(eventType) && _listeners != null) + if (_internalSwitch!.ShouldTrace(eventType) && _listeners is not null) { TraceEventCache manager = new TraceEventCache(); @@ -221,7 +221,7 @@ public void TraceEvent(TraceEventType eventType, int id, string? message) { Initialize(); - if (_internalSwitch!.ShouldTrace(eventType) && _listeners != null) + if (_internalSwitch!.ShouldTrace(eventType) && _listeners is not null) { TraceEventCache manager = new TraceEventCache(); @@ -266,7 +266,7 @@ public void TraceEvent(TraceEventType eventType, int id, string format, params o { Initialize(); - if (_internalSwitch!.ShouldTrace(eventType) && _listeners != null) + if (_internalSwitch!.ShouldTrace(eventType) && _listeners is not null) { TraceEventCache manager = new TraceEventCache(); @@ -311,7 +311,7 @@ public void TraceData(TraceEventType eventType, int id, object? data) { Initialize(); - if (_internalSwitch!.ShouldTrace(eventType) && _listeners != null) + if (_internalSwitch!.ShouldTrace(eventType) && _listeners is not null) { TraceEventCache manager = new TraceEventCache(); @@ -356,7 +356,7 @@ public void TraceData(TraceEventType eventType, int id, params object?[]? data) { Initialize(); - if (_internalSwitch!.ShouldTrace(eventType) && _listeners != null) + if (_internalSwitch!.ShouldTrace(eventType) && _listeners is not null) { TraceEventCache manager = new TraceEventCache(); @@ -418,7 +418,7 @@ public void TraceTransfer(int id, string? message, Guid relatedActivityId) TraceEventCache manager = new TraceEventCache(); - if (_internalSwitch!.ShouldTrace(TraceEventType.Transfer) && _listeners != null) + if (_internalSwitch!.ShouldTrace(TraceEventType.Transfer) && _listeners is not null) { if (TraceInternal.UseGlobalLock) { @@ -474,7 +474,7 @@ public StringDictionary Attributes // Ensure that config is loaded Initialize(); - if (_attributes == null) + if (_attributes is null) _attributes = new StringDictionary(); return _attributes; @@ -510,7 +510,7 @@ public SourceSwitch Switch } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(Switch)); Initialize(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs index 8e2f891799f0e7..12ff801ad00fd4 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs @@ -37,7 +37,7 @@ static ADAMStoreCtx() LoadFilterMappingTable(mappingIndex, s_filterPropertiesTableRaw); LoadPropertyMappingTable(mappingIndex, s_propertyMappingTableRaw); - if (NonPresentAttrDefaultStateMapping == null) + if (NonPresentAttrDefaultStateMapping is null) NonPresentAttrDefaultStateMapping = new Dictionary(); for (int i = 0; i < s_presenceStateTable.GetLength(0); i++) @@ -97,7 +97,7 @@ protected override void LoadDomainInfo() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "LoadComputerInfo"); - Debug.Assert(this.ctxBase != null); + Debug.Assert(this.ctxBase is not null); // // DNS Domain Name @@ -166,7 +166,7 @@ internal override ResultSet GetGroupsMemberOfAZ(Principal p) Debug.Assert(p.unpersisted == false); Debug.Assert(p is UserPrincipal); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); DirectoryEntry principalDE = (DirectoryEntry)p.UnderlyingObject; @@ -214,11 +214,11 @@ internal override void SetPassword(AuthenticablePrincipal p, string newPassword) { Debug.Assert(p.fakePrincipal == false); - Debug.Assert(p != null); - Debug.Assert(newPassword != null); // but it could be an empty string + Debug.Assert(p is not null); + Debug.Assert(newPassword is not null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); SetupPasswordModification(p); @@ -238,12 +238,12 @@ internal override void ChangePassword(AuthenticablePrincipal p, string oldPasswo // Shouldn't be being called if this is the case Debug.Assert(p.unpersisted == false); - Debug.Assert(p != null); - Debug.Assert(newPassword != null); // but it could be an empty string - Debug.Assert(oldPassword != null); // but it could be an empty string + Debug.Assert(p is not null); + Debug.Assert(newPassword is not null); // but it could be an empty string + Debug.Assert(oldPassword is not null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); SetupPasswordModification(p); @@ -266,7 +266,7 @@ private List PopulatAuxObjectList(string auxClassName) try { - using (DirectoryEntry deRoot = new DirectoryEntry("LDAP://" + userSuppliedServerName + "/rootDSE", credentials == null ? null : credentials.UserName, credentials == null ? null : credentials.Password, authTypes)) + using (DirectoryEntry deRoot = new DirectoryEntry("LDAP://" + userSuppliedServerName + "/rootDSE", credentials is null ? null : credentials.UserName, credentials is null ? null : credentials.Password, authTypes)) { if (deRoot.Properties["schemaNamingContext"].Count == 0) { @@ -277,7 +277,7 @@ private List PopulatAuxObjectList(string auxClassName) SchemaNamingContext = (string)deRoot.Properties["schemaNamingContext"].Value; } - using (DirectoryEntry deSCN = new DirectoryEntry("LDAP://" + userSuppliedServerName + "/" + SchemaNamingContext, credentials == null ? null : credentials.UserName, credentials == null ? null : credentials.Password, authTypes)) + using (DirectoryEntry deSCN = new DirectoryEntry("LDAP://" + userSuppliedServerName + "/" + SchemaNamingContext, credentials is null ? null : credentials.UserName, credentials is null ? null : credentials.Password, authTypes)) { using (DirectorySearcher dirSearcher = new DirectorySearcher(deSCN)) { @@ -289,7 +289,7 @@ private List PopulatAuxObjectList(string auxClassName) { foreach (SearchResult res in searchResCollection) { - if (null == res.Properties["ldapDisplayName"]) + if (res.Properties["ldapDisplayName"] is null) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "ADAMStoreCtx", "PopulatAuxObjectList Unable to read ldapDisplayName from " + SchemaNamingContext); throw new PrincipalOperationException(SR.ADAMStoreUnableToPopulateSchemaList); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs index 5e89d45e7e9087..4f151325e9ea4a 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs @@ -46,7 +46,7 @@ internal ADDNConstraintLinkedAttrSet( bool recursive, ADStoreCtx storeCtx) : base(groupDN, members, primaryGroupDN, queryMembersSearcher, recursive, storeCtx) { - Debug.Assert(constraintData != null); + Debug.Assert(constraintData is not null); _constraint = constraint; _constraintData = constraintData; @@ -63,7 +63,7 @@ internal ADDNConstraintLinkedAttrSet( ADStoreCtx storeCtx) : base(groupDN, membersSearcher, primaryGroupDN, primaryGroupMembersSearcher, recursive, storeCtx) { - Debug.Assert(constraintData != null); + Debug.Assert(constraintData is not null); _constraint = constraint; _constraintData = constraintData; @@ -85,7 +85,7 @@ internal override bool MoveNext() { while (!match) { - if (null == this.current) + if (this.current is null) return false; switch (_constraint) @@ -104,7 +104,7 @@ internal override bool MoveNext() case ConstraintType.ResultValidatorDelegateMatch: { ResultValidator resultValidator = _constraintData as ResultValidator; - if (resultValidator != null) + if (resultValidator is not null) { dSPropertyCollection resultPropCollection = null; if (this.current is SearchResult) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs index 7d4739ae1c36da..190529ba7809da 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs @@ -44,17 +44,17 @@ internal ADDNLinkedAttrSet( "ADDNLinkedAttrSet", "ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, PG queryFilter={3}, PG queryBase={4}", groupDN, - (primaryGroupDN != null ? primaryGroupDN : "NULL"), + (primaryGroupDN is not null ? primaryGroupDN : "NULL"), recursive, - (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"), - (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); + (primaryGroupMembersSearcher is not null ? primaryGroupMembersSearcher.Filter : "NULL"), + (primaryGroupMembersSearcher is not null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); _groupsVisited.Add(groupDN); // so we don't revisit it _recursive = recursive; _storeCtx = storeCtx; _originalStoreCtx = storeCtx; - if (null != members) + if (members is not null) { foreach (IEnumerable enumerator in members) { @@ -67,7 +67,7 @@ internal ADDNLinkedAttrSet( _currentMembersSearcher = null; _primaryGroupDN = primaryGroupDN; - if (primaryGroupDN == null) + if (primaryGroupDN is null) _returnedPrimaryGroup = true; // so we don't bother trying to return the primary group _primaryGroupMembersSearcher = primaryGroupMembersSearcher; @@ -89,12 +89,12 @@ internal ADDNLinkedAttrSet( "ADDNLinkedAttrSet", "ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, M queryFilter={3}, M queryBase={4}, PG queryFilter={5}, PG queryBase={6}", groupDN, - (primaryGroupDN != null ? primaryGroupDN : "NULL"), + (primaryGroupDN is not null ? primaryGroupDN : "NULL"), recursive, - (membersSearcher != null ? membersSearcher[0].Filter : "NULL"), - (membersSearcher != null ? membersSearcher[0].SearchRoot.Path : "NULL"), - (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"), - (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); + (membersSearcher is not null ? membersSearcher[0].Filter : "NULL"), + (membersSearcher is not null ? membersSearcher[0].SearchRoot.Path : "NULL"), + (primaryGroupMembersSearcher is not null ? primaryGroupMembersSearcher.Filter : "NULL"), + (primaryGroupMembersSearcher is not null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); _groupsVisited.Add(groupDN); // so we don't revisit it _recursive = recursive; @@ -106,10 +106,10 @@ internal ADDNLinkedAttrSet( _membersEnum = null; _primaryGroupDN = primaryGroupDN; - if (primaryGroupDN == null) + if (primaryGroupDN is null) _returnedPrimaryGroup = true; // so we don't bother trying to return the primary group - if (null != membersSearcher) + if (membersSearcher is not null) { foreach (DirectorySearcher ds in membersSearcher) { @@ -132,7 +132,7 @@ internal override object CurrentAsPrincipal { get { - if (this.current != null) + if (this.current is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using current"); if (this.current is DirectoryEntry) @@ -145,7 +145,7 @@ internal override object CurrentAsPrincipal else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using currentForeignPrincipal"); - Debug.Assert(_currentForeignPrincipal != null); + Debug.Assert(_currentForeignPrincipal is not null); return _currentForeignPrincipal; } } @@ -209,7 +209,7 @@ internal override bool MoveNext() private bool MoveNextPrimaryGroupDN() { // Do the special primary group ID processing if we haven't yet returned the primary group. - Debug.Assert(_primaryGroupDN != null); + Debug.Assert(_primaryGroupDN is not null); this.current = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(_primaryGroupDN), @@ -233,9 +233,9 @@ private bool GetNextSearchResult() do { - if (_currentMembersSearcher == null) + if (_currentMembersSearcher is null) { - Debug.Assert(_memberSearchersQueue != null); + Debug.Assert(_memberSearchersQueue is not null); if (_memberSearchersQueue.Count == 0) { @@ -247,7 +247,7 @@ private bool GetNextSearchResult() // Remove the next searcher from the queue and place it in the current search variable. _currentMembersSearcher = _memberSearchersQueue.Dequeue(); _memberSearchResults = _currentMembersSearcher.FindAll(); - Debug.Assert(_memberSearchResults != null); + Debug.Assert(_memberSearchResults is not null); _memberSearchResultsEnumerator = _memberSearchResults.GetEnumerator(); } } @@ -418,12 +418,12 @@ private bool GetNextEnum() if (!memberFound) { IDisposable disposableMembers = _members as IDisposable; - if (disposableMembers != null) + if (disposableMembers is not null) { disposableMembers.Dispose(); } IDisposable disposableMembersEnum = _membersEnum as IDisposable; - if (disposableMembersEnum != null) + if (disposableMembersEnum is not null) { disposableMembersEnum.Dispose(); } @@ -532,7 +532,7 @@ private bool MoveNextMemberEnum() } finally { - if (disposeMemberDE && memberDE != null) + if (disposeMemberDE && memberDE is not null) { //This means the constructed member is not used in the new principal memberDE.Dispose(); @@ -664,7 +664,7 @@ private bool MoveNextForeign(ref bool outerNeedToRetry) _fakePrincipalMembers[0].Dispose(); _fakePrincipalMembers.RemoveAt(0); } - else if ((_foreignMembersToReturn != null) && (_foreignMembersToReturn.Length > 0)) + else if ((_foreignMembersToReturn is not null) && (_foreignMembersToReturn.Length > 0)) { StoreCtx foreignStoreCtx; @@ -672,7 +672,7 @@ private bool MoveNextForeign(ref bool outerNeedToRetry) // sidIssuerName is null only if SID was not resolved // return a unknown principal back - if (null == foreignSid.sidIssuerName) + if (foreignSid.sidIssuerName is null) { // create and return the unknown principal if it is not yet present in usersVisited if (!_usersVisited.ContainsKey(foreignSid.name)) @@ -715,8 +715,8 @@ private bool MoveNextForeign(ref bool outerNeedToRetry) ContextType.Domain, foreignSid.sidIssuerName, null, - (this.storeCtx.Credentials != null ? this.storeCtx.Credentials.UserName : null), - (this.storeCtx.Credentials != null ? storeCtx.storeCtx.Credentials.Password : null), + (this.storeCtx.Credentials is not null ? this.storeCtx.Credentials.UserName : null), + (this.storeCtx.Credentials is not null ? storeCtx.storeCtx.Credentials.Password : null), remoteOptions); #endif @@ -729,7 +729,7 @@ private bool MoveNextForeign(ref bool outerNeedToRetry) (new SecurityIdentifier(Utils.ConvertNativeSidToByteArray(_foreignMembersToReturn[0].pSid), 0)).ToString(), DateTime.UtcNow); - if (null == foreignPrincipal) + if (foreignPrincipal is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: no matching principal"); throw new PrincipalOperationException(SR.ADStoreCtxFailedFindCrossStoreTarget); @@ -894,17 +894,17 @@ private bool MoveNextQueryPrimaryGroupMember() { bool f = false; - if (_primaryGroupMembersSearcher != null) + if (_primaryGroupMembersSearcher is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher"); - if (_queryMembersResults == null) + if (_queryMembersResults is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: issuing query"); _queryMembersResults = _primaryGroupMembersSearcher.FindAll(); - Debug.Assert(_queryMembersResults != null); + Debug.Assert(_queryMembersResults is not null); _queryMembersResultEnumerator = _queryMembersResults.GetEnumerator(); } @@ -914,7 +914,7 @@ private bool MoveNextQueryPrimaryGroupMember() if (f) { this.current = (SearchResult)_queryMembersResultEnumerator.Current; - Debug.Assert(this.current != null); + Debug.Assert(this.current is not null); _currentForeignDE = null; _currentForeignPrincipal = null; @@ -966,7 +966,7 @@ internal override void Reset() _storeCtx = _originalStoreCtx; this.current = null; - if (_primaryGroupDN != null) + if (_primaryGroupDN is not null) _returnedPrimaryGroup = false; _foreignMembersCurrentGroup.Clear(); @@ -981,7 +981,7 @@ internal override void Reset() _foreignGroups.Clear(); _queryMembersResultEnumerator = null; - if (_queryMembersResults != null) + if (_queryMembersResults is not null) { _queryMembersResults.Dispose(); _queryMembersResults = null; @@ -994,7 +994,7 @@ internal override void Reset() } _memberSearchResultsEnumerator = null; - if (_memberSearchResults != null) + if (_memberSearchResults is not null) { _memberSearchResults.Dispose(); _memberSearchResults = null; @@ -1064,7 +1064,7 @@ internal override ResultSetBookmark BookmarkAndReset() { _membersQueue.Clear(); - if (_originalMembers != null) + if (_originalMembers is not null) { foreach (IEnumerable ie in _originalMembers) { @@ -1090,7 +1090,7 @@ internal override ResultSetBookmark BookmarkAndReset() bookmark.current = this.current; bookmark.returnedPrimaryGroup = _returnedPrimaryGroup; this.current = null; - if (_primaryGroupDN != null) + if (_primaryGroupDN is not null) _returnedPrimaryGroup = false; bookmark.foreignMembersCurrentGroup = _foreignMembersCurrentGroup; @@ -1160,7 +1160,7 @@ internal override void RestoreBookmark(ResultSetBookmark bookmark) _currentForeignPrincipal = adBookmark.currentForeignPrincipal; _currentForeignDE = adBookmark.currentForeignDE; _foreignGroups = adBookmark.foreignGroups; - if (_queryMembersResults != null) + if (_queryMembersResults is not null) _queryMembersResults.Dispose(); _queryMembersResults = adBookmark.queryMembersResults; _queryMembersResultEnumerator = adBookmark.queryMembersResultEnumerator; @@ -1178,7 +1178,7 @@ internal override void RestoreBookmark(ResultSetBookmark bookmark) { _membersQueue.Clear(); - if (null != adBookmark.membersQueue) + if (adBookmark.membersQueue is not null) { foreach (IEnumerable ie in adBookmark.membersQueue) { @@ -1196,7 +1196,7 @@ internal override void RestoreBookmark(ResultSetBookmark bookmark) _memberSearchersQueue.Clear(); - if (null != adBookmark.memberSearcherQueue) + if (adBookmark.memberSearcherQueue is not null) { foreach (DirectorySearcher ds in adBookmark.memberSearcherQueue) { @@ -1215,31 +1215,31 @@ public override void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing"); - if (_primaryGroupMembersSearcher != null) + if (_primaryGroupMembersSearcher is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing primaryGroupMembersSearcher"); _primaryGroupMembersSearcher.Dispose(); } - if (_queryMembersResults != null) + if (_queryMembersResults is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing queryMembersResults"); _queryMembersResults.Dispose(); } - if (_currentMembersSearcher != null) + if (_currentMembersSearcher is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersSearcher"); _currentMembersSearcher.Dispose(); } - if (_memberSearchResults != null) + if (_memberSearchResults is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchResults"); _memberSearchResults.Dispose(); } - if (_memberSearchersQueue != null) + if (_memberSearchersQueue is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchersQueue"); foreach (DirectorySearcher ds in _memberSearchersQueue) @@ -1250,30 +1250,30 @@ public override void Dispose() _memberSearchersQueue.Clear(); } IDisposable disposableMembers = _members as IDisposable; - if (disposableMembers != null) + if (disposableMembers is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing members Enumerable"); disposableMembers.Dispose(); } IDisposable disposableMembersEnum = _membersEnum as IDisposable; - if (disposableMembersEnum != null) + if (disposableMembersEnum is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersEnum Enumerator"); disposableMembersEnum.Dispose(); } - if (_membersQueue != null) + if (_membersQueue is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersQueue"); foreach (IEnumerable enumerable in _membersQueue) { IDisposable disposableEnum = enumerable as IDisposable; - if (disposableEnum != null) + if (disposableEnum is not null) { disposableEnum.Dispose(); } } } - if (_foreignGroups != null) + if (_foreignGroups is not null) { foreach (GroupPrincipal gp in _foreignGroups) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs index b100cff9817ac5..b765a97353289d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs @@ -48,7 +48,7 @@ internal override object CurrentAsPrincipal // Since this class is only used internally, none of our code should be even calling this // if MoveNext returned false, or before calling MoveNext. - Debug.Assert(_endReached == false && _current != null); + Debug.Assert(_endReached == false && _current is not null); return ADUtils.SearchResultAsPrincipal(_current, _storeCtx, _discriminant); } @@ -61,7 +61,7 @@ internal override bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADEntriesSet", "MoveNext"); - Debug.Assert(_enumerator != null); + Debug.Assert(_enumerator is not null); bool f = _enumerator.MoveNext(); @@ -88,7 +88,7 @@ internal override void Reset() _endReached = false; _current = null; - if (_enumerator != null) + if (_enumerator is not null) _enumerator.Reset(); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index b2ac217818c342..bd36085fc40f98 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -63,7 +63,7 @@ protected virtual int MappingTableIndex protected static void LoadFilterMappingTable(int mappingIndex, object[,] rawFilterPropertiesTable) { - if (null == s_filterPropertiesTable) + if (s_filterPropertiesTable is null) s_filterPropertiesTable = new Hashtable(); Hashtable mappingTable = new Hashtable(); @@ -74,11 +74,11 @@ protected static void LoadFilterMappingTable(int mappingIndex, object[,] rawFilt string adPropertyName = rawFilterPropertiesTable[i, 1] as string; FilterConverterDelegate f = rawFilterPropertiesTable[i, 2] as FilterConverterDelegate; - Debug.Assert(qbeType != null); - Debug.Assert(f != null); + Debug.Assert(qbeType is not null); + Debug.Assert(f is not null); // There should only be one entry per QBE type - Debug.Assert(mappingTable[qbeType] == null); + Debug.Assert(mappingTable[qbeType] is null); FilterPropertyTableEntry entry = new FilterPropertyTableEntry(); entry.suggestedADPropertyName = adPropertyName; @@ -95,16 +95,16 @@ protected static void LoadPropertyMappingTable(int mappingIndex, object[,] rawPr // // Load the propertyMappingTableByProperty and propertyMappingTableByLDAP tables // - if (null == s_propertyMappingTableByProperty) + if (s_propertyMappingTableByProperty is null) s_propertyMappingTableByProperty = new Hashtable(); - if (null == s_propertyMappingTableByLDAP) + if (s_propertyMappingTableByLDAP is null) s_propertyMappingTableByLDAP = new Hashtable(); - if (null == s_propertyMappingTableByPropertyFull) + if (s_propertyMappingTableByPropertyFull is null) s_propertyMappingTableByPropertyFull = new Hashtable(); - if (null == TypeToLdapPropListMap) + if (TypeToLdapPropListMap is null) TypeToLdapPropListMap = new Dictionary>(); Hashtable mappingTableByProperty = new Hashtable(); @@ -122,9 +122,9 @@ protected static void LoadPropertyMappingTable(int mappingIndex, object[,] rawPr FromLdapConverterDelegate fromLdap = rawPropertyMappingTable[i, 2] as FromLdapConverterDelegate; ToLdapConverterDelegate toLdap = rawPropertyMappingTable[i, 3] as ToLdapConverterDelegate; - Debug.Assert(propertyName != null); - Debug.Assert((ldapAttribute != null && fromLdap != null) || (fromLdap == null)); - //Debug.Assert(toLdap != null); + Debug.Assert(propertyName is not null); + Debug.Assert((ldapAttribute is not null && fromLdap is not null) || (fromLdap is null)); + //Debug.Assert(toLdap is not null); // Build the table entry. The same entry will be used in both tables. // Once constructed, the table entries are treated as read-only, so there's @@ -137,7 +137,7 @@ protected static void LoadPropertyMappingTable(int mappingIndex, object[,] rawPr // Build a mapping table from PAPI propertyname to ldapAttribute that we can use below // to build a list of ldap attributes for each object type. - if (null != ldapAttribute) + if (ldapAttribute is not null) { if (propertyNameToLdapAttr.ContainsKey(propertyName)) { @@ -153,15 +153,15 @@ protected static void LoadPropertyMappingTable(int mappingIndex, object[,] rawPr // propertyMappingTableByProperty // If toLdap is null, there's no PAPI->LDAP mapping for this property // (it's probably read-only, e.g., "lastLogon"). - if (toLdap != null) + if (toLdap is not null) { - if (mappingTableByProperty[propertyName] == null) + if (mappingTableByProperty[propertyName] is null) mappingTableByProperty[propertyName] = new ArrayList(); ((ArrayList)mappingTableByProperty[propertyName]).Add(propertyEntry); } - if (mappingTableByPropertyFull[propertyName] == null) + if (mappingTableByPropertyFull[propertyName] is null) mappingTableByPropertyFull[propertyName] = new ArrayList(); ((ArrayList)mappingTableByPropertyFull[propertyName]).Add(propertyEntry); @@ -169,11 +169,11 @@ protected static void LoadPropertyMappingTable(int mappingIndex, object[,] rawPr // mappingTableByLDAP // If fromLdap is null, there's no direct LDAP->PAPI mapping for this property. // It's probably a property that requires custom handling, such as IdentityClaim. - if (fromLdap != null) + if (fromLdap is not null) { string ldapAttributeLower = ldapAttribute.ToLowerInvariant(); - if (mappingTableByLDAP[ldapAttributeLower] == null) + if (mappingTableByLDAP[ldapAttributeLower] is null) mappingTableByLDAP[ldapAttributeLower] = new ArrayList(); ((ArrayList)mappingTableByLDAP[ldapAttributeLower]).Add(propertyEntry); @@ -284,7 +284,7 @@ public ADStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, stri { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "Constructing ADStoreCtx for {0}", ctxBase.Path); - Debug.Assert(ctxBase != null); + Debug.Assert(ctxBase is not null); // This will also detect if the server is down or nonexistent if (!IsContainer(ctxBase)) @@ -293,7 +293,7 @@ public ADStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, stri this.ctxBase = ctxBase; _ownCtxBase = ownCtxBase; - if (username != null && password != null) + if (username is not null && password is not null) this.credentials = new NetCred(username, password); this.contextOptions = options; @@ -347,7 +347,7 @@ internal override string BasePath { get { - Debug.Assert(this.ctxBase != null); + Debug.Assert(this.ctxBase is not null); return this.ctxBase.Path; } } @@ -388,9 +388,9 @@ internal override void Insert(Principal p) SetPasswordSecurityifNeccessary(p); // Load in the StoreKey - Debug.Assert(p.Key == null); // since it was previously unpersisted + Debug.Assert(p.Key is null); // since it was previously unpersisted - Debug.Assert(p.UnderlyingObject != null); // since we just persisted it + Debug.Assert(p.UnderlyingObject is not null); // since we just persisted it Debug.Assert(p.UnderlyingObject is DirectoryEntry); ADStoreKey key = new ADStoreKey(((DirectoryEntry)p.UnderlyingObject).Guid); @@ -411,7 +411,7 @@ internal override void Insert(Principal p) try { GlobalDebug.WriteLineIf(GlobalDebug.Error, "ADStoreCtx", "Insert, Save Failed (attempting to delete) Exception {0} ", e.Message); - if (null != p.UnderlyingObject) + if (p.UnderlyingObject is not null) { SDSUtils.DeleteDirectoryEntry((DirectoryEntry)p.UnderlyingObject); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "Insert, object deleted"); @@ -665,7 +665,7 @@ internal override void Update(Principal p) Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); // Commit the properties @@ -700,7 +700,7 @@ internal override void Delete(Principal p) // Principal.Delete() shouldn't be calling us on an unpersisted Principal. Debug.Assert(p.unpersisted == false); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); SDSUtils.DeleteDirectoryEntry((DirectoryEntry)p.UnderlyingObject); @@ -715,8 +715,8 @@ internal override void Move(StoreCtx originalStore, Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "Move"); - Debug.Assert(p != null); - Debug.Assert(originalStore != null); + Debug.Assert(p is not null); + Debug.Assert(originalStore is not null); Debug.Assert(originalStore is ADStoreCtx); string name = null; @@ -724,7 +724,7 @@ internal override void Move(StoreCtx originalStore, Principal p) string baseObjectRdnPrefix = null; Type principalType = p.GetType(); - if (null == rdnPrefix) + if (rdnPrefix is null) { throw new InvalidOperationException(SR.ExtensionInvalidClassAttributes); } @@ -744,7 +744,7 @@ internal override void Move(StoreCtx originalStore, Principal p) DirectoryRdnPrefixAttribute[] MyAttribute = (DirectoryRdnPrefixAttribute[])Attribute.GetCustomAttributes(principalType.BaseType, typeof(DirectoryRdnPrefixAttribute), false); - if (MyAttribute == null) + if (MyAttribute is null) throw new InvalidOperationException(SR.ExtensionInvalidClassAttributes); string defaultRdn = null; @@ -753,7 +753,7 @@ internal override void Move(StoreCtx originalStore, Principal p) // that matches the principals context or the first rdnPrefix that has a null context type for (int i = 0; i < MyAttribute.Length; i++) { - if ((MyAttribute[i].Context == null && null == defaultRdn) || + if ((MyAttribute[i].Context is null && defaultRdn is null) || (p.ContextType == MyAttribute[i].Context)) { defaultRdn = MyAttribute[i].RdnPrefix; @@ -774,7 +774,7 @@ internal override void Move(StoreCtx originalStore, Principal p) p.LoadValueIntoProperty(PropertyNames.PrincipalName, p.GetValueForProperty(PropertyNames.PrincipalName)); - if (null != baseObjectRdnPrefix) + if (baseObjectRdnPrefix is not null) { ((DirectoryEntry)p.GetUnderlyingObject()).Properties[baseObjectRdnPrefix].Value = (string)p.GetValueForProperty(PropertyNames.PrincipalName); } @@ -794,13 +794,13 @@ internal override void Move(StoreCtx originalStore, Principal p) /// Principal to set the user account control bits for internal override void InitializeUserAccountControl(AuthenticablePrincipal p) { - Debug.Assert(p != null); + Debug.Assert(p is not null); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == true); // should only ever be called for new principals // set the userAccountControl bits on the underlying directory entry DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); Type principalType = p.GetType(); if ((principalType == typeof(ComputerPrincipal)) || (principalType.IsSubclassOf(typeof(ComputerPrincipal)))) @@ -830,7 +830,7 @@ internal override bool IsLockedOut(AuthenticablePrincipal p) Debug.Assert(p.unpersisted == false); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); de.RefreshCache(new string[] { "msDS-User-Account-Control-Computed", "lockoutTime" }); @@ -902,11 +902,11 @@ internal override void SetPassword(AuthenticablePrincipal p, string newPassword) { Debug.Assert(p.fakePrincipal == false); - Debug.Assert(p != null); - Debug.Assert(newPassword != null); // but it could be an empty string + Debug.Assert(p is not null); + Debug.Assert(newPassword is not null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); SDSUtils.SetPassword(de, newPassword); } @@ -924,9 +924,9 @@ internal override void ChangePassword(AuthenticablePrincipal p, string oldPasswo // Shouldn't be being called if this is the case Debug.Assert(p.unpersisted == false); - Debug.Assert(p != null); - Debug.Assert(newPassword != null); // but it could be an empty string - Debug.Assert(oldPassword != null); // but it could be an empty string + Debug.Assert(p is not null); + Debug.Assert(newPassword is not null); // but it could be an empty string + Debug.Assert(oldPassword is not null); // but it could be an empty string if ((p.GetType() == typeof(ComputerPrincipal)) || (p.GetType().IsSubclassOf(typeof(ComputerPrincipal)))) { @@ -935,7 +935,7 @@ internal override void ChangePassword(AuthenticablePrincipal p, string oldPasswo } DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); SDSUtils.ChangePassword(de, oldPassword, newPassword); } @@ -975,7 +975,7 @@ protected void WriteAttribute(Principal p, string attribute, int value) { ; - Debug.Assert(p != null); + Debug.Assert(p is not null); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; @@ -984,7 +984,7 @@ protected void WriteAttribute(Principal p, string attribute, int value) protected void WriteAttribute(Principal p, string attribute, T value) { - Debug.Assert(p != null); + Debug.Assert(p is not null); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; @@ -1024,7 +1024,7 @@ internal override ResultSet FindByExpirationTime( private ResultSet FindByDate(Type subtype, string[] ldapAttributes, MatchType matchType, DateTime value) { - Debug.Assert(ldapAttributes != null); + Debug.Assert(ldapAttributes is not null); Debug.Assert(ldapAttributes.Length > 0); Debug.Assert(subtype == typeof(Principal) || subtype.IsSubclassOf(typeof(Principal))); DirectorySearcher ds = new DirectorySearcher(this.ctxBase); @@ -1119,7 +1119,7 @@ private ResultSet FindByDate(Type subtype, string[] ldapAttributes, MatchType ma // Perform the search SearchResultCollection src = ds.FindAll(); - Debug.Assert(src != null); + Debug.Assert(src is not null); // Create a ResultSet for the search results ADEntriesSet resultSet = new ADEntriesSet(src, this); @@ -1162,7 +1162,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) return GetGroupsMemberOf(p, this); } - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); string primaryGroupDN = null; ResultSet resultSet = null; @@ -1192,9 +1192,9 @@ internal override ResultSet GetGroupsMemberOf(Principal p) // duplicates because the list of global groups will show up on both the GC and DC. Debug.Assert(p.ContextType == ContextType.Domain); - Forest forest = Forest.GetForest(new DirectoryContext(DirectoryContextType.Forest, this.DnsForestName, this.credentials != null ? this.credentials.UserName : null, this.credentials != null ? this.credentials.Password : null)); + Forest forest = Forest.GetForest(new DirectoryContext(DirectoryContextType.Forest, this.DnsForestName, this.credentials is not null ? this.credentials.UserName : null, this.credentials is not null ? this.credentials.Password : null)); - DirectoryContext dc = new DirectoryContext(DirectoryContextType.Domain, this.DnsDomainName, this.credentials != null ? this.credentials.UserName : null, this.credentials != null ? this.credentials.Password : null); + DirectoryContext dc = new DirectoryContext(DirectoryContextType.Domain, this.DnsDomainName, this.credentials is not null ? this.credentials.UserName : null, this.credentials is not null ? this.credentials.Password : null); DomainController dd = DomainController.FindOne(dc); GlobalCatalog gc = null; @@ -1213,7 +1213,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) } } - roots.Add(new DirectoryEntry("GC://" + gc.Name + "/" + p.DistinguishedName, this.credentials != null ? this.credentials.UserName : null, this.credentials != null ? this.credentials.Password : null, this.AuthTypes)); + roots.Add(new DirectoryEntry("GC://" + gc.Name + "/" + p.DistinguishedName, this.credentials is not null ? this.credentials.UserName : null, this.credentials is not null ? this.credentials.Password : null, this.AuthTypes)); if (!string.Equals(this.DnsDomainName, gc.Domain.Name, StringComparison.OrdinalIgnoreCase)) { @@ -1251,11 +1251,11 @@ internal override ResultSet GetGroupsMemberOf(Principal p) } finally { - if (gc != null) + if (gc is not null) { gc.Dispose(); } - if (forest != null) + if (forest is not null) { forest.Dispose(); } @@ -1330,7 +1330,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) if (useASQ) { - if (resultValidator != null) + if (resultValidator is not null) { resultSet = new ADDNConstraintLinkedAttrSet( ADDNConstraintLinkedAttrSet.ConstraintType.ResultValidatorDelegateMatch, @@ -1343,7 +1343,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) } else { - if (resultValidator != null) + if (resultValidator is not null) { resultSet = new ADDNConstraintLinkedAttrSet( ADDNConstraintLinkedAttrSet.ConstraintType.ResultValidatorDelegateMatch, @@ -1362,12 +1362,12 @@ internal override ResultSet GetGroupsMemberOf(Principal p) } finally { - if (null != gcPrincipalDe) + if (gcPrincipalDe is not null) { gcPrincipalDe.Dispose(); } - if (null != memberOfSearcher) + if (memberOfSearcher is not null) { memberOfSearcher.Dispose(); } @@ -1381,7 +1381,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // Get the Principal's SID, so we can look it up by SID in our store SecurityIdentifier Sid = foreignPrincipal.Sid; - if (Sid == null) + if (Sid is null) throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); // Search our store for a object with a matching SID. This could be a user/group/computer object, @@ -1430,22 +1430,22 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC { if (rootPrincipalExists) { - if (this.DefaultNamingContext != null) + if (this.DefaultNamingContext is not null) { - dncContainer = new DirectoryEntry(@"LDAP://" + this.UserSuppliedServerName + @"/" + this.DefaultNamingContext, Credentials != null ? this.Credentials.UserName : null, Credentials != null ? this.Credentials.Password : null, this.AuthTypes); + dncContainer = new DirectoryEntry(@"LDAP://" + this.UserSuppliedServerName + @"/" + this.DefaultNamingContext, Credentials is not null ? this.Credentials.UserName : null, Credentials is not null ? this.Credentials.Password : null, this.AuthTypes); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetGroupsMemberOf(ctx): Read DNC of {0}", this.DefaultNamingContext); fspWkDn = ADUtils.RetriveWkDn(dncContainer, this.DefaultNamingContext, this.UserSuppliedServerName, Constants.GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE); - if (null != fspWkDn) + if (fspWkDn is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetGroupsMemberOf(ctx): Read fsp DN {0}", fspWkDn); - fspContainer = new DirectoryEntry(fspWkDn, Credentials != null ? this.credentials.UserName : null, Credentials != null ? this.credentials.Password : null, this.authTypes); + fspContainer = new DirectoryEntry(fspWkDn, Credentials is not null ? this.credentials.UserName : null, Credentials is not null ? this.credentials.Password : null, this.authTypes); } } - ds = new DirectorySearcher((fspContainer != null) ? fspContainer : ((dncContainer != null ? dncContainer : this.ctxBase))); + ds = new DirectorySearcher((fspContainer is not null) ? fspContainer : ((dncContainer is not null ? dncContainer : this.ctxBase))); // Pick some reasonable default values ds.PageSize = 256; @@ -1454,7 +1454,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // Build the LDAP filter // Converr the object to a SDDL format string stringSid = Utils.SecurityIdentifierToLdapHexFilterString(Sid); - if (stringSid == null) + if (stringSid is null) throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); ds.Filter = "(objectSid=" + stringSid + ")"; @@ -1471,7 +1471,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // a member of any groups in this store. SearchResult sr = ds.FindOne(); - if (sr == null) + if (sr is null) { // no match so we better do a root level search in case we are targetting a domain where // the user is not an FSP. @@ -1480,7 +1480,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // We already did a root level search so just exit. - if (null == fspWkDn) + if (fspWkDn is null) return new EmptySet(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetGroupsMemberOf(ctx): performing DNC level search"); @@ -1488,7 +1488,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC ds.SearchRoot = dncContainer; sr = ds.FindOne(); - if (sr == null) + if (sr is null) return new EmptySet(); } @@ -1540,11 +1540,11 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC } finally { - if (null != fspContainer) + if (fspContainer is not null) fspContainer.Dispose(); - if (null != ds) + if (ds is not null) ds.Dispose(); - if (null != dncContainer) + if (dncContainer is not null) dncContainer.Dispose(); } } @@ -1559,7 +1559,7 @@ private string GetGroupDnFromGroupID(byte[] userSid, int primaryGroupId) try { string sddlSid = Utils.ConvertSidToSDDL(userSid); - if (sddlSid != null) + if (sddlSid is not null) { // Next, we modify the SDDL SID to replace with final subauthority // with the primary group's RID (the primaryGroupID) @@ -1584,7 +1584,7 @@ private string GetGroupDnFromGroupID(byte[] userSid, int primaryGroupId) UnsafeNativeMethods.LocalFree(pGroupSid); } - if (groupSid != null) + if (groupSid is not null) { return ""; } @@ -1602,7 +1602,7 @@ internal override ResultSet GetGroupsMemberOfAZ(Principal p) // Get the user SID that AuthZ will use. SecurityIdentifier SidObj = p.Sid; - if (SidObj == null) + if (SidObj is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADStoreCtx", "GetGroupsMemberOfAZ: no SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -1611,7 +1611,7 @@ internal override ResultSet GetGroupsMemberOfAZ(Principal p) byte[] sid = new byte[SidObj.BinaryLength]; SidObj.GetBinaryForm(sid, 0); - if (sid == null) + if (sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADStoreCtx", "GetGroupsMemberOfAZ: bad SID IC"); throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat); @@ -1619,7 +1619,7 @@ internal override ResultSet GetGroupsMemberOfAZ(Principal p) try { - if (true == ADUtils.VerifyOutboundTrust(this.DnsDomainName, (this.credentials == null ? null : this.credentials.UserName), (this.credentials == null ? null : this.credentials.Password))) + if (true == ADUtils.VerifyOutboundTrust(this.DnsDomainName, (this.credentials is null ? null : this.credentials.UserName), (this.credentials is null ? null : this.credentials.Password))) { return new AuthZSet(sid, this.credentials, this.contextOptions, this.FlatDomainName, this, this.ctxBase); } @@ -1654,7 +1654,7 @@ internal override BookmarkableResultSet GetGroupMembership(GroupPrincipal g, boo return new EmptySet(); } - Debug.Assert(g.UnderlyingObject != null); + Debug.Assert(g.UnderlyingObject is not null); try { @@ -1717,7 +1717,7 @@ internal override BookmarkableResultSet GetGroupMembership(GroupPrincipal g, boo private DirectorySearcher GetDirectorySearcherFromGroupID(byte[] groupSid) { - Debug.Assert(groupSid != null); + Debug.Assert(groupSid is not null); // Get the group's RID from the group's SID int groupRid = Utils.GetLastRidFromSid(groupSid); @@ -1760,14 +1760,14 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) return false; } - Debug.Assert(g.UnderlyingObject != null && g.UnderlyingObject is DirectoryEntry); + Debug.Assert(g.UnderlyingObject is not null && g.UnderlyingObject is DirectoryEntry); IEnumerable cachedMembersEnum = null; //This variables stores a reference to the direct members enumerator of the group. // Only real principals can be directly a member of the group, since only real principals // actually exist in the store. if (!p.fakePrincipal) { - Debug.Assert(p.UnderlyingObject != null && p.UnderlyingObject is DirectoryEntry); + Debug.Assert(p.UnderlyingObject is not null && p.UnderlyingObject is DirectoryEntry); //// Test for direct membership //// @@ -1782,9 +1782,9 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) if (g.IsSmallGroup()) { // small groups has special search object that holds the member attribute so we use it for our search (no need to use the DirectoryEntry) - Debug.Assert(g.SmallGroupMemberSearchResult != null); + Debug.Assert(g.SmallGroupMemberSearchResult is not null); cachedMembersEnum = g.SmallGroupMemberSearchResult.Properties["member"]; - if ((g.SmallGroupMemberSearchResult != null) && g.SmallGroupMemberSearchResult.Properties["member"].Contains(principalDN)) + if ((g.SmallGroupMemberSearchResult is not null) && g.SmallGroupMemberSearchResult.Properties["member"].Contains(principalDN)) { return true; } @@ -1814,7 +1814,7 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) // Get the Principal's SID, so we can look it up by SID in our store SecurityIdentifier Sid = p.Sid; - if (Sid == null) + if (Sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADStoreCtx", "IsMemberOfInStore: no SID IC or null UrnValue"); throw new ArgumentException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -1840,7 +1840,7 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) // Build the LDAP filter, Convert the sid to SDDL format string stringSid = Utils.SecurityIdentifierToLdapHexFilterString(Sid); - if (stringSid == null) + if (stringSid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADStoreCtx", "IsMemberOfInStore: bad SID IC"); throw new ArgumentException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -1857,7 +1857,7 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) SearchResult sr = ds.FindOne(); // No FPO ---> not a member - if (sr == null) + if (sr is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "IsMemberOfInStore: no FPO found"); return false; @@ -1878,11 +1878,11 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) } finally { - if (ds != null) + if (ds is not null) { ds.Dispose(); } - if (defaultNCDirEntry != null) + if (defaultNCDirEntry is not null) { defaultNCDirEntry.Dispose(); } @@ -1909,7 +1909,7 @@ internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanatio return true; } - Debug.Assert(g.UnderlyingObject != null); + Debug.Assert(g.UnderlyingObject is not null); DirectoryEntry groupDE = (DirectoryEntry)g.UnderlyingObject; // Create a DirectorySearcher for users who are members of this group via their primaryGroupId attribute @@ -1931,7 +1931,7 @@ internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanatio SearchResult sr = ds.FindOne(); - if (sr != null) + if (sr is not null) { // there is such a member, we can't clear the group GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "IsMemberOfInStore: found member, can't clear"); @@ -1960,7 +1960,7 @@ internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanatio } finally { - if (ds != null) + if (ds is not null) ds.Dispose(); } } @@ -2011,8 +2011,8 @@ internal override bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal membe try { - Debug.Assert(g.UnderlyingObject != null); - Debug.Assert(member.UnderlyingObject != null); + Debug.Assert(g.UnderlyingObject is not null); + Debug.Assert(member.UnderlyingObject is not null); DirectoryEntry groupDE = (DirectoryEntry)g.UnderlyingObject; DirectoryEntry memberDE = (DirectoryEntry)member.UnderlyingObject; @@ -2166,8 +2166,8 @@ internal override Principal ResolveCrossStoreRefToPrincipal(object o) ContextType.Domain, domainName, null, - (this.credentials != null ? credentials.UserName : null), - (this.credentials != null ? credentials.Password : null), + (this.credentials is not null ? credentials.UserName : null), + (this.credentials is not null ? credentials.Password : null), remoteOptions); #endif @@ -2180,7 +2180,7 @@ internal override Principal ResolveCrossStoreRefToPrincipal(object o) (new SecurityIdentifier(sid, 0)).ToString(), DateTime.UtcNow); - if (p != null) + if (p is not null) return p; else { @@ -2285,11 +2285,11 @@ internal string ContextBasePartitionDN { get { - if (this.contextBasePartitionDN == null) + if (this.contextBasePartitionDN is null) { lock (this.domainInfoLock) { - if (contextBasePartitionDN == null) + if (contextBasePartitionDN is null) LoadDomainInfo(); } } @@ -2302,11 +2302,11 @@ internal string DefaultNamingContext { get { - if (this.defaultNamingContext == null) + if (this.defaultNamingContext is null) { lock (this.domainInfoLock) { - if (defaultNamingContext == null) + if (defaultNamingContext is null) LoadDomainInfo(); } } @@ -2319,11 +2319,11 @@ private string FlatDomainName { get { - if (this.domainFlatName == null) + if (this.domainFlatName is null) { lock (this.domainInfoLock) { - if (domainFlatName == null) + if (domainFlatName is null) LoadDomainInfo(); } } @@ -2336,11 +2336,11 @@ internal string DnsDomainName { get { - if (this.domainDnsName == null) + if (this.domainDnsName is null) { lock (this.domainInfoLock) { - if (domainDnsName == null) + if (domainDnsName is null) LoadDomainInfo(); } } @@ -2353,11 +2353,11 @@ internal string DnsHostName { get { - if (this.dnsHostName == null) + if (this.dnsHostName is null) { lock (this.domainInfoLock) { - if (dnsHostName == null) + if (dnsHostName is null) LoadDomainInfo(); } } @@ -2370,11 +2370,11 @@ internal string DnsForestName { get { - if (this.forestDnsName == null) + if (this.forestDnsName is null) { lock (this.domainInfoLock) { - if (forestDnsName == null) + if (forestDnsName is null) LoadDomainInfo(); } } @@ -2387,11 +2387,11 @@ internal string UserSuppliedServerName { get { - if (this.userSuppliedServerName == null) + if (this.userSuppliedServerName is null) { lock (this.domainInfoLock) { - if (this.userSuppliedServerName == null) + if (this.userSuppliedServerName is null) LoadDomainInfo(); } } @@ -2406,11 +2406,11 @@ private ulong LockoutDuration { // We test domainDnsName for null because lockoutDuration could legitimately be 0, // but lockoutDuration is valid iff domainDnsName is non-null - if (this.domainDnsName == null) + if (this.domainDnsName is null) { lock (this.domainInfoLock) { - if (domainDnsName == null) + if (domainDnsName is null) LoadDomainInfo(); } } @@ -2439,7 +2439,7 @@ protected virtual void LoadDomainInfo() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "LoadComputerInfo"); - Debug.Assert(this.ctxBase != null); + Debug.Assert(this.ctxBase is not null); // // DNS Domain Name diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs index ce4f990717e296..3188b4a83e4bc4 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs @@ -38,7 +38,7 @@ internal override object PushChangesToNative(Principal p) { DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - if (de == null) + if (de is null) { // Must be a newly-inserted Principal for which PushChangesToNative has not yet // been called. @@ -61,7 +61,7 @@ internal override object PushChangesToNative(Principal p) { objectClass = p.ExtensionHelper.StructuralObjectClass; - if (null == objectClass || null == rdnPrefix) + if (objectClass is null || null == rdnPrefix) { throw new InvalidOperationException(SR.ExtensionInvalidClassAttributes); } @@ -78,7 +78,7 @@ internal override object PushChangesToNative(Principal p) DirectoryRdnPrefixAttribute[] MyAttribute = (DirectoryRdnPrefixAttribute[])Attribute.GetCustomAttributes(principalType.BaseType, typeof(DirectoryRdnPrefixAttribute), false); - if (MyAttribute == null) + if (MyAttribute is null) throw new InvalidOperationException(SR.ExtensionInvalidClassAttributes); string defaultRdn = null; @@ -87,7 +87,7 @@ internal override object PushChangesToNative(Principal p) // that matches the principals context or the first rdnPrefix that has a null context type for (int i = 0; i < MyAttribute.Length; i++) { - if ((MyAttribute[i].Context == null && null == defaultRdn) || + if ((MyAttribute[i].Context is null && defaultRdn is null) || (p.ContextType == MyAttribute[i].Context)) { defaultRdn = MyAttribute[i].RdnPrefix; @@ -113,11 +113,11 @@ internal override object PushChangesToNative(Principal p) // They set a display name. string name = (string)p.GetValueForProperty(PropertyNames.PrincipalName); - if ((name != null) && (name.Length > 0)) + if ((name is not null) && (name.Length > 0)) rdnValue = ADUtils.EscapeDNComponent(name); } - if (rdnValue == null) + if (rdnValue is null) { if (p.GetChangeStatusForProperty(PropertyNames.PrincipalSamAccountName)) { @@ -133,20 +133,20 @@ internal override object PushChangesToNative(Principal p) samAccountName; } - if ((samAccountName != null) && (samAccountName.Length > 0)) + if ((samAccountName is not null) && (samAccountName.Length > 0)) { rdnValue = ADUtils.EscapeDNComponent(samAccountName); } } } - if (rdnPrefix == null) + if (rdnPrefix is null) { // There was no rdn prefix attribute set on the principal class throw new InvalidOperationException(SR.ExtensionInvalidClassAttributes); } - if (rdnValue == null) + if (rdnValue is null) { // They didn't set a display name or SAM IdentityClaim (or set an empty/invalid value for those). throw new InvalidOperationException(SR.NameMustBeSetToPersistPrincipal); @@ -159,7 +159,7 @@ internal override object PushChangesToNative(Principal p) de = this.ctxBase.Children.Add(rdn, objectClass); } - if (null != baseObjectRdnPrefix) + if (baseObjectRdnPrefix is not null) { de.Properties[baseObjectRdnPrefix].Value = rdnValue; } @@ -234,7 +234,7 @@ internal override object PushChangesToNative(Principal p) // We need to determine the type and then use the appropriate object. internal override Principal GetAsPrincipal(object storeObject, object discriminant) { - Debug.Assert(storeObject != null); + Debug.Assert(storeObject is not null); DirectoryEntry de = null; SearchResult sr = null; @@ -255,7 +255,7 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina distinguishedName = (string)sr.Properties["distinguishedName"][0]; } - GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetAsPrincipal: using path={0}", (null != de ? de.Path : "searchResult")); + GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetAsPrincipal: using path={0}", (de is not null ? de.Path : "searchResult")); // Construct an appropriate Principal object. @@ -286,7 +286,7 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina } } - if (de != null) + if (de is not null) { //NOTE: If target is GC then we do NOT use variable "de". So, need to dispose this at the end. p = SDSUtils.DirectoryEntryToPrincipal((targetIsFromGC ? dcEntry : de), constructedContext ?? this.OwningContext, (Type)discriminant); @@ -298,11 +298,11 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina p.UnderlyingObject = (targetIsFromGC ? dcEntry : sr.GetDirectoryEntry()); } - Debug.Assert(p != null); + Debug.Assert(p is not null); Guid g; - if (de != null) + if (de is not null) g = de.Guid; else { @@ -321,7 +321,7 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina } finally { - if (targetIsFromGC && de != null) + if (targetIsFromGC && de is not null) { //Since target is GC, variable "de" is not getting used. Disposing it. de.Dispose(); @@ -351,17 +351,17 @@ private string GetEscapedDN(string dn) internal override void Load(Principal p, string principalPropertyName) { - Debug.Assert(p != null); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p is not null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); dSPropertyCollection props; SearchResult sr = (SearchResult)p.UnderlyingSearchObject; - if (null == sr) + if (sr is null) { DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); Debug.Assert(p.GetUnderlyingObjectType() == typeof(DirectoryEntry)); props = new dSPropertyCollection(de.Properties); @@ -376,16 +376,16 @@ internal override void Load(Principal p, string principalPropertyName) ArrayList entries = (ArrayList)propertyMappingTable[principalPropertyName]; // We don't support this property and cannot load it. To maintain backward compatibility with the old code just return. - if (entries == null) + if (entries is null) return; - Debug.Assert(null != entries); + Debug.Assert(entries is not null); try { foreach (PropertyMappingTableEntry entry in entries) { - if (null != entry.ldapToPapiConverter) + if (entry.ldapToPapiConverter is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "Load_PropertyName: loading {0}", entry.propertyName); entry.ldapToPapiConverter(props, entry.suggestedADPropertyName, p, entry.propertyName); @@ -401,12 +401,12 @@ internal override void Load(Principal p, string principalPropertyName) // Loads the store values from p.UnderlyingObject into p, performing schema mapping as needed. internal override void Load(Principal p) { - Debug.Assert(p != null); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p is not null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "Entering Load, type={0}, path={1}", p.GetType(), de.Path); @@ -465,8 +465,8 @@ private Principal FindPrincipalByIdentRefHelper( "ADStoreCtx", "FindPrincipalByIdentRefHelper: type={0}, scheme={1}, value={2}, useSidHistory={3}", principalType.ToString(), - (urnScheme != null ? urnScheme : "NULL"), - (urnValue != null ? urnValue : "NULL"), + (urnScheme is not null ? urnScheme : "NULL"), + (urnValue is not null ? urnValue : "NULL"), useSidHistory); // @@ -507,7 +507,7 @@ private Principal FindPrincipalByIdentRefHelper( ldapFilter.Append(GetObjectClassPortion(principalType)); // Build the rest of the filter based off of the user's specified IdentityReference. - if (urnScheme != null) + if (urnScheme is not null) { // If they're searching by SID for a SID corresponding to a fake group, construct // and return the fake group @@ -519,7 +519,7 @@ private Principal FindPrincipalByIdentRefHelper( sid.GetBinaryForm(sidb, 0); // = Utils.StringToByteArray(urnValue); - if (sid == null) + if (sid is null) throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat); IntPtr pSid = IntPtr.Zero; @@ -573,7 +573,7 @@ private Principal FindPrincipalByIdentRefHelper( { } - if (sidb != null) + if (sidb is not null) { // They passed in a hex string, is it a valid SID, and if so, does it correspond to a fake // principal? @@ -623,7 +623,7 @@ private Principal FindPrincipalByIdentRefHelper( foreach (string urnSchemeToTry in urnSchemesToTry) { if (BuildLdapFilterFromIdentityClaim(urnValue, urnSchemeToTry, ref filterVal, useSidHistory, false)) - if (null != filterVal) + if (filterVal is not null) innerLdapFilter.Append(filterVal); } @@ -643,9 +643,9 @@ private Principal FindPrincipalByIdentRefHelper( // src = ds.FindAll(); - Debug.Assert(src != null); + Debug.Assert(src is not null); - if (src == null) + if (src is null) return null; // Did we find a match? @@ -669,7 +669,7 @@ private Principal FindPrincipalByIdentRefHelper( finally { ds.Dispose(); - if (src != null) + if (src is not null) { src.Dispose(); } @@ -681,7 +681,7 @@ private Principal FindPrincipalByIdentRefHelper( // for ADStoreCtx). For others, it may vary depending on the Principal passed in. internal override Type NativeType(Principal p) { - Debug.Assert(p != null); + Debug.Assert(p is not null); return typeof(DirectoryEntry); } @@ -1176,10 +1176,10 @@ protected static void StringToLdapConverter(Principal p, string propertyName, Di { string value = (string)p.GetValueForProperty(propertyName); - if (p.unpersisted && value == null) + if (p.unpersisted && value is null) return; - if ((value == null) || (value.Length > 0)) + if ((value is null) || (value.Length > 0)) de.Properties[suggestedAdProperty].Value = value; else throw new ArgumentException(SR.Format(SR.InvalidStringValueForStore, propertyName)); @@ -1189,10 +1189,10 @@ protected static void BinaryToLdapConverter(Principal p, string propertyName, Di { byte[] value = (byte[])p.GetValueForProperty(propertyName); - if (p.unpersisted && value == null) + if (p.unpersisted && value is null) return; - if (value != null && value.Length != 0) + if (value is not null && value.Length != 0) de.Properties[suggestedAdProperty].Value = value; else de.Properties[suggestedAdProperty].Value = null; @@ -1207,10 +1207,10 @@ protected static void BoolToLdapConverter(Principal p, string propertyName, Dire { object value = (bool)p.GetValueForProperty(propertyName); - if (p.unpersisted && value == null) + if (p.unpersisted && value is null) return; - if (value != null) + if (value is not null) de.Properties[suggestedAdProperty].Value = (bool)value; else de.Properties[suggestedAdProperty].Value = null; @@ -1225,7 +1225,7 @@ protected static void AcctDisabledToLdapConverter(Principal p, string propertyNa if (!p.unpersisted) { object value = (bool)p.GetValueForProperty(propertyName); - if (value != null) + if (value is not null) de.Properties[suggestedAdProperty].Value = !(bool)value; else de.Properties[suggestedAdProperty].Value = null; @@ -1252,7 +1252,7 @@ protected static void CommaStringToLdapConverter(Principal p, string propertyNam string s = (sb.Length > 0) ? sb.ToString() : null; - if (p.unpersisted && s == null) + if (p.unpersisted && s is null) return; de.Properties[suggestedAdProperty].Value = s; @@ -1294,7 +1294,7 @@ protected static void AcctExpirToLdapConverter(Principal p, string propertyName, { Nullable dt = (Nullable)p.GetValueForProperty(propertyName); - if (p.unpersisted && dt == null) + if (p.unpersisted && dt is null) return; UnsafeNativeMethods.ADsLargeInteger largeIntObj = new UnsafeNativeMethods.ADsLargeInteger(); @@ -1331,7 +1331,7 @@ protected static void ExtensionCacheToLdapConverter(Principal p, string property foreach (KeyValuePair kvp in cacheValues.properties) { - if (!kvp.Value.Filter && null != kvp.Value.Value && kvp.Value.Value.Length != 0) + if (!kvp.Value.Filter && kvp.Value.Value is not null && kvp.Value.Value.Length != 0) { // array of objects ( .Length > 1 && typeof(array[0] != ICollection or IList ) // Single collection ( .Length == 1 ) && typeof(array[0] == ICollection ) && typeof(array[0][0] != ICollection or IList ) @@ -1359,7 +1359,7 @@ protected static void ExtensionCacheToLdapConverter(Principal p, string property foreach (object oVal in valueCollection) { - if (null != oVal) + if (oVal is not null) { if ((oVal is ICollection || oVal is IList) && !(oVal is byte[])) throw new ArgumentException(SR.InvalidExtensionCollectionType); @@ -1370,7 +1370,7 @@ protected static void ExtensionCacheToLdapConverter(Principal p, string property // Do nothing if we are not persisted and the value is null. We can't delete a property that // has not already been set. - if (p.unpersisted && null == oVal) + if (p.unpersisted && oVal is null) continue; de.Properties[kvp.Key].Add(oVal); @@ -1382,7 +1382,7 @@ protected static void ExtensionCacheToLdapConverter(Principal p, string property GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheToLdapConverter - Adding " + kvp.Value.Value.ToString()); // Do nothing if we are not persisted and the value is null. We can't delete a property that // has not already been set. - if (p.unpersisted && (null == kvp.Value.Value[0])) + if (p.unpersisted && (kvp.Value.Value[0] is null)) continue; de.Properties[kvp.Key].Value = kvp.Value.Value[0]; @@ -1495,13 +1495,13 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, credentials, authTypes); - Debug.Assert(copyOfDe != null); + Debug.Assert(copyOfDe is not null); copyOfDe.Properties["member"].Clear(); copyOfDe.CommitChanges(); } finally { - if (copyOfDe != null) + if (copyOfDe is not null) copyOfDe.Dispose(); } } @@ -1537,7 +1537,7 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, if (member.unpersisted) throw new InvalidOperationException(SR.StoreCtxGroupHasUnpersistedInsertedPrincipal); - Debug.Assert(member.Context != null); + Debug.Assert(member.Context is not null); // Can only insert AD principals (no reg-SAM/MSAM principals) if (member.ContextType == ContextType.Machine) @@ -1562,7 +1562,7 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, // Build a SID DN. This needs to be a DN path not an ADSI sid path with the LDAP prefix. string memberSidDN = GetSidPathFromPrincipal(member); - if (memberSidDN == null) + if (memberSidDN is null) throw new PrincipalOperationException(SR.ADStoreCtxCouldntGetSIDForGroupMember); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "UpdateGroupMembership: add {0}", memberSidDN); @@ -1608,7 +1608,7 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, // Build a SID DN. string memberSidDN = GetSidPathFromPrincipal(member); - if (memberSidDN == null) + if (memberSidDN is null) throw new PrincipalOperationException(SR.ADStoreCtxCouldntGetSIDForGroupMember); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "UpdateGroupMembership: remove via SID {0}", memberSidDN); @@ -1628,7 +1628,7 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, } finally { - if (null != groupDe) + if (groupDe is not null) groupDe.Dispose(); } } @@ -1641,7 +1641,7 @@ protected static string GetSidPathFromPrincipal(Principal p) if (p.fakePrincipal) { SecurityIdentifier Sid = p.Sid; - if (Sid == null) + if (Sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADStoreCtx", "GetSidADsPathFromPrincipal: no SID IC (fake principal)"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -1653,7 +1653,7 @@ protected static string GetSidPathFromPrincipal(Principal p) { // Retrieve the member's SID DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); // since member can't be unpersisted + Debug.Assert(de is not null); // since member can't be unpersisted // Force it to load if it hasn't been already loaded if (!de.Properties.Contains("objectSid")) @@ -1661,7 +1661,7 @@ protected static string GetSidPathFromPrincipal(Principal p) byte[] sid = (byte[])de.Properties["objectSid"].Value; - if (sid == null) + if (sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADStoreCtx", "GetSidADsPathFromPrincipal: no SID"); return null; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs index 136d28275e7cb3..5b1feded367088 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs @@ -103,7 +103,7 @@ protected void BuildPropertySet(Type p, StringCollection propertySet) // Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native // searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one // doesn't already exist) and returns the native searcher. - // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null), + // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter is null), // produces a query that will match all principals in the store. // // For stores which don't have a native searcher (SAM), the StoreCtx @@ -114,7 +114,7 @@ protected void BuildPropertySet(Type p, StringCollection propertySet) internal override object PushFilterToNativeSearcher(PrincipalSearcher ps) { // This is the first time we're being called on this principal. Create a fresh searcher. - if (ps.UnderlyingSearcher == null) + if (ps.UnderlyingSearcher is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: creating fresh DirectorySearcher"); @@ -129,7 +129,7 @@ internal override object PushFilterToNativeSearcher(PrincipalSearcher ps) StringBuilder ldapFilter = new StringBuilder(); - if (qbeFilter == null) + if (qbeFilter is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: no qbeFilter specified"); @@ -156,7 +156,7 @@ internal override object PushFilterToNativeSearcher(PrincipalSearcher ps) { FilterPropertyTableEntry entry = (FilterPropertyTableEntry)filterTable[filter.GetType()]; - if (entry == null) + if (entry is null) { // Must be a property we don't support throw new InvalidOperationException( @@ -202,7 +202,7 @@ protected virtual string GetObjectClassPortion(Type principalType) else { string objClass = ExtensionHelper.ReadStructuralObjectClass(principalType); - if (null == objClass) + if (objClass is null) { Debug.Fail($"ADStoreCtx.GetObjectClassPortion: fell off end looking for {principalType}"); throw new InvalidOperationException(SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForQuery, principalType)); @@ -221,7 +221,7 @@ protected virtual string GetObjectClassPortion(Type principalType) // Given a PrincipalSearcher containg a query filter, transforms it into the store schema // and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit, // or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1). - // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null), + // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter is null), // matches all principals in the store. // // The collection may not be complete, i.e., paging - the returned ResultSet will automatically @@ -243,7 +243,7 @@ internal override ResultSet Query(PrincipalSearcher ps, int sizeLimit) // Perform the actual search SearchResultCollection src = ds.FindAll(); - Debug.Assert(src != null); + Debug.Assert(src is not null); // Create a ResultSet for the search results ADEntriesSet resultSet = new ADEntriesSet(src, this, ps.QueryFilter.GetType()); @@ -327,7 +327,7 @@ protected static string StringConverter(FilterBase filter, string suggestedAdPro { StringBuilder sb = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { sb.Append('('); sb.Append(suggestedAdProperty); @@ -352,7 +352,7 @@ protected static string AcctDisabledConverter(FilterBase filter, string suggeste // this is stored as accountDisabled where TRUE = disabled and FALSE = enabled so here we need to revese the value. StringBuilder sb = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { sb.Append('('); sb.Append(suggestedAdProperty); @@ -374,12 +374,12 @@ protected static string AcctDisabledConverter(FilterBase filter, string suggeste // i.e. ms-DS-UserPasswordNotRequired in ADAM where non existence equals false. protected static string DefaultValueBoolConverter(FilterBase filter, string suggestedAdProperty) { - Debug.Assert(NonPresentAttrDefaultStateMapping != null); + Debug.Assert(NonPresentAttrDefaultStateMapping is not null); Debug.Assert(NonPresentAttrDefaultStateMapping.ContainsKey(suggestedAdProperty)); StringBuilder sb = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { bool defaultState = NonPresentAttrDefaultStateMapping[suggestedAdProperty]; @@ -416,7 +416,7 @@ protected static string BoolConverter(FilterBase filter, string suggestedAdPrope { StringBuilder sb = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { sb.Append('('); sb.Append(suggestedAdProperty); @@ -438,7 +438,7 @@ protected static string CommaStringConverter(FilterBase filter, string suggested { StringBuilder sb = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { sb.Append('('); sb.Append(suggestedAdProperty); @@ -459,7 +459,7 @@ protected static string CommaStringConverter(FilterBase filter, string suggested protected static bool IdentityClaimToFilter(string identity, string identityFormat, ref string filter, bool throwOnFail) { - if (identity == null) + if (identity is null) identity = ""; StringBuilder sb = new StringBuilder(); @@ -497,7 +497,7 @@ protected static bool IdentityClaimToFilter(string identity, string identityForm string ldapHexGuid = ADUtils.HexStringToLdapHexString(stringguid.ToString()); - if (ldapHexGuid == null) + if (ldapHexGuid is null) { if (throwOnFail) throw new ArgumentException(SR.StoreCtxGuidIdentityClaimBadFormat); @@ -572,11 +572,11 @@ protected static string IdentityClaimConverter(FilterBase filter, string suggest { IdentityClaim ic = (IdentityClaim)filter.Value; - if (ic.UrnScheme == null) + if (ic.UrnScheme is null) throw new ArgumentException(SR.StoreCtxIdentityClaimMustHaveScheme); string urnValue = ic.UrnValue; - if (urnValue == null) + if (urnValue is null) urnValue = ""; string filterString = null; @@ -601,7 +601,7 @@ protected static bool SecurityIdentityClaimConverterHelper(string urnValue, bool { // Now we convert the native SID to a byte[] SID sidB = Utils.ConvertNativeSidToByteArray(pBytePtr); - if (null == sidB) + if (sidB is null) { if (throwOnFail) throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat); @@ -630,7 +630,7 @@ protected static bool SecurityIdentityClaimConverterHelper(string urnValue, bool } string ldapHexSid = ADUtils.HexStringToLdapHexString(stringizedBinarySid.ToString()); - if (ldapHexSid == null) + if (ldapHexSid is null) return false; if (useSidHistory) @@ -756,7 +756,7 @@ protected static string BinaryConverter(FilterBase filter, string suggestedAdPro { StringBuilder sb = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { sb.Append('('); sb.Append(suggestedAdProperty); @@ -806,7 +806,7 @@ protected static string GuidConverter(FilterBase filter, string suggestedAdPrope Nullable guid = (Nullable)filter.Value; StringBuilder sb = new StringBuilder(); - if (guid == null) + if (guid is null) { // Spoke with ColinBr. Both values are used to represent "no expiration date set". // sb.Append("(|(accountExpires=9223372036854775807)(accountExpires=0))"); @@ -818,7 +818,7 @@ protected static string GuidConverter(FilterBase filter, string suggestedAdPrope // Transform from hex string ("1AFF") to LDAP hex string ("\1A\FF") string ldapHexGuid = ADUtils.HexStringToLdapHexString(guid.ToString()); - if (ldapHexGuid == null) + if (ldapHexGuid is null) throw new InvalidOperationException(SR.StoreCtxGuidIdentityClaimBadFormat); sb.Append(ldapHexGuid); @@ -1123,13 +1123,13 @@ protected static string ExtensionCacheConverter(FilterBase filter, string sugges StringBuilder query = new StringBuilder(); - if (filter.Value != null) + if (filter.Value is not null) { ExtensionCache ec = (ExtensionCache)filter.Value; foreach (KeyValuePair kvp in ec.properties) { - Type type = kvp.Value.Type == null ? kvp.Value.Value.GetType() : kvp.Value.Type; + Type type = kvp.Value.Type is null ? kvp.Value.Value.GetType() : kvp.Value.Type; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter filter type " + type.ToString()); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter match type " + kvp.Value.MatchType.ToString()); 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 5576526f500933..125d4cb911fa20 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,8 +33,8 @@ public ADStoreKey(Guid guid) public ADStoreKey(string domainName, byte[] sid) { - Debug.Assert(domainName != null && domainName.Length > 0); - Debug.Assert(sid != null && sid.Length != 0); + Debug.Assert(domainName is not null && domainName.Length > 0); + Debug.Assert(sid is not null && sid.Length != 0); // Make a copy of the SID, since a byte[] is mutable _sid = new byte[sid.Length]; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADUtils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADUtils.cs index 0db5839d93b140..950d1711524f86 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADUtils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADUtils.cs @@ -324,7 +324,7 @@ internal static long LargeIntToInt64(UnsafeNativeMethods.IADsLargeInteger largeI // Returns null if input string is not a valid hex string. internal static string HexStringToLdapHexString(string s) { - Debug.Assert(s != null); + Debug.Assert(s is not null); if (s.Length % 2 != 0) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/DSPropertyCollection.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/DSPropertyCollection.cs index 65498e61b4819b..3dd05de6b3a801 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/DSPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/DSPropertyCollection.cs @@ -26,7 +26,7 @@ public dSPropertyValueCollection this[string propertyName] { get { - if (propertyName == null) + if (propertyName is null) throw new ArgumentNullException(nameof(propertyName)); if (null != _pc) @@ -54,7 +54,7 @@ public object this[int index] { get { - if (_pc != null) + if (_pc is not null) { return _pc[index]; } @@ -68,13 +68,13 @@ public int Count { get { - return (_pc != null ? _pc.Count : _rc.Count); + return (_pc is not null ? _pc.Count : _rc.Count); } } public IEnumerator GetEnumerator() { - return (_pc != null ? _pc.GetEnumerator() : _rc.GetEnumerator()); + return (_pc is not null ? _pc.GetEnumerator() : _rc.GetEnumerator()); } } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/RangeRetriever.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/RangeRetriever.cs index a39d0c626102a7..76458905835dc2 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/RangeRetriever.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/RangeRetriever.cs @@ -74,14 +74,14 @@ public bool MoveNext() return false; } - if (!_endReached && _currentEnumerator == null) + if (!_endReached && _currentEnumerator is null) { // First time we're being called GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "MoveNext: first time"); _currentEnumerator = GetNextChunk(); - if (_currentEnumerator == null) + if (_currentEnumerator is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "MoveNext: got null enumerator for first time"); _endReached = true; @@ -112,7 +112,7 @@ public bool MoveNext() GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "MoveNext: retrieving next range"); _currentEnumerator = GetNextChunk(); - if (_currentEnumerator == null) + if (_currentEnumerator is null) { // No more chunks remain GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "MoveNext: end reached"); @@ -184,7 +184,7 @@ private IEnumerator GetNextChunk() PropertyValueCollection pvc = _de.Properties[_propertyName]; - if (pvc == null || pvc.Count == 0) + if (pvc is null || pvc.Count == 0) { // No results (the property may have been empty) GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "GetNextChunk: empty property?"); @@ -221,7 +221,7 @@ public object Current { // Technically, should throw an InvalidOperationException if the enumerator is positioned before // the beginning or after the end, but this will only be used internally. - Debug.Assert(_currentResult != null && _endReached == false); + Debug.Assert(_currentResult is not null && _endReached == false); GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "Current: currentResult={0}", _currentResult.ToString()); return _currentResult; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs index 07a3bc43b90bdc..ea4e05d1cfc02d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs @@ -40,9 +40,9 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti string contextName = name; string userName = null; bool explicitCreds = false; - if (credentials != null && credentials.UserName != null) + if (credentials is not null && credentials.UserName is not null) { - if (credentials.Domain != null) + if (credentials.Domain is not null) userName = credentials.Domain + "\\" + credentials.UserName; else userName = credentials.UserName; @@ -83,7 +83,7 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti PrincipalContext ctx = null; // Wait for the PrincipalContext to be ready - if (contextReadyEvent != null) + if (contextReadyEvent is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting"); @@ -96,12 +96,12 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti { CredHolder credHolder = (CredHolder)_table[contextName]; - if (credHolder != null) + if (credHolder is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName); credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); - Debug.Assert(credTable != null); + Debug.Assert(credTable is not null); object o = credTable[userName]; @@ -116,7 +116,7 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti } WeakReference refToContext = o as WeakReference; - if (refToContext != null) + if (refToContext is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null"); @@ -124,7 +124,7 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti // If the PrincipalContext hasn't been GCed or disposed, use it. // Otherwise, we'll need to create a new one - if (ctx != null && ctx.Disposed == false) + if (ctx is not null && ctx.Disposed == false) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext"); return ctx; @@ -140,7 +140,7 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti // Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable // are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext. - if (credHolder == null) + if (credHolder is null) { GlobalDebug.WriteLineIf( GlobalDebug.Info, @@ -171,8 +171,8 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti contextName, null, contextOptions, - (credentials != null ? credentials.UserName : null), - (credentials != null ? credentials.Password : null) + (credentials is not null ? credentials.UserName : null), + (credentials is not null ? credentials.Password : null) ); lock (_tableLock) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs index 7ffa76e66d7027..64d687b02e192b 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs @@ -43,7 +43,7 @@ internal static Principal SearchResultToPrincipal(SearchResult sr, PrincipalCont { p = GroupPrincipal.MakeGroup(owningContext); } - else if (null == principalType || + else if (principalType is null || typeof(AuthenticablePrincipal) == principalType || typeof(Principal) == principalType) { @@ -101,7 +101,7 @@ internal static Principal DirectoryEntryToPrincipal(DirectoryEntry de, Principal { p = GroupPrincipal.MakeGroup(owningContext); } - else if (null == principalType || + else if (principalType is null || typeof(AuthenticablePrincipal) == principalType || typeof(Principal) == principalType) { @@ -177,7 +177,7 @@ internal static AuthenticationTypes MapOptionsToAuthTypes(ContextOptions options internal static void MoveDirectoryEntry(DirectoryEntry deToMove, DirectoryEntry newParent, string newName) { - if (newName != null) + if (newName is not null) deToMove.MoveTo(newParent, newName); else deToMove.MoveTo(newParent); @@ -207,9 +207,9 @@ internal static void InsertPrincipal( { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "Entering InsertPrincipal"); - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); Debug.Assert(storeCtx is ADStoreCtx || storeCtx is SAMStoreCtx); - Debug.Assert(p != null); + Debug.Assert(p is not null); if ((!(p is UserPrincipal)) && (!(p is GroupPrincipal)) && @@ -243,7 +243,7 @@ internal static void InsertPrincipal( Debug.Assert(p is AuthenticablePrincipal); string password = (string)p.GetValueForProperty(PropertyNames.PwdInfoPassword); - Debug.Assert(password != null); // if null, PasswordInfo should not have indicated it was changed + Debug.Assert(password is not null); // if null, PasswordInfo should not have indicated it was changed storeCtx.SetPassword((AuthenticablePrincipal)p, password); } @@ -274,10 +274,10 @@ internal static void ApplyChangesToDirectory( AuthenticationTypes authTypes) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "Entering ApplyChangesToDirectory"); - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); Debug.Assert(storeCtx is ADStoreCtx || storeCtx is SAMStoreCtx || storeCtx is ADAMStoreCtx); - Debug.Assert(p != null); - Debug.Assert(updateGroupMembership != null); + Debug.Assert(p is not null); + Debug.Assert(updateGroupMembership is not null); // Update the properties in the DirectoryEntry. Note that this does NOT // update group membership. @@ -309,8 +309,8 @@ internal static void ApplyChangesToDirectory( internal static void SetPassword(DirectoryEntry de, string newPassword) { - Debug.Assert(newPassword != null); // but it could be an empty string - Debug.Assert(de != null); + Debug.Assert(newPassword is not null); // but it could be an empty string + Debug.Assert(de is not null); try { @@ -341,10 +341,10 @@ internal static void SetPassword(DirectoryEntry de, string newPassword) internal static void ChangePassword(DirectoryEntry de, string oldPassword, string newPassword) { - Debug.Assert(newPassword != null); // but it could be an empty string - Debug.Assert(oldPassword != null); // but it could be an empty string + Debug.Assert(newPassword is not null); // but it could be an empty string + Debug.Assert(oldPassword is not null); // but it could be an empty string - Debug.Assert(de != null); + Debug.Assert(de is not null); try { @@ -376,8 +376,8 @@ internal static void ChangePassword(DirectoryEntry de, string oldPassword, strin internal static DirectoryEntry BuildDirectoryEntry(string path, NetCred credentials, AuthenticationTypes authTypes) { DirectoryEntry de = new DirectoryEntry(path, - credentials != null ? credentials.UserName : null, - credentials != null ? credentials.Password : null, + credentials is not null ? credentials.UserName : null, + credentials is not null ? credentials.Password : null, authTypes); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "BuildDirectoryEntry (1): built DE for " + de.Path); @@ -389,8 +389,8 @@ internal static DirectoryEntry BuildDirectoryEntry(NetCred credentials, Authenti { DirectoryEntry de = new DirectoryEntry(); - de.Username = credentials != null ? credentials.UserName : null; - de.Password = credentials != null ? credentials.Password : null; + de.Username = credentials is not null ? credentials.UserName : null; + de.Password = credentials is not null ? credentials.Password : null; de.AuthenticationType = authTypes; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "BuildDirectoryEntry (2): built DE"); @@ -400,7 +400,7 @@ internal static DirectoryEntry BuildDirectoryEntry(NetCred credentials, Authenti internal static void WriteAttribute(string dePath, string attribute, T value, NetCred credentials, AuthenticationTypes authTypes) { - Debug.Assert(attribute != null && attribute.Length > 0); + Debug.Assert(attribute is not null && attribute.Length > 0); // Ideally, we'd just like to set the property in the principal's DirectoryEntry and write // the changes to the store. However, there might be other changes in the DirectoryEntry, @@ -413,7 +413,7 @@ internal static void WriteAttribute(string dePath, string attribute, T value, { copyOfDe = SDSUtils.BuildDirectoryEntry(dePath, credentials, authTypes); - Debug.Assert(copyOfDe != null); + Debug.Assert(copyOfDe is not null); // So we don't do a implicit GetInfo() and retrieve every attribute copyOfDe.RefreshCache(new string[] { attribute }); @@ -428,7 +428,7 @@ internal static void WriteAttribute(string dePath, string attribute, T value, } finally { - if (copyOfDe != null) + if (copyOfDe is not null) copyOfDe.Dispose(); } } @@ -443,7 +443,7 @@ internal static void WriteAttribute(string dePath, string attribute, int value, attribute, dePath); - Debug.Assert(attribute != null && attribute.Length > 0); + Debug.Assert(attribute is not null && attribute.Length > 0); // Ideally, we'd just like to set the property in the principal's DirectoryEntry and write // the changes to the store. However, there might be other changes in the DirectoryEntry, @@ -456,7 +456,7 @@ internal static void WriteAttribute(string dePath, string attribute, int value, { copyOfDe = SDSUtils.BuildDirectoryEntry(dePath, credentials, authTypes); - Debug.Assert(copyOfDe != null); + Debug.Assert(copyOfDe is not null); // So we don't do a implicit GetInfo() and retrieve every attribute copyOfDe.RefreshCache(new string[] { attribute }); @@ -480,7 +480,7 @@ internal static void WriteAttribute(string dePath, string attribute, int value, } finally { - if (copyOfDe != null) + if (copyOfDe is not null) copyOfDe.Dispose(); } } @@ -490,7 +490,7 @@ internal static void WriteAttribute(string dePath, string attribute, int value, // internal static void SingleScalarFromDirectoryEntry(dSPropertyCollection properties, string suggestedProperty, Principal p, string propertyName) { - if (properties[suggestedProperty].Count != 0 && properties[suggestedProperty][0] != null) + if (properties[suggestedProperty].Count != 0 && properties[suggestedProperty][0] is not null) { // We're intended to handle single-valued scalar properties Debug.Assert(properties[suggestedProperty].Count == 1); @@ -603,7 +603,7 @@ internal static void MultiStringToDirectoryEntryConverter(Principal p, string pr { PrincipalValueCollection trackingList = (PrincipalValueCollection)p.GetValueForProperty(propertyName); - if (p.unpersisted && trackingList == null) + if (p.unpersisted && trackingList is null) return; List insertedValues = trackingList.Inserted; @@ -617,23 +617,23 @@ internal static void MultiStringToDirectoryEntryConverter(Principal p, string pr // we want to maintain idempotency foreach (string value in removedValues) { - if (value != null && properties.Contains(value)) + if (value is not null && properties.Contains(value)) properties.Remove(value); } foreach (Pair changedValue in changedValues) { // Remove the original value and add in the new value - Debug.Assert(changedValue.Left != null); // since it came from the system + Debug.Assert(changedValue.Left is not null); // since it came from the system properties.Remove(changedValue.Left); - if (changedValue.Right != null && !properties.Contains(changedValue.Right)) + if (changedValue.Right is not null && !properties.Contains(changedValue.Right)) properties.Add(changedValue.Right); } foreach (string value in insertedValues) { - if (value != null && !properties.Contains(value)) + if (value is not null && !properties.Contains(value)) properties.Add(value); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs index 109b59086c4bc5..87e17ba59abbbe 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs @@ -21,7 +21,7 @@ internal SidList(List sidListByteFormat) : this(sidListByteFormat, null, internal SidList(List sidListByteFormat, string target, NetCred credentials) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: processing {0} ByteFormat SIDs", sidListByteFormat.Count); - GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: Targetting {0} ", (target != null) ? target : "local store"); + GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: Targetting {0} ", (target is not null) ? target : "local store"); // Build the list of SIDs to resolve IntPtr hUser = IntPtr.Zero; @@ -36,7 +36,7 @@ internal SidList(List sidListByteFormat, string target, NetCred credenti try { - if (credentials != null) + if (credentials is not null) { Utils.BeginImpersonation(credentials, out hUser); } @@ -100,7 +100,7 @@ protected void TranslateSids(string target, IntPtr[] pSids) Marshal.StructureToPtr(oa, pOA, false); int err = 0; - if (target == null) + if (target is null) { err = UnsafeNativeMethods.LsaOpenPolicy( IntPtr.Zero, diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs index bd9cc4962d7eb5..251b913a9705e3 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs @@ -47,7 +47,7 @@ internal override object CurrentAsPrincipal { get { - if (_currentSID != null) + if (_currentSID is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "TokenGroupSet", "CurrentAsPrincipal: using current"); @@ -79,7 +79,7 @@ internal override bool MoveNext() { if (_atBeginning) { - Debug.Assert(_principalDN != null); + Debug.Assert(_principalDN is not null); _current = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(_principalDN), @@ -129,7 +129,7 @@ public override void Dispose() { if (!_disposed) { - if (_current != null) + if (_current is not null) _current.Dispose(); _disposed = true; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AccountInfo.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AccountInfo.cs index 822a5d0b1ab6c2..a2f799e2cb9a4a 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AccountInfo.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AccountInfo.cs @@ -244,7 +244,7 @@ public bool IsAccountLockedOut() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "IsAccountLockedOut: sending lockout query"); - Debug.Assert(_owningPrincipal.Context != null); + Debug.Assert(_owningPrincipal.Context is not null); return _owningPrincipal.GetStoreCtxToUse().IsLockedOut(_owningPrincipal); } @@ -261,7 +261,7 @@ public void UnlockAccount() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "UnlockAccount: sending unlock request"); - Debug.Assert(_owningPrincipal.Context != null); + Debug.Assert(_owningPrincipal.Context is not null); _owningPrincipal.GetStoreCtxToUse().UnlockAccount(_owningPrincipal); } @@ -375,10 +375,10 @@ internal bool GetChangeStatusForProperty(string propertyName) case (PropertyNames.AcctInfoPermittedLogonTimes): // If they're equal, they have _not_ changed - if ((_permittedLogonTimes == null) && (_permittedLogonTimesOriginal == null)) + if ((_permittedLogonTimes is null) && (_permittedLogonTimesOriginal is null)) return false; - if ((_permittedLogonTimes == null) || (_permittedLogonTimesOriginal == null)) + if ((_permittedLogonTimes is null) || (_permittedLogonTimesOriginal is null)) return true; return !Utils.AreBytesEqual(_permittedLogonTimes, _permittedLogonTimesOriginal); @@ -451,7 +451,7 @@ internal void ResetAllChangeStatus() _permittedWorkstations.ResetTracking(); - _permittedLogonTimesOriginal = (_permittedLogonTimes != null) ? + _permittedLogonTimesOriginal = (_permittedLogonTimes is not null) ? (byte[])_permittedLogonTimes.Clone() : null; _expirationDateChanged = (_expirationDateChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs index 19efbfba03ffd5..84d19d77369b1b 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs @@ -194,13 +194,13 @@ out pClientContext { GlobalDebug.WriteLineIf(GlobalDebug.Error, "AuthZSet", "Caught exception {0} with message {1}", e.GetType(), e.Message); - if (_psBuffer != null && !_psBuffer.IsInvalid) + if (_psBuffer is not null && !_psBuffer.IsInvalid) _psBuffer.Close(); - if (_psUserSid != null && !_psUserSid.IsInvalid) + if (_psUserSid is not null && !_psUserSid.IsInvalid) _psUserSid.Close(); - if (_psMachineSid != null && !_psMachineSid.IsInvalid) + if (_psMachineSid is not null && !_psMachineSid.IsInvalid) _psMachineSid.Close(); // We're on a platform that doesn't have the AuthZ library @@ -308,13 +308,13 @@ internal override object CurrentAsPrincipal } // The SID comes from another domain. Use the domain name that the OS resolved the SID to. - if (sidIssuerName == null) + if (sidIssuerName is null) { sidIssuerName = _groupSidList[_currentGroup].sidIssuerName; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: different domain ({0}) than user ({1})", sidIssuerName, _flatUserAuthority); } - Debug.Assert(sidIssuerName != null); + Debug.Assert(sidIssuerName is not null); Debug.Assert(sidIssuerName.Length > 0); // Determine whether it's a local (WinNT) or Active Directory domain (LDAP) group @@ -365,15 +365,15 @@ internal override object CurrentAsPrincipal DefaultContextOptions.MachineDefaultContextOption); #else PrincipalContext ctx = (PrincipalContext) this.contexts[sidIssuerName]; - if (ctx == null) + if (ctx is null) { // Build a PrincipalContext for the machine ctx = new PrincipalContext( ContextType.Machine, sidIssuerName, null, - (this.credentials != null ? credentials.UserName : null), - (this.credentials != null ? credentials.Password : null), + (this.credentials is not null ? credentials.UserName : null), + (this.credentials is not null ? credentials.Password : null), DefaultContextOptions.MachineDefaultContextOption); this.contexts[sidIssuerName] = ctx; @@ -396,7 +396,7 @@ internal override object CurrentAsPrincipal _contextOptions); #else PrincipalContext ctx = (PrincipalContext) this.contexts[sidIssuerName]; - if (ctx == null) + if (ctx is null) { // Determine the domain DNS name @@ -409,8 +409,8 @@ internal override object CurrentAsPrincipal ContextType.Domain, info.DomainName, null, - (this.credentials != null ? credentials.UserName : null), - (this.credentials != null ? credentials.Password : null), + (this.credentials is not null ? credentials.UserName : null), + (this.credentials is not null ? credentials.Password : null), this.contextOptions); this.contexts[sidIssuerName] = ctx; @@ -431,7 +431,7 @@ internal override object CurrentAsPrincipal group = (GroupPrincipal)((ADStoreCtx)ctx.QueryCtx).FindPrincipalBySID(typeof(GroupPrincipal), ir, true); } - if (group == null) + if (group is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "CurrentAsPrincipal: Couldn't find group {0}"); throw new NoMatchingPrincipalException(SR.AuthZCantFindGroup); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs index 187f25acd300a4..c70aa35bef05ec 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs @@ -75,7 +75,7 @@ private AccountInfo AccountInfo // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); - if (_accountInfo == null) + if (_accountInfo is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "AccountInfo: creating new AccountInfo"); _accountInfo = new AccountInfo(this); @@ -170,7 +170,7 @@ private PasswordInfo PasswordInfo // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); - if (_passwordInfo == null) + if (_passwordInfo is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "PasswordInfo: creating new PasswordInfo"); _passwordInfo = new PasswordInfo(this); @@ -326,7 +326,7 @@ protected static PrincipalSearchResult FindByPasswordSetTime(PrincipalCont // protected internal AuthenticablePrincipal(PrincipalContext context) { - if (context == null) + if (context is null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; @@ -336,12 +336,12 @@ protected internal AuthenticablePrincipal(PrincipalContext context) protected internal AuthenticablePrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { - if (samAccountName != null) + if (samAccountName is not null) { this.SamAccountName = samAccountName; } - if (password != null) + if (password is not null) { this.SetPassword(password); } @@ -363,10 +363,10 @@ private static void CheckFindByArgs(PrincipalContext context, DateTime time, Mat (!subtype.IsSubclassOf(typeof(AuthenticablePrincipal)))) throw new ArgumentException(SR.AuthenticablePrincipalMustBeSubtypeOfAuthPrinc); - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (subtype == null) + if (subtype is null) throw new ArgumentNullException(nameof(subtype)); } @@ -398,7 +398,7 @@ internal override void LoadValueIntoProperty(string propertyName, object value) { // If this is the first AccountInfo attribute we're loading, // we'll need to create the AccountInfo to hold it - if (_accountInfo == null) + if (_accountInfo is null) _accountInfo = new AccountInfo(this); _accountInfo.LoadValueIntoProperty(propertyName, value); @@ -407,7 +407,7 @@ internal override void LoadValueIntoProperty(string propertyName, object value) { // If this is the first PasswordInfo attribute we're loading, // we'll need to create the PasswordInfo to hold it - if (_passwordInfo == null) + if (_passwordInfo is null) _passwordInfo = new PasswordInfo(this); _passwordInfo.LoadValueIntoProperty(propertyName, value); @@ -449,14 +449,14 @@ internal override bool GetChangeStatusForProperty(string propertyName) if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { - if (_accountInfo == null) + if (_accountInfo is null) return false; return _accountInfo.GetChangeStatusForProperty(propertyName); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { - if (_passwordInfo == null) + if (_passwordInfo is null) return false; return _passwordInfo.GetChangeStatusForProperty(propertyName); @@ -485,12 +485,12 @@ internal override object GetValueForProperty(string propertyName) object val = rosf.GetValueForProperty(propertyName); - if (null != val) + if (val is not null) return val; if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { - if (_accountInfo == null) + if (_accountInfo is null) { // Should never happen, since GetChangeStatusForProperty returned false Debug.Fail("AuthenticablePrincipal.GetValueForProperty(AcctInfo): shouldn't be here"); @@ -501,7 +501,7 @@ internal override object GetValueForProperty(string propertyName) } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { - if (_passwordInfo == null) + if (_passwordInfo is null) { // Should never happen, since GetChangeStatusForProperty returned false Debug.Fail("AuthenticablePrincipal.GetValueForProperty(PwdInfo): shouldn't be here"); @@ -526,12 +526,12 @@ internal override void ResetAllChangeStatus() RefreshOriginalThumbprintList(); - if (_accountInfo != null) + if (_accountInfo is not null) { _accountInfo.ResetAllChangeStatus(); } - if (_passwordInfo != null) + if (_passwordInfo is not null) { _passwordInfo.ResetAllChangeStatus(); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Computer.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Computer.cs index 4c96f7e08ac6eb..5d92458b38f894 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Computer.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Computer.cs @@ -24,7 +24,7 @@ public ComputerPrincipal(PrincipalContext context) : base(context) public ComputerPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { - if (samAccountName == null || password == null) + if (samAccountName is null || password is null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType == ContextType.ApplicationDirectory && this.GetType() == typeof(ComputerPrincipal)) @@ -112,7 +112,7 @@ internal static ComputerPrincipal MakeComputer(PrincipalContext ctx) // internal override void LoadValueIntoProperty(string propertyName, object value) { - GlobalDebug.WriteLineIf(GlobalDebug.Info, "Computer", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value == null ? "null" : value.ToString())); + GlobalDebug.WriteLineIf(GlobalDebug.Info, "Computer", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value is null ? "null" : value.ToString())); switch (propertyName) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs index ce5e870eea23c7..f7eeaa521e3b3c 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs @@ -70,7 +70,7 @@ public CredentialValidator(ContextType contextType, string serverName, ServerPro { _fastConcurrentSupported = !(serverProperties.OsVersion == DomainControllerMode.Win2k); - if (contextType == ContextType.Machine && serverName == null) + if (contextType == ContextType.Machine && serverName is null) { _serverName = Environment.MachineName; } @@ -101,7 +101,7 @@ private bool BindSam(string target, string userName, string password) Thread.CurrentThread.SetApartmentState(ApartmentState.MTA); // We need the credentials to be in the form \\ // if they just passed user then append the machine name here. - if (null != userName) + if (userName is not null) { int index = userName.IndexOf('\\'); if (index == -1) @@ -141,7 +141,7 @@ private bool BindSam(string target, string userName, string password) } finally { - if (value != null) + if (value is not null) System.Runtime.InteropServices.Marshal.ReleaseComObject(value); } @@ -227,7 +227,7 @@ private void lockedLdapBind(LdapConnection current, NetworkCredential creds, Con current.AuthType = ((ContextOptions.SimpleBind & contextOptions) > 0 ? AuthType.Basic : AuthType.Negotiate); current.SessionOptions.Signing = ((ContextOptions.Signing & contextOptions) > 0 ? true : false); current.SessionOptions.Sealing = ((ContextOptions.Sealing & contextOptions) > 0 ? true : false); - if ((null == creds.UserName) && (null == creds.Password)) + if ((creds.UserName is null) && (creds.Password is null)) { current.Bind(); } @@ -244,7 +244,7 @@ public bool Validate(string userName, string password) // empty username and password on the local box // causes authentication to succeed. If the username is empty we should just fail it // here. - if (userName != null && userName.Length == 0) + if (userName is not null && userName.Length == 0) return false; if (_contextType == ContextType.Domain || _contextType == ContextType.ApplicationDirectory) @@ -311,7 +311,7 @@ public bool Validate(string userName, string password, ContextOptions connection // empty username and password on the local box // causes authentication to succeed. If the username is empty we should just fail it // here. - if (userName != null && userName.Length == 0) + if (userName is not null && userName.Length == 0) return false; if (_contextType == ContextType.Domain || _contextType == ContextType.ApplicationDirectory) @@ -374,8 +374,8 @@ public PrincipalContext( { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering ctor"); - if ((userName == null && password != null) || - (userName != null && password == null)) + if ((userName is null && password is not null) || + (userName is not null && password is null)) throw new ArgumentException(SR.ContextBadUserPwdCombo); if ((options & ~(ContextOptions.Signing | ContextOptions.Negotiate | ContextOptions.Sealing | ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind | ContextOptions.ServerBind)) != 0) @@ -404,7 +404,7 @@ public PrincipalContext( throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(ContextType)); } - if ((contextType == ContextType.Machine) && (container != null)) + if ((contextType == ContextType.Machine) && (container is not null)) throw new ArgumentException(SR.ContextNoContainerForMachineCtx); if ((contextType == ContextType.ApplicationDirectory) && ((string.IsNullOrEmpty(container)) || (string.IsNullOrEmpty(name)))) @@ -486,10 +486,10 @@ public string ConnectedServer Initialize(); // Unless we're not initialized, connectedServer should not be null - Debug.Assert(_connectedServer != null || _initialized == false); + Debug.Assert(_connectedServer is not null || _initialized == false); // connectedServer should never be an empty string - Debug.Assert(_connectedServer == null || _connectedServer.Length != 0); + Debug.Assert(_connectedServer is null || _connectedServer.Length != 0); return _connectedServer; } @@ -504,8 +504,8 @@ public bool ValidateCredentials(string userName, string password) { CheckDisposed(); - if ((userName == null && password != null) || - (userName != null && password == null)) + if ((userName is null && password is not null) || + (userName is not null && password is null)) throw new ArgumentException(SR.ContextBadUserPwdCombo); #if TESTHOOK @@ -527,8 +527,8 @@ public bool ValidateCredentials(string userName, string password, ContextOptions // Perform credential validation using fast concurrent bind... CheckDisposed(); - if ((userName == null && password != null) || - (userName != null && password == null)) + if ((userName is null && password is not null) || + (userName is not null && password is null)) throw new ArgumentException(SR.ContextBadUserPwdCombo); if (options != ContextOptions.Negotiate && _contextType == ContextType.Machine) @@ -593,7 +593,7 @@ private void DoApplicationDirectoryInit() Debug.Assert(_contextType == ContextType.ApplicationDirectory); - if (_container == null) + if (_container is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoApplicationDirecotryInit: using no-container path"); DoLDAPDirectoryInitNoContainer(); @@ -610,7 +610,7 @@ private void DoMachineInit() GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering DoMachineInit"); Debug.Assert(_contextType == ContextType.Machine); - Debug.Assert(_container == null); + Debug.Assert(_container is null); DirectoryEntry de = null; @@ -618,7 +618,7 @@ private void DoMachineInit() { string hostname = _name; - if (hostname == null) + if (hostname is null) hostname = Utils.GetComputerFlatName(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: hostname is " + hostname); @@ -652,7 +652,7 @@ private void DoMachineInit() " and message " + e.Message); // Cleanup the DE on failure - if (de != null) + if (de is not null) de.Dispose(); throw; @@ -665,7 +665,7 @@ private void DoDomainInit() Debug.Assert(_contextType == ContextType.Domain); - if (_container == null) + if (_container is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoDomainInit: using no-container path"); DoLDAPDirectoryInitNoContainer(); @@ -698,7 +698,7 @@ private void DoLDAPDirectoryInit() // use the servername if they gave us one, else let ADSI figure it out string serverName = ""; - if (_name != null) + if (_name is not null) { if (_contextType == ContextType.ApplicationDirectory) { @@ -759,7 +759,7 @@ private void DoLDAPDirectoryInit() finally { // Cleanup the DE on failure - if (de != null) + if (de is not null) de.Dispose(); } } @@ -790,7 +790,7 @@ private void DoLDAPDirectoryInitNoContainer() // use the servername if they gave us one, else let ADSI figure it out string serverName = ""; - if (_name != null) + if (_name is not null) { serverName = _name + "/"; } @@ -816,7 +816,7 @@ private void DoLDAPDirectoryInitNoContainer() finally { // Don't allow the DE to leak - if (deRootDse != null) + if (deRootDse is not null) deRootDse.Dispose(); } @@ -847,7 +847,7 @@ private void DoLDAPDirectoryInitNoContainer() { if (Utils.AreBytesEqual(USERS_CONTAINER_GUID, (byte[])value.BinaryValue)) { - Debug.Assert(adsPathUserGroupOrg == null); + Debug.Assert(adsPathUserGroupOrg is null); adsPathUserGroupOrg = "LDAP://" + serverName + value.DNString; GlobalDebug.WriteLineIf( @@ -859,7 +859,7 @@ private void DoLDAPDirectoryInitNoContainer() // Is it the computer container? if (Utils.AreBytesEqual(COMPUTERS_CONTAINER_GUID, (byte[])value.BinaryValue)) { - Debug.Assert(adsPathComputer == null); + Debug.Assert(adsPathComputer is null); adsPathComputer = "LDAP://" + serverName + value.DNString; GlobalDebug.WriteLineIf( @@ -869,7 +869,7 @@ private void DoLDAPDirectoryInitNoContainer() } } - if ((adsPathUserGroupOrg == null) || (adsPathComputer == null)) + if ((adsPathUserGroupOrg is null) || (adsPathComputer is null)) { // Something's wrong with the domain, it's not exposing the proper // well-known object fields. @@ -913,22 +913,22 @@ private void DoLDAPDirectoryInitNoContainer() // Cleanup on failure. Once a DE has been successfully handed off to a ADStoreCtx, // that ADStoreCtx will handle Dispose()'ing it - if (deUserGroupOrg != null) + if (deUserGroupOrg is not null) deUserGroupOrg.Dispose(); - if (deComputer != null) + if (deComputer is not null) deComputer.Dispose(); - if (deBase != null) + if (deBase is not null) deBase.Dispose(); - if (storeCtxUserGroupOrg != null) + if (storeCtxUserGroupOrg is not null) storeCtxUserGroupOrg.Dispose(); - if (storeCtxComputer != null) + if (storeCtxComputer is not null) storeCtxComputer.Dispose(); - if (storeCtxBase != null) + if (storeCtxBase is not null) storeCtxBase.Dispose(); throw; @@ -998,16 +998,16 @@ public void Dispose() // This is okay, since StoreCtxs allow multiple Dispose() calls, and ignore // all but the first call. - if (_userCtx != null) + if (_userCtx is not null) _userCtx.Dispose(); - if (_groupCtx != null) + if (_groupCtx is not null) _groupCtx.Dispose(); - if (_computerCtx != null) + if (_computerCtx is not null) _computerCtx.Dispose(); - if (_queryCtx != null) + if (_queryCtx is not null) _queryCtx.Dispose(); _disposed = true; @@ -1173,7 +1173,7 @@ internal void ReadServerConfig(string serverName, ref ServerProperties propertie } finally { - if (ldapConnection != null) + if (ldapConnection is not null) { ldapConnection.Dispose(); } @@ -1184,7 +1184,7 @@ private StoreCtx CreateContextFromDirectoryEntry(DirectoryEntry entry) { StoreCtx storeCtx; - Debug.Assert(entry != null); + Debug.Assert(entry is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "CreateContextFromDirectoryEntry: path is " + entry.Path); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ExtensionHelper.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ExtensionHelper.cs index 212b1f664952b3..0a901b3db1c548 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ExtensionHelper.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ExtensionHelper.cs @@ -23,14 +23,14 @@ internal string RdnPrefix DirectoryRdnPrefixAttribute[] MyAttribute = (DirectoryRdnPrefixAttribute[])Attribute.GetCustomAttributes(_p.GetType(), typeof(DirectoryRdnPrefixAttribute), false); - if (MyAttribute == null) + if (MyAttribute is null) return null; string defaultRdn = null; for (int i = 0; i < MyAttribute.Length; i++) { - if (MyAttribute[i].Context == null && null == defaultRdn) + if (MyAttribute[i].Context is null && defaultRdn is null) { defaultRdn = MyAttribute[i].RdnPrefix; } @@ -49,14 +49,14 @@ internal static string ReadStructuralObjectClass(Type principalType) DirectoryObjectClassAttribute[] MyAttribute = (DirectoryObjectClassAttribute[])Attribute.GetCustomAttributes(principalType, typeof(DirectoryObjectClassAttribute), false); - if (MyAttribute == null) + if (MyAttribute is null) return null; string defaultObjectClass = null; for (int i = 0; i < MyAttribute.Length; i++) { - if (MyAttribute[i].Context == null && null == defaultObjectClass) + if (MyAttribute[i].Context is null && defaultObjectClass is null) { defaultObjectClass = MyAttribute[i].ObjectClass; } @@ -78,14 +78,14 @@ internal string StructuralObjectClass DirectoryObjectClassAttribute[] MyAttribute = (DirectoryObjectClassAttribute[])Attribute.GetCustomAttributes(_p.GetType(), typeof(DirectoryObjectClassAttribute), false); - if (MyAttribute == null) + if (MyAttribute is null) return null; string defaultObjectClass = null; for (int i = 0; i < MyAttribute.Length; i++) { - if (MyAttribute[i].Context == null && null == defaultObjectClass) + if (MyAttribute[i].Context is null && defaultObjectClass is null) { defaultObjectClass = MyAttribute[i].ObjectClass; } @@ -103,19 +103,19 @@ internal string SchemaAttributeName(string propertyName) { System.Reflection.PropertyInfo propInfo = this.GetType().GetProperty(propertyName); - if ( null == propInfo ) + if ( propInfo is null ) return null; DirectoryPropertyAttribute[] MyAttribute = (DirectoryPropertyAttribute[])Attribute.GetCustomAttributes(propInfo, typeof(DirectoryPropertyAttribute)); - if (MyAttribute == null) + if (MyAttribute is null) return null; string defaultAttribute = null; for (int i = 0; i < MyAttribute.Length; i++) { - if (MyAttribute[i].Context == null) + if (MyAttribute[i].Context is null) { defaultAttribute = MyAttribute[i].SchemaAttributeName; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResult.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResult.cs index a1c6f9b9a503fc..3770662c71430d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResult.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResult.cs @@ -34,7 +34,7 @@ public void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearchResult", "Dispose: disposing"); - if (_resultSet != null) + if (_resultSet is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearchResult", "Dispose: disposing resultSet"); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs index fc60e2c928a972..abfece48127efc 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs @@ -26,7 +26,7 @@ public T Current CheckDisposed(); - if (_beforeStart == true || _endReached == true || _resultSet == null) + if (_beforeStart == true || _endReached == true || _resultSet is null) { // Either we're before the beginning or after the end of the collection. GlobalDebug.WriteLineIf( @@ -73,7 +73,7 @@ public bool MoveNext() } // No ResultSet, so we've already reached the end - if (_resultSet == null) + if (_resultSet is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "MoveNext: no resultSet"); return false; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs index 3fc786a1705b28..595d1379d4738a 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs @@ -15,7 +15,7 @@ public class GroupPrincipal : Principal // public GroupPrincipal(PrincipalContext context) { - if (context == null) + if (context is null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; @@ -24,7 +24,7 @@ public GroupPrincipal(PrincipalContext context) public GroupPrincipal(PrincipalContext context, string samAccountName) : this(context) { - if (samAccountName == null) + if (samAccountName is null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) @@ -144,7 +144,7 @@ public PrincipalCollection Members // Check that we actually support this propery in our store //CheckSupportedProperty(PropertyNames.GroupMembers); - if (_members == null) + if (_members is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: creating fresh PrincipalCollection"); @@ -221,7 +221,7 @@ public override void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Dispose: disposing"); - if (_members != null) + if (_members is not null) _members.Dispose(); _disposed = true; @@ -255,7 +255,7 @@ internal static GroupPrincipal MakeGroup(PrincipalContext ctx) internal override void LoadValueIntoProperty(string propertyName, object value) { - GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value != null ? value.ToString() : "null")); + GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value is not null ? value.ToString() : "null")); switch (propertyName) { @@ -298,7 +298,7 @@ internal override bool GetChangeStatusForProperty(string propertyName) case PropertyNames.GroupMembers: // If Members was never loaded, it couldn't possibly have changed - if (_members != null) + if (_members is not null) return _members.Changed; else { @@ -333,7 +333,7 @@ internal override void ResetAllChangeStatus() _groupScopeChanged = (_groupScopeChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _isSecurityGroupChanged = (_isSecurityGroupChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; - if (_members != null) + if (_members is not null) _members.ResetTracking(); base.ResetAllChangeStatus(); @@ -365,13 +365,13 @@ internal bool IsSmallGroup() _isSmallGroup = false; DirectoryEntry de = (DirectoryEntry)this.UnderlyingObject; - Debug.Assert(de != null); - if (de != null) + Debug.Assert(de is not null); + if (de is not null) { using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base)) { SearchResult sr = ds.FindOne(); - if (sr != null) + if (sr is not null) { bool rangePropertyFound = false; foreach (string propName in sr.Properties.PropertyNames) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs index 13713bcb4e5a4c..74e496e644e573 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs @@ -57,7 +57,7 @@ public string Domain private unsafe void SplitUsername(string username, ref string parsedUserName, ref string parsedDomainName) { // If the user has passed null creds then parsed components should also be null. - if (username == null) + if (username is null) { parsedDomainName = null; parsedUserName = null; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PasswordInfo.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PasswordInfo.cs index a478199410e07a..6ec0b8da6a57b0 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PasswordInfo.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PasswordInfo.cs @@ -133,7 +133,7 @@ public bool AllowReversiblePasswordEncryption public void SetPassword(string newPassword) { - if (newPassword == null) + if (newPassword is null) throw new ArgumentNullException(nameof(newPassword)); // If we're not persisted, we just save up the change until we're Saved @@ -151,10 +151,10 @@ public void SetPassword(string newPassword) public void ChangePassword(string oldPassword, string newPassword) { - if (oldPassword == null) + if (oldPassword is null) throw new ArgumentNullException(nameof(oldPassword)); - if (newPassword == null) + if (newPassword is null) throw new ArgumentNullException(nameof(newPassword)); // While you can reset the password on an unpersisted principal (and it will be used as the initial password @@ -240,7 +240,7 @@ void HandleSet(ref T currentValue, T newValue, ref bool changed, string name) internal void LoadValueIntoProperty(string propertyName, object value) { - if (value != null) + if (value is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); } @@ -307,7 +307,7 @@ internal bool GetChangeStatusForProperty(string propertyName) return _allowReversiblePasswordEncryptionChanged == LoadState.Changed; case (PropertyNames.PwdInfoPassword): - return (_storedNewPassword != null); + return (_storedNewPassword is not null); case (PropertyNames.PwdInfoExpireImmediately): return (_expirePasswordImmediately != false); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs index f98261081b3858..1936f84b959664 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs @@ -32,7 +32,7 @@ public PrincipalContext Context CheckDisposedOrDeleted(); // The only way we can't have a PrincipalContext is if we're unpersisted - Debug.Assert(_ctx != null || this.unpersisted == true); + Debug.Assert(_ctx is not null || this.unpersisted == true); return _ctx; } @@ -47,9 +47,9 @@ public ContextType ContextType CheckDisposedOrDeleted(); // The only way we can't have a PrincipalContext is if we're unpersisted - Debug.Assert(_ctx != null || this.unpersisted == true); + Debug.Assert(_ctx is not null || this.unpersisted == true); - if (_ctx == null) + if (_ctx is null) throw new InvalidOperationException(SR.PrincipalMustSetContextForProperty); return _ctx.ContextType; @@ -122,7 +122,7 @@ public string SamAccountName set { - if (null == value || 0 == value.Length) + if (value is null || 0 == value.Length) throw new ArgumentNullException(nameof(value)); if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalSamAccountName)) @@ -229,7 +229,7 @@ public string Name // Context type could be null for an unpersisted user. // Default to the original domain behavior if a context is not set. - ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType; + ContextType ct = (_ctx is null) ? ContextType.Domain : _ctx.ContextType; if (ct == ContextType.Machine) { @@ -242,13 +242,13 @@ public string Name } set { - if (null == value || 0 == value.Length) + if (value is null || 0 == value.Length) throw new ArgumentNullException(nameof(value)); if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); - ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType; + ContextType ct = (_ctx is null) ? ContextType.Domain : _ctx.ContextType; if (ct == ContextType.Machine) { @@ -301,7 +301,7 @@ public void Save() // We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted // and they never set a PrincipalContext. - if (_ctx == null) + if (_ctx is null) { Debug.Assert(this.unpersisted == true); throw new InvalidOperationException(SR.PrincipalMustSetContextForSave); @@ -309,7 +309,7 @@ public void Save() // Call the appropriate operation depending on whether this is an insert or update StoreCtx storeCtxToUse = GetStoreCtxToUse(); - Debug.Assert(storeCtxToUse != null); // since we know this.ctx isn't null + Debug.Assert(storeCtxToUse is not null); // since we know this.ctx isn't null if (this.unpersisted) { @@ -338,7 +338,7 @@ public void Save(PrincipalContext context) // We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted // and they never set a PrincipalContext. - if (context == null) + if (context is null) { Debug.Assert(this.unpersisted == true); throw new InvalidOperationException(SR.NullArguments); @@ -371,8 +371,8 @@ public void Save(PrincipalContext context) // Call the appropriate operation depending on whether this is an insert or update StoreCtx newStoreCtx = GetStoreCtxToUse(); - Debug.Assert(newStoreCtx != null); // since we know this.ctx isn't null - Debug.Assert(originalStoreCtx != null); // since we know this.ctx isn't null + Debug.Assert(newStoreCtx is not null); // since we know this.ctx isn't null + Debug.Assert(originalStoreCtx is not null); // since we know this.ctx isn't null if (this.unpersisted) { @@ -457,7 +457,7 @@ public void Delete() // Since we're not unpersisted, we must have come back from a query, and the query logic would // have filled in a PrincipalContext on us. - Debug.Assert(_ctx != null); + Debug.Assert(_ctx is not null); _ctx.QueryCtx.Delete(this); _isDeleted = true; @@ -467,13 +467,13 @@ public override bool Equals(object o) { Principal that = o as Principal; - if (that == null) + if (that is null) return false; if (object.ReferenceEquals(this, that)) return true; - if ((_key != null) && (that._key != null) && (_key.Equals(that._key))) + if ((_key is not null) && (that._key is not null) && (_key.Equals(that._key))) return true; return false; @@ -492,7 +492,7 @@ public object GetUnderlyingObject() // Make sure we're not a fake principal CheckFakePrincipal(); - if (this.UnderlyingObject == null) + if (this.UnderlyingObject is null) { throw new InvalidOperationException(SR.PrincipalMustPersistFirst); } @@ -511,7 +511,7 @@ public Type GetUnderlyingObjectType() if (this.unpersisted) { // If we're unpersisted, we can't determine the native type until our PrincipalContext has been set. - if (_ctx != null) + if (_ctx is not null) { return _ctx.ContextForType(this.GetType()).NativeType(this); } @@ -522,7 +522,7 @@ public Type GetUnderlyingObjectType() } else { - Debug.Assert(_ctx != null); + Debug.Assert(_ctx is not null); return _ctx.QueryCtx.NativeType(this); } } @@ -534,7 +534,7 @@ public PrincipalSearchResult GetGroups() public PrincipalSearchResult GetGroups(PrincipalContext contextToQuery) { - if (contextToQuery == null) + if (contextToQuery is null) throw new ArgumentNullException(nameof(contextToQuery)); return new PrincipalSearchResult(GetGroupsHelper(contextToQuery)); @@ -545,7 +545,7 @@ public bool IsMemberOf(GroupPrincipal group) // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); - if (group == null) + if (group is null) throw new ArgumentNullException(nameof(group)); return group.Members.Contains(this); @@ -556,15 +556,15 @@ public bool IsMemberOf(PrincipalContext context, IdentityType identityType, stri // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (identityValue == null) + if (identityValue is null) throw new ArgumentNullException(nameof(identityValue)); GroupPrincipal g = GroupPrincipal.FindByIdentity(context, identityType, identityValue); - if (g != null) + if (g is not null) { return IsMemberOf(g); } @@ -584,13 +584,13 @@ public virtual void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing"); - if ((this.UnderlyingObject != null) && (this.UnderlyingObject is IDisposable)) + if ((this.UnderlyingObject is not null) && (this.UnderlyingObject is IDisposable)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying object"); ((IDisposable)this.UnderlyingObject).Dispose(); } - if ((this.UnderlyingSearchObject != null) && (this.UnderlyingSearchObject is IDisposable)) + if ((this.UnderlyingSearchObject is not null) && (this.UnderlyingSearchObject is IDisposable)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying search object"); ((IDisposable)this.UnderlyingSearchObject).Dispose(); @@ -619,7 +619,7 @@ protected Principal() protected object[] ExtensionGet(string attribute) { - if (null == attribute) + if (attribute is null) throw new ArgumentException(SR.NullArguments); ExtensionCacheValue val; @@ -676,7 +676,7 @@ private void ValidateExtensionObject(object value) } else { - if (value != null && value is ICollection) + if (value is not null && value is ICollection) { ICollection collection = (ICollection)value; if (collection.Count == 0) @@ -692,7 +692,7 @@ private void ValidateExtensionObject(object value) protected void ExtensionSet(string attribute, object value) { - if (null == attribute) + if (attribute is null) throw new ArgumentException(SR.NullArguments); ValidateExtensionObject(value); @@ -707,7 +707,7 @@ protected void ExtensionSet(string attribute, object value) internal void AdvancedFilterSet(string attribute, object value, Type objectType, MatchType mt) { - if (null == attribute) + if (attribute is null) throw new ArgumentException(SR.NullArguments); ValidateExtensionObject(value); @@ -766,7 +766,7 @@ protected internal PrincipalContext ContextRaw set { // Verify that the passed context is not disposed. - if (value != null) + if (value is not null) value.CheckDisposed(); _ctx = value; } @@ -778,14 +778,14 @@ internal static Principal MakePrincipal(PrincipalContext ctx, Type principalType System.Reflection.ConstructorInfo CI = principalType.GetConstructor(new Type[] { typeof(PrincipalContext) }); - if (null == CI) + if (CI is null) { throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor); } p = (Principal)CI.Invoke(new object[] { ctx }); - if (null == p) + if (p is null) { throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor); } @@ -800,7 +800,7 @@ internal static Principal MakePrincipal(PrincipalContext ctx, Type principalType // Returns null if no context has been set yet. internal StoreCtx GetStoreCtxToUse() { - if (_ctx == null) + if (_ctx is null) { Debug.Assert(this.unpersisted == true); return null; @@ -825,7 +825,7 @@ internal object UnderlyingObject { get { - if (_underlyingObject != null) + if (_underlyingObject is not null) return _underlyingObject; return null; @@ -846,7 +846,7 @@ internal object UnderlyingSearchObject { get { - if (_underlyingSearchObject != null) + if (_underlyingSearchObject is not null) return _underlyingSearchObject; return null; @@ -900,10 +900,10 @@ protected void CheckDisposedOrDeleted() [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, string identityValue) { - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (identityValue == null) + if (identityValue is null) throw new ArgumentNullException(nameof(identityValue)); return FindByIdentityWithTypeHelper(context, principalType, null, identityValue, DateTime.UtcNow); @@ -912,10 +912,10 @@ protected static Principal FindByIdentityWithType(PrincipalContext context, Type [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, string identityValue) { - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (identityValue == null) + if (identityValue is null) throw new ArgumentNullException(nameof(identityValue)); if ((identityType < IdentityType.SamAccountName) || (identityType > IdentityType.Guid)) @@ -927,10 +927,10 @@ protected static Principal FindByIdentityWithType(PrincipalContext context, Type private static Principal FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable identityType, string identityValue, DateTime refDate) { // Ask the store to find a Principal based on this IdentityReference info. - Principal p = context.QueryCtx.FindPrincipalByIdentRef(principalType, (identityType == null) ? null : (string)IdentMap.StringMap[(int)identityType, 1], identityValue, refDate); + Principal p = context.QueryCtx.FindPrincipalByIdentRef(principalType, (identityType is null) ? null : (string)IdentMap.StringMap[(int)identityType, 1], identityValue, refDate); // Did we find a match? - if (p != null) + if (p is not null) { // Given the native object, ask the StoreCtx to construct a Principal object for us. return p; @@ -956,7 +956,7 @@ private ResultSet GetGroupsHelper() } StoreCtx storeCtx = GetStoreCtxToUse(); - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: querying"); ResultSet resultSet = storeCtx.GetGroupsMemberOf(this); @@ -969,11 +969,11 @@ private ResultSet GetGroupsHelper(PrincipalContext contextToQuery) // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); - if (_ctx == null) + if (_ctx is null) throw new InvalidOperationException(SR.UserMustSetContextForMethod); StoreCtx storeCtx = GetStoreCtxToUse(); - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); return contextToQuery.QueryCtx.GetGroupsMemberOf(this, storeCtx); } @@ -994,7 +994,7 @@ internal void LoadIfNeeded(string principalPropertyName) else if (!this.unpersisted) { // We came back from a query --> our PrincipalContext must be filled in - Debug.Assert(_ctx != null); + Debug.Assert(_ctx is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: loading"); @@ -1081,7 +1081,7 @@ internal void HandleSet(ref T currentValue, T newValue, ref LoadState state, // ExtensionCache is never directly loaded by the store hence it does not exist in the switch internal virtual void LoadValueIntoProperty(string propertyName, object value) { - GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value == null ? "null" : value.ToString())); + GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value is null ? "null" : value.ToString())); switch (propertyName) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs index 097704bd2d76a9..4b0829c6561d73 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs @@ -21,7 +21,7 @@ void ICollection.CopyTo(Array array, int index) if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) @@ -77,7 +77,7 @@ void ICollection.CopyTo(Array array, int index) } finally { - if (bookmark != null) + if (bookmark is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: restoring from bookmark"); _resultSet.RestoreBookmark(bookmark); @@ -195,7 +195,7 @@ public int Count } finally { - if (bookmark != null) + if (bookmark is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: restoring from bookmark"); _resultSet.Reset(); @@ -245,7 +245,7 @@ public void Add(Principal principal) { CheckDisposed(); - if (principal == null) + if (principal is null) throw new ArgumentNullException(nameof(principal)); if (Contains(principal)) @@ -289,15 +289,15 @@ public void Add(PrincipalContext context, IdentityType identityType, string iden { CheckDisposed(); - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (identityValue == null) + if (identityValue is null) throw new ArgumentNullException(nameof(identityValue)); Principal principal = Principal.FindByIdentity(context, identityType, identityValue); - if (principal != null) + if (principal is not null) { Add(principal); } @@ -322,14 +322,14 @@ public void Clear() // reason it couldn't is if it's an AD group with one principals that are members of it // by virtue of their primaryGroupId. // - // If storeCtxToUse == null, then we must be unpersisted, in which case there clearly + // If storeCtxToUse is null, then we must be unpersisted, in which case there clearly // can't be any such primary group members pointing to this group on the store. StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); string explanation; - Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true); + Debug.Assert(storeCtxToUse is not null || _owningGroup.unpersisted == true); - if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupBeCleared(_owningGroup, out explanation))) + if ((storeCtxToUse is not null) && (!storeCtxToUse.CanGroupBeCleared(_owningGroup, out explanation))) throw new InvalidOperationException(explanation); MarkChange(); @@ -368,21 +368,21 @@ public bool Remove(Principal principal) { CheckDisposed(); - if (principal == null) + if (principal is null) throw new ArgumentNullException(nameof(principal)); // Ask the StoreCtx to verify that this member can be removed. Right now, the only // reason it couldn't is if it's actually a member by virtue of its primaryGroupId // pointing to this group. // - // If storeCtxToUse == null, then we must be unpersisted, in which case there clearly + // If storeCtxToUse is null, then we must be unpersisted, in which case there clearly // can't be any such primary group members pointing to this group on the store. StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); string explanation; - Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true); + Debug.Assert(storeCtxToUse is not null || _owningGroup.unpersisted == true); - if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupMemberBeRemoved(_owningGroup, principal, out explanation))) + if ((storeCtxToUse is not null) && (!storeCtxToUse.CanGroupMemberBeRemoved(_owningGroup, principal, out explanation))) throw new InvalidOperationException(explanation); bool removed = false; @@ -436,15 +436,15 @@ public bool Remove(PrincipalContext context, IdentityType identityType, string i { CheckDisposed(); - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (identityValue == null) + if (identityValue is null) throw new ArgumentNullException(nameof(identityValue)); Principal principal = Principal.FindByIdentity(context, identityType, identityValue); - if (principal == null) + if (principal is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Remove(urn/urn): no match"); throw new NoMatchingPrincipalException(SR.NoMatchingPrincipalExceptionText); @@ -461,7 +461,7 @@ private bool ContainsEnumTest(Principal principal) { CheckDisposed(); - if (principal == null) + if (principal is null) throw new ArgumentNullException(nameof(principal)); // Yes, this is potentially quite expensive. Contains is unfortunately @@ -495,7 +495,7 @@ private bool ContainsEnumTest(Principal principal) } finally { - if (bookmark != null) + if (bookmark is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: restoring from bookmark"); _resultSet.RestoreBookmark(bookmark); @@ -510,7 +510,7 @@ private bool ContainsNativeTest(Principal principal) { CheckDisposed(); - if (principal == null) + if (principal is null) throw new ArgumentNullException(nameof(principal)); // If they explicitly inserted it, then we certainly contain it @@ -565,12 +565,12 @@ public bool Contains(Principal principal) // If the store has a shortcut for testing membership, use it. // Otherwise we enumerate all members and look for a match. - if ((storeCtxToUse != null) && (storeCtxToUse.SupportsNativeMembershipTest)) + if ((storeCtxToUse is not null) && (storeCtxToUse.SupportsNativeMembershipTest)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Contains: using native test (store ctx is null = {0})", - (storeCtxToUse == null)); + (storeCtxToUse is null)); return ContainsNativeTest(principal); } @@ -585,17 +585,17 @@ public bool Contains(PrincipalContext context, IdentityType identityType, string { CheckDisposed(); - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if (identityValue == null) + if (identityValue is null) throw new ArgumentNullException(nameof(identityValue)); bool found = false; Principal principal = Principal.FindByIdentity(context, identityType, identityValue); - if (principal != null) + if (principal is not null) found = Contains(principal); return found; @@ -611,7 +611,7 @@ internal PrincipalCollection(BookmarkableResultSet results, GroupPrincipal ownin { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Ctor"); - Debug.Assert(results != null); + Debug.Assert(results is not null); _resultSet = results; _owningGroup = owningGroup; @@ -632,7 +632,7 @@ internal void Dispose() lock (_resultSet) { - if (_resultSet != null) + if (_resultSet is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing resultSet"); _resultSet.Dispose(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollectionEnumerator.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollectionEnumerator.cs index 0b7efe1cd818ed..db5642172334fa 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollectionEnumerator.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollectionEnumerator.cs @@ -38,7 +38,7 @@ public Principal Current throw new InvalidOperationException(SR.PrincipalCollectionEnumInvalidPos); } - Debug.Assert(_current != null); + Debug.Assert(_current is not null); return _current; } } @@ -97,7 +97,7 @@ public bool MoveNext() } } - Debug.Assert(_resultSet != null); + Debug.Assert(_resultSet is not null); if (_currentMode == CurrentEnumeratorMode.ResultSet) { @@ -245,7 +245,7 @@ List insertedValuesPending { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Ctor"); - Debug.Assert(resultSet != null); + Debug.Assert(resultSet is not null); _resultSet = resultSet; _memberCollection = memberCollection; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs index ab29b38327be6c..7b4a7b9e5e29c7 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs @@ -21,7 +21,7 @@ public PrincipalSearcher() public PrincipalSearcher(Principal queryFilter) { - if (null == queryFilter) + if (queryFilter is null) throw new ArgumentException(null, nameof(queryFilter)); _ctx = queryFilter.Context; @@ -54,14 +54,14 @@ public Principal QueryFilter set { - if (null == value) + if (value is null) throw new ArgumentNullException(nameof(QueryFilter)); CheckDisposed(); - Debug.Assert(value.Context != null); + Debug.Assert(value.Context is not null); // Make sure they're not passing in a persisted Principal object - if ((value != null) && (!value.unpersisted)) + if ((value is not null) && (!value.unpersisted)) throw new ArgumentException(SR.PrincipalSearcherPersistedPrincipal); _qbeFilter = value; @@ -126,7 +126,7 @@ public object GetUnderlyingSearcher() CheckDisposed(); // We have to have a filter - if (_qbeFilter == null) + if (_qbeFilter is null) throw new InvalidOperationException(SR.PrincipalSearcherMustSetFilter); // Double-check that the Principal isn't persisted. We don't allow them to assign a persisted @@ -140,7 +140,7 @@ public object GetUnderlyingSearcher() throw new InvalidOperationException(SR.PrincipalSearcherNonReferentialProps); StoreCtx storeCtx = _ctx.QueryCtx; - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); // The underlying context must actually support search (i.e., no MSAM/reg-SAM) if (storeCtx.SupportsSearchNatively == false) @@ -160,11 +160,11 @@ public Type GetUnderlyingSearcherType() CheckDisposed(); // We have to have a filter - if (_qbeFilter == null) + if (_qbeFilter is null) throw new InvalidOperationException(SR.PrincipalSearcherMustSetFilter); StoreCtx storeCtx = _ctx.QueryCtx; - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); // The underlying context must actually support search (i.e., no MSAM/reg-SAM) if (storeCtx.SupportsSearchNatively == false) @@ -179,7 +179,7 @@ public virtual void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Dispose: disposing"); - if ((this.UnderlyingSearcher != null) && (this.UnderlyingSearcher is IDisposable)) + if ((this.UnderlyingSearcher is not null) && (this.UnderlyingSearcher is IDisposable)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, @@ -247,7 +247,7 @@ private PrincipalSearchResult FindAll(bool returnOne) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering FindAll, returnOne=" + returnOne.ToString()); - if (_qbeFilter == null) + if (_qbeFilter is null) throw new InvalidOperationException(SR.PrincipalSearcherMustSetFilter); // Double-check that the Principal isn't persisted. We don't allow them to assign a persisted // Principal as the filter, but they could have persisted it after assigning it to the QueryFilter @@ -271,7 +271,7 @@ private void SetDefaultPageSizeForContext() { _pageSize = 0; - if (_qbeFilter != null) + if (_qbeFilter is not null) { // If our context is AD-backed (has an ADStoreCtx), use pagesize of 256. // Otherwise, turn off paging. @@ -295,7 +295,7 @@ private bool HasReferentialPropertiesSet() { // If using a null query filter, nothing to validate, as it can't have any referential // properties set. - if (_qbeFilter == null) + if (_qbeFilter is null) return false; // Since the QBE filter must be in the "unpersisted" state, any set properties have their changed @@ -311,7 +311,7 @@ private bool HasReferentialPropertiesSet() ArrayList referentialProperties = (ArrayList)ReferentialProperties.Properties[t]; - if (referentialProperties != null) + if (referentialProperties is not null) { foreach (string propertyName in referentialProperties) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/QbeFilterDescription.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/QbeFilterDescription.cs index 35980616f8a128..c09a1062781b43 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/QbeFilterDescription.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/QbeFilterDescription.cs @@ -88,7 +88,7 @@ public static object CreateFilter(string propertyName) GlobalDebug.WriteLineIf(GlobalDebug.Info, "QbeFilterDescription", "FilterFactory.CreateFilter: name=" + propertyName); Type type = (Type)s_subclasses[propertyName]; - Debug.Assert(type != null); + Debug.Assert(type is not null); return System.Activator.CreateInstance(type); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMGroupsSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMGroupsSet.cs index b4f4afe53b6d4e..740b0a61d888d9 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMGroupsSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMGroupsSet.cs @@ -32,7 +32,7 @@ internal override object CurrentAsPrincipal { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "CurrentAsPrincipal"); - Debug.Assert(_current != null); + Debug.Assert(_current is not null); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs index e8070d4ca35349..ba6d9a07a18cda 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs @@ -42,19 +42,19 @@ internal override object CurrentAsPrincipal { get { - if (_current != null) + if (_current is not null) { // Local principal --- handle it ourself GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning current"); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } - else if (_currentFakePrincipal != null) + else if (_currentFakePrincipal is not null) { // Local fake principal --- handle it ourself GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning currentFakePrincipal"); return _currentFakePrincipal; } - else if (_currentForeign != null) + else if (_currentForeign is not null) { // Foreign, non-recursive principal. Just return the principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning currentForeign"); @@ -63,7 +63,7 @@ internal override object CurrentAsPrincipal else { // Foreign recursive expansion. Proxy the call to the foreign ResultSet. - Debug.Assert(_foreignResultSet != null); + Debug.Assert(_foreignResultSet is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning foreignResultSet"); return _foreignResultSet.CurrentAsPrincipal; } @@ -119,7 +119,7 @@ private bool MoveNextLocal() _current = null; _currentForeign = null; - if (_foreignResultSet != null) + if (_foreignResultSet is not null) _foreignResultSet.Dispose(); _foreignResultSet = null; return true; @@ -195,7 +195,7 @@ private bool MoveNextLocal() _currentFakePrincipal = null; _currentForeign = null; - if (_foreignResultSet != null) + if (_foreignResultSet is not null) _foreignResultSet.Dispose(); _foreignResultSet = null; return true; @@ -297,7 +297,7 @@ private bool MoveNextForeign() _currentFakePrincipal = null; _currentForeign = foreignPrincipal; - if (_foreignResultSet != null) + if (_foreignResultSet is not null) _foreignResultSet.Dispose(); _foreignResultSet = null; return true; @@ -313,7 +313,7 @@ private bool MoveNextForeign() } } - if (_foreignResultSet == null && _foreignGroups.Count > 0) + if (_foreignResultSet is null && _foreignGroups.Count > 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", @@ -337,7 +337,7 @@ private bool MoveNextForeign() // We're either just beginning the recursive expansion of a foreign group, or we're continuing the expansion // that we started on a previous call to MoveNext(). - if (_foreignResultSet != null) + if (_foreignResultSet is not null) { Debug.Assert(_recursive == true); @@ -465,7 +465,7 @@ internal override void Reset() _foreignMembers.Clear(); _foreignGroups.Clear(); - if (_foreignResultSet != null) + if (_foreignResultSet is not null) { _foreignResultSet.Dispose(); _foreignResultSet = null; @@ -532,7 +532,7 @@ internal override void RestoreBookmark(ResultSetBookmark bookmark) _foreignMembers = samBookmark.foreignMembers; _foreignGroups = samBookmark.foreignGroups; - if (_foreignResultSet != null) + if (_foreignResultSet is not null) _foreignResultSet.Dispose(); _foreignResultSet = samBookmark.foreignResultSet; @@ -547,7 +547,7 @@ public override void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Dispose: disposing"); - if (_foreignResultSet != null) + if (_foreignResultSet is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Dispose: disposing foreignResultSet"); _foreignResultSet.Dispose(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs index 20793aebefccac..9fa35a0df89102 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs @@ -45,7 +45,7 @@ internal override object CurrentAsPrincipal // Since this class is only used internally, none of our code should be even calling this // if MoveNext returned false, or before calling MoveNext. - Debug.Assert(_endReached == false && _current != null); + Debug.Assert(_endReached == false && _current is not null); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } @@ -58,7 +58,7 @@ internal override bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "Entering MoveNext"); - Debug.Assert(_enumerator != null); + Debug.Assert(_enumerator is not null); bool needToRetry = false; bool f; @@ -158,13 +158,13 @@ internal override void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "Reset"); - // if current == null, we're already at the beginning - if (_current != null) + // if current is null, we're already at the beginning + if (_current is not null) { _endReached = false; _current = null; - if (_enumerator != null) + if (_enumerator is not null) _enumerator.Reset(); _resultsReturned = 0; @@ -227,12 +227,12 @@ private static Hashtable CreateFilterPropertiesTable() string winNTPropertyName = s_filterPropertiesTableRaw[i, 1] as string; MatcherDelegate f = s_filterPropertiesTableRaw[i, 2] as MatcherDelegate; - Debug.Assert(qbeType != null); - Debug.Assert(winNTPropertyName != null); - Debug.Assert(f != null); + Debug.Assert(qbeType is not null); + Debug.Assert(winNTPropertyName is not null); + Debug.Assert(f is not null); // There should only be one entry per QBE type - Debug.Assert(filterPropertiesTable[qbeType] == null); + Debug.Assert(filterPropertiesTable[qbeType] is null); FilterPropertyTableEntry entry = new FilterPropertyTableEntry(); entry.winNTPropertyName = winNTPropertyName; @@ -250,7 +250,7 @@ internal override bool Matches(DirectoryEntry de) // (In reg-SAM, computers don't have accounts and therefore don't have SIDs, but ADSI // creates fake Computer objects for them. In LSAM, computers CAN have accounts, and thus // SIDs). - if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0) + if (de.Properties["objectSid"] is null || de.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SamMatcher: Matches: skipping no-SID {0}", de.Path); return false; @@ -261,7 +261,7 @@ internal override bool Matches(DirectoryEntry de) { FilterPropertyTableEntry entry = (FilterPropertyTableEntry)s_filterPropertiesTable[filter.GetType()]; - if (entry == null) + if (entry is null) { // Must be a property we don't support throw new NotSupportedException( @@ -333,7 +333,7 @@ private static bool WildcardStringMatch(FilterBase filter, string wildcardFilter // each time a query was performed. Regex regex = filter.Extra as Regex; - if (regex == null) + if (regex is null) { regex = new Regex(SAMUtils.PAPIQueryToRegexString(wildcardFilter), RegexOptions.Singleline); filter.Extra = regex; @@ -350,18 +350,18 @@ private static bool DateTimeMatcher(FilterBase filter, string winNTPropertyName, { QbeMatchType valueToMatch = (QbeMatchType)filter.Value; - if (null == valueToMatch.Value) + if (valueToMatch.Value is null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || - (de.Properties[winNTPropertyName].Value == null)) + (de.Properties[winNTPropertyName].Value is null)) return true; } else { Debug.Assert(valueToMatch.Value is DateTime); - if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Value != null)) + if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Value is not null)) { DateTime value; @@ -412,7 +412,7 @@ private static bool StringMatcher(FilterBase filter, string winNTPropertyName, D { string valueToMatch = (string)filter.Value; - if (valueToMatch == null) + if (valueToMatch is null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || @@ -425,7 +425,7 @@ private static bool StringMatcher(FilterBase filter, string winNTPropertyName, D { string value = (string)de.Properties[winNTPropertyName].Value; - if (value != null) + if (value is not null) { return WildcardStringMatch(filter, valueToMatch, value); } @@ -440,11 +440,11 @@ private static bool IntMatcher(FilterBase filter, string winNTPropertyName, Dire QbeMatchType valueToMatch = (QbeMatchType)filter.Value; bool result = false; - if (null == valueToMatch.Value) + if (valueToMatch.Value is null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || - (de.Properties[winNTPropertyName].Value == null)) + (de.Properties[winNTPropertyName].Value is null)) result = true; } else @@ -482,7 +482,7 @@ private static bool SamAccountNameMatcher(FilterBase filter, string winNTPropert string samAccountName = (index != -1) ? samToMatch.Substring(index + 1) : // +1 to skip the '/' samToMatch; - if (de.Properties["Name"].Count > 0 && de.Properties["Name"].Value != null) + if (de.Properties["Name"].Count > 0 && de.Properties["Name"].Value is not null) { return WildcardStringMatch(filter, samAccountName, (string)de.Properties["Name"].Value); /* @@ -500,10 +500,10 @@ private static bool SidMatcher(FilterBase filter, string winNTPropertyName, Dire { byte[] sidToMatch = Utils.StringToByteArray((string)filter.Value); - if (sidToMatch == null) + if (sidToMatch is null) throw new InvalidOperationException(SR.StoreCtxSecurityIdentityClaimBadFormat); - if (de.Properties["objectSid"].Count > 0 && de.Properties["objectSid"].Value != null) + if (de.Properties["objectSid"].Count > 0 && de.Properties["objectSid"].Value is not null) { return Utils.AreBytesEqual(sidToMatch, (byte[])de.Properties["objectSid"].Value); } @@ -570,7 +570,7 @@ private static bool MultiStringMatcher(FilterBase filter, string winNTPropertyNa { string valueToMatch = (string)filter.Value; - if (valueToMatch == null) + if (valueToMatch is null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || @@ -583,7 +583,7 @@ private static bool MultiStringMatcher(FilterBase filter, string winNTPropertyNa { foreach (string value in de.Properties[winNTPropertyName]) { - if (value != null) + if (value is not null) { return WildcardStringMatch(filter, valueToMatch, value); } @@ -598,11 +598,11 @@ private static bool BinaryMatcher(FilterBase filter, string winNTPropertyName, D { byte[] valueToMatch = (byte[])filter.Value; - if (valueToMatch == null) + if (valueToMatch is null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || - (de.Properties[winNTPropertyName].Value == null)) + (de.Properties[winNTPropertyName].Value is null)) return true; } else @@ -611,7 +611,7 @@ private static bool BinaryMatcher(FilterBase filter, string winNTPropertyName, D { byte[] value = (byte[])de.Properties[winNTPropertyName].Value; - if ((value != null) && Utils.AreBytesEqual(value, valueToMatch)) + if ((value is not null) && Utils.AreBytesEqual(value, valueToMatch)) return true; } } @@ -630,12 +630,12 @@ private static bool ExpirationDateMatcher(FilterBase filter, string winNTPropert { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || - (de.Properties[winNTPropertyName].Value == null)) + (de.Properties[winNTPropertyName].Value is null)) return true; } else { - if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Value != null)) + if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Value is not null)) { DateTime value = (DateTime)de.Properties[winNTPropertyName].Value; @@ -692,7 +692,7 @@ internal override bool Matches(DirectoryEntry de) // (In reg-SAM, computers don't have accounts and therefore don't have SIDs, but ADSI // creates fake Computer objects for them. In LSAM, computers CAN have accounts, and thus // SIDs). - if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0) + if (de.Properties["objectSid"] is null || de.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "FindByDateMatcher: Matches: skipping no-SID {0}", de.Path); return false; @@ -810,7 +810,7 @@ internal class GroupMemberMatcher : SAMMatcher internal GroupMemberMatcher(byte[] memberSidToMatch) { - Debug.Assert(memberSidToMatch != null); + Debug.Assert(memberSidToMatch is not null); Debug.Assert(memberSidToMatch.Length != 0); _memberSidToMatch = memberSidToMatch; } @@ -821,7 +821,7 @@ internal override bool Matches(DirectoryEntry groupDE) // (In reg-SAM, computers don't have accounts and therefore don't have SIDs, but ADSI // creates fake Computer objects for them. In LSAM, computers CAN have accounts, and thus // SIDs). - if (groupDE.Properties["objectSid"] == null || groupDE.Properties["objectSid"].Count == 0) + if (groupDE.Properties["objectSid"] is null || groupDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "GroupMemberMatcher: Matches: skipping no-SID group={0}", groupDE.Path); return false; @@ -838,7 +838,7 @@ internal override bool Matches(DirectoryEntry groupDE) DirectoryEntry memberDE = new DirectoryEntry(nativeMember); // No SID --> not interesting - if (memberDE.Properties["objectSid"] == null || memberDE.Properties["objectSid"].Count == 0) + if (memberDE.Properties["objectSid"] is null || memberDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "GroupMemberMatcher: Matches: skipping member no-SID member={0}", memberDE.Path); continue; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index 65f616ea199fb8..4edee6c924ec94 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -58,8 +58,8 @@ static SAMStoreCtx() FromWinNTConverterDelegate fromWinNT = s_propertyMappingTableRaw[i, 3] as FromWinNTConverterDelegate; ToWinNTConverterDelegate toWinNT = s_propertyMappingTableRaw[i, 4] as ToWinNTConverterDelegate; - Debug.Assert(propertyName != null); - Debug.Assert((winNTAttribute != null && fromWinNT != null) || (fromWinNT == null)); + Debug.Assert(propertyName is not null); + Debug.Assert((winNTAttribute is not null && fromWinNT is not null) || (fromWinNT is null)); Debug.Assert(principalType == typeof(Principal) || principalType.IsSubclassOf(typeof(Principal))); // Build the table entry. The same entry will be used in both tables. @@ -109,7 +109,7 @@ static SAMStoreCtx() BitMask = ObjectMask.Principal; } - if ((winNTAttribute == null) || (winNTAttribute == "*******")) + if ((winNTAttribute is null) || (winNTAttribute == "*******")) { BitMask = ObjectMask.None; } @@ -127,11 +127,11 @@ static SAMStoreCtx() // *PropertyMappingTableByProperty // If toWinNT is null, there's no PAPI->WinNT mapping for this property // (it's probably read-only, e.g., "LastLogon"). - // if (toWinNT != null) + // if (toWinNT is not null) // { foreach (Hashtable propertyMappingTableByProperty in byPropertyTables) { - if (propertyMappingTableByProperty[propertyName] == null) + if (propertyMappingTableByProperty[propertyName] is null) propertyMappingTableByProperty[propertyName] = new ArrayList(); ((ArrayList)propertyMappingTableByProperty[propertyName]).Add(propertyEntry); @@ -141,13 +141,13 @@ static SAMStoreCtx() // *PropertyMappingTableByWinNT // If fromLdap is null, there's no direct WinNT->PAPI mapping for this property. // It's probably a property that requires custom handling, such as an IdentityClaim. - if (fromWinNT != null) + if (fromWinNT is not null) { string winNTAttributeLower = winNTAttribute.ToLowerInvariant(); foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables) { - if (propertyMappingTableByWinNT[winNTAttributeLower] == null) + if (propertyMappingTableByWinNT[winNTAttributeLower] is null) propertyMappingTableByWinNT[winNTAttributeLower] = new ArrayList(); ((ArrayList)propertyMappingTableByWinNT[winNTAttributeLower]).Add(propertyEntry); @@ -159,7 +159,7 @@ static SAMStoreCtx() // Throws exception if ctxBase is not a computer object public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options) { - Debug.Assert(ctxBase != null); + Debug.Assert(ctxBase is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Constructing SAMStoreCtx for {0}", ctxBase.Path); Debug.Assert(SAMUtils.IsOfObjectClass(ctxBase, "Computer")); @@ -167,7 +167,7 @@ public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, str _ctxBase = ctxBase; _ownCtxBase = ownCtxBase; - if (username != null && password != null) + if (username is not null && password is not null) _credentials = new NetCred(username, password); _contextOptions = options; @@ -203,7 +203,7 @@ internal override string BasePath { get { - Debug.Assert(_ctxBase != null); + Debug.Assert(_ctxBase is not null); return _ctxBase.Path; } } @@ -238,14 +238,14 @@ internal override void Insert(Principal p) ((DirectoryEntry)p.UnderlyingObject).RefreshCache(); // Load in the StoreKey - Debug.Assert(p.Key == null); // since it was previously unpersisted + Debug.Assert(p.Key is null); // since it was previously unpersisted - Debug.Assert(p.UnderlyingObject != null); // since we just persisted it + Debug.Assert(p.UnderlyingObject is not null); // since we just persisted it Debug.Assert(p.UnderlyingObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; // We just created a principal, so it should have an objectSid - Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1)); + Debug.Assert((de.Properties["objectSid"] is not null) && (de.Properties["objectSid"].Count == 1)); SAMStoreKey key = new SAMStoreKey( this.MachineFlatName, @@ -270,7 +270,7 @@ internal override void Update(Principal p) Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); try @@ -300,7 +300,7 @@ internal override void Delete(Principal p) // Principal.Delete() shouldn't be calling us on an unpersisted Principal. Debug.Assert(p.unpersisted == false); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); @@ -367,13 +367,13 @@ internal override void Move(StoreCtx originalStore, Principal p) /// Principal to set the user account control bits for internal override void InitializeUserAccountControl(AuthenticablePrincipal p) { - Debug.Assert(p != null); + Debug.Assert(p is not null); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == true); // should only ever be called for new principals // set the userAccountControl bits on the underlying directory entry DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); Type principalType = p.GetType(); if ((principalType == typeof(UserPrincipal)) || (principalType.IsSubclassOf(typeof(UserPrincipal)))) @@ -389,7 +389,7 @@ internal override bool IsLockedOut(AuthenticablePrincipal p) Debug.Assert(p.unpersisted == false); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); try { @@ -422,7 +422,7 @@ internal override void UnlockAccount(AuthenticablePrincipal p) } DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); // After setting the property, we need to commit the change to the store. // We do it in a copy of de, so that we don't inadvertently commit any other @@ -433,7 +433,7 @@ internal override void UnlockAccount(AuthenticablePrincipal p) { copyOfDe = SDSUtils.BuildDirectoryEntry(de.Path, _credentials, _authTypes); - Debug.Assert(copyOfDe != null); + Debug.Assert(copyOfDe is not null); copyOfDe.InvokeSet("IsAccountLocked", new object[] { false }); copyOfDe.CommitChanges(); } @@ -445,7 +445,7 @@ internal override void UnlockAccount(AuthenticablePrincipal p) } finally { - if (copyOfDe != null) + if (copyOfDe is not null) copyOfDe.Dispose(); } } @@ -467,11 +467,11 @@ internal override void SetPassword(AuthenticablePrincipal p, string newPassword) throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordSet); } - Debug.Assert(p != null); - Debug.Assert(newPassword != null); // but it could be an empty string + Debug.Assert(p is not null); + Debug.Assert(newPassword is not null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); SDSUtils.SetPassword(de, newPassword); } @@ -492,12 +492,12 @@ internal override void ChangePassword(AuthenticablePrincipal p, string oldPasswo throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordSet); } - Debug.Assert(p != null); - Debug.Assert(newPassword != null); // but it could be an empty string - Debug.Assert(oldPassword != null); // but it could be an empty string + Debug.Assert(p is not null); + Debug.Assert(newPassword is not null); // but it could be an empty string + Debug.Assert(oldPassword is not null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); SDSUtils.ChangePassword(de, oldPassword, newPassword); } @@ -534,7 +534,7 @@ private void WriteAttribute(AuthenticablePrincipal p, string attribute, int valu { Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); - Debug.Assert(p != null); + Debug.Assert(p is not null); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; @@ -590,7 +590,7 @@ Type principalType // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; - Debug.Assert(entries != null); + Debug.Assert(entries is not null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List schemaTypes = GetSchemaFilter(principalType); @@ -624,7 +624,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) return new EmptySet(); } - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p.UnderlyingObject is not null); DirectoryEntry userDE = (DirectoryEntry)p.UnderlyingObject; @@ -645,7 +645,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; - Debug.Assert(entries != null); + Debug.Assert(entries is not null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List schemaTypes = GetSchemaFilter(typeof(GroupPrincipal)); @@ -654,7 +654,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) byte[] SidB = new byte[principalSid.BinaryLength]; principalSid.GetBinaryForm(SidB, 0); - if (principalSid == null) + if (principalSid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf: bad SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -688,7 +688,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // Get the Principal's SID, so we can look it up by SID in our store SecurityIdentifier Sid = foreignPrincipal.Sid; - if (Sid == null) + if (Sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -699,7 +699,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // If no corresponding principal exists in this store, then by definition the principal isn't // a member of any groups in this store. - if (u == null) + if (u is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no corresponding user, returning empty set"); return new EmptySet(); @@ -720,7 +720,7 @@ internal override ResultSet GetGroupsMemberOfAZ(Principal p) // Get the user SID that AuthZ will use. SecurityIdentifier Sid = p.Sid; - if (Sid == null) + if (Sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: no SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); @@ -729,7 +729,7 @@ internal override ResultSet GetGroupsMemberOfAZ(Principal p) byte[] Sidb = new byte[Sid.BinaryLength]; Sid.GetBinaryForm(Sidb, 0); - if (Sidb == null) + if (Sidb is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: Bad SID IC"); throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat); @@ -759,7 +759,7 @@ internal override BookmarkableResultSet GetGroupMembership(GroupPrincipal g, boo return new EmptySet(); } - Debug.Assert(g.UnderlyingObject != null); + Debug.Assert(g.UnderlyingObject is not null); DirectoryEntry groupDE = (DirectoryEntry)g.UnderlyingObject; @@ -860,8 +860,8 @@ internal override Principal ResolveCrossStoreRefToPrincipal(object o) ContextType.Domain, domainName, null, - (this.credentials != null ? credentials.UserName : null), - (this.credentials != null ? credentials.Password : null), + (this.credentials is not null ? credentials.UserName : null), + (this.credentials is not null ? credentials.Password : null), DefaultContextOptions.ADDefaultContextOption); #endif @@ -874,7 +874,7 @@ internal override Principal ResolveCrossStoreRefToPrincipal(object o) sidObj.ToString(), DateTime.UtcNow); - if (p != null) + if (p is not null) return p; else { @@ -971,16 +971,16 @@ internal string MachineUserSuppliedName { get { - if (_machineUserSuppliedName == null) + if (_machineUserSuppliedName is null) { lock (_computerInfoLock) { - if (_machineUserSuppliedName == null) + if (_machineUserSuppliedName is null) LoadComputerInfo(); } } - Debug.Assert(_machineUserSuppliedName != null); + Debug.Assert(_machineUserSuppliedName is not null); return _machineUserSuppliedName; } } @@ -989,16 +989,16 @@ internal string MachineFlatName { get { - if (_machineFlatName == null) + if (_machineFlatName is null) { lock (_computerInfoLock) { - if (_machineFlatName == null) + if (_machineFlatName is null) LoadComputerInfo(); } } - Debug.Assert(_machineFlatName != null); + Debug.Assert(_machineFlatName is not null); return _machineFlatName; } } @@ -1013,7 +1013,7 @@ private void LoadComputerInfo() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo"); - Debug.Assert(_ctxBase != null); + Debug.Assert(_ctxBase is not null); Debug.Assert(SAMUtils.IsOfObjectClass(_ctxBase, "Computer")); // diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs index 3be71349a6a42a..ea9208637a4176 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs @@ -36,7 +36,7 @@ internal override object PushChangesToNative(Principal p) GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Entering PushChangesToNative, type={0}", p.GetType()); - if (de == null) + if (de is null) { // Must be a newly-inserted Principal for which PushChangesToNative has not yet // been called. @@ -57,7 +57,7 @@ internal override object PushChangesToNative(Principal p) // Determine the SAM account name for the entry we'll be creating. Use the name from the NT4 IdentityClaim. string samAccountName = GetSamAccountName(p); - if (samAccountName == null) + if (samAccountName is null) { // They didn't set a NT4 IdentityClaim. throw new InvalidOperationException(SR.NameMustBeSetToPersistPrincipal); @@ -109,7 +109,7 @@ internal override object PushChangesToNative(Principal p) foreach (PropertyMappingTableEntry propertyEntry in propertyEntries) { - if (null != propertyEntry.papiToWinNTConverter) + if (propertyEntry.papiToWinNTConverter is not null) { if (p.GetChangeStatusForProperty(propertyEntry.propertyName)) { @@ -141,7 +141,7 @@ internal override object PushChangesToNative(Principal p) Debug.Assert(p is AuthenticablePrincipal); string password = (string)p.GetValueForProperty(PropertyNames.PwdInfoPassword); - Debug.Assert(password != null); // if null, PasswordInfo should not have indicated it was changed + Debug.Assert(password is not null); // if null, PasswordInfo should not have indicated it was changed SDSUtils.SetPassword(de, password); } @@ -162,7 +162,7 @@ private string GetSamAccountName(Principal p) string Name = p.SamAccountName; - if (Name == null) + if (Name is null) return null; // Split the SAM account name out of the UrnValue @@ -197,9 +197,9 @@ private string GetSamAccountName(Principal p) internal override Principal GetAsPrincipal(object storeObject, object discriminant) { // SAM doesn't use discriminant, should always be null. - Debug.Assert(discriminant == null); + Debug.Assert(discriminant is null); - Debug.Assert(storeObject != null); + Debug.Assert(storeObject is not null); Debug.Assert(storeObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)storeObject; @@ -208,12 +208,12 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina // Construct an appropriate Principal object. Principal p = SDSUtils.DirectoryEntryToPrincipal(de, this.OwningContext, null); - Debug.Assert(p != null); + Debug.Assert(p is not null); // Assign a SAMStoreKey to the newly-constructed Principal. // If it doesn't have an objectSid, it's not a principal and we shouldn't be here. - Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1)); + Debug.Assert((de.Properties["objectSid"] is not null) && (de.Properties["objectSid"].Count == 1)); SAMStoreKey key = new SAMStoreKey(this.MachineFlatName, (byte[])de.Properties["objectSid"].Value); p.Key = key; @@ -223,8 +223,8 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina internal override void Load(Principal p, string principalPropertyName) { - Debug.Assert(p != null); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p is not null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; @@ -249,14 +249,14 @@ internal override void Load(Principal p, string principalPropertyName) ArrayList entries = (ArrayList)propertyMappingTableByProperty[principalPropertyName]; // We don't support this property and cannot load it. To maintain backward compatibility with the old code just return. - if (entries == null) + if (entries is null) return; try { foreach (PropertyMappingTableEntry entry in entries) { - if (null != entry.winNTToPapiConverter) + if (entry.winNTToPapiConverter is not null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Load_PropertyName: loading {0}", entry.propertyName); entry.winNTToPapiConverter(de, entry.suggestedWinNTPropertyName, p, entry.propertyName); @@ -274,12 +274,12 @@ internal override void Load(Principal p) { try { - Debug.Assert(p != null); - Debug.Assert(p.UnderlyingObject != null); + Debug.Assert(p is not null); + Debug.Assert(p.UnderlyingObject is not null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; - Debug.Assert(de != null); + Debug.Assert(de is not null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Entering Load, type={0}, path={1}", p.GetType(), de.Path); @@ -310,7 +310,7 @@ internal override void Load(Principal p) ArrayList entries = (ArrayList)propertyMappingTableByWinNT[samAttribute.ToLowerInvariant()]; // If it's not in the table, it's not an SAM attribute we care about - if (entries == null) + if (entries is null) continue; // Load it into the Principal. Some LDAP attributes (such as userAccountControl) @@ -343,7 +343,7 @@ internal override Principal FindPrincipalByIdentRef( byte[] sid = new byte[sidObj.BinaryLength]; sidObj.GetBinaryForm(sid, 0); - if (sid == null) + if (sid is null) throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat); // If they're searching by SID for a SID corresponding to a fake group, construct @@ -372,14 +372,14 @@ internal override Principal FindPrincipalByIdentRef( // Not a fake group. Search for the real group. object o = FindNativeBySIDIdentRef(principalType, sid); - return (o != null) ? GetAsPrincipal(o, null) : null; + return (o is not null) ? GetAsPrincipal(o, null) : null; } else if (urnScheme == UrnScheme.SamAccountScheme || urnScheme == UrnScheme.NameScheme) { object o = FindNativeByNT4IdentRef(principalType, urnValue); - return (o != null) ? GetAsPrincipal(o, null) : null; + return (o is not null) ? GetAsPrincipal(o, null) : null; } - else if (urnScheme == null) + else if (urnScheme is null) { object sidPrincipal = null; object nt4Principal = null; @@ -404,7 +404,7 @@ internal override Principal FindPrincipalByIdentRef( // If null, must have been a non-SID UrnValue. Ignore it, and // continue on to try NT4 Account IdentityClaim. - if (sid != null) + if (sid is not null) { // Are they perhaps searching for a fake group? // If they passed in a valid SID for a fake group, construct and return the fake @@ -455,17 +455,17 @@ internal override Principal FindPrincipalByIdentRef( GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindPrincipalByIdentRef: scheme==null, found nt4={0}, found sid={1}", - (nt4Principal != null), - (sidPrincipal != null)); + (nt4Principal is not null), + (sidPrincipal is not null)); // If they both succeeded in finding a match, we have too many matches. // Throw an exception. - if ((sidPrincipal != null) && (nt4Principal != null)) + if ((sidPrincipal is not null) && (nt4Principal is not null)) throw new MultipleMatchesException(SR.MultipleMatchingPrincipals); // Return whichever one matched. If neither matched, this will return null. - return (sidPrincipal != null) ? GetAsPrincipal(sidPrincipal, null) : - ((nt4Principal != null) ? GetAsPrincipal(nt4Principal, null) : + return (sidPrincipal is not null) ? GetAsPrincipal(sidPrincipal, null) : + ((nt4Principal is not null) ? GetAsPrincipal(nt4Principal, null) : null); } else @@ -572,7 +572,7 @@ private object FindNativeByNT4IdentRef(Type principalType, string urnValue) // If it has no SID, it's not a security principal, and we're not interested in it. // This also has the side effect of forcing the object to load, thereby testing // whether or not it exists. - if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0) + if (de.Properties["objectSid"] is null || de.Properties["objectSid"].Count == 0) return false; } catch (System.Runtime.InteropServices.COMException e) @@ -627,7 +627,7 @@ private object FindNativeByNT4IdentRef(Type principalType, string urnValue) // for ADStoreCtx). For others, it may vary depending on the Principal passed in. internal override Type NativeType(Principal p) { - Debug.Assert(p != null); + Debug.Assert(p is not null); return typeof(DirectoryEntry); } @@ -910,10 +910,10 @@ private static void StringToWinNTConverter(Principal p, string propertyName, Dir { string value = (string)p.GetValueForProperty(propertyName); - if (p.unpersisted && value == null) + if (p.unpersisted && value is null) return; - if (value != null && value.Length > 0) + if (value is not null && value.Length > 0) de.Properties[suggestedWinNTProperty].Value = value; else de.Properties[suggestedWinNTProperty].Value = ""; @@ -930,10 +930,10 @@ private static void LogonHoursToWinNTConverter(Principal p, string propertyName, byte[] value = (byte[])p.GetValueForProperty(propertyName); - if (p.unpersisted && value == null) + if (p.unpersisted && value is null) return; - if (value != null && value.Length != 0) + if (value is not null && value.Length != 0) { de.Properties[suggestedWinNTProperty].Value = value; } @@ -987,7 +987,7 @@ private static void AcctExpirDateToNTConverter(Principal p, string propertyName, { Nullable value = (Nullable)p.GetValueForProperty(propertyName); - if (p.unpersisted && value == null) + if (p.unpersisted && value is null) return; // ADSI's WinNT provider uses 1/1/1970 to represent "never expires" when setting the property @@ -1081,7 +1081,7 @@ private static void UpdateGroupMembership(Principal group, DirectoryEntry de, Ne if (member.unpersisted) throw new InvalidOperationException(SR.StoreCtxGroupHasUnpersistedInsertedPrincipal); - Debug.Assert(member.Context != null); + Debug.Assert(member.Context is not null); // There's no restriction on the type of principal to be inserted (AD/reg-SAM/MSAM), but it needs // to have a SID IdentityClaim. We'll check that as we go. @@ -1095,7 +1095,7 @@ private static void UpdateGroupMembership(Principal group, DirectoryEntry de, Ne // Build a SID ADsPath string memberSidPath = GetSidADsPathFromPrincipal(member); - if (memberSidPath == null) + if (memberSidPath is null) throw new InvalidOperationException(SR.SAMStoreCtxCouldntGetSIDForGroupMember); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: inserting {0}", memberSidPath); @@ -1123,7 +1123,7 @@ private static void UpdateGroupMembership(Principal group, DirectoryEntry de, Ne // Build a SID ADsPath string memberSidPath = GetSidADsPathFromPrincipal(member); - if (memberSidPath == null) + if (memberSidPath is null) throw new InvalidOperationException(SR.SAMStoreCtxCouldntGetSIDForGroupMember); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: removing {0}", memberSidPath); @@ -1153,7 +1153,7 @@ private static string GetSidADsPathFromPrincipal(Principal p) SecurityIdentifier Sid = p.Sid; - if (Sid == null) + if (Sid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetSidADsPathFromPrincipal: no SID"); return null; @@ -1161,7 +1161,7 @@ private static string GetSidADsPathFromPrincipal(Principal p) string sddlSid = Sid.ToString(); - if (sddlSid == null) + if (sddlSid is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_Query.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_Query.cs index b48fe5051878d5..22628da59e3bd1 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_Query.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_Query.cs @@ -33,7 +33,7 @@ internal override Type SearcherNativeType() // Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native // searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one // doesn't already exist) and returns the native searcher. - // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null), + // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter is null), // produces a query that will match all principals in the store. // // For stores which don't have a native searcher (SAM), the StoreCtx @@ -44,7 +44,7 @@ internal override Type SearcherNativeType() internal override object PushFilterToNativeSearcher(PrincipalSearcher ps) { // There's no underlying searcher for SAM - Debug.Assert(ps.UnderlyingSearcher == null); + Debug.Assert(ps.UnderlyingSearcher is null); Principal qbeFilter = ps.QueryFilter; QbeFilterDescription filters; @@ -53,7 +53,7 @@ internal override object PushFilterToNativeSearcher(PrincipalSearcher ps) // Otherwise, use an empty set. Note that we don't worry about filtering by // the type of the qbeFilter object (e.g., restricting the returned principals // to only Users, or only Groups) --- that's handled in Query(). - if (qbeFilter != null) + if (qbeFilter is not null) filters = BuildQbeFilterDescription(qbeFilter); else filters = new QbeFilterDescription(); @@ -65,7 +65,7 @@ internal override object PushFilterToNativeSearcher(PrincipalSearcher ps) // Given a PrincipalSearcher containg a query filter, transforms it into the store schema // and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit, // or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1). - // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null), + // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter is null), // matches all principals in the store. // // The collection may not be complete, i.e., paging - the returned ResultSet will automatically @@ -86,12 +86,12 @@ internal override ResultSet Query(PrincipalSearcher ps, int sizeLimit) // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; - Debug.Assert(entries != null); + Debug.Assert(entries is not null); // Determine the principal types of interest. The SAMQuerySet will use this to restrict // the types of DirectoryEntry objects returned. Type qbeFilterType = typeof(Principal); - if (ps.QueryFilter != null) + if (ps.QueryFilter is not null) qbeFilterType = ps.QueryFilter.GetType(); List schemaTypes = GetSchemaFilter(qbeFilterType); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs index 11b7612c9ab5e2..11d7219a8c9def 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs @@ -14,8 +14,8 @@ internal class SAMStoreKey : StoreKey public SAMStoreKey(string machineName, byte[] sid) { - Debug.Assert(machineName != null && machineName.Length > 0); - Debug.Assert(sid != null && sid.Length > 0); + Debug.Assert(machineName is not null && machineName.Length > 0); + Debug.Assert(sid is not null && sid.Length > 0); _machineName = machineName; 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 999d44c6357da4..61e8a15a4fe9a9 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 @@ -51,7 +51,7 @@ internal static bool GetOSVersion(DirectoryEntry computerDE, out int versionMajo } // Couldn't retrieve the value - if (version == null || version.Length == 0) + if (version is null || version.Length == 0) return false; // This string should be in the form "M.N", where M and N are integers. diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs index 4ad0ab90f05e63..82bca580435e4c 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs @@ -34,7 +34,7 @@ internal PrincipalContext OwningContext set { - Debug.Assert(value != null); + Debug.Assert(value is not null); _owningContext = value; } } @@ -171,7 +171,7 @@ internal abstract ResultSet FindByExpirationTime( // Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native // searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one // doesn't already exist) and returns the native searcher. - // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null), + // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter is null), // produces a query that will match all principals in the store. // // For stores which don't have a native searcher (SAM), the StoreCtx @@ -185,7 +185,7 @@ internal abstract ResultSet FindByExpirationTime( // Given a PrincipalSearcher containg a query filter, transforms it into the store schema // and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit, // or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1). - // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null), + // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter is null), // matches all principals in the store. // // The collection may not be complete, i.e., paging - the returned ResultSet will automatically @@ -402,7 +402,7 @@ private void BuildFilterSet(Principal p, string[] propertySet, QbeFilterDescript object filter = FilterFactory.CreateFilter(propertyName); - if (value == null) + if (value is null) { ((FilterBase)filter).Value = null; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs index eb16ae3118c16c..3034cd9b54d987 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs @@ -19,7 +19,7 @@ void ICollection.CopyTo(Array array, int index) if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollectionEnumerator.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollectionEnumerator.cs index 81cd5ab77c9a84..f384d9bd635920 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollectionEnumerator.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollectionEnumerator.cs @@ -22,7 +22,7 @@ public T Current // Since MoveNext() saved off the current value for us, this is largely trivial. - if (_endReached == true || _enumerator == null) + if (_endReached == true || _enumerator is null) { // Either we're at the end or before the beginning GlobalDebug.WriteLineIf(GlobalDebug.Warn, "TrackedCollectionEnumerator", "Current: bad position, endReached={0}", _endReached); @@ -58,13 +58,13 @@ public bool MoveNext() return false; } - if (_enumerator == null) + if (_enumerator is null) { // Must be at the very beginning GlobalDebug.WriteLineIf(GlobalDebug.Info, "TrackedCollectionEnumerator", "MoveNext: at beginning"); _enumerator = ((IEnumerable)_combinedValues).GetEnumerator(); - Debug.Assert(_enumerator != null); + Debug.Assert(_enumerator is not null); } bool gotNextValue = _enumerator.MoveNext(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/UnknownPrincipal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/UnknownPrincipal.cs index 238d4b34573499..2a09297187ccb1 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/UnknownPrincipal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/UnknownPrincipal.cs @@ -16,7 +16,7 @@ internal class UnknownPrincipal : Principal // private UnknownPrincipal(PrincipalContext context) { - if (context == null) + if (context is null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/User.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/User.cs index 96a2d684a938d9..b1836989b87bbf 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/User.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/User.cs @@ -16,7 +16,7 @@ public class UserPrincipal : AuthenticablePrincipal // public UserPrincipal(PrincipalContext context) : base(context) { - if (context == null) + if (context is null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; @@ -25,7 +25,7 @@ public UserPrincipal(PrincipalContext context) : base(context) public UserPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { - if (samAccountName == null || password == null) + if (samAccountName is null || password is null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) @@ -222,7 +222,7 @@ public static UserPrincipal Current // We're running as the user, we know they must exist, but perhaps we don't have access // to their user object - if (user == null) + if (user is null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "User", "Current: found no user"); throw new NoMatchingPrincipalException(SR.UserCouldNotFindCurrent); @@ -304,7 +304,7 @@ private ResultSet GetAuthorizationGroupsHelper() } StoreCtx storeCtx = GetStoreCtxToUse(); - Debug.Assert(storeCtx != null); + Debug.Assert(storeCtx is not null); GlobalDebug.WriteLineIf( GlobalDebug.Info, @@ -326,7 +326,7 @@ private ResultSet GetAuthorizationGroupsHelper() // internal override void LoadValueIntoProperty(string propertyName, object value) { - if (value == null) + if (value is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value= null"); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs index 41d629044809f8..f4f0623b93d1dd 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs @@ -614,7 +614,7 @@ internal static unsafe int LookupSid(string serverName, NetCred credentials, byt // hUser could be null if no credentials were specified Debug.Assert(hUser != IntPtr.Zero || - (credentials == null || (credentials.UserName == null && credentials.Password == null))); + (credentials is null || (credentials.UserName is null && credentials.Password is null))); int f = Interop.Advapi32.LookupAccountSid(serverName, sid, null, ref nameLength, null, ref domainNameLength, out accountUsage); @@ -670,8 +670,8 @@ internal static Principal ConstructFakePrincipalFromSID( "Utils", "ConstructFakePrincipalFromSID: Build principal for SID={0}, server={1}, authority={2}", Utils.ByteArrayToString(sid), - (serverName != null ? serverName : "NULL"), - (authorityName != null ? authorityName : "NULL")); + (serverName is not null ? serverName : "NULL"), + (authorityName is not null ? authorityName : "NULL")); Debug.Assert(ClassifySID(sid) == SidType.FakeObject); @@ -736,7 +736,7 @@ internal static bool BeginImpersonation(NetCred credential, out IntPtr hUserToke IntPtr hToken = IntPtr.Zero; // default credential is specified, no need to do impersonation - if (credential == null) + if (credential is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: nothing to impersonate"); return false; @@ -749,7 +749,7 @@ internal static bool BeginImpersonation(NetCred credential, out IntPtr hUserToke string domainName = credential.Domain; // no need to do impersonation as username and password are both null - if (userName == null && password == null) + if (userName is null && password is null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: nothing to impersonate (2)"); return false; @@ -806,7 +806,7 @@ internal static bool IsMachineDC(string computerName) try { - if (null == computerName) + if (computerName is null) err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(null, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); else err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(computerName, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ValueCollection.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ValueCollection.cs index cac56ee9535a53..5696291357e1ba 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ValueCollection.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/ValueCollection.cs @@ -32,7 +32,7 @@ bool IList.IsReadOnly int IList.Add(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _inner.Add((T)value); @@ -46,7 +46,7 @@ void IList.Clear() bool IList.Contains(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); return _inner.Contains((T)value); @@ -54,7 +54,7 @@ bool IList.Contains(object value) int IList.IndexOf(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); return IndexOf((T)value); @@ -62,7 +62,7 @@ int IList.IndexOf(object value) void IList.Insert(int index, object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); Insert(index, (T)value); @@ -70,7 +70,7 @@ void IList.Insert(int index, object value) void IList.Remove(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _inner.Remove((T)value); @@ -90,7 +90,7 @@ object IList.this[int index] set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); this[index] = (T)value; @@ -175,7 +175,7 @@ public bool IsReadOnly // Adds obj to the end of the list by inserting it into insertedValues. public void Add(T value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _inner.Add(value); @@ -188,7 +188,7 @@ public void Clear() public bool Contains(T value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); return _inner.Contains(value); @@ -196,7 +196,7 @@ public bool Contains(T value) public int IndexOf(T value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); int index = 0; @@ -225,7 +225,7 @@ public void Insert(int index, T value) { _inner.MarkChange(); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if ((index < 0) || (index > _inner.combinedValues.Count)) @@ -243,7 +243,7 @@ public void Insert(int index, T value) public bool Remove(T value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); return _inner.Remove(value); @@ -311,7 +311,7 @@ public T this[int index] throw new ArgumentOutOfRangeException(nameof(index)); } - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); TrackedCollection.ValueEl el = _inner.combinedValues[index]; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs index a48059fab57298..80cc4454316738 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs @@ -57,7 +57,7 @@ internal AdamInstance(DirectoryContext context, string adamHostName, DirectoryEn this.replicaName = adamHostName; string portNumber; Utils.SplitServerNameAndPortNumber(context.Name, out portNumber); - if (portNumber != null) + if (portNumber is not null) { this.replicaName = this.replicaName + ":" + portNumber; } @@ -113,7 +113,7 @@ public static AdamInstance GetAdamInstance(DirectoryContext context) string dnsHostName = null; // check that the context is not null - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -166,7 +166,7 @@ public static AdamInstance GetAdamInstance(DirectoryContext context) public static AdamInstance FindOne(DirectoryContext context, string partitionName) { // validate parameters (partitionName validated by the call to ConfigSet) - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -177,7 +177,7 @@ public static AdamInstance FindOne(DirectoryContext context, string partitionNam throw new ArgumentException(SR.TargetShouldBeConfigSet, nameof(context)); } - if (partitionName == null) + if (partitionName is null) { throw new ArgumentNullException(nameof(partitionName)); } @@ -198,7 +198,7 @@ public static AdamInstanceCollection FindAll(DirectoryContext context, string pa AdamInstanceCollection adamInstanceCollection = null; // validate parameters (partitionName validated by the call to ConfigSet) - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -209,7 +209,7 @@ public static AdamInstanceCollection FindAll(DirectoryContext context, string pa throw new ArgumentException(SR.TargetShouldBeConfigSet, nameof(context)); } - if (partitionName == null) + if (partitionName is null) { throw new ArgumentNullException(nameof(partitionName)); } @@ -299,7 +299,7 @@ public void SeizeRoleOwnership(AdamRole role) } finally { - if (roleObjectEntry != null) + if (roleObjectEntry is not null) { roleObjectEntry.Dispose(); } @@ -330,7 +330,7 @@ public override ReplicationCursorCollection GetReplicationCursors(string partiti if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -364,7 +364,7 @@ public override ReplicationNeighborCollection GetReplicationNeighbors(string par if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -403,7 +403,7 @@ public override ActiveDirectoryReplicationMetadata GetReplicationMetadata(string if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (objectPath == null) + if (objectPath is null) throw new ArgumentNullException(nameof(objectPath)); if (objectPath.Length == 0) @@ -420,13 +420,13 @@ public override void SyncReplicaFromServer(string partition, string sourceServer if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(partition)); - if (sourceServer == null) + if (sourceServer is null) throw new ArgumentNullException(nameof(sourceServer)); if (sourceServer.Length == 0) @@ -442,7 +442,7 @@ public override void TriggerSyncReplicaFromNeighbors(string partition) if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -458,7 +458,7 @@ public override void SyncReplicaFromAllServers(string partition, SyncFromAllServ if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -501,7 +501,7 @@ public ConfigurationSet ConfigurationSet get { CheckIfDisposed(); - if (_currentConfigSet == null) + if (_currentConfigSet is null) { DirectoryContext configSetContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _currentConfigSet = ConfigurationSet.GetConfigurationSet(configSetContext); @@ -515,7 +515,7 @@ public string HostName get { CheckIfDisposed(); - if (_cachedHostName == null) + if (_cachedHostName is null) { DirectoryEntry serverEntry = directoryEntryMgr.GetCachedDirectoryEntry(ServerObjectName); _cachedHostName = (string)PropertyManager.GetPropertyValue(context, serverEntry, PropertyManager.DnsHostName); @@ -564,7 +564,7 @@ public AdamRoleCollection Roles try { - if (_cachedRoles == null) + if (_cachedRoles is null) { // check for the fsmoRoleOwner attribute on the Config and Schema objects ArrayList roleList = new ArrayList(); @@ -591,11 +591,11 @@ public AdamRoleCollection Roles } finally { - if (schemaEntry != null) + if (schemaEntry is not null) { schemaEntry.Dispose(); } - if (partitionsEntry != null) + if (partitionsEntry is not null) { partitionsEntry.Dispose(); } @@ -615,7 +615,7 @@ public string DefaultPartition try { ntdsaEntry.RefreshCache(); - if (ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value == null) + if (ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value is null) { // property has not been set _cachedDefaultPartition = null; @@ -638,7 +638,7 @@ public string DefaultPartition CheckIfDisposed(); DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); - if (value == null) + if (value is null) { if (ntdsaEntry.Properties.Contains(PropertyManager.MsDSDefaultNamingContext)) { @@ -690,7 +690,7 @@ public override string SiteName get { CheckIfDisposed(); - if (cachedSiteName == null) + if (cachedSiteName is null) { DirectoryEntry siteEntry = DirectoryEntryManager.GetDirectoryEntry(context, SiteObjectName); try @@ -711,7 +711,7 @@ internal string SiteObjectName get { CheckIfDisposed(); - if (cachedSiteObjectName == null) + if (cachedSiteObjectName is null) { // get the site object name from the server object name // CN=server1,CN=Servers,CN=Site1,CN=Sites @@ -737,7 +737,7 @@ internal string ServerObjectName get { CheckIfDisposed(); - if (cachedServerObjectName == null) + if (cachedServerObjectName is null) { DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try @@ -762,7 +762,7 @@ internal string NtdsaObjectName get { CheckIfDisposed(); - if (cachedNtdsaObjectName == null) + if (cachedNtdsaObjectName is null) { DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs index eec24034647579..c6d8187f427988 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs @@ -11,7 +11,7 @@ internal AdamInstanceCollection() { } internal AdamInstanceCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -21,7 +21,7 @@ internal AdamInstanceCollection(ArrayList values) public bool Contains(AdamInstance adamInstance) { - if (adamInstance == null) + if (adamInstance is null) { throw new ArgumentNullException(nameof(adamInstance)); } @@ -39,7 +39,7 @@ public bool Contains(AdamInstance adamInstance) public int IndexOf(AdamInstance adamInstance) { - if (adamInstance == null) + if (adamInstance is null) { throw new ArgumentNullException(nameof(adamInstance)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs index a7522a47b5a7ae..5b4323064e9363 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs @@ -27,17 +27,17 @@ internal ActiveDirectoryInterSiteTransport(DirectoryContext context, ActiveDirec public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context, ActiveDirectoryTransportType transport) { - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name - if (context.Name != null) + if (context.Name is not null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); @@ -350,7 +350,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (_cachedEntry != null) + if (_cachedEntry is not null) _cachedEntry.Dispose(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs index f73a65ae2f2d59..589dfe2f4c2a1d 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs @@ -57,7 +57,7 @@ public ActiveDirectorySchedule() public ActiveDirectorySchedule(ActiveDirectorySchedule schedule) : this() { - if (schedule == null) + if (schedule is null) throw new ArgumentNullException(nameof(schedule)); bool[] tmpSchedule = schedule._scheduleArray; @@ -84,7 +84,7 @@ internal ActiveDirectorySchedule(bool[] schedule) : this() } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); ValidateRawArray(value); @@ -126,7 +126,7 @@ public void SetSchedule(DayOfWeek day, HourOfDay fromHour, MinuteOfHour fromMinu public void SetSchedule(DayOfWeek[] days, HourOfDay fromHour, MinuteOfHour fromMinute, HourOfDay toHour, MinuteOfHour toMinute) { - if (days == null) + if (days is null) throw new ArgumentNullException(nameof(days)); for (int i = 0; i < days.Length; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs index 229c1dc56d1acd..4077fa92bccaa1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -61,13 +61,13 @@ protected override void Dispose(bool disposing) if (disposing) { // dispose schema entry - if (_schemaEntry != null) + if (_schemaEntry is not null) { _schemaEntry.Dispose(); _schemaEntry = null; } // dispose the abstract schema entry - if (_abstractSchemaEntry != null) + if (_abstractSchemaEntry is not null) { _abstractSchemaEntry.Dispose(); _abstractSchemaEntry = null; @@ -86,7 +86,7 @@ protected override void Dispose(bool disposing) #region public methods public static ActiveDirectorySchema GetSchema(DirectoryContext context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -99,12 +99,12 @@ public static ActiveDirectorySchema GetSchema(DirectoryContext context) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(ActiveDirectorySchema), null); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) @@ -192,7 +192,7 @@ public void RefreshSchema() // refresh the schema on the client // bind to the abstract schema - if (_abstractSchemaEntry == null) + if (_abstractSchemaEntry is null) { _abstractSchemaEntry = directoryEntryMgr.GetCachedDirectoryEntry("Schema"); } @@ -204,7 +204,7 @@ public void RefreshSchema() } finally { - if (rootDSE != null) + if (rootDSE is not null) { rootDSE.Dispose(); } @@ -227,7 +227,7 @@ public ActiveDirectorySchemaClass FindDefunctClass(string commonName) { CheckIfDisposed(); - if (commonName == null) + if (commonName is null) { throw new ArgumentNullException(nameof(commonName)); } @@ -303,7 +303,7 @@ public ActiveDirectorySchemaProperty FindDefunctProperty(string commonName) { CheckIfDisposed(); - if (commonName == null) + if (commonName is null) { throw new ArgumentNullException(nameof(commonName)); } @@ -407,7 +407,7 @@ public DirectoryServer SchemaRoleOwner get { CheckIfDisposed(); - if (_cachedSchemaRoleOwner == null) + if (_cachedSchemaRoleOwner is null) { _cachedSchemaRoleOwner = GetSchemaRoleOwner(); } @@ -443,7 +443,7 @@ internal static ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties bool isDefunct = false; - if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0)) + if ((res.Properties[PropertyManager.IsDefunct] is not null) && (res.Properties[PropertyManager.IsDefunct].Count > 0)) { isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0]; } @@ -466,7 +466,7 @@ internal static ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties finally { // dispose off the result collection - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } @@ -500,7 +500,7 @@ internal static ReadOnlyActiveDirectorySchemaClassCollection GetAllClasses(Direc bool isDefunct = false; - if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0)) + if ((res.Properties[PropertyManager.IsDefunct] is not null) && (res.Properties[PropertyManager.IsDefunct].Count > 0)) { isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0]; } @@ -523,7 +523,7 @@ internal static ReadOnlyActiveDirectorySchemaClassCollection GetAllClasses(Direc finally { // dispose off the result collection - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs index b03c89f67ee1a7..cc2d34676451f2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -48,17 +48,17 @@ public class ActiveDirectorySchemaClass : IDisposable #region constructors public ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayName) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) @@ -67,7 +67,7 @@ public ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayNa } } - if (ldapDisplayName == null) + if (ldapDisplayName is null) { throw new ArgumentNullException(nameof(ldapDisplayName)); } @@ -142,7 +142,7 @@ internal ActiveDirectorySchemaClass(DirectoryContext context, string commonName, // all relevant properties have already been retrieved from the server _propertyValuesFromServer = propertyValuesFromServer; - Debug.Assert(_propertyValuesFromServer != null); + Debug.Assert(_propertyValuesFromServer is not null); _propertiesFromSchemaContainerInitialized = true; _classEntry = GetSchemaClassDirectoryEntry(); @@ -195,25 +195,25 @@ protected virtual void Dispose(bool disposing) if (disposing) { // dispose schema entry - if (_schemaEntry != null) + if (_schemaEntry is not null) { _schemaEntry.Dispose(); _schemaEntry = null; } // dispose class entry - if (_classEntry != null) + if (_classEntry is not null) { _classEntry.Dispose(); _classEntry = null; } // dispose abstract class entry - if (_abstractClassEntry != null) + if (_abstractClassEntry is not null) { _abstractClassEntry.Dispose(); _abstractClassEntry = null; } // dispose the schema object - if (_schema != null) + if (_schema is not null) { _schema.Dispose(); } @@ -228,17 +228,17 @@ public static ActiveDirectorySchemaClass FindByName(DirectoryContext context, st { ActiveDirectorySchemaClass schemaClass = null; - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } - if (context.Name != null) + if (context.Name is not null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) { @@ -246,7 +246,7 @@ public static ActiveDirectorySchemaClass FindByName(DirectoryContext context, st } } - if (ldapDisplayName == null) + if (ldapDisplayName is null) { throw new ArgumentNullException(nameof(ldapDisplayName)); } @@ -288,7 +288,7 @@ public void Save() try { // create a new directory entry for this class - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -318,25 +318,25 @@ public void Save() SetProperty(PropertyManager.Description, _description); // set the possibleSuperiors property - if (_possibleSuperiors != null) + if (_possibleSuperiors is not null) { _classEntry.Properties[PropertyManager.PossibleSuperiors].AddRange(_possibleSuperiors.GetMultiValuedProperty()); } // set the mandatoryProperties property - if (_mandatoryProperties != null) + if (_mandatoryProperties is not null) { _classEntry.Properties[PropertyManager.MustContain].AddRange(_mandatoryProperties.GetMultiValuedProperty()); } // set the optionalProperties property - if (_optionalProperties != null) + if (_optionalProperties is not null) { _classEntry.Properties[PropertyManager.MayContain].AddRange(_optionalProperties.GetMultiValuedProperty()); } // set the subClassOf property - if (_subClassOf != null) + if (_subClassOf is not null) { SetProperty(PropertyManager.SubClassOf, _subClassOf.Name); } @@ -350,13 +350,13 @@ public void Save() SetProperty(PropertyManager.ObjectClassCategory, _type); // set the schemaIDGuid property - if (_schemaGuidBinaryForm != null) + if (_schemaGuidBinaryForm is not null) { SetProperty(PropertyManager.SchemaIDGuid, _schemaGuidBinaryForm); } // set the default security descriptor - if (_defaultSDSddlForm != null) + if (_defaultSDSddlForm is not null) { SetProperty(PropertyManager.DefaultSecurityDescriptor, _defaultSDSddlForm); } @@ -368,7 +368,7 @@ public void Save() _classEntry.CommitChanges(); // Refresh the schema cache on the schema role owner - if (_schema == null) + if (_schema is null) { ActiveDirectorySchema schemaObject = ActiveDirectorySchema.GetSchema(_context); bool alreadyUsingSchemaRoleOwnerContext = false; @@ -393,7 +393,7 @@ public void Save() } finally { - if (schemaRoleOwner != null) + if (schemaRoleOwner is not null) { schemaRoleOwner.Dispose(); } @@ -450,7 +450,7 @@ public DirectoryEntry GetDirectoryEntry() } GetSchemaClassDirectoryEntry(); - Debug.Assert(_classEntry != null); + Debug.Assert(_classEntry is not null); return DirectoryEntryManager.GetDirectoryEntryInternal(_context, _classEntry.Path); } @@ -474,7 +474,7 @@ public string CommonName if (isBound) { - if (_commonName == null) + if (_commonName is null) { // get the property from the server _commonName = (string)GetValueFromCache(PropertyManager.Cn, true); @@ -503,7 +503,7 @@ public string Oid if (isBound) { - if (_oid == null) + if (_oid is null) { // get the property from the abstract schema/ schema container // (for non-defunt classes this property is available in the abstract schema) @@ -596,7 +596,7 @@ public ActiveDirectorySchemaClassCollection PossibleSuperiors { CheckIfDisposed(); - if (_possibleSuperiors == null) + if (_possibleSuperiors is null) { if (isBound) { @@ -673,7 +673,7 @@ public ReadOnlyActiveDirectorySchemaClassCollection PossibleInferiors { CheckIfDisposed(); - if (_possibleInferiors == null) + if (_possibleInferiors is null) { if (isBound) { @@ -695,7 +695,7 @@ public ActiveDirectorySchemaPropertyCollection MandatoryProperties { CheckIfDisposed(); - if (_mandatoryProperties == null) + if (_mandatoryProperties is null) { if (isBound) { @@ -771,7 +771,7 @@ public ActiveDirectorySchemaPropertyCollection OptionalProperties { CheckIfDisposed(); - if (_optionalProperties == null) + if (_optionalProperties is null) { if (isBound) { @@ -856,7 +856,7 @@ public ActiveDirectorySchemaClassCollection AuxiliaryClasses { CheckIfDisposed(); - if (_auxiliaryClasses == null) + if (_auxiliaryClasses is null) { if (isBound) { @@ -934,7 +934,7 @@ public ActiveDirectorySchemaClass SubClassOf if (isBound) { - if (_subClassOf == null) + if (_subClassOf is null) { // get the property from the server _subClassOf = new ActiveDirectorySchemaClass(_context, (string)GetValueFromCache(PropertyManager.SubClassOf, true), (DirectoryEntry)null, _schemaEntry); @@ -999,7 +999,7 @@ public Guid SchemaGuid if (isBound) { - if (_schemaGuidBinaryForm == null) + if (_schemaGuidBinaryForm is null) { // get the property from the server _schemaGuidBinaryForm = (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true); @@ -1041,7 +1041,7 @@ public ActiveDirectorySecurity DefaultObjectSecurityDescriptor } // we cache the sddl form and create a ActiveDirectorySecurity object each time - if (_defaultSDSddlForm != null) + if (_defaultSDSddlForm is not null) { defaultObjectSecurityDescriptor = new ActiveDirectorySecurity(); defaultObjectSecurityDescriptor.SetSecurityDescriptorSddlForm(_defaultSDSddlForm); @@ -1056,9 +1056,9 @@ public ActiveDirectorySecurity DefaultObjectSecurityDescriptor if (isBound) { // set the value on the directory entry - SetProperty(PropertyManager.DefaultSecurityDescriptor, (value == null) ? null : value.GetSecurityDescriptorSddlForm(AccessControlSections.All)); + SetProperty(PropertyManager.DefaultSecurityDescriptor, (value is null) ? null : value.GetSecurityDescriptorSddlForm(AccessControlSections.All)); } - _defaultSDSddlForm = (value == null) ? null : value.GetSecurityDescriptorSddlForm(AccessControlSections.All); + _defaultSDSddlForm = (value is null) ? null : value.GetSecurityDescriptorSddlForm(AccessControlSections.All); } } @@ -1087,10 +1087,10 @@ private object GetValueFromCache(string propertyName, bool mustExist) // retrieve the properties from the server if necessary InitializePropertiesFromSchemaContainer(); - Debug.Assert(_propertyValuesFromServer != null); + Debug.Assert(_propertyValuesFromServer is not null); ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLowerInvariant()]; - Debug.Assert(values != null); + Debug.Assert(values is not null); if (values.Count < 1 && mustExist) { throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound, propertyName)); @@ -1112,10 +1112,10 @@ private ICollection GetValuesFromCache(string propertyName) // retrieve the properties from the server if necessary InitializePropertiesFromSchemaContainer(); - Debug.Assert(_propertyValuesFromServer != null); + Debug.Assert(_propertyValuesFromServer is not null); ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLowerInvariant()]; - Debug.Assert(values != null); + Debug.Assert(values is not null); return values; } @@ -1126,7 +1126,7 @@ private void InitializePropertiesFromSchemaContainer() { if (!_propertiesFromSchemaContainerInitialized) { - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -1257,7 +1257,7 @@ internal static Hashtable GetPropertiesFromSchemaContainer(DirectoryContext cont internal DirectoryEntry GetSchemaClassDirectoryEntry() { - if (_classEntry == null) + if (_classEntry is null) { InitializePropertiesFromSchemaContainer(); _classEntry = DirectoryEntryManager.GetDirectoryEntry(_context, (string)GetValueFromCache(PropertyManager.DistinguishedName, true)); @@ -1270,11 +1270,11 @@ private void SetProperty(string propertyName, object value) { // get the distinguished name to construct the directory entry GetSchemaClassDirectoryEntry(); - Debug.Assert(_classEntry != null); + Debug.Assert(_classEntry is not null); try { - if ((value == null)) + if ((value is null)) { if (_classEntry.Properties.Contains(propertyName)) { @@ -1308,7 +1308,7 @@ private ArrayList GetClasses(ICollection ldapDisplayNames) return classes; } - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -1361,7 +1361,7 @@ private ArrayList GetClasses(ICollection ldapDisplayNames) } finally { - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } @@ -1386,7 +1386,7 @@ private ArrayList GetProperties(ICollection ldapDisplayNames) return properties; } - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -1439,7 +1439,7 @@ private ArrayList GetProperties(ICollection ldapDisplayNames) } finally { - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs index 47cb7878f8ea90..e3493f20b6d1a9 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -56,7 +56,7 @@ public ActiveDirectorySchemaClass this[int index] get => (ActiveDirectorySchemaClass)List[index]; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -79,7 +79,7 @@ public ActiveDirectorySchemaClass this[int index] public int Add(ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentNullException(nameof(schemaClass)); } @@ -101,14 +101,14 @@ public int Add(ActiveDirectorySchemaClass schemaClass) public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) { - if (schemaClasses == null) + if (schemaClasses is null) { throw new ArgumentNullException(nameof(schemaClasses)); } foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentException(null, nameof(schemaClasses)); } @@ -122,14 +122,14 @@ public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) { - if (schemaClasses == null) + if (schemaClasses is null) { throw new ArgumentNullException(nameof(schemaClasses)); } foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentException(null, nameof(schemaClasses)); } @@ -144,14 +144,14 @@ public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) { - if (schemaClasses == null) + if (schemaClasses is null) { throw new ArgumentNullException(nameof(schemaClasses)); } foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentException(null, nameof(schemaClasses)); } @@ -166,7 +166,7 @@ public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) public void Remove(ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentNullException(nameof(schemaClass)); } @@ -190,7 +190,7 @@ public void Remove(ActiveDirectorySchemaClass schemaClass) public void Insert(int index, ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentNullException(nameof(schemaClass)); } @@ -212,7 +212,7 @@ public void Insert(int index, ActiveDirectorySchemaClass schemaClass) public bool Contains(ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentNullException(nameof(schemaClass)); } @@ -241,7 +241,7 @@ public void CopyTo(ActiveDirectorySchemaClass[] schemaClasses, int index) public int IndexOf(ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) { throw new ArgumentNullException(nameof(schemaClass)); } @@ -267,7 +267,7 @@ protected override void OnClearComplete() { if (_isBound) { - if (_classEntry == null) + if (_classEntry is null) { _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); } @@ -290,7 +290,7 @@ protected override void OnInsertComplete(int index, object value) { if (_isBound) { - if (_classEntry == null) + if (_classEntry is null) { _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); } @@ -310,7 +310,7 @@ protected override void OnRemoveComplete(int index, object value) { if (_isBound) { - if (_classEntry == null) + if (_classEntry is null) { _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); } @@ -352,7 +352,7 @@ protected override void OnSetComplete(int index, object oldValue, object newValu protected override void OnValidate(object value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs index bb0cbdd538e0ff..9a75afa2f1e94c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs @@ -102,17 +102,17 @@ public class ActiveDirectorySchemaProperty : IDisposable #region constructors public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) @@ -121,7 +121,7 @@ public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDispla } } - if (ldapDisplayName == null) + if (ldapDisplayName is null) { throw new ArgumentNullException(nameof(ldapDisplayName)); } @@ -195,7 +195,7 @@ internal ActiveDirectorySchemaProperty(DirectoryContext context, string commonNa // all relevant properties have already been retrieved from the server _propertyValuesFromServer = propertyValuesFromServer; - Debug.Assert(_propertyValuesFromServer != null); + Debug.Assert(_propertyValuesFromServer is not null); _propertiesFromSchemaContainerInitialized = true; _propertyEntry = GetSchemaPropertyDirectoryEntry(); @@ -248,25 +248,25 @@ protected virtual void Dispose(bool disposing) if (disposing) { // dispose schema entry - if (_schemaEntry != null) + if (_schemaEntry is not null) { _schemaEntry.Dispose(); _schemaEntry = null; } // dispose property entry - if (_propertyEntry != null) + if (_propertyEntry is not null) { _propertyEntry.Dispose(); _propertyEntry = null; } // dispose abstract class entry - if (_abstractPropertyEntry != null) + if (_abstractPropertyEntry is not null) { _abstractPropertyEntry.Dispose(); _abstractPropertyEntry = null; } // dispose the schema object - if (_schema != null) + if (_schema is not null) { _schema.Dispose(); } @@ -282,17 +282,17 @@ public static ActiveDirectorySchemaProperty FindByName(DirectoryContext context, { ActiveDirectorySchemaProperty schemaProperty = null; - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) @@ -301,7 +301,7 @@ public static ActiveDirectorySchemaProperty FindByName(DirectoryContext context, } } - if (ldapDisplayName == null) + if (ldapDisplayName is null) { throw new ArgumentNullException(nameof(ldapDisplayName)); } @@ -329,7 +329,7 @@ public void Save() try { // create a new directory entry for this class - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -374,13 +374,13 @@ public void Save() _propertyEntry.Properties[PropertyManager.IsDefunct].Value = _isDefunct; // set the range lower attribute - if (_rangeLower != null) + if (_rangeLower is not null) { _propertyEntry.Properties[PropertyManager.RangeLower].Value = (int)_rangeLower.Value; } // set the range upper attribute - if (_rangeUpper != null) + if (_rangeUpper is not null) { _propertyEntry.Properties[PropertyManager.RangeUpper].Value = (int)_rangeUpper.Value; } @@ -392,13 +392,13 @@ public void Save() } // set the link id - if (_linkId != null) + if (_linkId is not null) { _propertyEntry.Properties[PropertyManager.LinkID].Value = (int)_linkId.Value; } // set the schemaIDGuid property - if (_schemaGuidBinaryForm != null) + if (_schemaGuidBinaryForm is not null) { SetProperty(PropertyManager.SchemaIDGuid, _schemaGuidBinaryForm); } @@ -410,7 +410,7 @@ public void Save() _propertyEntry.CommitChanges(); // Refresh the schema cache on the schema role owner - if (_schema == null) + if (_schema is null) { ActiveDirectorySchema schemaObject = ActiveDirectorySchema.GetSchema(_context); bool alreadyUsingSchemaRoleOwnerContext = false; @@ -435,7 +435,7 @@ public void Save() } finally { - if (schemaRoleOwner != null) + if (schemaRoleOwner is not null) { schemaRoleOwner.Dispose(); } @@ -487,7 +487,7 @@ public DirectoryEntry GetDirectoryEntry() } GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); return DirectoryEntryManager.GetDirectoryEntryInternal(_context, _propertyEntry.Path); } @@ -512,7 +512,7 @@ public string CommonName if (isBound) { - if (_commonName == null) + if (_commonName is null) { // get the property from the server _commonName = (string)GetValueFromCache(PropertyManager.Cn, true); @@ -524,7 +524,7 @@ public string CommonName { CheckIfDisposed(); - if (value != null && value.Length == 0) + if (value is not null && value.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(value)); if (isBound) @@ -544,7 +544,7 @@ public string Oid if (isBound) { - if (_oid == null) + if (_oid is null) { // get the property from the abstract schema/ schema container // (for non-defunt classes this property is available in the abstract schema) @@ -571,7 +571,7 @@ public string Oid { CheckIfDisposed(); - if (value != null && value.Length == 0) + if (value is not null && value.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(value)); if (isBound) @@ -594,7 +594,7 @@ public ActiveDirectorySyntax Syntax if (!_syntaxInitialized) { byte[] omObjectClassBinaryForm = (byte[])GetValueFromCache(PropertyManager.OMObjectClass, false); - OMObjectClass omObjectClass = (omObjectClassBinaryForm != null) ? new OMObjectClass(omObjectClassBinaryForm) : null; + OMObjectClass omObjectClass = (omObjectClassBinaryForm is not null) ? new OMObjectClass(omObjectClassBinaryForm) : null; _syntax = MapSyntax((string)GetValueFromCache(PropertyManager.AttributeSyntax, true), (int)GetValueFromCache(PropertyManager.OMSyntax, true), @@ -643,7 +643,7 @@ public string Description { CheckIfDisposed(); - if (value != null && value.Length == 0) + if (value is not null && value.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(value)); if (isBound) @@ -695,7 +695,7 @@ public bool IsSingleValued { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.IsSingleValued].Value = value; @@ -831,7 +831,7 @@ public bool IsInGlobalCatalog { // get the property from the server object value = GetValueFromCache(PropertyManager.IsMemberOfPartialAttributeSet, false); - _isInGlobalCatalog = (value != null) ? (bool)value : false; + _isInGlobalCatalog = (value is not null) ? (bool)value : false; _isInGlobalCatalogInitialized = true; } } @@ -845,7 +845,7 @@ public bool IsInGlobalCatalog { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.IsMemberOfPartialAttributeSet].Value = value; @@ -867,7 +867,7 @@ public Nullable RangeLower // get the property from the server // if the property is not set then we will return null object value = GetValueFromCache(PropertyManager.RangeLower, false); - if (value == null) + if (value is null) { _rangeLower = null; } @@ -888,10 +888,10 @@ public Nullable RangeLower { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry - if (value == null) + if (value is null) { if (_propertyEntry.Properties.Contains(PropertyManager.RangeLower)) { @@ -920,7 +920,7 @@ public Nullable RangeUpper // get the property from the server // if the property is not set then we will return null object value = GetValueFromCache(PropertyManager.RangeUpper, false); - if (value == null) + if (value is null) { _rangeUpper = null; } @@ -941,10 +941,10 @@ public Nullable RangeUpper { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry - if (value == null) + if (value is null) { if (_propertyEntry.Properties.Contains(PropertyManager.RangeUpper)) { @@ -992,7 +992,7 @@ public ActiveDirectorySchemaProperty Link if (!_linkedPropertyInitialized) { object value = GetValueFromCache(PropertyManager.LinkID, false); - int tempLinkId = (value != null) ? (int)value : -1; + int tempLinkId = (value is not null) ? (int)value : -1; if (tempLinkId != -1) { @@ -1000,7 +1000,7 @@ public ActiveDirectorySchemaProperty Link try { - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -1039,7 +1039,7 @@ public Nullable LinkId { object value = GetValueFromCache(PropertyManager.LinkID, false); // if the property was not set we will return null - if (value == null) + if (value is null) { _linkId = null; } @@ -1060,10 +1060,10 @@ public Nullable LinkId { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry - if (value == null) + if (value is null) { if (_propertyEntry.Properties.Contains(PropertyManager.LinkID)) { @@ -1087,7 +1087,7 @@ public Guid SchemaGuid if (isBound) { - if (_schemaGuidBinaryForm == null) + if (_schemaGuidBinaryForm is null) { // get the property from the server _schemaGuidBinaryForm = (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true); @@ -1135,13 +1135,13 @@ private object GetValueFromCache(string propertyName, bool mustExist) // retrieve the properties from the server if necessary InitializePropertiesFromSchemaContainer(); - Debug.Assert(_propertyValuesFromServer != null); + Debug.Assert(_propertyValuesFromServer is not null); ResultPropertyValueCollection propertyValues = null; try { propertyValues = _propertyValuesFromServer.Properties[propertyName]; - if ((propertyValues == null) || (propertyValues.Count < 1)) + if ((propertyValues is null) || (propertyValues.Count < 1)) { if (mustExist) { @@ -1168,7 +1168,7 @@ private void InitializePropertiesFromSchemaContainer() { if (!_propertiesFromSchemaContainerInitialized) { - if (_schemaEntry == null) + if (_schemaEntry is null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } @@ -1305,7 +1305,7 @@ internal static SearchResult GetPropertiesFromSchemaContainer(DirectoryContext c } } - if (propertyValuesFromServer == null) + if (propertyValuesFromServer is null) { throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaProperty), name); } @@ -1315,7 +1315,7 @@ internal static SearchResult GetPropertiesFromSchemaContainer(DirectoryContext c internal DirectoryEntry GetSchemaPropertyDirectoryEntry() { - if (_propertyEntry == null) + if (_propertyEntry is null) { InitializePropertiesFromSchemaContainer(); _propertyEntry = DirectoryEntryManager.GetDirectoryEntry(_context, (string)GetValueFromCache(PropertyManager.DistinguishedName, true)); @@ -1338,7 +1338,7 @@ private void InitializeSearchFlags() { object value = GetValueFromCache(PropertyManager.SearchFlags, false); - if (value != null) + if (value is not null) { _searchFlags = (SearchFlags)((int)value); } @@ -1362,7 +1362,7 @@ private void SetBitInSearchFlags(SearchFlags searchFlagBit) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.SearchFlags].Value = (int)_searchFlags; @@ -1378,7 +1378,7 @@ private void ResetBitInSearchFlags(SearchFlags searchFlagBit) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.SearchFlags].Value = (int)_searchFlags; @@ -1389,9 +1389,9 @@ private void SetProperty(string propertyName, object value) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); - if (value == null) + if (value is null) { if (_propertyEntry.Properties.Contains(propertyName)) { @@ -1425,12 +1425,12 @@ private void SetSyntax(ActiveDirectorySyntax syntax) // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); - Debug.Assert(_propertyEntry != null); + Debug.Assert(_propertyEntry is not null); _propertyEntry.Properties[PropertyManager.AttributeSyntax].Value = s_syntaxes[(int)syntax].attributeSyntax; _propertyEntry.Properties[PropertyManager.OMSyntax].Value = s_syntaxes[(int)syntax].oMSyntax; OMObjectClass oMObjectClass = s_syntaxes[(int)syntax].oMObjectClass; - if (oMObjectClass != null) + if (oMObjectClass is not null) { _propertyEntry.Properties[PropertyManager.OMObjectClass].Value = oMObjectClass.Data; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs index 30a327356dd4dc..1ded4cbbebcc96 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -56,7 +56,7 @@ public ActiveDirectorySchemaProperty this[int index] get => (ActiveDirectorySchemaProperty)List[index]; set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!value.isBound) @@ -77,7 +77,7 @@ public ActiveDirectorySchemaProperty this[int index] public int Add(ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) { throw new ArgumentNullException(nameof(schemaProperty)); } @@ -99,14 +99,14 @@ public int Add(ActiveDirectorySchemaProperty schemaProperty) public void AddRange(ActiveDirectorySchemaProperty[] properties) { - if (properties == null) + if (properties is null) { throw new ArgumentNullException(nameof(properties)); } foreach (ActiveDirectorySchemaProperty property in properties) { - if (property == null) + if (property is null) { throw new ArgumentException(null, nameof(properties)); } @@ -120,14 +120,14 @@ public void AddRange(ActiveDirectorySchemaProperty[] properties) public void AddRange(ActiveDirectorySchemaPropertyCollection properties) { - if (properties == null) + if (properties is null) { throw new ArgumentNullException(nameof(properties)); } foreach (ActiveDirectorySchemaProperty property in properties) { - if (property == null) + if (property is null) { throw new ArgumentException(null, nameof(properties)); } @@ -143,14 +143,14 @@ public void AddRange(ActiveDirectorySchemaPropertyCollection properties) public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) { - if (properties == null) + if (properties is null) { throw new ArgumentNullException(nameof(properties)); } foreach (ActiveDirectorySchemaProperty property in properties) { - if (property == null) + if (property is null) { throw new ArgumentException(null, nameof(properties)); } @@ -166,7 +166,7 @@ public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) public void Remove(ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) { throw new ArgumentNullException(nameof(schemaProperty)); } @@ -190,7 +190,7 @@ public void Remove(ActiveDirectorySchemaProperty schemaProperty) public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) { throw new ArgumentNullException(nameof(schemaProperty)); } @@ -212,7 +212,7 @@ public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty) public bool Contains(ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) { throw new ArgumentNullException(nameof(schemaProperty)); } @@ -255,7 +255,7 @@ public void CopyTo(ActiveDirectorySchemaProperty[] properties, int index) public int IndexOf(ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) { throw new ArgumentNullException(nameof(schemaProperty)); } @@ -280,7 +280,7 @@ protected override void OnClearComplete() { if (_isBound) { - if (_classEntry == null) + if (_classEntry is null) { _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); } @@ -303,7 +303,7 @@ protected override void OnInsertComplete(int index, object value) { if (_isBound) { - if (_classEntry == null) + if (_classEntry is null) { _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); } @@ -323,7 +323,7 @@ protected override void OnRemoveComplete(int index, object value) { if (_isBound) { - if (_classEntry == null) + if (_classEntry is null) { _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); } @@ -365,7 +365,7 @@ protected override void OnSetComplete(int index, object oldValue, object newValu protected override void OnValidate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySchemaProperty)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs index 489bee4c7b443e..d45d9823fac5b8 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -95,7 +95,7 @@ public static ActiveDirectorySite FindByName(DirectoryContext context, string si false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); - if (srchResult == null) + if (srchResult is null) { // no such site object throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName); @@ -158,7 +158,7 @@ public ActiveDirectorySite(DirectoryContext context, string siteName) } finally { - if (de != null) + if (de is not null) de.Dispose(); } @@ -210,7 +210,7 @@ public static ActiveDirectorySite GetComputerSite() try { string siteName = Marshal.PtrToStringUni(ptr); - Debug.Assert(siteName != null); + Debug.Assert(siteName is not null); // find the forest this machine belongs to string forestName = Locator.GetDomainControllerInfo(null, null, null, (long)PrivateLocatorFlags.DirectoryServicesRequired).DnsForestName; @@ -356,7 +356,7 @@ public DirectoryServer InterSiteTopologyGenerator if (existing) { // have not load topology generator information from the directory and user has not set it yet - if (_topologyGenerator == null && !_topologyTouched) + if (_topologyGenerator is null && !_topologyTouched) { bool ISTGExist; try @@ -411,7 +411,7 @@ public DirectoryServer InterSiteTopologyGenerator if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (existing) @@ -500,7 +500,7 @@ public string Location try { - if (value == null) + if (value is null) { if (cachedEntry.Properties.Contains("location")) cachedEntry.Properties["location"].Clear(); @@ -598,7 +598,7 @@ public ActiveDirectorySchedule IntraSiteReplicationSchedule if (NTDSSiteEntry.Properties.Contains("schedule")) { byte[] tmpSchedule = (byte[])NTDSSiteEntry.Properties["schedule"][0]; - Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188); + Debug.Assert(tmpSchedule is not null && tmpSchedule.Length == 188); schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(tmpSchedule); } @@ -610,7 +610,7 @@ public ActiveDirectorySchedule IntraSiteReplicationSchedule } else { - if (_replicationSchedule != null) + if (_replicationSchedule is not null) { // newly created site, get the schedule if already has been set by the user schedule = new ActiveDirectorySchedule(); @@ -629,7 +629,7 @@ public ActiveDirectorySchedule IntraSiteReplicationSchedule { try { - if (value == null) + if (value is null) { // clear it out if existing before if (NTDSSiteEntry.Properties.Contains("schedule")) @@ -647,7 +647,7 @@ public ActiveDirectorySchedule IntraSiteReplicationSchedule else { // clear out the schedule - if (value == null) + if (value is null) _replicationSchedule = null; else { @@ -684,7 +684,7 @@ private DirectoryEntry NTDSSiteEntry { get { - if (_ntdsEntry == null) + if (_ntdsEntry is null) { DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Site Settings," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)); try @@ -803,13 +803,13 @@ public void Save() DirectoryEntry tmpEntry = cachedEntry.Children.Add("CN=NTDS Site Settings", "nTDSSiteSettings"); //set properties on the Site NTDS settings object DirectoryServer replica = InterSiteTopologyGenerator; - if (replica != null) + if (replica is not null) { string ntdsaName = (replica is DomainController) ? ((DomainController)replica).NtdsaObjectName : ((AdamInstance)replica).NtdsaObjectName; tmpEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName; } tmpEntry.Properties["options"].Value = _siteOptions; - if (_replicationSchedule != null) + if (_replicationSchedule is not null) { tmpEntry.Properties["schedule"].Value = _replicationSchedule; } @@ -934,7 +934,7 @@ private ReadOnlyDirectoryServerCollection GetBridgeheadServers() string fromSite = Utils.GetPartialDN(fromServer, 3); pathCracker.Set(fromSite, NativeComInterfaces.ADS_SETTYPE_DN); fromSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); - Debug.Assert(fromSite != null && Utils.Compare(fromSite, 0, 3, "CN=", 0, 3) == 0); + Debug.Assert(fromSite is not null && Utils.Compare(fromSite, 0, 3, "CN=", 0, 3) == 0); fromSite = fromSite.Substring(3); string serverObjectName = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 2); @@ -1013,7 +1013,7 @@ private ReadOnlyDirectoryServerCollection GetBridgeheadServers() // escaping manipulation pathCracker.Set(otherSite, NativeComInterfaces.ADS_SETTYPE_DN); otherSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); - Debug.Assert(otherSite != null && Utils.Compare(otherSite, 0, 3, "CN=", 0, 3) == 0); + Debug.Assert(otherSite is not null && Utils.Compare(otherSite, 0, 3, "CN=", 0, 3) == 0); otherSite = otherSite.Substring(3); // check whether from different sites @@ -1088,10 +1088,10 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) + if (cachedEntry is not null) cachedEntry.Dispose(); - if (_ntdsEntry != null) + if (_ntdsEntry is not null) _ntdsEntry.Dispose(); } @@ -1103,23 +1103,23 @@ protected virtual void Dispose(bool disposing) private static void ValidateArgument(DirectoryContext context, string siteName) { // basic validation first - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name - if (context.Name != null) + if (context.Name is not null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } - if (siteName == null) + if (siteName is null) throw new ArgumentNullException(nameof(siteName)); if (siteName.Length == 0) @@ -1333,7 +1333,7 @@ private void GetDomains() if (nameResult.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || nameResult.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY) { string domainName = Marshal.PtrToStringUni(nameResult.pName); - if (domainName != null && domainName.Length > 0) + if (domainName is not null && domainName.Length > 0) { string d = Utils.GetDnsNameFromDN(domainName); Domain domain = new Domain(Utils.GetNewDirectoryContext(d, DirectoryContextType.Domain, context), d); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs index 702e3e537bc11a..79fe5bc8247fe6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs @@ -27,7 +27,7 @@ public ActiveDirectorySite this[int index] { ActiveDirectorySite site = (ActiveDirectorySite)value; - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(value)); if (!site.existing) @@ -42,7 +42,7 @@ public ActiveDirectorySite this[int index] public int Add(ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); if (!site.existing) @@ -56,7 +56,7 @@ public int Add(ActiveDirectorySite site) public void AddRange(ActiveDirectorySite[] sites) { - if (sites == null) + if (sites is null) throw new ArgumentNullException(nameof(sites)); for (int i = 0; ((i) < (sites.Length)); i = ((i) + (1))) @@ -65,7 +65,7 @@ public void AddRange(ActiveDirectorySite[] sites) public void AddRange(ActiveDirectorySiteCollection sites) { - if (sites == null) + if (sites is null) throw new ArgumentNullException(nameof(sites)); int count = sites.Count; @@ -75,7 +75,7 @@ public void AddRange(ActiveDirectorySiteCollection sites) public bool Contains(ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); if (!site.existing) @@ -103,7 +103,7 @@ public void CopyTo(ActiveDirectorySite[] array, int index) public int IndexOf(ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); if (!site.existing) @@ -126,7 +126,7 @@ public int IndexOf(ActiveDirectorySite site) public void Insert(int index, ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); if (!site.existing) @@ -140,7 +140,7 @@ public void Insert(int index, ActiveDirectorySite site) public void Remove(ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); if (!site.existing) @@ -228,7 +228,7 @@ protected override void OnSetComplete(int index, object oldValue, object newValu protected override void OnValidate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySite)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs index 71a82836c57d58..745f989a755dde 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs @@ -77,7 +77,7 @@ public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName, Ac cachedEntry = de.Children.Add(rdn, "siteLink"); cachedEntry.Properties["cost"].Value = appDefaultCost; cachedEntry.Properties["replInterval"].Value = appDefaultInterval; - if (schedule != null) + if (schedule is not null) cachedEntry.Properties[nameof(schedule)].Value = schedule.GetUnmanagedSchedule(); } catch (COMException e) @@ -155,7 +155,7 @@ public static ActiveDirectorySiteLink FindByName(DirectoryContext context, strin false /* don't need to cache result */ ); SearchResult srchResult = adSearcher.FindOne(); - if (srchResult == null) + if (srchResult is null) { // no such sitelink object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLink), siteLinkName); @@ -538,7 +538,7 @@ public ActiveDirectorySchedule InterSiteReplicationSchedule if (cachedEntry.Properties.Contains("schedule")) { byte[] tmpSchedule = (byte[])cachedEntry.Properties["schedule"][0]; - Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188); + Debug.Assert(tmpSchedule is not null && tmpSchedule.Length == 188); schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(tmpSchedule); } @@ -557,7 +557,7 @@ public ActiveDirectorySchedule InterSiteReplicationSchedule try { - if (value == null) + if (value is null) { if (cachedEntry.Properties.Contains("schedule")) cachedEntry.Properties["schedule"].Clear(); @@ -654,7 +654,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) + if (cachedEntry is not null) cachedEntry.Dispose(); } @@ -666,23 +666,23 @@ protected virtual void Dispose(bool disposing) private static void ValidateArgument(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport) { // basic validation first - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name - if (context.Name != null) + if (context.Name is not null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } - if (siteLinkName == null) + if (siteLinkName is null) throw new ArgumentNullException(nameof(siteLinkName)); if (siteLinkName.Length == 0) @@ -706,7 +706,7 @@ private void GetSites() ArrayList siteLists = (ArrayList)values[propertyName.ToLowerInvariant()]; // somehow no site list - if (siteLists == null) + if (siteLists is null) return; for (int i = 0; i < siteLists.Count; i++) @@ -716,7 +716,7 @@ private void GetSites() // escaping manipulation pathCracker.Set(dn, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); - Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); + Debug.Assert(rdn is not null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); rdn = rdn.Substring(3); ActiveDirectorySite site = new ActiveDirectorySite(context, rdn, true); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs index 41b64799d90855..940d42e0fb8eb7 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs @@ -142,7 +142,7 @@ public static ActiveDirectorySiteLinkBridge FindByName(DirectoryContext context, false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); - if (srchResult == null) + if (srchResult is null) { // no such site link bridge object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); @@ -310,7 +310,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) + if (cachedEntry is not null) cachedEntry.Dispose(); } @@ -322,23 +322,23 @@ protected virtual void Dispose(bool disposing) private static void ValidateArgument(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { // basic validation first - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name - if (context.Name != null) + if (context.Name is not null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } - if (bridgeName == null) + if (bridgeName is null) throw new ArgumentNullException(nameof(bridgeName)); if (bridgeName.Length == 0) @@ -362,7 +362,7 @@ private void GetLinks() ArrayList siteLinkLists = (ArrayList)values[propertyName.ToLowerInvariant()]; // somehow no site link list - if (siteLinkLists == null) + if (siteLinkLists is null) return; // construct the site link object @@ -372,7 +372,7 @@ private void GetLinks() // escaping manipulation pathCracker.Set(dn, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); - Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); + Debug.Assert(rdn is not null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); rdn = rdn.Substring(3); DirectoryEntry entry = DirectoryEntryManager.GetDirectoryEntry(context, dn); ActiveDirectorySiteLink link = new ActiveDirectorySiteLink(context, rdn, _transport, true, entry); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs index 4db6e1ea2230fd..6d5c4b97c873bd 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs @@ -21,7 +21,7 @@ public ActiveDirectorySiteLink this[int index] { ActiveDirectorySiteLink link = (ActiveDirectorySiteLink)value; - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(value)); if (!link.existing) @@ -36,7 +36,7 @@ public ActiveDirectorySiteLink this[int index] public int Add(ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); if (!link.existing) @@ -50,7 +50,7 @@ public int Add(ActiveDirectorySiteLink link) public void AddRange(ActiveDirectorySiteLink[] links) { - if (links == null) + if (links is null) throw new ArgumentNullException(nameof(links)); for (int i = 0; i < links.Length; i = i + 1) @@ -59,7 +59,7 @@ public void AddRange(ActiveDirectorySiteLink[] links) public void AddRange(ActiveDirectorySiteLinkCollection links) { - if (links == null) + if (links is null) throw new ArgumentNullException(nameof(links)); int count = links.Count; @@ -69,7 +69,7 @@ public void AddRange(ActiveDirectorySiteLinkCollection links) public bool Contains(ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); if (!link.existing) @@ -97,7 +97,7 @@ public void CopyTo(ActiveDirectorySiteLink[] array, int index) public int IndexOf(ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); if (!link.existing) @@ -120,7 +120,7 @@ public int IndexOf(ActiveDirectorySiteLink link) public void Insert(int index, ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); if (!link.existing) @@ -134,7 +134,7 @@ public void Insert(int index, ActiveDirectorySiteLink link) public void Remove(ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); if (!link.existing) @@ -222,7 +222,7 @@ protected override void OnSetComplete(int index, object oldValue, object newValu protected override void OnValidate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySiteLink)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs index 7e7f5df935baf7..19e4fe6263052c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs @@ -52,7 +52,7 @@ public static ActiveDirectorySubnet FindByName(DirectoryContext context, string false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); - if (srchResult == null) + if (srchResult is null) { // no such subnet object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); @@ -73,13 +73,13 @@ public static ActiveDirectorySubnet FindByName(DirectoryContext context, string // escaping manipulation pathCracker.Set(tmp, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); - Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); + Debug.Assert(rdn is not null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); siteName = rdn.Substring(3); } // it is an existing subnet object ActiveDirectorySubnet subnet = null; - if (siteName == null) + if (siteName is null) subnet = new ActiveDirectorySubnet(context, subnetName, null, true); else subnet = new ActiveDirectorySubnet(context, subnetName, siteName, true); @@ -102,7 +102,7 @@ public static ActiveDirectorySubnet FindByName(DirectoryContext context, string } finally { - if (de != null) + if (de is not null) de.Dispose(); } } @@ -143,14 +143,14 @@ public ActiveDirectorySubnet(DirectoryContext context, string subnetName) } finally { - if (de != null) + if (de is not null) de.Dispose(); } } public ActiveDirectorySubnet(DirectoryContext context, string subnetName, string siteName) : this(context, subnetName) { - if (siteName == null) + if (siteName is null) throw new ArgumentNullException(nameof(siteName)); if (siteName.Length == 0) @@ -174,7 +174,7 @@ internal ActiveDirectorySubnet(DirectoryContext context, string subnetName, stri this.context = context; _name = subnetName; - if (siteName != null) + if (siteName is not null) { try { @@ -214,7 +214,7 @@ public ActiveDirectorySite Site if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (value != null) + if (value is not null) { // check whether the site exists or not, you can not create a new site and set it to a subnet object with commit change to site object first if (!value.existing) @@ -252,7 +252,7 @@ public string Location // if the value is null, it means that user wants to clear the value try { - if (value == null) + if (value is null) { if (cachedEntry.Properties.Contains("location")) cachedEntry.Properties["location"].Clear(); @@ -279,7 +279,7 @@ public void Save() if (existing) { // check whether site has been changed or not - if (_site == null) + if (_site is null) { // user wants to remove this subnet object from previous site if (cachedEntry.Properties.Contains("siteObject")) @@ -294,7 +294,7 @@ public void Save() } else { - if (Site != null) + if (Site is not null) cachedEntry.Properties["siteObject"].Add(_site.cachedEntry.Properties["distinguishedName"][0]); cachedEntry.CommitChanges(); @@ -365,7 +365,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) + if (cachedEntry is not null) cachedEntry.Dispose(); } @@ -377,24 +377,24 @@ protected virtual void Dispose(bool disposing) private static void ValidateArgument(DirectoryContext context, string subnetName) { // basic validation first - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name - if (context.Name != null) + if (context.Name is not null) { // we only allow target to be forest, server name or ADAM config set if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } - if (subnetName == null) + if (subnetName is null) throw new ArgumentNullException(nameof(subnetName)); if (subnetName.Length == 0) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs index c2c7217c8c51ef..df698ef7f4dc89 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs @@ -31,7 +31,7 @@ public ActiveDirectorySubnet this[int index] { ActiveDirectorySubnet subnet = (ActiveDirectorySubnet)value; - if (subnet == null) + if (subnet is null) throw new ArgumentNullException(nameof(value)); if (!subnet.existing) @@ -46,7 +46,7 @@ public ActiveDirectorySubnet this[int index] public int Add(ActiveDirectorySubnet subnet) { - if (subnet == null) + if (subnet is null) throw new ArgumentNullException(nameof(subnet)); if (!subnet.existing) @@ -60,12 +60,12 @@ public int Add(ActiveDirectorySubnet subnet) public void AddRange(ActiveDirectorySubnet[] subnets) { - if (subnets == null) + if (subnets is null) throw new ArgumentNullException(nameof(subnets)); foreach (ActiveDirectorySubnet s in subnets) { - if (s == null) + if (s is null) { throw new ArgumentException(null, nameof(subnets)); } @@ -77,7 +77,7 @@ public void AddRange(ActiveDirectorySubnet[] subnets) public void AddRange(ActiveDirectorySubnetCollection subnets) { - if (subnets == null) + if (subnets is null) throw new ArgumentNullException(nameof(subnets)); int count = subnets.Count; @@ -87,7 +87,7 @@ public void AddRange(ActiveDirectorySubnetCollection subnets) public bool Contains(ActiveDirectorySubnet subnet) { - if (subnet == null) + if (subnet is null) throw new ArgumentNullException(nameof(subnet)); if (!subnet.existing) @@ -115,7 +115,7 @@ public void CopyTo(ActiveDirectorySubnet[] array, int index) public int IndexOf(ActiveDirectorySubnet subnet) { - if (subnet == null) + if (subnet is null) throw new ArgumentNullException(nameof(subnet)); if (!subnet.existing) @@ -138,7 +138,7 @@ public int IndexOf(ActiveDirectorySubnet subnet) public void Insert(int index, ActiveDirectorySubnet subnet) { - if (subnet == null) + if (subnet is null) throw new ArgumentNullException(nameof(subnet)); if (!subnet.existing) @@ -152,7 +152,7 @@ public void Insert(int index, ActiveDirectorySubnet subnet) public void Remove(ActiveDirectorySubnet subnet) { - if (subnet == null) + if (subnet is null) throw new ArgumentNullException(nameof(subnet)); if (!subnet.existing) @@ -259,7 +259,7 @@ protected override void OnSetComplete(int index, object oldValue, object newValu protected override void OnValidate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySubnet)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs index a393c306c9a6e4..7d7ff24d3df730 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs @@ -81,9 +81,9 @@ public bool Equals(Syntax syntax) } else { - if (((this.oMObjectClass != null) && (syntax.oMObjectClass == null)) - || ((this.oMObjectClass == null) && (syntax.oMObjectClass != null)) - || ((this.oMObjectClass != null) && (syntax.oMObjectClass != null) && (!this.oMObjectClass.Equals(syntax.oMObjectClass)))) + if (((this.oMObjectClass is not null) && (syntax.oMObjectClass is null)) + || ((this.oMObjectClass is null) && (syntax.oMObjectClass is not null)) + || ((this.oMObjectClass is not null) && (syntax.oMObjectClass is not null) && (!this.oMObjectClass.Equals(syntax.oMObjectClass)))) { result = false; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs index 7243275e5c934f..6d85e57616c236 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs @@ -80,12 +80,12 @@ protected override void Dispose(bool disposing) // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. - if (_crossRefEntry != null) + if (_crossRefEntry is not null) { _crossRefEntry.Dispose(); _crossRefEntry = null; } - if (_domainDNSEntry != null) + if (_domainDNSEntry is not null) { _domainDNSEntry.Dispose(); _domainDNSEntry = null; @@ -106,7 +106,7 @@ protected override void Dispose(bool disposing) public static ApplicationPartition GetApplicationPartition(DirectoryContext context) { // validate the context - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -161,15 +161,15 @@ public static ApplicationPartition FindByName(DirectoryContext context, string d DirectoryContext appNCContext = null; // check that the argument is not null - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid forest name, configset name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || context.isServer())) @@ -179,7 +179,7 @@ public static ApplicationPartition FindByName(DirectoryContext context, string d } // check that the distingushed name of the application partition is not null or empty - if (distinguishedName == null) + if (distinguishedName is null) throw new ArgumentNullException(nameof(distinguishedName)); if (distinguishedName.Length == 0) @@ -258,7 +258,7 @@ public static ApplicationPartition FindByName(DirectoryContext context, string d partitionsEntry.Dispose(); } - if (res == null) + if (res is null) { // the specified application partition could not be found in the given forest throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); @@ -375,7 +375,7 @@ public DirectoryServer FindDirectoryServer(string siteName) CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -429,7 +429,7 @@ public DirectoryServer FindDirectoryServer(string siteName, bool forceRediscover CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -480,7 +480,7 @@ public ReadOnlyDirectoryServerCollection FindAllDirectoryServers(string siteName { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -526,7 +526,7 @@ public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers(str { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -695,9 +695,9 @@ public void Save() _committed = true; // commit the replica locations information or security reference domain if applicable - if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) + if ((_cachedDirectoryServers is not null) || (_securityRefDomainModified)) { - if (_cachedDirectoryServers != null) + if (_cachedDirectoryServers is not null) { _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].AddRange(_cachedDirectoryServers.GetMultiValuedProperty()); } @@ -719,13 +719,13 @@ public void Save() { // just save the crossRef entry for teh directory servers and the // security reference domain information - if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) + if ((_cachedDirectoryServers is not null) || (_securityRefDomainModified)) { try { // we should already have the crossRef entries as some attribute on it has already // been modified - Debug.Assert(_crossRefEntry != null, "ApplicationPartition::Save - crossRefEntry on already committed partition which is being modified is null."); + Debug.Assert(_crossRefEntry is not null, "ApplicationPartition::Save - crossRefEntry on already committed partition which is being modified is null."); _crossRefEntry.CommitChanges(); } catch (COMException e) @@ -761,7 +761,7 @@ public DirectoryServerCollection DirectoryServers get { CheckIfDisposed(); - if (_cachedDirectoryServers == null) + if (_cachedDirectoryServers is null) { ReadOnlyDirectoryServerCollection servers = (_committed) ? FindAllDirectoryServers() : new ReadOnlyDirectoryServerCollection(); bool isADAM = (_appType == ApplicationPartitionType.ADAMApplicationPartition) ? true : false; @@ -833,7 +833,7 @@ public string SecurityReferenceDomain GetCrossRefEntry(); // modify the security reference domain // this will get committed when the crossRefEntry is committed - if (value == null) + if (value is null) { if (_crossRefEntry.Properties.Contains(PropertyManager.MsDSSDReferenceDomain)) { @@ -849,7 +849,7 @@ public string SecurityReferenceDomain } else { - if (!((_securityRefDomain == null) && (value == null))) + if (!((_securityRefDomain is null) && (value is null))) { _securityRefDomain = value; _securityRefDomainModified = true; @@ -863,19 +863,19 @@ public string SecurityReferenceDomain private void ValidateApplicationPartitionParameters(DirectoryContext context, string distinguishedName, string objectClass, bool objectClassSpecified) { // validate context - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } // contexttype should be DirectoryServer - if ((context.Name == null) || (!context.isServer())) + if ((context.Name is null) || (!context.isServer())) { throw new ArgumentException(SR.TargetShouldBeServer, nameof(context)); } // check that the distinguished name is not null or empty - if (distinguishedName == null) + if (distinguishedName is null) { throw new ArgumentNullException(nameof(distinguishedName)); } @@ -913,7 +913,7 @@ private void ValidateApplicationPartitionParameters(DirectoryContext context, st { // ADAM case and objectClass is explicitly specified, so must be validated - if (objectClass == null) + if (objectClass is null) { throw new ArgumentNullException(nameof(objectClass)); } @@ -982,12 +982,12 @@ private void CreateApplicationPartition(string distinguishedName, string objectC finally { // dispose all resources - if (parent != null) + if (parent is not null) { parent.Dispose(); } - if (tempEntry != null) + if (tempEntry is not null) { tempEntry.Dispose(); } @@ -1029,12 +1029,12 @@ private void CreateApplicationPartition(string distinguishedName, string objectC finally { // dispose all resources - if (parent != null) + if (parent is not null) { parent.Dispose(); } - if (tempEntry != null) + if (tempEntry is not null) { tempEntry.Dispose(); } @@ -1049,7 +1049,7 @@ private void CreateApplicationPartition(string distinguishedName, string objectC private void InitializeCrossRef(string distinguishedName) { - if (_crossRefEntry != null) + if (_crossRefEntry is not null) // already initialized return; @@ -1088,7 +1088,7 @@ private void InitializeCrossRef(string distinguishedName) } finally { - if (partitionsEntry != null) + if (partitionsEntry is not null) { partitionsEntry.Dispose(); } @@ -1135,7 +1135,7 @@ private static ApplicationPartitionType GetApplicationPartitionType(DirectoryCon // this is so that we do not encounter any replication delay related issues internal DirectoryEntry GetCrossRefEntry() { - if (_crossRefEntry != null) + if (_crossRefEntry is not null) { return _crossRefEntry; } @@ -1181,7 +1181,7 @@ private DirectoryServer FindDirectoryServerInternal(string siteName, bool forceR int errorCode = 0; DomainControllerInfo domainControllerInfo; - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } @@ -1223,7 +1223,7 @@ private DirectoryServer FindDirectoryServerInternal(string siteName, bool forceR private ReadOnlyDirectoryServerCollection FindAllDirectoryServersInternal(string siteName) { - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } @@ -1246,7 +1246,7 @@ private ReadOnlyDirectoryServerCollection FindAllDirectoryServersInternal(string private ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServersInternal(string siteName) { - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs index fc685d93102201..ed4f1f69236161 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs @@ -11,7 +11,7 @@ internal ApplicationPartitionCollection() { } internal ApplicationPartitionCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -21,7 +21,7 @@ internal ApplicationPartitionCollection(ArrayList values) public bool Contains(ApplicationPartition applicationPartition) { - if (applicationPartition == null) + if (applicationPartition is null) { throw new ArgumentNullException(nameof(applicationPartition)); } @@ -39,7 +39,7 @@ public bool Contains(ApplicationPartition applicationPartition) public int IndexOf(ApplicationPartition applicationPartition) { - if (applicationPartition == null) + if (applicationPartition is null) { throw new ArgumentNullException(nameof(applicationPartition)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs index 7ea6de6e22565c..a88b4c568267ce 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs @@ -22,7 +22,7 @@ internal AttributeMetadata(IntPtr info, bool advanced, DirectoryServer server, H { DS_REPL_ATTR_META_DATA_2 attrMetaData = new DS_REPL_ATTR_META_DATA_2(); Marshal.PtrToStructure(info, attrMetaData); - Debug.Assert(attrMetaData != null); + Debug.Assert(attrMetaData is not null); Name = Marshal.PtrToStringUni(attrMetaData.pszAttributeName); Version = attrMetaData.dwVersion; @@ -37,7 +37,7 @@ internal AttributeMetadata(IntPtr info, bool advanced, DirectoryServer server, H { DS_REPL_ATTR_META_DATA attrMetaData = new DS_REPL_ATTR_META_DATA(); Marshal.PtrToStructure(info, attrMetaData); - Debug.Assert(attrMetaData != null); + Debug.Assert(attrMetaData is not null); Name = Marshal.PtrToStringUni(attrMetaData.pszAttributeName); Version = attrMetaData.dwVersion; @@ -68,7 +68,7 @@ public string OriginatingServer { get { - if (_originatingServerName == null) + if (_originatingServerName is null) { // check whether we have got it before if (_nameTable.Contains(LastOriginatingInvocationId)) @@ -76,7 +76,7 @@ public string OriginatingServer _originatingServerName = (string)_nameTable[LastOriginatingInvocationId]; } // do the translation for downlevel platform or kcc is able to do the name translation - else if (!_advanced || (_advanced && _pszLastOriginatingDsaDN != null)) + else if (!_advanced || (_advanced && _pszLastOriginatingDsaDN is not null)) { _originatingServerName = Utils.GetServerNameFromInvocationID(_pszLastOriginatingDsaDN, LastOriginatingInvocationId, _server); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs index b6f4fc6085e2d4..5e93d6605e027f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs @@ -13,7 +13,7 @@ internal AttributeMetadataCollection() { } public bool Contains(AttributeMetadata metadata) { - if (metadata == null) + if (metadata is null) throw new ArgumentNullException(nameof(metadata)); for (int i = 0; i < InnerList.Count; i++) @@ -31,7 +31,7 @@ public bool Contains(AttributeMetadata metadata) public int IndexOf(AttributeMetadata metadata) { - if (metadata == null) + if (metadata is null) throw new ArgumentNullException(nameof(metadata)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs index ef94d0c08fec5c..448454a35c8082 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs @@ -72,7 +72,7 @@ protected virtual void Dispose(bool disposing) public static ConfigurationSet GetConfigurationSet(DirectoryContext context) { // check that the argument is not null - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // target should ConfigurationSet or DirectoryServer @@ -161,7 +161,7 @@ public AdamInstance FindAdamInstance(string partitionName) { CheckIfDisposed(); - if (partitionName == null) + if (partitionName is null) { throw new ArgumentNullException(nameof(partitionName)); } @@ -177,7 +177,7 @@ public AdamInstance FindAdamInstance(string partitionName, string siteName) // null partitionName would signify that we don't care about the partition // - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -196,7 +196,7 @@ public AdamInstanceCollection FindAllAdamInstances(string partitionName) { CheckIfDisposed(); - if (partitionName == null) + if (partitionName is null) { throw new ArgumentNullException(nameof(partitionName)); } @@ -212,7 +212,7 @@ public AdamInstanceCollection FindAllAdamInstances(string partitionName, string // null partitionName would signify that we don't care about the partition // - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -280,7 +280,7 @@ public ReadOnlySiteCollection Sites get { CheckIfDisposed(); - if (_cachedSites == null) + if (_cachedSites is null) { _cachedSites = new ReadOnlySiteCollection(GetSites()); } @@ -293,7 +293,7 @@ public AdamInstanceCollection AdamInstances get { CheckIfDisposed(); - if (_cachedADAMInstances == null) + if (_cachedADAMInstances is null) { _cachedADAMInstances = FindAllAdamInstances(); } @@ -306,7 +306,7 @@ public ApplicationPartitionCollection ApplicationPartitions get { CheckIfDisposed(); - if (_cachedApplicationPartitions == null) + if (_cachedApplicationPartitions is null) { _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions()); } @@ -319,7 +319,7 @@ public ActiveDirectorySchema Schema get { CheckIfDisposed(); - if (_cachedSchema == null) + if (_cachedSchema is null) { try { @@ -339,7 +339,7 @@ public AdamInstance SchemaRoleOwner get { CheckIfDisposed(); - if (_cachedSchemaRoleOwner == null) + if (_cachedSchemaRoleOwner is null) { _cachedSchemaRoleOwner = GetRoleOwner(AdamRole.SchemaRole); } @@ -352,7 +352,7 @@ public AdamInstance NamingRoleOwner get { CheckIfDisposed(); - if (_cachedNamingRoleOwner == null) + if (_cachedNamingRoleOwner is null) { _cachedNamingRoleOwner = GetRoleOwner(AdamRole.NamingRole); } @@ -508,12 +508,12 @@ internal static AdamInstance FindOneAdamInstance(DirectoryContext context, strin internal static AdamInstance FindOneAdamInstance(string configSetName, DirectoryContext context, string partitionName, string siteName) { // can expect valid context (non-null) - if (partitionName != null && partitionName.Length == 0) + if (partitionName is not null && partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(partitionName)); } - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } @@ -531,12 +531,12 @@ internal static AdamInstance FindOneAdamInstance(string configSetName, Directory internal static AdamInstanceCollection FindAdamInstances(DirectoryContext context, string partitionName, string siteName) { // can expect valid context (non-null) - if (partitionName != null && partitionName.Length == 0) + if (partitionName is not null && partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(partitionName)); } - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } @@ -589,7 +589,7 @@ internal static AdamInstance FindAliveAdamInstance(string configSetName, Directo { // if we are passed the timeout period, we should throw, else do nothing if (DateTime.UtcNow.Subtract(startTime) > s_locationTimeout) - throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null); + throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, (configSetName is not null) ? configSetName : context.Name), typeof(AdamInstance), null); } else throw ExceptionHelper.GetExceptionFromCOMException(context, e); @@ -602,7 +602,7 @@ internal static AdamInstance FindAliveAdamInstance(string configSetName, Directo } // if we reach here, we haven't found an adam instance - throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null); + throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, (configSetName is not null) ? configSetName : context.Name), typeof(AdamInstance), null); } /// Returns a DomainController object for the DC that holds the specified FSMO role @@ -641,7 +641,7 @@ private AdamInstance GetRoleOwner(AdamRole role) } finally { - if (entry != null) + if (entry is not null) { entry.Dispose(); } @@ -686,7 +686,7 @@ private ArrayList GetSites() } finally { - if (resCol != null) + if (resCol is not null) { // call dispose on search result collection resCol.Dispose(); @@ -759,7 +759,7 @@ private ArrayList GetApplicationPartitions() } finally { - if (resCol != null) + if (resCol is not null) { // call dispose on search result collection resCol.Dispose(); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs index b60222552fdab9..3a6b25059391e1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs @@ -47,11 +47,11 @@ internal void InitializeDirectoryContext(DirectoryContextType contextType, strin _name = name; _contextType = contextType; _credential = new NetworkCredential(username, password); - if (username == null) + if (username is null) { usernameIsNull = true; } - if (password == null) + if (password is null) { passwordIsNull = true; } @@ -62,7 +62,7 @@ internal DirectoryContext(DirectoryContextType contextType, string name, Directo _name = name; _contextType = contextType; - if (context != null) + if (context is not null) { _credential = context.Credential; this.usernameIsNull = context.usernameIsNull; @@ -118,7 +118,7 @@ public DirectoryContext(DirectoryContextType contextType, string name) throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType)); } - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -152,7 +152,7 @@ public DirectoryContext(DirectoryContextType contextType, string name, string us throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType)); } - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -189,11 +189,11 @@ internal static bool IsContextValid(DirectoryContext context, DirectoryContextTy { bool contextIsValid = false; - if ((contextType == DirectoryContextType.Domain) || ((contextType == DirectoryContextType.Forest) && (context.Name == null))) + if ((contextType == DirectoryContextType.Domain) || ((contextType == DirectoryContextType.Forest) && (context.Name is null))) { string tmpTarget = context.Name; - if (tmpTarget == null) + if (tmpTarget is null) { // GetLoggedOnDomain returns the dns name of the logged on user's domain context.serverName = GetLoggedOnDomain(); @@ -222,8 +222,8 @@ internal static bool IsContextValid(DirectoryContext context, DirectoryContextTy } else { - Debug.Assert(domainControllerInfo != null); - Debug.Assert(domainControllerInfo.DomainName != null); + Debug.Assert(domainControllerInfo is not null); + Debug.Assert(domainControllerInfo.DomainName is not null); context.serverName = domainControllerInfo.DomainName; contextIsValid = true; } @@ -239,8 +239,8 @@ internal static bool IsContextValid(DirectoryContext context, DirectoryContextTy } else { - Debug.Assert(domainControllerInfo != null); - Debug.Assert(domainControllerInfo.DomainName != null); + Debug.Assert(domainControllerInfo is not null); + Debug.Assert(domainControllerInfo.DomainName is not null); context.serverName = domainControllerInfo.DomainName; contextIsValid = true; } @@ -248,7 +248,7 @@ internal static bool IsContextValid(DirectoryContext context, DirectoryContextTy } else if (contextType == DirectoryContextType.Forest) { - Debug.Assert(context.Name != null); + Debug.Assert(context.Name is not null); // check for forest int errorCode = 0; @@ -271,8 +271,8 @@ internal static bool IsContextValid(DirectoryContext context, DirectoryContextTy } else { - Debug.Assert(domainControllerInfo != null); - Debug.Assert(domainControllerInfo.DnsForestName != null); + Debug.Assert(domainControllerInfo is not null); + Debug.Assert(domainControllerInfo.DnsForestName is not null); context.serverName = domainControllerInfo.DnsForestName; contextIsValid = true; } @@ -288,15 +288,15 @@ internal static bool IsContextValid(DirectoryContext context, DirectoryContextTy } else { - Debug.Assert(domainControllerInfo != null); - Debug.Assert(domainControllerInfo.DnsForestName != null); + Debug.Assert(domainControllerInfo is not null); + Debug.Assert(domainControllerInfo.DnsForestName is not null); context.serverName = domainControllerInfo.DnsForestName; contextIsValid = true; } } else if (contextType == DirectoryContextType.ApplicationPartition) { - Debug.Assert(context.Name != null); + Debug.Assert(context.Name is not null); // check for application partition int errorCode = 0; @@ -453,7 +453,7 @@ internal bool isCurrentForest() { bool result = false; - Debug.Assert(_name != null); + Debug.Assert(_name is not null); DomainControllerInfo domainControllerInfo = Locator.GetDomainControllerInfo(null, _name, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName)); DomainControllerInfo currentDomainControllerInfo; @@ -463,8 +463,8 @@ internal bool isCurrentForest() if (errorCode == 0) { - Debug.Assert(domainControllerInfo.DnsForestName != null); - Debug.Assert(currentDomainControllerInfo.DnsForestName != null); + Debug.Assert(domainControllerInfo.DnsForestName is not null); + Debug.Assert(currentDomainControllerInfo.DnsForestName is not null); result = (Utils.Compare(domainControllerInfo.DnsForestName, currentDomainControllerInfo.DnsForestName) == 0); } @@ -486,7 +486,7 @@ internal bool useServerBind() internal string GetServerName() { - if (serverName == null) + if (serverName is null) { switch (_contextType) { @@ -511,7 +511,7 @@ internal string GetServerName() // if the forest name was explicitly specified and the forest is the same as the current forest // we want to find a DC in the current domain // - if ((_name == null) || ((_contextType == DirectoryContextType.Forest) && (isCurrentForest()))) + if ((_name is null) || ((_contextType == DirectoryContextType.Forest) && (isCurrentForest()))) { serverName = GetLoggedOnDomain(); } @@ -524,7 +524,7 @@ internal string GetServerName() case DirectoryContextType.ApplicationPartition: { // if this is an appNC the target should not be null - Debug.Assert(_name != null); + Debug.Assert(_name is not null); serverName = _name; break; @@ -532,7 +532,7 @@ internal string GetServerName() case DirectoryContextType.DirectoryServer: { // this should not happen (We should have checks for this earlier itself) - Debug.Assert(_name != null); + Debug.Assert(_name is not null); serverName = _name; break; } @@ -585,7 +585,7 @@ internal static string GetLoggedOnDomain() // // callerName is of the form domain\username // - Debug.Assert((responseBuffer.callerName != null), "NativeMethods.LsaCallAuthenticationPackage returned null callerName."); + Debug.Assert((responseBuffer.callerName is not null), "NativeMethods.LsaCallAuthenticationPackage returned null callerName."); int index = responseBuffer.callerName.IndexOf('\\'); Debug.Assert((index != -1), "NativeMethods.LsaCallAuthenticationPackage returned callerName not in domain\\username format."); domainName = responseBuffer.callerName.Substring(0, index); @@ -635,7 +635,7 @@ internal static string GetLoggedOnDomain() // domainName will be null and we fall back to the machine's domain domainName = GetDnsDomainName(domainName); - if (domainName == null) + if (domainName is null) { // // we should never get to this point here since we should have already verified that the context is valid @@ -674,8 +674,8 @@ internal static string GetDnsDomainName(string domainName) throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } - Debug.Assert(domainControllerInfo != null); - Debug.Assert(domainControllerInfo.DomainName != null); + Debug.Assert(domainControllerInfo is not null); + Debug.Assert(domainControllerInfo.DomainName is not null); return domainControllerInfo.DomainName; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs index 1491969e088e88..e17f5da71acc60 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs @@ -22,7 +22,7 @@ public DistinguishedName(string dn) public bool Equals(DistinguishedName dn) { bool result = true; - if ((dn == null) || (Components.GetLength(0) != dn.Components.GetLength(0))) + if ((dn is null) || (Components.GetLength(0) != dn.Components.GetLength(0))) { result = false; } @@ -43,7 +43,7 @@ public bool Equals(DistinguishedName dn) public override bool Equals(object obj) { - if ((obj == null) || (!(obj is DistinguishedName))) + if ((obj is null) || (!(obj is DistinguishedName))) { return false; } @@ -143,7 +143,7 @@ internal void RemoveIfExists(string distinguishedName) if (_directoryEntries.ContainsKey(dn)) { DirectoryEntry tmp = (DirectoryEntry)_directoryEntries[dn]; - if (tmp != null) + if (tmp is not null) { _directoryEntries.Remove(dn); tmp.Dispose(); @@ -153,7 +153,7 @@ internal void RemoveIfExists(string distinguishedName) private DirectoryEntry GetNewDirectoryEntry(string dn) { - if (_bindingPrefix == null) + if (_bindingPrefix is null) { _bindingPrefix = "LDAP://" + _context.GetServerName() + "/"; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 933b665a49c53d..b70acefbf8f6a5 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -78,7 +78,7 @@ public void MoveToAnotherSite(string siteName) CheckIfDisposed(); // validate siteName - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -115,7 +115,7 @@ public void MoveToAnotherSite(string siteName) } finally { - if (newParentEntry != null) + if (newParentEntry is not null) { newParentEntry.Dispose(); } @@ -126,19 +126,19 @@ public void MoveToAnotherSite(string siteName) siteInfoModified = true; cachedSiteName = null; - if (cachedSiteObjectName != null) + if (cachedSiteObjectName is not null) { directoryEntryMgr.RemoveIfExists(cachedSiteObjectName); cachedSiteObjectName = null; } - if (cachedServerObjectName != null) + if (cachedServerObjectName is not null) { directoryEntryMgr.RemoveIfExists(cachedServerObjectName); cachedServerObjectName = null; } - if (cachedNtdsaObjectName != null) + if (cachedNtdsaObjectName is not null) { directoryEntryMgr.RemoveIfExists(cachedNtdsaObjectName); cachedNtdsaObjectName = null; @@ -195,7 +195,7 @@ public ReadOnlyStringCollection Partitions get { CheckIfDisposed(); - if (cachedPartitions == null) + if (cachedPartitions is null) { cachedPartitions = new ReadOnlyStringCollection(GetPartitions()); } @@ -257,7 +257,7 @@ internal ArrayList GetPartitions() ArrayList readOnlyPartitions = (ArrayList)values[PropertyManager.HasPartialReplicaNCs.ToLowerInvariant()]; - Debug.Assert(readOnlyPartitions != null); + Debug.Assert(readOnlyPartitions is not null); foreach (string readOnlyPartition in readOnlyPartitions) { partitionList.Add(readOnlyPartition); @@ -269,12 +269,12 @@ internal ArrayList GetPartitions() } finally { - if (rootDSE != null) + if (rootDSE is not null) { rootDSE.Dispose(); } - if (serverNtdsaEntry != null) + if (serverNtdsaEntry is not null) { serverNtdsaEntry.Dispose(); } @@ -354,7 +354,7 @@ internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondar if (result != 0) { - if (partition != null) + if (partition is not null) { // this is the case of meta data if (type == (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ) @@ -495,7 +495,7 @@ internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, Directory { DS_REPL_NEIGHBORS neighbors = new DS_REPL_NEIGHBORS(); Marshal.PtrToStructure(info, neighbors); - Debug.Assert(neighbors != null); + Debug.Assert(neighbors is not null); count = neighbors.cNumNeighbors; if (count > 0) collection.AddHelper(neighbors, info); @@ -581,7 +581,7 @@ internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, Int internal bool SyncAllCallbackRoutine(IntPtr data, IntPtr update) { - if (SyncFromAllServersCallback == null) + if (SyncFromAllServersCallback is null) { // user does not specify callback, resume the DsReplicaSyncAll execution return true; @@ -606,7 +606,7 @@ internal bool SyncAllCallbackRoutine(IntPtr data, IntPtr update) { // error information is available exception = ExceptionHelper.CreateSyncAllException(temp, true); - if (exception == null) + if (exception is null) { // this is the special case that we ingore the failure when SyncAllOptions.CheckServerAlivenessOnly is specified return true; @@ -657,7 +657,7 @@ internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallb if (errorInfo != (IntPtr)0) { SyncFromAllServersOperationException e = ExceptionHelper.CreateSyncAllException(errorInfo, false); - if (e == null) + if (e is null) return; else throw e; @@ -704,7 +704,7 @@ internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, unmanagedGuid = Marshal.AllocHGlobal(structSize); try { - if (sourceServer != null) + if (sourceServer is not null) { DirectoryContext newContext = Utils.GetNewDirectoryContext(sourceServer, DirectoryContextType.DirectoryServer, context); if (isADAM) @@ -753,17 +753,17 @@ internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, if (unmanagedGuid != (IntPtr)0) Marshal.FreeHGlobal(unmanagedGuid); - if (adamServer != null) + if (adamServer is not null) adamServer.Dispose(); - if (dcServer != null) + if (dcServer is not null) dcServer.Dispose(); } } internal ReplicationConnectionCollection GetInboundConnectionsHelper() { - if (_inbound == null) + if (_inbound is null) { // construct the replicationconnection collection _inbound = new ReplicationConnectionCollection(); @@ -795,7 +795,7 @@ internal ReplicationConnectionCollection GetInboundConnectionsHelper() } finally { - if (srchResults != null) + if (srchResults is not null) srchResults.Dispose(); de.Dispose(); @@ -808,7 +808,7 @@ internal ReplicationConnectionCollection GetInboundConnectionsHelper() internal ReplicationConnectionCollection GetOutboundConnectionsHelper() { // this is the first time that user tries to retrieve this property, so get it from the directory - if (_outbound == null) + if (_outbound is null) { // search base is the site container string siteName = (this is DomainController) ? ((DomainController)this).SiteObjectName : ((AdamInstance)this).SiteObjectName; @@ -840,7 +840,7 @@ internal ReplicationConnectionCollection GetOutboundConnectionsHelper() } finally { - if (results != null) + if (results is not null) results.Dispose(); de.Dispose(); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs index 380cf49f2c4e0b..6820a37c54e3cc 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs @@ -49,7 +49,7 @@ public DirectoryServer this[int index] { DirectoryServer server = (DirectoryServer)value; - if (server == null) + if (server is null) throw new ArgumentNullException(nameof(value)); if (!Contains(server)) @@ -61,7 +61,7 @@ public DirectoryServer this[int index] public int Add(DirectoryServer server) { - if (server == null) + if (server is null) throw new ArgumentNullException(nameof(server)); // make sure that it is within the current site @@ -92,7 +92,7 @@ public int Add(DirectoryServer server) else { string siteName = (server is DomainController) ? ((DomainController)server).SiteObjectName : ((AdamInstance)server).SiteObjectName; - Debug.Assert(siteName != null); + Debug.Assert(siteName is not null); if (Utils.Compare(siteDN, siteName) != 0) { throw new ArgumentException(SR.NotWithinSite); @@ -107,12 +107,12 @@ public int Add(DirectoryServer server) public void AddRange(DirectoryServer[] servers) { - if (servers == null) + if (servers is null) throw new ArgumentNullException(nameof(servers)); foreach (DirectoryServer s in servers) { - if (s == null) + if (s is null) { throw new ArgumentException(null, nameof(servers)); } @@ -124,7 +124,7 @@ public void AddRange(DirectoryServer[] servers) public bool Contains(DirectoryServer server) { - if (server == null) + if (server is null) throw new ArgumentNullException(nameof(server)); for (int i = 0; i < InnerList.Count; i++) @@ -146,7 +146,7 @@ public void CopyTo(DirectoryServer[] array, int index) public int IndexOf(DirectoryServer server) { - if (server == null) + if (server is null) throw new ArgumentNullException(nameof(server)); for (int i = 0; i < InnerList.Count; i++) @@ -163,7 +163,7 @@ public int IndexOf(DirectoryServer server) public void Insert(int index, DirectoryServer server) { - if (server == null) + if (server is null) throw new ArgumentNullException(nameof(server)); if (_isForNC) @@ -194,7 +194,7 @@ public void Insert(int index, DirectoryServer server) { // make sure that it is within the current site string siteName = (server is DomainController) ? ((DomainController)server).SiteObjectName : ((AdamInstance)server).SiteObjectName; - Debug.Assert(siteName != null); + Debug.Assert(siteName is not null); if (Utils.Compare(siteDN, siteName) != 0) { throw new ArgumentException(SR.NotWithinSite, nameof(server)); @@ -209,7 +209,7 @@ public void Insert(int index, DirectoryServer server) public void Remove(DirectoryServer server) { - if (server == null) + if (server is null) throw new ArgumentNullException(nameof(server)); for (int i = 0; i < InnerList.Count; i++) @@ -244,7 +244,7 @@ protected override void OnClearComplete() // if the property exists, clear it out if (_isForNC) { - if (_crossRefEntry != null) + if (_crossRefEntry is not null) { try { @@ -272,7 +272,7 @@ protected override void OnInsertComplete(int index, object value) { if (_isForNC) { - if (_crossRefEntry != null) + if (_crossRefEntry is not null) { try { @@ -319,7 +319,7 @@ protected override void OnRemoveComplete(int index, object value) { try { - if (_crossRefEntry != null) + if (_crossRefEntry is not null) { string ntdsaName = (value is DomainController) ? ((DomainController)value).NtdsaObjectName : ((AdamInstance)value).NtdsaObjectName; _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].Remove(ntdsaName); @@ -365,7 +365,7 @@ protected override void OnSetComplete(int index, object oldValue, object newValu protected override void OnValidate(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (_isForNC) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs index e3c5178acad3bb..09729436c80c72 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs @@ -60,7 +60,7 @@ internal Domain(DirectoryContext context, string domainName) public static Domain GetDomain(DirectoryContext context) { // check that the argument is not null - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // contexttype should be Domain or DirectoryServer @@ -70,12 +70,12 @@ public static Domain GetDomain(DirectoryContext context) throw new ArgumentException(SR.TargetShouldBeServerORDomain, nameof(context)); } - if ((context.Name == null) && (!context.isDomain())) + if ((context.Name is null) && (!context.isDomain())) { throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(Domain), null); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid domain name or a server if (!((context.isDomain()) || (context.isServer()))) @@ -136,7 +136,7 @@ public static Domain GetDomain(DirectoryContext context) public static Domain GetComputerDomain() { string computerDomainName = DirectoryContext.GetDnsDomainName(null); - if (computerDomainName == null) + if (computerDomainName is null) { throw new ActiveDirectoryObjectNotFoundException(SR.ComputerNotJoinedToDomain, typeof(Domain), null); } @@ -242,7 +242,7 @@ public void RaiseDomainFunctionalityLevel(int domainMode) } finally { - if (domainEntry != null) + if (domainEntry is not null) { domainEntry.Dispose(); } @@ -400,7 +400,7 @@ public void RaiseDomainFunctionality(DomainMode domainMode) } finally { - if (domainEntry != null) + if (domainEntry is not null) { domainEntry.Dispose(); } @@ -423,7 +423,7 @@ public DomainController FindDomainController(string siteName) { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -442,7 +442,7 @@ public DomainController FindDomainController(string siteName, LocatorOptions fla { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -461,7 +461,7 @@ public DomainControllerCollection FindAllDomainControllers(string siteName) { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -483,7 +483,7 @@ public DomainControllerCollection FindAllDiscoverableDomainControllers(string si CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -515,7 +515,7 @@ public TrustRelationshipInformation GetTrustRelationship(string targetDomainName { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -539,7 +539,7 @@ public bool GetSelectiveAuthenticationStatus(string targetDomainName) { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -552,7 +552,7 @@ public void SetSelectiveAuthenticationStatus(string targetDomainName, bool enabl { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -565,7 +565,7 @@ public bool GetSidFilteringStatus(string targetDomainName) { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -578,7 +578,7 @@ public void SetSidFilteringStatus(string targetDomainName, bool enable) { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -591,7 +591,7 @@ public void DeleteLocalSideOfTrustRelationship(string targetDomainName) { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -605,7 +605,7 @@ public void DeleteTrustRelationship(Domain targetDomain) { CheckIfDisposed(); - if (targetDomain == null) + if (targetDomain is null) throw new ArgumentNullException(nameof(targetDomain)); // first delete the trust on the remote side @@ -619,7 +619,7 @@ public void VerifyOutboundTrustRelationship(string targetDomainName) { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -632,7 +632,7 @@ public void VerifyTrustRelationship(Domain targetDomain, TrustDirection directio { CheckIfDisposed(); - if (targetDomain == null) + if (targetDomain is null) throw new ArgumentNullException(nameof(targetDomain)); if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) @@ -669,7 +669,7 @@ public void CreateLocalSideOfTrustRelationship(string targetDomainName, TrustDir { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -678,7 +678,7 @@ public void CreateLocalSideOfTrustRelationship(string targetDomainName, TrustDir if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection)); - if (trustPassword == null) + if (trustPassword is null) throw new ArgumentNullException(nameof(trustPassword)); if (trustPassword.Length == 0) @@ -696,7 +696,7 @@ public void CreateTrustRelationship(Domain targetDomain, TrustDirection directio { CheckIfDisposed(); - if (targetDomain == null) + if (targetDomain is null) throw new ArgumentNullException(nameof(targetDomain)); if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) @@ -721,13 +721,13 @@ public void UpdateLocalSideOfTrustRelationship(string targetDomainName, string n { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName)); - if (newTrustPassword == null) + if (newTrustPassword is null) throw new ArgumentNullException(nameof(newTrustPassword)); if (newTrustPassword.Length == 0) @@ -740,7 +740,7 @@ public void UpdateLocalSideOfTrustRelationship(string targetDomainName, TrustDir { CheckIfDisposed(); - if (targetDomainName == null) + if (targetDomainName is null) throw new ArgumentNullException(nameof(targetDomainName)); if (targetDomainName.Length == 0) @@ -749,7 +749,7 @@ public void UpdateLocalSideOfTrustRelationship(string targetDomainName, TrustDir if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection)); - if (newTrustPassword == null) + if (newTrustPassword is null) throw new ArgumentNullException(nameof(newTrustPassword)); if (newTrustPassword.Length == 0) @@ -762,7 +762,7 @@ public void UpdateTrustRelationship(Domain targetDomain, TrustDirection newTrust { CheckIfDisposed(); - if (targetDomain == null) + if (targetDomain is null) throw new ArgumentNullException(nameof(targetDomain)); if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional) @@ -789,7 +789,7 @@ public void RepairTrustRelationship(Domain targetDomain) CheckIfDisposed(); - if (targetDomain == null) + if (targetDomain is null) throw new ArgumentNullException(nameof(targetDomain)); // first try to reset the secure channel @@ -839,7 +839,7 @@ public Forest Forest get { CheckIfDisposed(); - if (_cachedForest == null) + if (_cachedForest is null) { // get the name of rootDomainNamingContext DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); @@ -857,7 +857,7 @@ public DomainControllerCollection DomainControllers get { CheckIfDisposed(); - if (_cachedDomainControllers == null) + if (_cachedDomainControllers is null) { _cachedDomainControllers = FindAllDomainControllers(); } @@ -870,7 +870,7 @@ public DomainCollection Children get { CheckIfDisposed(); - if (_cachedChildren == null) + if (_cachedChildren is null) { _cachedChildren = new DomainCollection(GetChildDomains()); } @@ -923,7 +923,7 @@ public DomainController PdcRoleOwner get { CheckIfDisposed(); - if (_cachedPdcRoleOwner == null) + if (_cachedPdcRoleOwner is null) { _cachedPdcRoleOwner = GetRoleOwner(ActiveDirectoryRole.PdcRole); } @@ -936,7 +936,7 @@ public DomainController RidRoleOwner get { CheckIfDisposed(); - if (_cachedRidRoleOwner == null) + if (_cachedRidRoleOwner is null) { _cachedRidRoleOwner = GetRoleOwner(ActiveDirectoryRole.RidRole); } @@ -949,7 +949,7 @@ public DomainController InfrastructureRoleOwner get { CheckIfDisposed(); - if (_cachedInfrastructureRoleOwner == null) + if (_cachedInfrastructureRoleOwner is null) { _cachedInfrastructureRoleOwner = GetRoleOwner(ActiveDirectoryRole.InfrastructureRole); } @@ -983,7 +983,7 @@ private int GetDomainModeLevel() finally { rootDSE.Dispose(); - if (domainEntry != null) + if (domainEntry is not null) { domainEntry.Dispose(); } @@ -1061,7 +1061,7 @@ private DomainMode GetDomainMode() } finally { - if (domainEntry != null) + if (domainEntry is not null) { domainEntry.Dispose(); } @@ -1108,7 +1108,7 @@ private DomainController GetRoleOwner(ActiveDirectoryRole role) } finally { - if (entry != null) + if (entry is not null) { entry.Dispose(); } @@ -1172,7 +1172,7 @@ private void LoadCrossRefAttributes() } finally { - if (partitionsEntry != null) + if (partitionsEntry is not null) { partitionsEntry.Dispose(); } @@ -1181,11 +1181,11 @@ private void LoadCrossRefAttributes() private Domain GetParent() { - if (_crossRefDN == null) + if (_crossRefDN is null) { LoadCrossRefAttributes(); } - if (_trustParent != null) + if (_trustParent is not null) { DirectoryEntry parentCrossRef = DirectoryEntryManager.GetDirectoryEntry(context, _trustParent); string parentDomainName = null; @@ -1210,7 +1210,7 @@ private ArrayList GetChildDomains() { ArrayList childDomains = new ArrayList(); - if (_crossRefDN == null) + if (_crossRefDN is null) { LoadCrossRefAttributes(); } @@ -1264,11 +1264,11 @@ private ArrayList GetChildDomains() } finally { - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } - if (partitionsEntry != null) + if (partitionsEntry is not null) { partitionsEntry.Dispose(); } @@ -1364,14 +1364,14 @@ private ArrayList GetTrustsHelper(string targetDomainName) obj.ParentIndex = unmanagedTrust.ParentIndex; // check whether it is the case that we are only interested in the trust with target as specified - if (targetDomainName != null) + if (targetDomainName is not null) { bool sameTarget = false; // check whether it is the same target - if (obj.DnsDomainName != null && Utils.Compare(targetDomainName, obj.DnsDomainName) == 0) + if (obj.DnsDomainName is not null && Utils.Compare(targetDomainName, obj.DnsDomainName) == 0) sameTarget = true; - else if (obj.NetbiosDomainName != null && Utils.Compare(targetDomainName, obj.NetbiosDomainName) == 0) + else if (obj.NetbiosDomainName is not null && Utils.Compare(targetDomainName, obj.NetbiosDomainName) == 0) sameTarget = true; // we only want to need local domain and specified target domain trusts @@ -1418,7 +1418,7 @@ private ArrayList GetTrustsHelper(string targetDomainName) continue; // parent domain - if (localDomainParent != null && Utils.Compare(localDomainParent, tmpObject.DnsDomainName) == 0) + if (localDomainParent is not null && Utils.Compare(localDomainParent, tmpObject.DnsDomainName) == 0) { tmpObject.TrustType = TrustType.ParentChild; continue; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs index f74cd29a2b90e2..49538ce2e493de 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs @@ -11,7 +11,7 @@ internal DomainCollection() { } internal DomainCollection(ArrayList values) { - if (values != null) + if (values is not null) { for (int i = 0; i < values.Count; i++) { @@ -24,7 +24,7 @@ internal DomainCollection(ArrayList values) public bool Contains(Domain domain) { - if (domain == null) + if (domain is null) throw new ArgumentNullException(nameof(domain)); for (int i = 0; i < InnerList.Count; i++) @@ -40,7 +40,7 @@ public bool Contains(Domain domain) public int IndexOf(Domain domain) { - if (domain == null) + if (domain is null) throw new ArgumentNullException(nameof(domain)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs index 2a1b4f6f71d19d..98c37b48eccd9d 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs @@ -124,7 +124,7 @@ public static DomainController GetDomainController(DirectoryContext context) DirectoryEntryManager directoryEntryMgr = null; // check that the context argument is not null - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // target should be DC @@ -173,7 +173,7 @@ public static DomainController GetDomainController(DirectoryContext context) public static DomainController FindOne(DirectoryContext context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -188,7 +188,7 @@ public static DomainController FindOne(DirectoryContext context) public static DomainController FindOne(DirectoryContext context, string siteName) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -198,7 +198,7 @@ public static DomainController FindOne(DirectoryContext context, string siteName throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context)); } - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -208,7 +208,7 @@ public static DomainController FindOne(DirectoryContext context, string siteName public static DomainController FindOne(DirectoryContext context, LocatorOptions flag) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -223,7 +223,7 @@ public static DomainController FindOne(DirectoryContext context, LocatorOptions public static DomainController FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -233,7 +233,7 @@ public static DomainController FindOne(DirectoryContext context, string siteName throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context)); } - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -243,7 +243,7 @@ public static DomainController FindOne(DirectoryContext context, string siteName public static DomainControllerCollection FindAll(DirectoryContext context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -261,7 +261,7 @@ public static DomainControllerCollection FindAll(DirectoryContext context) public static DomainControllerCollection FindAll(DirectoryContext context, string siteName) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -271,7 +271,7 @@ public static DomainControllerCollection FindAll(DirectoryContext context, strin throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context)); } - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -292,7 +292,7 @@ public virtual GlobalCatalog EnableGlobalCatalog() DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); // set the NTDSDSA_OPT_IS_GC flag on the "options" property int options = 0; - if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null) + if (serverNtdsaEntry.Properties[PropertyManager.Options].Value is not null) { options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value; } @@ -318,7 +318,7 @@ public virtual bool IsGlobalCatalog() // check if the NTDSDSA_OPT_IS_GC flag is set in the // "options" attribute (lowest bit) int options = 0; - if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null) + if (serverNtdsaEntry.Properties[PropertyManager.Options].Value is not null) { options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value; } @@ -429,7 +429,7 @@ public void SeizeRoleOwnership(ActiveDirectoryRole role) } finally { - if (roleObjectEntry != null) + if (roleObjectEntry is not null) { roleObjectEntry.Dispose(); } @@ -467,7 +467,7 @@ public override ReplicationCursorCollection GetReplicationCursors(string partiti if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -501,7 +501,7 @@ public override ReplicationNeighborCollection GetReplicationNeighbors(string par if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -540,7 +540,7 @@ public override ActiveDirectoryReplicationMetadata GetReplicationMetadata(string if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (objectPath == null) + if (objectPath is null) throw new ArgumentNullException(nameof(objectPath)); if (objectPath.Length == 0) @@ -557,13 +557,13 @@ public override void SyncReplicaFromServer(string partition, string sourceServer if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(partition)); - if (sourceServer == null) + if (sourceServer is null) throw new ArgumentNullException(nameof(sourceServer)); if (sourceServer.Length == 0) @@ -579,7 +579,7 @@ public override void TriggerSyncReplicaFromNeighbors(string partition) if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -595,7 +595,7 @@ public override void SyncReplicaFromAllServers(string partition, SyncFromAllServ if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (partition == null) + if (partition is null) throw new ArgumentNullException(nameof(partition)); if (partition.Length == 0) @@ -614,7 +614,7 @@ public Forest Forest get { CheckIfDisposed(); - if (_currentForest == null) + if (_currentForest is null) { DirectoryContext forestContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _currentForest = Forest.GetForest(forestContext); @@ -670,7 +670,7 @@ public string OSVersion get { CheckIfDisposed(); - if (_cachedOSVersion == null) + if (_cachedOSVersion is null) { // get the operating system version attribute DirectoryEntry computerEntry = directoryEntryMgr.GetCachedDirectoryEntry(ComputerObjectName); @@ -712,7 +712,7 @@ public ActiveDirectoryRoleCollection Roles get { CheckIfDisposed(); - if (_cachedRoles == null) + if (_cachedRoles is null) { _cachedRoles = new ActiveDirectoryRoleCollection(GetRoles()); } @@ -725,7 +725,7 @@ public Domain Domain get { CheckIfDisposed(); - if (_cachedDomain == null) + if (_cachedDomain is null) { string domainName = null; try @@ -774,7 +774,7 @@ public override string SiteName { GetDomainControllerInfo(); } - if (cachedSiteName == null) + if (cachedSiteName is null) { throw new ActiveDirectoryOperationException(SR.Format(SR.SiteNameNotFound, Name)); } @@ -792,7 +792,7 @@ internal string SiteObjectName { GetDomainControllerInfo(); } - if (cachedSiteObjectName == null) + if (cachedSiteObjectName is null) { throw new ActiveDirectoryOperationException(SR.Format(SR.SiteObjectNameNotFound, Name)); } @@ -809,7 +809,7 @@ internal string ComputerObjectName { GetDomainControllerInfo(); } - if (_cachedComputerObjectName == null) + if (_cachedComputerObjectName is null) { throw new ActiveDirectoryOperationException(SR.Format(SR.ComputerObjectNameNotFound, Name)); } @@ -826,7 +826,7 @@ internal string ServerObjectName { GetDomainControllerInfo(); } - if (cachedServerObjectName == null) + if (cachedServerObjectName is null) { throw new ActiveDirectoryOperationException(SR.Format(SR.ServerObjectNameNotFound, Name)); } @@ -843,7 +843,7 @@ internal string NtdsaObjectName { GetDomainControllerInfo(); } - if (cachedNtdsaObjectName == null) + if (cachedNtdsaObjectName is null) { throw new ActiveDirectoryOperationException(SR.Format(SR.NtdsaObjectNameNotFound, Name)); } @@ -994,7 +994,7 @@ internal static DomainController FindOneInternal(DirectoryContext context, strin DomainControllerInfo domainControllerInfo; int errorCode = 0; - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } @@ -1005,7 +1005,7 @@ internal static DomainController FindOneInternal(DirectoryContext context, strin throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } - if (domainName == null) + if (domainName is null) { domainName = DirectoryContext.GetLoggedOnDomain(); } @@ -1041,16 +1041,16 @@ internal static DomainControllerCollection FindAllInternal(DirectoryContext cont { ArrayList dcList = new ArrayList(); - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } - if (domainName == null || !isDnsDomainName) + if (domainName is null || !isDnsDomainName) { // get the dns name of the domain DomainControllerInfo domainControllerInfo; - int errorCode = Locator.DsGetDcNameWrapper(null, (domainName != null) ? domainName : DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo); + int errorCode = Locator.DsGetDcNameWrapper(null, (domainName is not null) ? domainName : DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { @@ -1062,7 +1062,7 @@ internal static DomainControllerCollection FindAllInternal(DirectoryContext cont throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } - Debug.Assert(domainControllerInfo.DomainName != null); + Debug.Assert(domainControllerInfo.DomainName is not null); domainName = domainControllerInfo.DomainName; } @@ -1117,7 +1117,7 @@ private void GetDomainControllerInfo() DsDomainControllerInfo3 domainControllerInfo3 = new DsDomainControllerInfo3(); Marshal.PtrToStructure(currentDc, domainControllerInfo3); // check if this is the same as "this" DC - if (domainControllerInfo3 != null) + if (domainControllerInfo3 is not null) { if (Utils.Compare(domainControllerInfo3.dnsHostName, replicaName) == 0) { @@ -1139,7 +1139,7 @@ private void GetDomainControllerInfo() DsDomainControllerInfo2 domainControllerInfo2 = new DsDomainControllerInfo2(); Marshal.PtrToStructure(currentDc, domainControllerInfo2); // check if this is the same as "this" DC - if (domainControllerInfo2 != null) + if (domainControllerInfo2 is not null) { if (Utils.Compare(domainControllerInfo2.dnsHostName, replicaName) == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs index 85884103c98386..d8c7b0090b5ac6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs @@ -11,7 +11,7 @@ internal DomainControllerCollection() { } internal DomainControllerCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -21,7 +21,7 @@ internal DomainControllerCollection(ArrayList values) public bool Contains(DomainController domainController) { - if (domainController == null) + if (domainController is null) throw new ArgumentNullException(nameof(domainController)); for (int i = 0; i < InnerList.Count; i++) @@ -37,7 +37,7 @@ public bool Contains(DomainController domainController) public int IndexOf(DomainController domainController) { - if (domainController == null) + if (domainController is null) throw new ArgumentNullException(nameof(domainController)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs index 8517c23cb63e00..913e80ab9afb13 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs @@ -128,7 +128,7 @@ public override string Message get { string s = base.Message; - if (!((Name == null) || + if (!((Name is null) || (Name.Length == 0))) return s + Environment.NewLine + SR.Format(SR.Name, Name) + Environment.NewLine; else @@ -182,7 +182,7 @@ public SyncFromAllServersErrorInformation[] ErrorInformation { get { - if (_errors == null) + if (_errors is null) return Array.Empty(); SyncFromAllServersErrorInformation[] tempError = new SyncFromAllServersErrorInformation[_errors.Length]; @@ -310,7 +310,7 @@ internal static Exception GetExceptionFromCOMException(DirectoryContext context, // ServerDown/Unavailable/Busy // - if (context != null) + if (context is not null) { exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, context.GetServerName()); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs index b108641eb6611e..f05f036f10b243 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs @@ -88,7 +88,7 @@ public static Forest GetForest(DirectoryContext context) string rootDomainNC = null; // check that the argument is not null - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // contexttype should be Forest or DirectoryServer @@ -98,12 +98,12 @@ public static Forest GetForest(DirectoryContext context) throw new ArgumentException(SR.TargetShouldBeServerORForest, nameof(context)); } - if ((context.Name == null) && (!context.isRootDomain())) + if ((context.Name is null) && (!context.isRootDomain())) { throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(Forest), null); } - if (context.Name != null) + if (context.Name is not null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isServer()))) @@ -239,7 +239,7 @@ public GlobalCatalog FindGlobalCatalog(string siteName) { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -258,7 +258,7 @@ public GlobalCatalog FindGlobalCatalog(string siteName, LocatorOptions flag) { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -277,7 +277,7 @@ public GlobalCatalogCollection FindAllGlobalCatalogs(string siteName) { CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -299,7 +299,7 @@ public GlobalCatalogCollection FindAllDiscoverableGlobalCatalogs(string siteName CheckIfDisposed(); - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -323,7 +323,7 @@ public ForestTrustRelationshipInformation GetTrustRelationship(string targetFore { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -346,7 +346,7 @@ public bool GetSelectiveAuthenticationStatus(string targetForestName) { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -359,7 +359,7 @@ public void SetSelectiveAuthenticationStatus(string targetForestName, bool enabl { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -372,7 +372,7 @@ public bool GetSidFilteringStatus(string targetForestName) { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -385,7 +385,7 @@ public void SetSidFilteringStatus(string targetForestName, bool enable) { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -398,7 +398,7 @@ public void DeleteLocalSideOfTrustRelationship(string targetForestName) { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -412,7 +412,7 @@ public void DeleteTrustRelationship(Forest targetForest) { CheckIfDisposed(); - if (targetForest == null) + if (targetForest is null) throw new ArgumentNullException(nameof(targetForest)); // first delete the trust on the remote side @@ -426,7 +426,7 @@ public void VerifyOutboundTrustRelationship(string targetForestName) { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -439,7 +439,7 @@ public void VerifyTrustRelationship(Forest targetForest, TrustDirection directio { CheckIfDisposed(); - if (targetForest == null) + if (targetForest is null) throw new ArgumentNullException(nameof(targetForest)); if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) @@ -476,7 +476,7 @@ public void CreateLocalSideOfTrustRelationship(string targetForestName, TrustDir { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -485,7 +485,7 @@ public void CreateLocalSideOfTrustRelationship(string targetForestName, TrustDir if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection)); - if (trustPassword == null) + if (trustPassword is null) throw new ArgumentNullException(nameof(trustPassword)); if (trustPassword.Length == 0) @@ -503,7 +503,7 @@ public void CreateTrustRelationship(Forest targetForest, TrustDirection directio { CheckIfDisposed(); - if (targetForest == null) + if (targetForest is null) throw new ArgumentNullException(nameof(targetForest)); if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) @@ -528,13 +528,13 @@ public void UpdateLocalSideOfTrustRelationship(string targetForestName, string n { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName)); - if (newTrustPassword == null) + if (newTrustPassword is null) throw new ArgumentNullException(nameof(newTrustPassword)); if (newTrustPassword.Length == 0) @@ -547,7 +547,7 @@ public void UpdateLocalSideOfTrustRelationship(string targetForestName, TrustDir { CheckIfDisposed(); - if (targetForestName == null) + if (targetForestName is null) throw new ArgumentNullException(nameof(targetForestName)); if (targetForestName.Length == 0) @@ -556,7 +556,7 @@ public void UpdateLocalSideOfTrustRelationship(string targetForestName, TrustDir if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection)); - if (newTrustPassword == null) + if (newTrustPassword is null) throw new ArgumentNullException(nameof(newTrustPassword)); if (newTrustPassword.Length == 0) @@ -569,7 +569,7 @@ public void UpdateTrustRelationship(Forest targetForest, TrustDirection newTrust { CheckIfDisposed(); - if (targetForest == null) + if (targetForest is null) throw new ArgumentNullException(nameof(targetForest)); if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional) @@ -595,7 +595,7 @@ public void RepairTrustRelationship(Forest targetForest) TrustDirection direction = TrustDirection.Bidirectional; CheckIfDisposed(); - if (targetForest == null) + if (targetForest is null) throw new ArgumentNullException(nameof(targetForest)); // first try to reset the secure channel @@ -649,7 +649,7 @@ public ReadOnlySiteCollection Sites get { CheckIfDisposed(); - if (_cachedSites == null) + if (_cachedSites is null) { _cachedSites = new ReadOnlySiteCollection(GetSites()); } @@ -662,7 +662,7 @@ public DomainCollection Domains get { CheckIfDisposed(); - if (_cachedDomains == null) + if (_cachedDomains is null) { _cachedDomains = new DomainCollection(GetDomains()); } @@ -675,7 +675,7 @@ public GlobalCatalogCollection GlobalCatalogs get { CheckIfDisposed(); - if (_cachedGlobalCatalogs == null) + if (_cachedGlobalCatalogs is null) { _cachedGlobalCatalogs = FindAllGlobalCatalogs(); } @@ -688,7 +688,7 @@ public ApplicationPartitionCollection ApplicationPartitions get { CheckIfDisposed(); - if (_cachedApplicationPartitions == null) + if (_cachedApplicationPartitions is null) { _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions()); } @@ -729,7 +729,7 @@ public Domain RootDomain get { CheckIfDisposed(); - if (_cachedRootDomain == null) + if (_cachedRootDomain is null) { // Domain context is created by passing the name of the forest // (since the root domain and the forest have the same name) @@ -745,7 +745,7 @@ public ActiveDirectorySchema Schema get { CheckIfDisposed(); - if (_cachedSchema == null) + if (_cachedSchema is null) { try { @@ -765,7 +765,7 @@ public DomainController SchemaRoleOwner get { CheckIfDisposed(); - if (_cachedSchemaRoleOwner == null) + if (_cachedSchemaRoleOwner is null) { _cachedSchemaRoleOwner = GetRoleOwner(ActiveDirectoryRole.SchemaRole); } @@ -778,7 +778,7 @@ public DomainController NamingRoleOwner get { CheckIfDisposed(); - if (_cachedNamingRoleOwner == null) + if (_cachedNamingRoleOwner is null) { _cachedNamingRoleOwner = GetRoleOwner(ActiveDirectoryRole.NamingRole); } @@ -857,7 +857,7 @@ private DomainController GetRoleOwner(ActiveDirectoryRole role) } finally { - if (entry != null) + if (entry is not null) { entry.Dispose(); } @@ -1016,7 +1016,7 @@ private ArrayList GetApplicationPartitions() } finally { - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } @@ -1073,7 +1073,7 @@ private ArrayList GetDomains() } finally { - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } @@ -1152,7 +1152,7 @@ private TrustRelationshipInformationCollection GetTrustsHelper(string targetFore Marshal.PtrToStructure(addr, unmanagedTrust); // whether this is the case that a paticular forest trust info is needed - if (targetForestName != null) + if (targetForestName is not null) { bool sameTarget = false; string tmpDNSName = null; @@ -1164,9 +1164,9 @@ private TrustRelationshipInformationCollection GetTrustsHelper(string targetFore tmpNetBIOSName = Marshal.PtrToStringUni(unmanagedTrust.NetbiosDomainName); // check whether it is the same target - if (tmpDNSName != null && Utils.Compare(targetForestName, tmpDNSName) == 0) + if (tmpDNSName is not null && Utils.Compare(targetForestName, tmpDNSName) == 0) sameTarget = true; - else if (tmpNetBIOSName != null && Utils.Compare(targetForestName, tmpNetBIOSName) == 0) + else if (tmpNetBIOSName is not null && Utils.Compare(targetForestName, tmpNetBIOSName) == 0) sameTarget = true; if (!sameTarget) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs index e1ac191c7f32f5..5069bfb091f700 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs @@ -35,7 +35,7 @@ public ForestTrustRelationshipCollision this[int index] public bool Contains(ForestTrustRelationshipCollision collision) { - if (collision == null) + if (collision is null) throw new ArgumentNullException(nameof(collision)); return InnerList.Contains(collision); @@ -43,7 +43,7 @@ public bool Contains(ForestTrustRelationshipCollision collision) public int IndexOf(ForestTrustRelationshipCollision collision) { - if (collision == null) + if (collision is null) throw new ArgumentNullException(nameof(collision)); return InnerList.IndexOf(collision); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs index f75f66038aaa61..c4ee20b38c5833 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs @@ -16,7 +16,7 @@ public ForestTrustDomainInformation this[int index] public bool Contains(ForestTrustDomainInformation information) { - if (information == null) + if (information is null) throw new ArgumentNullException(nameof(information)); return InnerList.Contains(information); @@ -24,7 +24,7 @@ public bool Contains(ForestTrustDomainInformation information) public int IndexOf(ForestTrustDomainInformation information) { - if (information == null) + if (information is null) throw new ArgumentNullException(nameof(information)); return InnerList.IndexOf(information); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs index 9607bf5d609fce..8c074259cfa7a1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs @@ -32,7 +32,7 @@ internal ForestTrustRelationshipInformation(DirectoryContext context, string sou if (unmanagedTrust.NetbiosDomainName != (IntPtr)0) tmpNetBIOSName = Marshal.PtrToStringUni(unmanagedTrust.NetbiosDomainName); - this.target = (tmpDNSName == null ? tmpNetBIOSName : tmpDNSName); + this.target = (tmpDNSName is null ? tmpNetBIOSName : tmpDNSName); // direction if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND) != 0 && (unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND) != 0) @@ -200,12 +200,12 @@ public void Save() sidList.Add(pSid); record.DomainInfo.DNSNameBuffer = Marshal.StringToHGlobalUni(tmp.DnsName); ptrList.Add(record.DomainInfo.DNSNameBuffer); - record.DomainInfo.DNSNameLength = (short)(tmp.DnsName == null ? 0 : tmp.DnsName.Length * 2); // sizeof(WCHAR) - record.DomainInfo.DNSNameMaximumLength = (short)(tmp.DnsName == null ? 0 : tmp.DnsName.Length * 2); + record.DomainInfo.DNSNameLength = (short)(tmp.DnsName is null ? 0 : tmp.DnsName.Length * 2); // sizeof(WCHAR) + record.DomainInfo.DNSNameMaximumLength = (short)(tmp.DnsName is null ? 0 : tmp.DnsName.Length * 2); record.DomainInfo.NetBIOSNameBuffer = Marshal.StringToHGlobalUni(tmp.NetBiosName); ptrList.Add(record.DomainInfo.NetBIOSNameBuffer); - record.DomainInfo.NetBIOSNameLength = (short)(tmp.NetBiosName == null ? 0 : tmp.NetBiosName.Length * 2); - record.DomainInfo.NetBIOSNameMaximumLength = (short)(tmp.NetBiosName == null ? 0 : tmp.NetBiosName.Length * 2); + record.DomainInfo.NetBIOSNameLength = (short)(tmp.NetBiosName is null ? 0 : tmp.NetBiosName.Length * 2); + record.DomainInfo.NetBIOSNameMaximumLength = (short)(tmp.NetBiosName is null ? 0 : tmp.NetBiosName.Length * 2); tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); ptrList.Add(tmpPtr); Marshal.StructureToPtr(record, tmpPtr, false); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs index 8a2d291a0d3878..8b28ca99051a6b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs @@ -32,7 +32,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) DirectoryEntryManager directoryEntryMgr = null; // check that the context argument is not null - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // target should be GC @@ -88,7 +88,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -103,7 +103,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context, string siteName) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -113,7 +113,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -123,7 +123,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -138,7 +138,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -148,7 +148,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -158,7 +158,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalogCollection FindAll(DirectoryContext context) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -176,7 +176,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName) { - if (context == null) + if (context is null) { throw new ArgumentNullException(nameof(context)); } @@ -186,7 +186,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } - if (siteName == null) + if (siteName is null) { throw new ArgumentNullException(nameof(siteName)); } @@ -216,7 +216,7 @@ public DomainController DisableGlobalCatalog() try { - if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null) + if (serverNtdsaEntry.Properties[PropertyManager.Options].Value is not null) { options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value; } @@ -251,7 +251,7 @@ public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties() CheckIfDisabled(); // create an ActiveDirectorySchema object - if (_schema == null) + if (_schema is null) { string schemaNC = null; try @@ -371,7 +371,7 @@ private void CheckIfDisabled() DomainControllerInfo domainControllerInfo; int errorCode = 0; - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } @@ -382,7 +382,7 @@ private void CheckIfDisabled() throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } - if (forestName == null) + if (forestName is null) { // get the dns name of the logged on forest DomainControllerInfo tempDomainControllerInfo; @@ -398,7 +398,7 @@ private void CheckIfDisabled() throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } - Debug.Assert(tempDomainControllerInfo.DnsForestName != null); + Debug.Assert(tempDomainControllerInfo.DnsForestName is not null); forestName = tempDomainControllerInfo.DnsForestName; } @@ -434,7 +434,7 @@ internal static GlobalCatalogCollection FindAllInternal(DirectoryContext context { ArrayList gcList = new ArrayList(); - if (siteName != null && siteName.Length == 0) + if (siteName is not null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs index 1f82854c42dc96..f42c42711054f7 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs @@ -11,7 +11,7 @@ internal GlobalCatalogCollection() { } internal GlobalCatalogCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -21,7 +21,7 @@ internal GlobalCatalogCollection(ArrayList values) public bool Contains(GlobalCatalog globalCatalog) { - if (globalCatalog == null) + if (globalCatalog is null) throw new ArgumentNullException(nameof(globalCatalog)); for (int i = 0; i < InnerList.Count; i++) @@ -37,7 +37,7 @@ public bool Contains(GlobalCatalog globalCatalog) public int IndexOf(GlobalCatalog globalCatalog) { - if (globalCatalog == null) + if (globalCatalog is null) throw new ArgumentNullException(nameof(globalCatalog)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs index 07d17ee6b36b33..a2e80f695a24ee 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs @@ -33,11 +33,11 @@ internal static int DsGetDcNameWrapper(string computerName, string domainName, s int result = 0; // empty siteName/computerName should be treated as null - if ((computerName != null) && (computerName.Length == 0)) + if ((computerName is not null) && (computerName.Length == 0)) { computerName = null; } - if ((siteName != null) && (siteName.Length == 0)) + if ((siteName is not null) && (siteName.Length == 0)) { siteName = null; } @@ -80,7 +80,7 @@ internal static ArrayList EnumerateDomainControllers(DirectoryContext context, s // (site is either specified or defaulted to the site of the local machine) are also returned in this list. // - if (siteName == null) + if (siteName is null) { // // if the site name is not specified then we get the site specific records for the local machine's site (in the context of the domain/forest/application partition that is specified) @@ -204,7 +204,7 @@ private static Hashtable DnsQueryWrapper(string domainName, string siteName, lon IntPtr dnsResults = IntPtr.Zero; // construct the record name - if ((siteName != null) && (!(siteName.Length == 0))) + if ((siteName is not null) && (!(siteName.Length == 0))) { // only looking for domain controllers / global catalogs within a // particular site diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs index d0ed5fbad39c86..8a9d8aa2da0377 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs @@ -131,9 +131,9 @@ public static object GetPropertyValue(DirectoryEntry directoryEntry, string prop public static object GetPropertyValue(DirectoryContext context, DirectoryEntry directoryEntry, string propertyName) { - Debug.Assert(directoryEntry != null, "PropertyManager::GetPropertyValue - directoryEntry is null"); + Debug.Assert(directoryEntry is not null, "PropertyManager::GetPropertyValue - directoryEntry is null"); - Debug.Assert(propertyName != null, "PropertyManager::GetPropertyValue - propertyName is null"); + Debug.Assert(propertyName is not null, "PropertyManager::GetPropertyValue - propertyName is null"); try { @@ -159,15 +159,15 @@ public static object GetPropertyValue(DirectoryContext context, DirectoryEntry d public static object GetSearchResultPropertyValue(SearchResult res, string propertyName) { - Debug.Assert(res != null, "PropertyManager::GetSearchResultPropertyValue - res is null"); + Debug.Assert(res is not null, "PropertyManager::GetSearchResultPropertyValue - res is null"); - Debug.Assert(propertyName != null, "PropertyManager::GetSearchResultPropertyValue - propertyName is null"); + Debug.Assert(propertyName is not null, "PropertyManager::GetSearchResultPropertyValue - propertyName is null"); ResultPropertyValueCollection propertyValues = null; try { propertyValues = res.Properties[propertyName]; - if ((propertyValues == null) || (propertyValues.Count < 1)) + if ((propertyValues is null) || (propertyValues.Count < 1)) { throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound, propertyName)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs index bb181511f65eb8..deeb405168201f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs @@ -11,7 +11,7 @@ internal ReadOnlyActiveDirectorySchemaClassCollection() { } internal ReadOnlyActiveDirectorySchemaClassCollection(ICollection values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -24,7 +24,7 @@ public ActiveDirectorySchemaClass this[int index] public bool Contains(ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) throw new ArgumentNullException(nameof(schemaClass)); for (int i = 0; i < InnerList.Count; i++) @@ -40,7 +40,7 @@ public bool Contains(ActiveDirectorySchemaClass schemaClass) public int IndexOf(ActiveDirectorySchemaClass schemaClass) { - if (schemaClass == null) + if (schemaClass is null) throw new ArgumentNullException(nameof(schemaClass)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs index cdffa0bdab5fb1..5655282affcbbf 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs @@ -11,7 +11,7 @@ internal ReadOnlyActiveDirectorySchemaPropertyCollection() { } internal ReadOnlyActiveDirectorySchemaPropertyCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -24,7 +24,7 @@ public ActiveDirectorySchemaProperty this[int index] public bool Contains(ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) throw new ArgumentNullException(nameof(schemaProperty)); for (int i = 0; i < InnerList.Count; i++) { @@ -39,7 +39,7 @@ public bool Contains(ActiveDirectorySchemaProperty schemaProperty) public int IndexOf(ActiveDirectorySchemaProperty schemaProperty) { - if (schemaProperty == null) + if (schemaProperty is null) throw new ArgumentNullException(nameof(schemaProperty)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs index 54723e37d666c4..821496c16d286a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs @@ -11,7 +11,7 @@ internal ReadOnlyDirectoryServerCollection() { } internal ReadOnlyDirectoryServerCollection(ArrayList values) { - if (values != null) + if (values is not null) { for (int i = 0; i < values.Count; i++) { @@ -24,7 +24,7 @@ internal ReadOnlyDirectoryServerCollection(ArrayList values) public bool Contains(DirectoryServer directoryServer) { - if (directoryServer == null) + if (directoryServer is null) throw new ArgumentNullException(nameof(directoryServer)); for (int i = 0; i < InnerList.Count; i++) @@ -40,7 +40,7 @@ public bool Contains(DirectoryServer directoryServer) public int IndexOf(DirectoryServer directoryServer) { - if (directoryServer == null) + if (directoryServer is null) throw new ArgumentNullException(nameof(directoryServer)); for (int i = 0; i < InnerList.Count; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs index 09abb4f3023fe2..d904a5d6ea46ec 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs @@ -21,7 +21,7 @@ internal ReadOnlySiteCollection(ArrayList sites) public bool Contains(ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); string dn = (string)PropertyManager.GetPropertyValue(site.context, site.cachedEntry, PropertyManager.DistinguishedName); @@ -42,7 +42,7 @@ public bool Contains(ActiveDirectorySite site) public int IndexOf(ActiveDirectorySite site) { - if (site == null) + if (site is null) throw new ArgumentNullException(nameof(site)); string dn = (string)PropertyManager.GetPropertyValue(site.context, site.cachedEntry, PropertyManager.DistinguishedName); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs index 8b8938bc3e79db..9829276b90ca69 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs @@ -16,7 +16,7 @@ public ActiveDirectorySiteLinkBridge this[int index] public bool Contains(ActiveDirectorySiteLinkBridge bridge) { - if (bridge == null) + if (bridge is null) throw new ArgumentNullException(nameof(bridge)); string dn = (string)PropertyManager.GetPropertyValue(bridge.context, bridge.cachedEntry, PropertyManager.DistinguishedName); @@ -36,7 +36,7 @@ public bool Contains(ActiveDirectorySiteLinkBridge bridge) public int IndexOf(ActiveDirectorySiteLinkBridge bridge) { - if (bridge == null) + if (bridge is null) throw new ArgumentNullException(nameof(bridge)); string dn = (string)PropertyManager.GetPropertyValue(bridge.context, bridge.cachedEntry, PropertyManager.DistinguishedName); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs index a0fad5e1f4c4e9..58e01804272e45 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs @@ -16,7 +16,7 @@ public ActiveDirectorySiteLink this[int index] public bool Contains(ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); @@ -36,7 +36,7 @@ public bool Contains(ActiveDirectorySiteLink link) public int IndexOf(ActiveDirectorySiteLink link) { - if (link == null) + if (link is null) throw new ArgumentNullException(nameof(link)); string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs index 14be9c1e0686c3..9902522bfa17d8 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs @@ -11,7 +11,7 @@ internal ReadOnlyStringCollection() { } internal ReadOnlyStringCollection(ArrayList values) { - if (values == null) + if (values is null) { values = new ArrayList(); } @@ -33,7 +33,7 @@ public string this[int index] public bool Contains(string value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -51,7 +51,7 @@ public bool Contains(string value) public int IndexOf(string value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs index 68e87014e57220..bd3f116ea10cc6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs @@ -75,7 +75,7 @@ public static ReplicationConnection FindByName(DirectoryContext context, string } } - if (srchResult == null) + if (srchResult is null) { // no such connection object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name); @@ -118,7 +118,7 @@ public ReplicationConnection(DirectoryContext context, string name, DirectorySer { ValidateArgument(context, name); - if (sourceServer == null) + if (sourceServer is null) throw new ArgumentNullException(nameof(sourceServer)); if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp) @@ -156,7 +156,7 @@ public ReplicationConnection(DirectoryContext context, string name, DirectorySer cachedDirectoryEntry.Properties["fromServer"].Add(serverName); // schedule property - if (schedule != null) + if (schedule is not null) cachedDirectoryEntry.Properties[nameof(schedule)].Value = schedule.GetUnmanagedSchedule(); // transporttype property @@ -210,7 +210,7 @@ protected virtual void Dispose(bool disposing) { if (!_disposed) { - if (disposing && cachedDirectoryEntry != null) + if (disposing && cachedDirectoryEntry is not null) cachedDirectoryEntry.Dispose(); _disposed = true; @@ -241,7 +241,7 @@ public string SourceServer throw new ObjectDisposedException(GetType().Name); // get the source server - if (_sourceServerName == null) + if (_sourceServerName is null) { string sourceServerDN = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer); DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, sourceServerDN); @@ -270,7 +270,7 @@ public string DestinationServer if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (_destinationServerName == null) + if (_destinationServerName is null) { DirectoryEntry NTDSObject = null; DirectoryEntry serverObject = null; @@ -787,7 +787,7 @@ public ActiveDirectorySchedule ReplicationSchedule if (scheduleExists) { byte[] tmpSchedule = (byte[])cachedDirectoryEntry.Properties["schedule"][0]; - Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188); + Debug.Assert(tmpSchedule is not null && tmpSchedule.Length == 188); schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(tmpSchedule); } @@ -801,7 +801,7 @@ public ActiveDirectorySchedule ReplicationSchedule try { - if (value == null) + if (value is null) { if (cachedDirectoryEntry.Properties.Contains("schedule")) cachedDirectoryEntry.Properties["schedule"].Clear(); @@ -907,14 +907,14 @@ public DirectoryEntry GetDirectoryEntry() private static void ValidateArgument(DirectoryContext context, string name) { - if (context == null) + if (context is null) throw new ArgumentNullException(nameof(context)); // the target of the scope must be server - if (context.Name == null || !context.isServer()) + if (context.Name is null || !context.isServer()) throw new ArgumentException(SR.DirectoryContextNeedHost); - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) @@ -980,10 +980,10 @@ private void ValidateTargetAndSourceServer(DirectoryContext context, DirectorySe } finally { - if (targetDE != null) + if (targetDE is not null) targetDE.Close(); - if (sourceDE != null) + if (sourceDE is not null) sourceDE.Close(); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs index d8b238595b260c..b4a2aff440e8cd 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs @@ -13,7 +13,7 @@ internal ReplicationConnectionCollection() { } public bool Contains(ReplicationConnection connection) { - if (connection == null) + if (connection is null) throw new ArgumentNullException(nameof(connection)); if (!connection.existingConnection) @@ -36,7 +36,7 @@ public bool Contains(ReplicationConnection connection) public int IndexOf(ReplicationConnection connection) { - if (connection == null) + if (connection is null) throw new ArgumentNullException(nameof(connection)); if (!connection.existingConnection) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs index ef6a8b81d1aa8c..1c9a650a624798 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs @@ -53,7 +53,7 @@ public string SourceServer get { // get the source server name if we are on win2k, or above win2k and serverDN is not NULL (means KCC translation is successful) - if (!_advanced || (_advanced && _serverDN != null)) + if (!_advanced || (_advanced && _serverDN is not null)) { _sourceServer = Utils.GetServerNameFromInvocationID(_serverDN, SourceInvocationId, _server); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs index 318e309f69a762..3961321f4cfdf0 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs @@ -19,7 +19,7 @@ internal ReplicationCursorCollection(DirectoryServer server) public bool Contains(ReplicationCursor cursor) { - if (cursor == null) + if (cursor is null) throw new ArgumentNullException(nameof(cursor)); return InnerList.Contains(cursor); @@ -27,7 +27,7 @@ public bool Contains(ReplicationCursor cursor) public int IndexOf(ReplicationCursor cursor) { - if (cursor == null) + if (cursor is null) throw new ArgumentNullException(nameof(cursor)); return InnerList.IndexOf(cursor); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs index 359bac6cd77165..7adea2bbf07fad 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs @@ -34,14 +34,14 @@ public string SourceServer { get { - if (_sourceServer == null) + if (_sourceServer is null) { // check whether we have got it before if (_nameTable.Contains(SourceServerGuid)) { _sourceServer = (string)_nameTable[SourceServerGuid]; } - else if (_sourceDsaDN != null) + else if (_sourceDsaDN is not null) { _sourceServer = Utils.GetServerNameFromInvocationID(_sourceDsaDN, SourceServerGuid, _server); // add it to the hashtable diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs index 71e30f8778532c..e7946bb0e4c588 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs @@ -22,7 +22,7 @@ internal ReplicationFailureCollection(DirectoryServer server) public bool Contains(ReplicationFailure failure) { - if (failure == null) + if (failure is null) throw new ArgumentNullException(nameof(failure)); return InnerList.Contains(failure); @@ -30,7 +30,7 @@ public bool Contains(ReplicationFailure failure) public int IndexOf(ReplicationFailure failure) { - if (failure == null) + if (failure is null) throw new ArgumentNullException(nameof(failure)); return InnerList.IndexOf(failure); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs index 651d104f62fa56..940b308f6a5db4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs @@ -49,7 +49,7 @@ internal ReplicationNeighbor(IntPtr addr, DirectoryServer server, Hashtable tabl _sourceServerDN = Marshal.PtrToStringUni(neighbor.pszSourceDsaDN); string transportDN = Marshal.PtrToStringUni(neighbor.pszAsyncIntersiteTransportDN); - if (transportDN != null) + if (transportDN is not null) { string rdn = Utils.GetRdnFromDN(transportDN); string transport = (Utils.GetDNComponents(rdn))[0].Value; @@ -79,14 +79,14 @@ public string SourceServer { get { - if (_sourceServer == null) + if (_sourceServer is null) { // check whether we have got it before if (_nameTable.Contains(SourceInvocationId)) { _sourceServer = (string)_nameTable[SourceInvocationId]; } - else if (_sourceServerDN != null) + else if (_sourceServerDN is not null) { _sourceServer = Utils.GetServerNameFromInvocationID(_sourceServerDN, SourceInvocationId, _server); // add it to the hashtable diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs index abc6cd6128a580..a7a4d7f398dbd9 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs @@ -22,7 +22,7 @@ internal ReplicationNeighborCollection(DirectoryServer server) public bool Contains(ReplicationNeighbor neighbor) { - if (neighbor == null) + if (neighbor is null) throw new ArgumentNullException(nameof(neighbor)); return InnerList.Contains(neighbor); @@ -30,7 +30,7 @@ public bool Contains(ReplicationNeighbor neighbor) public int IndexOf(ReplicationNeighbor neighbor) { - if (neighbor == null) + if (neighbor is null) throw new ArgumentNullException(nameof(neighbor)); return InnerList.IndexOf(neighbor); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs index 0649dda9bd5f9f..bd43d243f0abf2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs @@ -58,14 +58,14 @@ public string SourceServer { get { - if (_sourceServer == null) + if (_sourceServer is null) { // check whether we have got it before if (_nameTable.Contains(SourceServerGuid)) { _sourceServer = (string)_nameTable[SourceServerGuid]; } - else if (_dsaDN != null) + else if (_dsaDN is not null) { _sourceServer = Utils.GetServerNameFromInvocationID(_dsaDN, SourceServerGuid, _server); // add it to the hashtable diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs index 0f5f2f30f3bbd7..51484fc40ec775 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs @@ -22,7 +22,7 @@ internal ReplicationOperationCollection(DirectoryServer server) public bool Contains(ReplicationOperation operation) { - if (operation == null) + if (operation is null) throw new ArgumentNullException(nameof(operation)); return InnerList.Contains(operation); @@ -30,7 +30,7 @@ public bool Contains(ReplicationOperation operation) public int IndexOf(ReplicationOperation operation) { - if (operation == null) + if (operation is null) throw new ArgumentNullException(nameof(operation)); return InnerList.IndexOf(operation); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs index 5a06075b618837..d979ece378768a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs @@ -12,7 +12,7 @@ internal ActiveDirectoryRoleCollection() { } internal ActiveDirectoryRoleCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } @@ -70,7 +70,7 @@ internal AdamRoleCollection() { } internal AdamRoleCollection(ArrayList values) { - if (values != null) + if (values is not null) { InnerList.AddRange(values); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs index 2bcf11b5cbec23..7594067db5cbf8 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs @@ -13,7 +13,7 @@ internal TopLevelNameCollection() { } public bool Contains(TopLevelName name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return InnerList.Contains(name); @@ -21,7 +21,7 @@ public bool Contains(TopLevelName name) public int IndexOf(TopLevelName name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return InnerList.IndexOf(name); @@ -34,7 +34,7 @@ public void CopyTo(TopLevelName[] names, int index) internal int Add(TopLevelName name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return InnerList.Add(name); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs index 94d69f31afa7b5..58cf3f3537a1d5 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs @@ -395,7 +395,7 @@ internal static void VerifyTrust(DirectoryContext context, string sourceName, st // validate the trust existence ValidateTrust(policyHandle, trustedDomainName, sourceName, targetName, isForest, (int)direction, policyServerName); // need to verify direction - if (preferredTargetServer == null) + if (preferredTargetServer is null) data = Marshal.StringToHGlobalUni(targetName); else // this is the case that we need to specifically go to a particular server. This is the way to tell netlogon to do that. diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs index eb633fc8973f5f..ca06f5bdc4e3cd 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs @@ -38,7 +38,7 @@ internal TrustRelationshipInformation(DirectoryContext context, string source, T // source this.source = source; // target - this.target = (obj.DnsDomainName == null ? obj.NetbiosDomainName : obj.DnsDomainName); + this.target = (obj.DnsDomainName is null ? obj.NetbiosDomainName : obj.DnsDomainName); // direction if ((obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND) != 0 && (obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND) != 0) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs index 99b3cc91e3e276..6d2575f66a515b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs @@ -32,7 +32,7 @@ public TrustRelationshipInformation this[int index] public bool Contains(TrustRelationshipInformation information) { - if (information == null) + if (information is null) throw new ArgumentNullException(nameof(information)); return InnerList.Contains(information); @@ -40,7 +40,7 @@ public bool Contains(TrustRelationshipInformation information) public int IndexOf(TrustRelationshipInformation information) { - if (information == null) + if (information is null) throw new ArgumentNullException(nameof(information)); return InnerList.IndexOf(information); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index 6bddb6fba29d09..a6845f9d849a07 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -104,7 +104,7 @@ internal static string GetDnsNameFromDN(string distinguishedName) string dnsName = null; IntPtr results = IntPtr.Zero; - Debug.Assert(distinguishedName != null); + Debug.Assert(distinguishedName is not null); // call DsCrackNamesW IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); @@ -131,7 +131,7 @@ internal static string GetDnsNameFromDN(string distinguishedName) Marshal.PtrToStructure(dsNameResult.items, dsNameResultItem); if (dsNameResultItem.status == NativeMethods.DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING || - dsNameResultItem.name == null) + dsNameResultItem.name is null) { throw new ArgumentException(SR.InvalidDNFormat, nameof(distinguishedName)); } @@ -192,7 +192,7 @@ internal static string GetDNFromDnsName(string dnsName) string dn = null; IntPtr results = IntPtr.Zero; - Debug.Assert(dnsName != null); + Debug.Assert(dnsName is not null); // call DsCrackNamesW IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); @@ -333,7 +333,7 @@ internal static string GetAdamDnsHostNameFromNTDSA(DirectoryContext context, str serversEntry.Dispose(); } - if ((ldapPort == -1) || (dnsHostName == null)) + if ((ldapPort == -1) || (dnsHostName is null)) { throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber, dn)); } @@ -393,7 +393,7 @@ internal static string GetAdamHostNameAndPortsFromNTDSA(DirectoryContext context serversEntry.Dispose(); } - if ((ldapPort == -1) || (sslPort == -1) || (dnsHostName == null)) + if ((ldapPort == -1) || (sslPort == -1) || (dnsHostName is null)) { throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber, dn)); } @@ -447,7 +447,7 @@ internal static string GetPartialDN(string distinguishedName, int startingIndex) // internal static Component[] GetDNComponents(string distinguishedName) { - Debug.Assert(distinguishedName != null, "Utils.GetDNComponents: distinguishedName is null"); + Debug.Assert(distinguishedName is not null, "Utils.GetDNComponents: distinguishedName is null"); // First split by ',' string[] components = Split(distinguishedName, ','); @@ -483,7 +483,7 @@ internal static Component[] GetDNComponents(string distinguishedName) // internal static bool IsValidDNFormat(string distinguishedName) { - Debug.Assert(distinguishedName != null, "Utils.GetDNComponents: distinguishedName is null"); + Debug.Assert(distinguishedName is not null, "Utils.GetDNComponents: distinguishedName is null"); // First split by ',' string[] components = Split(distinguishedName, ','); @@ -584,7 +584,7 @@ internal static DirectoryContext GetNewDirectoryContext(string name, DirectoryCo internal static void GetDomainAndUsername(DirectoryContext context, out string username, out string domain) { - if ((context.UserName != null) && (context.UserName.Length > 0)) + if ((context.UserName is not null) && (context.UserName.Length > 0)) { string tmpUsername = context.UserName; int index = -1; @@ -660,7 +660,7 @@ internal static IntPtr GetDSHandle(string domainControllerName, string domainNam IntPtr handle; // call DsBindWithCred - Debug.Assert((domainControllerName != null && domainName == null) || (domainName != null && domainControllerName == null)); + Debug.Assert((domainControllerName is not null && domainName is null) || (domainName is not null && domainControllerName is null)); IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsBindWithCredW"); if (functionPtr == (IntPtr)0) { @@ -671,7 +671,7 @@ internal static IntPtr GetDSHandle(string domainControllerName, string domainNam result = bindWithCred(domainControllerName, domainName, authIdentity, out handle); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(result, (domainControllerName != null) ? domainControllerName : domainName); + throw ExceptionHelper.GetExceptionFromErrorCode(result, (domainControllerName is not null) ? domainControllerName : domainName); } return handle; } @@ -695,7 +695,7 @@ internal static void FreeDSHandle(IntPtr dsHandle, LoadLibrarySafeHandle libHand internal static bool CheckCapability(DirectoryEntry rootDSE, Capability capability) { bool result = false; - if (rootDSE != null) + if (rootDSE is not null) { if (capability == Capability.ActiveDirectory) { @@ -770,7 +770,7 @@ internal static DirectoryEntry GetCrossRefEntry(DirectoryContext context, Direct { res = searcher.FindOne(); - if (res == null) + if (res is null) { // should not happen throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ActiveDirectoryPartition), partitionName); @@ -787,7 +787,7 @@ internal static DirectoryEntry GetCrossRefEntry(DirectoryContext context, Direct internal static ActiveDirectoryTransportType GetTransportTypeFromDN(string DN) { - Debug.Assert(DN != null); + Debug.Assert(DN is not null); string rdn = GetRdnFromDN(DN); Component[] component = GetDNComponents(rdn); @@ -826,7 +826,7 @@ internal static string GetServerNameFromInvocationID(string serverObjectDN, Guid { string originatingServerName = null; - if (serverObjectDN == null) + if (serverObjectDN is null) { // this is the win2k case, we need to get the DSA address first string siteName = (server is DomainController) ? ((DomainController)server).SiteObjectName : ((AdamInstance)server).SiteObjectName; @@ -869,7 +869,7 @@ internal static string GetServerNameFromInvocationID(string serverObjectDN, Guid try { srchResult = adSearcher.FindOne(); - if (srchResult != null) + if (srchResult is not null) { DirectoryEntry srvEntry = srchResult.GetDirectoryEntry().Parent; originatingServerName = (string)PropertyManager.GetPropertyValue(server.Context, srvEntry, PropertyManager.DnsHostName); @@ -920,7 +920,7 @@ internal static bool Impersonate(DirectoryContext context) IntPtr hToken = (IntPtr)0; // default credential is specified, no need to do impersonation - if ((context.UserName == null) && (context.Password == null)) + if ((context.UserName is null) && (context.Password is null)) return false; string userName; @@ -1137,7 +1137,7 @@ internal static Hashtable GetValuesWithRangeRetrieval(DirectoryEntry searchRootE propertiesStillToLoad.Clear(); res = searcher.FindOne(); - if (res != null) + if (res is not null) { foreach (string propertyNameWithRangeInfo in res.Properties.PropertyNames) { @@ -1234,7 +1234,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit // msDS-NC-Replica-Locations and msDS-NC-RO-Replica-Locations (for Configuration/Schema, these attributes are // not populated, so we just return a list of all the servers) // - if (partitionName != null && !isDefaultNC) + if (partitionName is not null && !isDefaultNC) { DistinguishedName dn = new DistinguishedName(partitionName); DistinguishedName configDn = new DistinguishedName(configurationNamingContext); @@ -1295,7 +1295,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit // extract the property values ArrayList replicaLocations = (ArrayList)values[PropertyManager.MsDSNCReplicaLocations.ToLowerInvariant()]; ArrayList roReplicaLocations = (ArrayList)values[PropertyManager.MsDSNCROReplicaLocations.ToLowerInvariant()]; - Debug.Assert(replicaLocations != null); + Debug.Assert(replicaLocations is not null); if (replicaLocations.Count == 0) { @@ -1339,11 +1339,11 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit } finally { - if (partitionsEntry != null) + if (partitionsEntry is not null) { partitionsEntry.Dispose(); } - if (fsmoPartitionsEntry != null) + if (fsmoPartitionsEntry is not null) { fsmoPartitionsEntry.Dispose(); } @@ -1355,7 +1355,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit try { // check whether we can narrow down our search within a specific site - if (siteName != null) + if (siteName is not null) { searchRootDN = "CN=Servers,CN=" + siteName + ",CN=Sites," + configurationNamingContext; } @@ -1375,7 +1375,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit if (isDefaultNC) { - Debug.Assert(partitionName != null); + Debug.Assert(partitionName is not null); Debug.Assert(!isGC); filter2 = "(|(&(" + PropertyManager.ObjectCategory + "=nTDSDSA)(" + PropertyManager.HasMasterNCs + @@ -1403,7 +1403,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit } else { - Debug.Assert(partitionName != null); + Debug.Assert(partitionName is not null); // resctrict the search to the servers that were listed in the crossRef if (isGC) { @@ -1516,7 +1516,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit propertyName = propertyWithRangeInfo; } - if (propertyName == null) + if (propertyName is null) { // property does not exist, possiblyno values, so continue continue; @@ -1581,7 +1581,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit } finally { - if (resCol != null) + if (resCol is not null) { resCol.Dispose(); } @@ -1656,7 +1656,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit propertyName = propertyWithRangeInfo2; } - if (propertyName == null) + if (propertyName is null) { // property does not exist, possiblyno values, so continue continue; @@ -1704,7 +1704,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit } catch (COMException e) { - if (e.ErrorCode == unchecked((int)0x80072030) && siteName != null) + if (e.ErrorCode == unchecked((int)0x80072030) && siteName is not null) { // this means that the site object does not exist, so we return an empty collection return dnsNames; @@ -1717,7 +1717,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit } finally { - if (searchRootEntry != null) + if (searchRootEntry is not null) { searchRootEntry.Dispose(); } @@ -1728,7 +1728,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit { string hostName = (string)serverNames[ntdsaName]; - if (hostName == null) + if (hostName is null) { Debug.Fail($"ConfigurationSet::GetReplicaList - no dnsHostName information for replica {ntdsaName}"); if (isADAM) @@ -1743,7 +1743,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit if (isADAM) { - if (serverPorts[ntdsaName] == null) + if (serverPorts[ntdsaName] is null) { Debug.Fail($"ConfigurationSet::GetReplicaList - no port number information for replica {ntdsaName}"); throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber, ntdsaName)); @@ -1846,7 +1846,7 @@ internal static int Compare(string s1, string s2, uint compareFlags) // // This method handles comparison of the specified strings // if and only if either one of the two strings or both are null. - if (s1 == null || s2 == null) + if (s1 is null || s2 is null) { return string.Compare(s1, s2); } @@ -1892,11 +1892,11 @@ internal static int Compare(string s1, string s2) internal static int Compare(string s1, int offset1, int length1, string s2, int offset2, int length2) { - if (s1 == null) + if (s1 is null) { throw new ArgumentNullException(nameof(s1)); } - if (s2 == null) + if (s2 is null) { throw new ArgumentNullException(nameof(s2)); } @@ -1905,11 +1905,11 @@ internal static int Compare(string s1, int offset1, int length1, string s2, int internal static int Compare(string s1, int offset1, int length1, string s2, int offset2, int length2, uint compareFlags) { - if (s1 == null) + if (s1 is null) { throw new ArgumentNullException(nameof(s1)); } - if (s2 == null) + if (s2 is null) { throw new ArgumentNullException(nameof(s2)); } @@ -1979,7 +1979,7 @@ internal static string SplitServerNameAndPortNumber(string serverName, out strin internal static string GetNtAuthorityString() { - if (s_NTAuthorityString == null) + if (s_NTAuthorityString is null) { SecurityIdentifier sidLocalSystem = new SecurityIdentifier("S-1-5-18"); NTAccount ntLocalSystem = (NTAccount)sidLocalSystem.Translate(typeof(NTAccount)); @@ -2236,7 +2236,7 @@ internal static bool IsMachineDC(string computerName) try { - if (null == computerName) + if (computerName is null) err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(IntPtr.Zero, DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); else err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(computerName, DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs index 8aae67d06a6c2c..712408b331ab6e 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs @@ -24,7 +24,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value != null && value is string) + if (value is not null && value is string) { string text = ((string)value).Trim(); @@ -34,11 +34,11 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c if (text.CompareTo(SR.DSNotSet) != 0) { DirectoryEntry newEntry = GetFromCache(text); - if (newEntry == null) + if (newEntry is null) { newEntry = new DirectoryEntry(text); s_componentsCreated[text] = newEntry; - if (context != null) + if (context is not null) context.Container.Add(newEntry); return newEntry; @@ -51,9 +51,9 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType != null && destinationType == typeof(string)) + if (destinationType is not null && destinationType == typeof(string)) { - if (value != null) + if (value is not null) return ((DirectoryEntry)value).Path; else return SR.DSNotSet; @@ -64,7 +64,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (s_values == null) + if (s_values is null) { s_values = new StandardValuesCollection(new object[] { null }); } @@ -76,7 +76,7 @@ internal static DirectoryEntry GetFromCache(string path) if (s_componentsCreated.ContainsKey(path)) { DirectoryEntry existingComponent = (DirectoryEntry)s_componentsCreated[path]; - if (existingComponent.Site == null) + if (existingComponent.Site is null) s_componentsCreated.Remove(path); else { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs index f9d3668525b605..1dcc2e1c69d3d4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs @@ -66,7 +66,7 @@ public DirectoryEntry Find(string name) public DirectoryEntry Find(string name, string schemaClassName) { CheckIsContainer(); - // Note: schemaClassName == null does not work for IIS: provider. + // Note: schemaClassName is null does not work for IIS: provider. object o = null; try { @@ -123,10 +123,10 @@ public DirectoryEntry Current { get { - if (_enumVariant == null) + if (_enumVariant is null) throw new InvalidOperationException(SR.DSNoCurrentChild); - if (_currentEntry == null) + if (_currentEntry is null) _currentEntry = new DirectoryEntry(_enumVariant.GetValue(), _container.UsePropertyCache, _container.GetUsername(), _container.GetPassword(), _container.AuthenticationType); return _currentEntry; @@ -139,7 +139,7 @@ public DirectoryEntry Current /// public bool MoveNext() { - if (_enumVariant == null) + if (_enumVariant is null) return false; _currentEntry = null; @@ -151,7 +151,7 @@ public bool MoveNext() /// public void Reset() { - if (_enumVariant != null) + if (_enumVariant is not null) { try { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index 3da8e109e6f68e..109bdd5f29efb6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -73,10 +73,10 @@ public DirectoryEntry(string path, string username, string password) : this(path public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType) : this(path) { _credentials = new NetworkCredential(username, password); - if (username == null) + if (username is null) _userNameIsNull = true; - if (password == null) + if (password is null) _passwordIsNull = true; _authenticationType = authenticationType; @@ -87,10 +87,10 @@ internal DirectoryEntry(string path, bool useCache, string username, string pass _path = path; _useCache = useCache; _credentials = new NetworkCredential(username, password); - if (username == null) + if (username is null) _userNameIsNull = true; - if (password == null) + if (password is null) _passwordIsNull = true; _authenticationType = authenticationType; @@ -115,7 +115,7 @@ internal DirectoryEntry(object adsObject, bool useCache, string username, string internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType, bool AdsObjIsExternal) { _adsObject = adsObject as UnsafeNativeMethods.IAds; - if (_adsObject == null) + if (_adsObject is null) throw new ArgumentException(SR.DSDoesNotImplementIADs); // GetInfo is not needed here. ADSI executes an implicit GetInfo when GetEx @@ -128,10 +128,10 @@ internal DirectoryEntry(object adsObject, bool useCache, string username, string _authenticationType = authenticationType; _credentials = new NetworkCredential(username, password); - if (username == null) + if (username is null) _userNameIsNull = true; - if (password == null) + if (password is null) _passwordIsNull = true; if (!useCache) @@ -170,7 +170,7 @@ public AuthenticationTypes AuthenticationType } } - private bool Bound => _adsObject != null; + private bool Bound => _adsObject is not null; /// /// Gets a @@ -226,7 +226,7 @@ public ActiveDirectorySecurity ObjectSecurity } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -310,14 +310,14 @@ public string Password if (value == GetPassword()) return; - if (_credentials == null) + if (_credentials is null) { _credentials = new NetworkCredential(); // have not set it yet _userNameIsNull = true; } - if (value == null) + if (value is null) _passwordIsNull = true; else _passwordIsNull = false; @@ -337,7 +337,7 @@ public string Path get => _path; set { - if (value == null) + if (value is null) value = ""; if (System.DirectoryServices.ActiveDirectory.Utils.Compare(_path, value) == 0) @@ -355,7 +355,7 @@ public PropertyCollection Properties { get { - if (_propertyCollection == null) + if (_propertyCollection is null) { _propertyCollection = new PropertyCollection(this); } @@ -427,7 +427,7 @@ public string Username { get { - if (_credentials == null || _userNameIsNull) + if (_credentials is null || _userNameIsNull) return null; return _credentials.UserName; @@ -437,13 +437,13 @@ public string Username if (value == GetUsername()) return; - if (_credentials == null) + if (_credentials is null) { _credentials = new NetworkCredential(); _passwordIsNull = true; } - if (value == null) + if (value is null) _userNameIsNull = true; else _userNameIsNull = false; @@ -517,10 +517,10 @@ internal void Bind(bool throwIfFail) if (_disposed) throw new ObjectDisposedException(GetType().Name); - if (_adsObject == null) + if (_adsObject is null) { string pathToUse = Path; - if (pathToUse == null || pathToUse.Length == 0) + if (pathToUse is null || pathToUse.Length == 0) { // 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); @@ -605,7 +605,7 @@ public void CommitChanges() { // unless we have modified the existing security descriptor (in-place) through ObjectSecurity property // there is nothing to do - if ((_objectSecurity == null) || (!_objectSecurity.IsModified())) + if ((_objectSecurity is null) || (!_objectSecurity.IsModified())) { return; } @@ -797,7 +797,7 @@ public object Invoke(string methodName, params object[] args) } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is not null) { if (e.InnerException is COMException) { @@ -835,7 +835,7 @@ public object InvokeGet(string propertyName) } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is not null) { if (e.InnerException is COMException) { @@ -868,7 +868,7 @@ public void InvokeSet(string propertyName, params object[] args) } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is not null) { if (e.InnerException is COMException) { @@ -992,11 +992,11 @@ public void RefreshCache(string[] propertyNames) // this is a half-lie, but oh well. Without it, this method is pointless. _cacheFilled = true; // we need to partially refresh that properties table. - if (_propertyCollection != null) + if (_propertyCollection is not null) { for (int i = 0; i < propertyNames.Length; i++) { - if (propertyNames[i] != null) + if (propertyNames[i] is not null) { string name = propertyNames[i].ToLowerInvariant(); _propertyCollection.valueTable.Remove(name); @@ -1039,7 +1039,7 @@ public void RefreshCache(string[] propertyNames) private void Unbind() { - if (_adsObject != null) + if (_adsObject is not null) System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject); _adsObject = null; // we need to release that properties table. @@ -1052,7 +1052,7 @@ private void Unbind() internal string GetUsername() { - if (_credentials == null || _userNameIsNull) + if (_credentials is null || _userNameIsNull) return null; return _credentials.UserName; @@ -1060,7 +1060,7 @@ internal string GetUsername() internal string GetPassword() { - if (_credentials == null || _passwordIsNull) + if (_credentials is null || _passwordIsNull) return null; return _credentials.Password; @@ -1155,7 +1155,7 @@ private ActiveDirectorySecurity GetObjectSecurityFromCache() private void SetObjectSecurityInCache() { - if ((_objectSecurity != null) && (_objectSecurityModified || _objectSecurity.IsModified())) + if ((_objectSecurity is not null) && (_objectSecurityModified || _objectSecurity.IsModified())) { UnsafeNativeMethods.IAdsPropertyValue sDValue = (UnsafeNativeMethods.IAdsPropertyValue)new UnsafeNativeMethods.PropertyValue(); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs index 444455bdae31d4..6b075f30d75b7e 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs @@ -125,7 +125,7 @@ public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] prop { _searchRoot = searchRoot; _filter = filter; - if (propertiesToLoad != null) + if (propertiesToLoad is not null) PropertiesToLoad.AddRange(propertiesToLoad); this.SearchScope = scope; } @@ -200,7 +200,7 @@ public string Filter get => _filter; set { - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) value = defaultFilter; _filter = value; } @@ -236,7 +236,7 @@ public StringCollection PropertiesToLoad { get { - if (_propertiesToLoad == null) + if (_propertiesToLoad is null) { _propertiesToLoad = new StringCollection(); } @@ -350,7 +350,7 @@ public DirectoryEntry SearchRoot { get { - if (_searchRoot == null && !DesignMode) + if (_searchRoot is null && !DesignMode) { // 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); @@ -411,7 +411,7 @@ public string AttributeScopeQuery get => _attributeScopeQuery; set { - if (value == null) + if (value is null) value = ""; // user explicitly set AttributeScopeQuery and value is not null or empty string @@ -499,7 +499,7 @@ public DirectorySynchronization DirectorySynchronization get { // if user specifies dirsync search preference and search is executed - if (directorySynchronizationSpecified && searchResult != null) + if (directorySynchronizationSpecified && searchResult is not null) { _sync.ResetDirectorySynchronizationCookie(searchResult.DirsyncCookie); } @@ -509,7 +509,7 @@ public DirectorySynchronization DirectorySynchronization set { // specify non-zero pagesize explicitly and also want dirsync - if (value != null) + if (value is not null) { if (PageSize != 0) throw new ArgumentException(SR.DSBadPageSizeDirsync); @@ -536,7 +536,7 @@ public DirectoryVirtualListView VirtualListView get { // if user specifies dirsync search preference and search is executed - if (directoryVirtualListViewSpecified && searchResult != null) + if (directoryVirtualListViewSpecified && searchResult is not null) { DirectoryVirtualListView tempval = searchResult.VLVResponse; _vlv.Offset = tempval.Offset; @@ -552,7 +552,7 @@ public DirectoryVirtualListView VirtualListView set { // if user explicitly set CacheResults to true and also want to set VLV - if (value != null) + if (value is not null) { if (_cacheResultsSpecified == true && CacheResults == true) throw new ArgumentException(SR.DSBadCacheResultsVLV); @@ -649,7 +649,7 @@ private SearchResultCollection FindAll(bool findMoreThanOne) } IntPtr resultsHandle; - if (properties != null) + if (properties is not null) { adsSearch.ExecuteSearch(Filter, properties, properties.Length, out resultsHandle); } @@ -808,7 +808,7 @@ private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch ad try { // sort - if (Sort.PropertyName != null && Sort.PropertyName.Length > 0) + if (Sort.PropertyName is not null && Sort.PropertyName.Length > 0) { info = default; info.dwSearchPref = (int)AdsSearchPreferences.SORT_ON; @@ -838,7 +838,7 @@ private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch ad else vlvValue.target = IntPtr.Zero; ptrVLVToFree = vlvValue.target; - if (_vlv.DirectoryVirtualListViewContext == null) + if (_vlv.DirectoryVirtualListViewContext is null) { vlvValue.contextIDlength = 0; vlvValue.contextID = (IntPtr)0; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySynchronization.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySynchronization.cs index fc624420ebd403..51bf22564940c1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySynchronization.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySynchronization.cs @@ -21,7 +21,7 @@ public DirectorySynchronization(DirectorySynchronizationOptions option) public DirectorySynchronization(DirectorySynchronization sync) { - if (sync != null) + if (sync is not null) { Option = sync.Option; ResetDirectorySynchronizationCookie(sync.GetDirectorySynchronizationCookie()); @@ -69,7 +69,7 @@ public byte[] GetDirectorySynchronizationCookie() public void ResetDirectorySynchronizationCookie(byte[] cookie) { - if (cookie == null) + if (cookie is null) { _cookie = Array.Empty(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs index bdee39650abd92..74cc4f0bb1ae2f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs @@ -13,7 +13,7 @@ public DirectoryVirtualListViewContext() : this(null) internal DirectoryVirtualListViewContext(byte[] context) { - if (context == null) + if (context is null) { _context = Array.Empty(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs index 260b3afc80ec58..bb6301b4df5810 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs @@ -30,7 +30,7 @@ public PropertyValueCollection this[string propertyName] { get { - if (propertyName == null) + if (propertyName is null) throw new ArgumentNullException(nameof(propertyName)); string name = propertyName.ToLowerInvariant(); @@ -152,7 +152,7 @@ void IDictionary.Remove(object key) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) @@ -205,7 +205,7 @@ public DictionaryEntry Entry { get { - if (_currentPropName == null) + if (_currentPropName is null) throw new InvalidOperationException(SR.DSNoCurrentProperty); return new DictionaryEntry(_currentPropName, new PropertyValueCollection(_parentEntry, _currentPropName)); @@ -231,7 +231,7 @@ public bool MoveNext() } if (hr == 0) { - if (prop != null) + if (prop is not null) _currentPropName = ((UnsafeNativeMethods.IAdsPropertyEntry)prop).Name; else _currentPropName = null; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs index 20e3cefde6c6b7..ddb985af26fe59 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs @@ -34,7 +34,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 (tempPath is null || tempPath.Length == 0) { // user does not specify path, so we bind to default naming context using LDAP provider. _needNewBehavior = true; @@ -86,13 +86,13 @@ public object Value } catch (System.Runtime.InteropServices.COMException e) { - if (e.ErrorCode != unchecked((int)0x80004005) || (value == null)) + if (e.ErrorCode != unchecked((int)0x80004005) || (value is null)) // WinNT provider throws E_FAIL when null value is specified though actually ADS_PROPERTY_CLEAR option is used, need to catch exception // here. But at the same time we don't want to catch the exception if user explicitly sets the value to null. throw; } - if (value == null) + if (value is null) return; // we could not do Clear and Add, we have to bypass the existing collection cache @@ -137,7 +137,7 @@ public object Value /// public void AddRange(object[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -152,7 +152,7 @@ public void AddRange(object[] value) /// public void AddRange(PropertyValueCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs index 0e243cdff3816f..65a8ba21c18bd6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs @@ -69,7 +69,7 @@ public int Add(string value) /// public void AddRange(string[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -84,7 +84,7 @@ public void AddRange(string[] value) public void AddRange(SchemaNameCollection value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -125,7 +125,7 @@ public IEnumerator GetEnumerator() private object[] GetValue() { object value = _propGetter(); - if (value == null) + if (value is null) return Array.Empty(); else return (object[])value; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs index cbe7b56fbbdc6e..d62046299aa61f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs @@ -26,7 +26,7 @@ internal SearchResult(NetworkCredential parentCredentials, AuthenticationTypes p /// public DirectoryEntry GetDirectoryEntry() { - if (_parentCredentials != null) + if (_parentCredentials is not null) return new DirectoryEntry(Path, true, _parentCredentials.UserName, _parentCredentials.Password, _parentAuthenticationType); else { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs index 4178c0524a38b9..072871f48151c1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs @@ -47,7 +47,7 @@ private ArrayList InnerList { get { - if (_innerList == null) + if (_innerList is null) { _innerList = new ArrayList(); IEnumerator enumerator = new ResultsEnumerator(this, @@ -66,7 +66,7 @@ internal UnsafeNativeMethods.IDirectorySearch SearchObject { get { - if (_searchObject == null) + if (_searchObject is null) { _searchObject = (UnsafeNativeMethods.IDirectorySearch)_rootEntry.AdsObject; // get it only once } @@ -165,7 +165,7 @@ protected virtual void Dispose(bool disposing) { if (!_disposed) { - if (_handle != (IntPtr)0 && _searchObject != null && disposing) + if (_handle != (IntPtr)0 && _searchObject is not null && disposing) { // NOTE: We can't call methods on SearchObject in the finalizer because it // runs on a different thread. The IDirectorySearch object is STA, so COM must create @@ -237,7 +237,7 @@ private class ResultsEnumerator : IEnumerator internal ResultsEnumerator(SearchResultCollection results, string parentUserName, string parentPassword, AuthenticationTypes parentAuthenticationType) { - if (parentUserName != null && parentPassword != null) + if (parentUserName is not null && parentPassword is not null) _parentCredentials = new NetworkCredential(parentUserName, parentPassword); _parentAuthenticationType = parentAuthenticationType; @@ -255,7 +255,7 @@ public SearchResult Current if (!_initialized || _eof) throw new InvalidOperationException(SR.DSNoCurrentEntry); - if (_currentResult == null) + if (_currentResult is null) _currentResult = GetCurrentResult(); return _currentResult; diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs index 0ea4b583bd73c1..6426d52c5721dc 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs @@ -386,14 +386,14 @@ public string Name { if ((state & StateNameValid) != 0) { - Debug.Assert(name != null); + Debug.Assert(name is not null); return name; } if (IsKnownColor) { string tablename = KnownColorNames.KnownColorToName((KnownColor)knownColor); - Debug.Assert(tablename != null, $"Could not find known color '{(KnownColor)knownColor}' in the KnownColorTable"); + Debug.Assert(tablename is not null, $"Could not find known color '{(KnownColor)knownColor}' in the KnownColorTable"); return tablename; } @@ -580,7 +580,7 @@ public override int GetHashCode() // an unnamed color with the same ARGB value. // 3. Have an unknown name. Will differ from other unknown-named colors only by name, so we // can usefully use the names hash code alone. - if (name != null && !IsKnownColor) + if (name is not null && !IsKnownColor) return name.GetHashCode(); return HashCode.Combine(value.GetHashCode(), state.GetHashCode(), knownColor.GetHashCode()); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs index 2af50e73c722a2..bc24ca1add7363 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs @@ -208,7 +208,7 @@ public static bool TryReadBitString( Slice(source, headerLength, contentsLength), ruleSet, destination, - contentsLength == null, + contentsLength is null, out localUbc, out int bytesRead, out int written)) @@ -313,7 +313,7 @@ public static byte[] ReadBitString( Slice(source, headerLength, contentsLength), ruleSet, rented, - contentsLength == null, + contentsLength is null, out localUbc, out int bytesRead, out int written)) @@ -489,7 +489,7 @@ private static int ProcessConstructedBitString( throw new AsnContentException(SR.ContentException_InvalidUnderCer_TryBerOrDer); } - Debug.Assert(length != null); + Debug.Assert(length is not null); ReadOnlySpan encodedValue = Slice(cur, headerLength, length.Value); ParsePrimitiveBitStringContents( @@ -506,7 +506,7 @@ private static int ProcessConstructedBitString( totalLength += contents.Length; lastSegmentLength = encodedValue.Length; - if (copyAction != null) + if (copyAction is not null) { copyAction(contents, normalizedLastByte, curDest); curDest = curDest.Slice(contents.Length); @@ -541,7 +541,7 @@ private static int ProcessConstructedBitString( throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer); } - if (readerStack == null) + if (readerStack is null) { readerStack = new Stack<(int, int, bool, int)>(); } @@ -556,7 +556,7 @@ private static int ProcessConstructedBitString( cur = Slice(cur, headerLength, length); bytesRead = headerLength; - isIndefinite = (length == null); + isIndefinite = (length is null); } else { diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Enumerated.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Enumerated.cs index 4bf10cc8b231ff..b28adbbf30fab7 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Enumerated.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Enumerated.cs @@ -193,7 +193,7 @@ public static Enum ReadEnumeratedValue( out int bytesConsumed, Asn1Tag? expectedTag = null) { - if (enumType == null) + if (enumType is null) throw new ArgumentNullException(nameof(enumType)); const UniversalTagNumber TagNumber = UniversalTagNumber.Enumerated; diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.GeneralizedTime.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.GeneralizedTime.cs index 9acf1d591d9a4f..03e353d9ace572 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.GeneralizedTime.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.GeneralizedTime.cs @@ -69,7 +69,7 @@ public static DateTimeOffset ReadGeneralizedTime( DateTimeOffset value = ParseGeneralizedTime(ruleSet, contents); - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, contents.Length); } @@ -166,13 +166,13 @@ private static DateTimeOffset ParseGeneralizedTime( { byte? nextState = GetNextState(contents[0]); - if (nextState == null) + if (nextState is null) { - if (minute == null) + if (minute is null) { minute = ParseNonNegativeIntAndSlice(ref contents, 2); } - else if (second == null) + else if (second is null) { second = ParseNonNegativeIntAndSlice(ref contents, 2); } @@ -252,7 +252,7 @@ private static DateTimeOffset ParseGeneralizedTime( { byte? nextState = GetNextState(contents[0]); - if (nextState == null) + if (nextState is null) { throw new AsnContentException(); } @@ -378,7 +378,7 @@ private static DateTimeOffset ParseGeneralizedTime( try { - if (timeOffset == null) + if (timeOffset is null) { // Use the local timezone offset since there's no information in the contents. // T-REC-X.680-201510 sec 46.2(a). diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.NamedBitList.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.NamedBitList.cs index ec1da0d280765c..2c722d7a858e35 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.NamedBitList.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.NamedBitList.cs @@ -181,7 +181,7 @@ public static Enum ReadNamedBitListValue( out int bytesConsumed, Asn1Tag? expectedTag = null) { - if (flagsEnumType == null) + if (flagsEnumType is null) throw new ArgumentNullException(nameof(flagsEnumType)); // This will throw an ArgumentException if TEnum isn't an enum type, @@ -327,7 +327,7 @@ public static BitArray ReadNamedBitList( Asn1Tag actualTag = ReadEncodedValue(source, ruleSet, out _, out int contentLength, out _); // Get the last ArgumentException out of the way before we rent arrays - if (expectedTag != null) + if (expectedTag is not null) { CheckExpectedTag(actualTag, expectedTag.Value, UniversalTagNumber.BitString); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs index db7bbee8a6bd46..da04981e920f81 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs @@ -100,7 +100,7 @@ public static bool TryReadOctetString( Slice(source, headerLength, contentLength), ruleSet, destination, - contentLength == null, + contentLength is null, out int bytesRead, out bytesWritten); @@ -172,7 +172,7 @@ public static byte[] ReadOctetString( byte[] ret = contents.ToArray(); - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, contents.Length); } @@ -352,7 +352,7 @@ private static int CopyConstructedOctetString( throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer); } - Debug.Assert(length != null); + Debug.Assert(length is not null); // The call to Slice here sanity checks the data bounds, length.Value is not // reliable unless this call has succeeded. @@ -406,7 +406,7 @@ private static int CopyConstructedOctetString( throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer); } - if (readerStack == null) + if (readerStack is null) { readerStack = new Stack<(int, int, bool, int)>(); } @@ -421,7 +421,7 @@ private static int CopyConstructedOctetString( cur = Slice(cur, headerLength, length); bytesRead = headerLength; - isIndefinite = (length == null); + isIndefinite = (length is null); } else { @@ -485,7 +485,7 @@ private static ReadOnlySpan GetOctetStringContents( ref byte[]? rented, Span tmpSpace = default) { - Debug.Assert(rented == null); + Debug.Assert(rented is null); if (TryReadPrimitiveOctetStringCore( source, @@ -508,7 +508,7 @@ private static ReadOnlySpan GetOctetStringContents( if (tmpSpace.Length > 0 && tooBig > tmpSpace.Length) { - bool isIndefinite = contentLength == null; + bool isIndefinite = contentLength is null; tooBig = CountConstructedOctetString(contents, ruleSet, isIndefinite); } @@ -522,7 +522,7 @@ private static ReadOnlySpan GetOctetStringContents( Slice(source, headerLength, contentLength), ruleSet, tmpSpace, - contentLength == null, + contentLength is null, out int bytesRead, out int bytesWritten)) { diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Oid.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Oid.cs index 44106332bf015f..d678f1c7781e89 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Oid.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Oid.cs @@ -216,7 +216,7 @@ private static string ReadObjectIdentifier( // * else: X = 2, Y = identifier - 80. byte firstArc; - if (smallValue != null) + if (smallValue is not null) { long firstIdentifier = smallValue.Value; @@ -241,7 +241,7 @@ private static string ReadObjectIdentifier( } else { - Debug.Assert(largeValue != null); + Debug.Assert(largeValue is not null); BigInteger firstIdentifier = largeValue.Value; // We're only here because we were bigger than long.MaxValue, so @@ -262,11 +262,11 @@ private static string ReadObjectIdentifier( { ReadSubIdentifier(contents, out bytesRead, out smallValue, out largeValue); // Exactly one should be non-null. - Debug.Assert((smallValue == null) != (largeValue == null)); + Debug.Assert((smallValue is null) != (largeValue is null)); builder.Append('.'); - if (smallValue != null) + if (smallValue is not null) { builder.Append(smallValue.Value); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Text.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Text.cs index 83862a750eb22f..a9a896d9915d49 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Text.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.Text.cs @@ -368,7 +368,7 @@ private static bool TryReadCharacterStringBytesCore( Slice(source, headerLength, contentLength), ruleSet, destination, - contentLength == null, + contentLength is null, out int bytesRead, out bytesWritten); @@ -464,7 +464,7 @@ private static string ReadCharacterStringCore( } } - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, contents.Length); } @@ -500,7 +500,7 @@ private static bool TryReadCharacterStringCore( encoding, out charsWritten); - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, contents.Length); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.UtcTime.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.UtcTime.cs index f7fa3c656646af..ecd503ca003236 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.UtcTime.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.UtcTime.cs @@ -94,7 +94,7 @@ public static DateTimeOffset ReadUtcTime( DateTimeOffset value = ParseUtcTime(contents, ruleSet, twoDigitYearMax); - if (rented != null) + if (rented is not null) { Debug.Fail($"UtcTime did not fit in tmpSpace ({contents.Length} total)"); CryptoPool.Return(rented, contents.Length); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.cs index d6f70cacab1960..abc720d3ec721d 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.cs @@ -196,7 +196,7 @@ private static ReadOnlySpan GetPrimitiveContentSpan( SR.Format(SR.ContentException_PrimitiveEncodingRequired, tagNumber)); } - if (encodedLength == null) + if (encodedLength is null) { throw new AsnContentException(); } @@ -376,12 +376,12 @@ private static Asn1Tag ReadTagAndLength( if (tag.IsConstructed) { // T-REC-X.690-201508 sec 9.1 (CER: Length forms) says constructed is always indefinite. - if (ruleSet == AsnEncodingRules.CER && length != null) + if (ruleSet == AsnEncodingRules.CER && length is not null) { throw GetValidityException(LengthValidity.CerRequiresIndefinite); } } - else if (length == null) + else if (length is null) { // T-REC-X.690-201508 sec 8.1.3.2 says primitive encodings must use a definite form. throw GetValidityException(LengthValidity.PrimitiveEncodingRequiresDefinite); @@ -412,20 +412,20 @@ private static LengthValidity ValidateLength( if (localTag.IsConstructed) { // T-REC-X.690-201508 sec 9.1 (CER: Length forms) says constructed is always indefinite. - if (ruleSet == AsnEncodingRules.CER && encodedLength != null) + if (ruleSet == AsnEncodingRules.CER && encodedLength is not null) { actualLength = bytesConsumed = 0; return LengthValidity.CerRequiresIndefinite; } } - else if (encodedLength == null) + else if (encodedLength is null) { // T-REC-X.690-201508 sec 8.1.3.2 says primitive encodings must use a definite form. actualLength = bytesConsumed = 0; return LengthValidity.PrimitiveEncodingRequiresDefinite; } - if (encodedLength != null) + if (encodedLength is not null) { int len = encodedLength.Value; int totalLength = len; @@ -503,7 +503,7 @@ private static int SeekEndOfContents(ReadOnlySpan source, AsnEncodingRules // We found another indefinite length, that means we need to find another // EndOfContents marker to balance it out. - if (length == null) + if (length is null) { depth++; cur = cur.Slice(bytesRead); @@ -565,7 +565,7 @@ private static ReadOnlySpan Slice(ReadOnlySpan source, int offset, i { Debug.Assert(offset >= 0); - if (length == null) + if (length is null) { return source.Slice(offset); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs index a29ad2ba063048..b1826a3993726d 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs @@ -32,7 +32,7 @@ public sealed partial class AsnWriter /// public void WriteEnumeratedValue(Enum value, Asn1Tag? tag = null) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); WriteEnumeratedValue(tag?.AsPrimitive() ?? Asn1Tag.Enumerated, value.GetType(), value); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs index 424e484abef2b9..3dfc9fdedde170 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs @@ -34,7 +34,7 @@ public sealed partial class AsnWriter /// public void WriteNamedBitList(Enum value, Asn1Tag? tag = null) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); CheckUniversalTag(tag, UniversalTagNumber.BitString); @@ -91,7 +91,7 @@ public void WriteNamedBitList(TEnum value, Asn1Tag? tag = null) where TEn /// public void WriteNamedBitList(BitArray value, Asn1Tag? tag = null) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); CheckUniversalTag(tag, UniversalTagNumber.BitString); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs index b9b77fad02eaf5..f04f5f0ad9bd3e 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs @@ -30,7 +30,7 @@ public sealed partial class AsnWriter /// public void WriteObjectIdentifier(string oidValue, Asn1Tag? tag = null) { - if (oidValue == null) + if (oidValue is null) throw new ArgumentNullException(nameof(oidValue)); WriteObjectIdentifier(oidValue.AsSpan(), tag); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs index 7f0ab728f6e77f..432788dc3361a4 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs @@ -38,7 +38,7 @@ public sealed partial class AsnWriter /// public void WriteCharacterString(UniversalTagNumber encodingType, string value, Asn1Tag? tag = null) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); WriteCharacterString(encodingType, value.AsSpan(), tag); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs index c5e10fdab20d63..28b792082df738 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs @@ -54,7 +54,7 @@ public void Reset() { if (_offset > 0) { - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); Array.Clear(_buffer, 0, _offset); _offset = 0; @@ -224,7 +224,7 @@ public bool EncodedValueEquals(ReadOnlySpan other) /// public bool EncodedValueEquals(AsnWriter other) { - if (other == null) + if (other is null) throw new ArgumentNullException(nameof(other)); return EncodeAsSpan().SequenceEqual(other.EncodeAsSpan()); @@ -237,7 +237,7 @@ private void EnsureWriteCapacity(int pendingCount) throw new OverflowException(); } - if (_buffer == null || _buffer.Length - _offset < pendingCount) + if (_buffer is null || _buffer.Length - _offset < pendingCount) { #if CHECK_ACCURATE_ENSURE // A debug paradigm to make sure that throughout the execution nothing ever writes @@ -245,7 +245,7 @@ private void EnsureWriteCapacity(int pendingCount) // and copies, so it's a #define opt-in. byte[] newBytes = new byte[_offset + pendingCount]; - if (_buffer != null) + if (_buffer is not null) { Span bufferSpan = _buffer.AsSpan(0, _offset); bufferSpan.CopyTo(newBytes); @@ -260,7 +260,7 @@ private void EnsureWriteCapacity(int pendingCount) byte[]? oldBytes = _buffer; Array.Resize(ref _buffer, BlockSize * blocks); - if (oldBytes != null) + if (oldBytes is not null) { oldBytes.AsSpan(0, _offset).Clear(); } @@ -382,7 +382,7 @@ private static int GetEncodedLengthSubsequentByteCount(int length) /// public void CopyTo(AsnWriter destination) { - if (destination == null) + if (destination is null) throw new ArgumentNullException(nameof(destination)); try @@ -444,7 +444,7 @@ private void WriteEndOfContents() private Scope PushTag(Asn1Tag tag, UniversalTagNumber tagType) { - if (_nestingStack == null) + if (_nestingStack is null) { _nestingStack = new Stack(); } @@ -460,7 +460,7 @@ private Scope PushTag(Asn1Tag tag, UniversalTagNumber tagType) private void PopTag(Asn1Tag tag, UniversalTagNumber tagType, bool sortContents = false) { - if (_nestingStack == null || _nestingStack.Count == 0) + if (_nestingStack is null || _nestingStack.Count == 0) { throw new InvalidOperationException(SR.AsnWriter_PopWrongTag); } @@ -566,7 +566,7 @@ private void PopTag(Asn1Tag tag, UniversalTagNumber tagType, bool sortContents = private static void SortContents(byte[] buffer, int start, int end) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(end >= start); int len = end - start; @@ -634,7 +634,7 @@ internal static void Reverse(Span span) private static void CheckUniversalTag(Asn1Tag? tag, UniversalTagNumber universalTagNumber) { - if (tag != null) + if (tag is not null) { Asn1Tag value = tag.Value; @@ -721,7 +721,7 @@ public override int GetHashCode() internal Scope(AsnWriter writer) { - Debug.Assert(writer._nestingStack != null); + Debug.Assert(writer._nestingStack is not null); _writer = writer; _frame = _writer._nestingStack.Peek(); @@ -730,9 +730,9 @@ internal Scope(AsnWriter writer) public void Dispose() { - Debug.Assert(_writer == null || _writer._nestingStack != null); + Debug.Assert(_writer is null || _writer._nestingStack is not null); - if (_writer == null || _writer._nestingStack!.Count == 0) + if (_writer is null || _writer._nestingStack!.Count == 0) { return; } diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs index 4bca2bac59c148..3792bc413dfd2e 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs @@ -19,7 +19,7 @@ public sealed partial class BrotliStream : Stream public BrotliStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false) { } public BrotliStream(Stream stream, CompressionMode mode, bool leaveOpen) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); switch (mode) @@ -44,7 +44,7 @@ public BrotliStream(Stream stream, CompressionMode mode, bool leaveOpen) private void EnsureNotDisposed() { - if (_stream == null) + if (_stream is null) throw new ObjectDisposedException(GetType().Name, SR.ObjectDisposed_StreamClosed); } @@ -52,7 +52,7 @@ protected override void Dispose(bool disposing) { try { - if (disposing && _stream != null) + if (disposing && _stream is not null) { if (_mode == CompressionMode.Compress) { @@ -76,7 +76,7 @@ public override async ValueTask DisposeAsync() { try { - if (_stream != null) + if (_stream is not null) { if (_mode == CompressionMode.Compress) { @@ -102,7 +102,7 @@ private void ReleaseStateForDispose() _decoder.Dispose(); byte[] buffer = _buffer; - if (buffer != null) + if (buffer is not null) { _buffer = null!; if (!AsyncOperationIsActive) @@ -114,7 +114,7 @@ private void ReleaseStateForDispose() private static void ValidateParameters(byte[] array, int offset, int count) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (offset < 0) @@ -128,8 +128,8 @@ private static void ValidateParameters(byte[] array, int offset, int count) } public Stream BaseStream => _stream; - public override bool CanRead => _mode == CompressionMode.Decompress && _stream != null && _stream.CanRead; - public override bool CanWrite => _mode == CompressionMode.Compress && _stream != null && _stream.CanWrite; + public override bool CanRead => _mode == CompressionMode.Decompress && _stream is not null && _stream.CanRead; + public override bool CanWrite => _mode == CompressionMode.Compress && _stream is not null && _stream.CanWrite; public override bool CanSeek => false; public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override long Length => throw new NotSupportedException(); diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs index d73883ed8b3b3a..b986a1ef7b2af8 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs @@ -24,7 +24,7 @@ internal void InitializeDecoder() internal void EnsureInitialized() { EnsureNotDisposed(); - if (_state == null) + if (_state is null) InitializeDecoder(); } @@ -43,7 +43,7 @@ private void EnsureNotDisposed() public OperationStatus Decompress(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten) { EnsureInitialized(); - Debug.Assert(_state != null); + Debug.Assert(_state is not null); bytesConsumed = 0; bytesWritten = 0; diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs index c6ab42b73329e5..57966644cbac73 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs @@ -40,7 +40,7 @@ internal void InitializeEncoder() internal void EnsureInitialized() { EnsureNotDisposed(); - if (_state == null) + if (_state is null) { InitializeEncoder(); } @@ -61,10 +61,10 @@ private void EnsureNotDisposed() internal void SetQuality(int quality) { EnsureNotDisposed(); - if (_state == null || _state.IsInvalid || _state.IsClosed) + if (_state is null || _state.IsInvalid || _state.IsClosed) { InitializeEncoder(); - Debug.Assert(_state != null && !_state.IsInvalid && !_state.IsClosed); + Debug.Assert(_state is not null && !_state.IsInvalid && !_state.IsClosed); } if (quality < BrotliUtils.Quality_Min || quality > BrotliUtils.Quality_Max) { @@ -79,10 +79,10 @@ internal void SetQuality(int quality) internal void SetWindow(int window) { EnsureNotDisposed(); - if (_state == null || _state.IsInvalid || _state.IsClosed) + if (_state is null || _state.IsInvalid || _state.IsClosed) { InitializeEncoder(); - Debug.Assert(_state != null && !_state.IsInvalid && !_state.IsClosed); + Debug.Assert(_state is not null && !_state.IsInvalid && !_state.IsClosed); } if (window < BrotliUtils.WindowBits_Min || window > BrotliUtils.WindowBits_Max) { @@ -121,7 +121,7 @@ public static int GetMaxCompressedLength(int inputSize) internal OperationStatus Compress(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, BrotliEncoderOperation operation) { EnsureInitialized(); - Debug.Assert(_state != null); + Debug.Assert(_state is not null); bytesWritten = 0; bytesConsumed = 0; diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliStream.Compress.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliStream.Compress.cs index 87171b9c1ee3be..0da168349213c7 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliStream.Compress.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliStream.Compress.cs @@ -111,7 +111,7 @@ public override void Flush() EnsureNotDisposed(); if (_mode == CompressionMode.Compress) { - if (_encoder._state == null || _encoder._state.IsClosed) + if (_encoder._state is null || _encoder._state.IsClosed) return; OperationStatus lastResult = OperationStatus.DestinationTooSmall; @@ -146,7 +146,7 @@ private async Task FlushAsyncCore(CancellationToken cancellationToken) AsyncOperationStarting(); try { - if (_encoder._state == null || _encoder._state.IsClosed) + if (_encoder._state is null || _encoder._state.IsClosed) return; OperationStatus lastResult = OperationStatus.DestinationTooSmall; diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/Crc32Helper.ZLib.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/Crc32Helper.ZLib.cs index 40cd3a07e0a2f1..8edd3a97bc3f1d 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/Crc32Helper.ZLib.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/Crc32Helper.ZLib.cs @@ -11,7 +11,7 @@ internal static class Crc32Helper // Calculate CRC based on the old CRC and the new bytes public static unsafe uint UpdateCrc32(uint crc32, byte[] buffer, int offset, int length) { - Debug.Assert((buffer != null) && (offset >= 0) && (length >= 0) && (offset <= buffer.Length - length)); + Debug.Assert((buffer is not null) && (offset >= 0) && (length >= 0) && (offset <= buffer.Length - length)); fixed (byte* bufferPtr = &buffer[offset]) { return Interop.zlib.crc32(crc32, bufferPtr, length); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs index ea6644fd9279ea..a3a9f5f2d95538 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs @@ -22,7 +22,7 @@ internal sealed partial class DeflateManagedStream : Stream // A specific constructor to allow decompression of Deflate64 internal DeflateManagedStream(Stream stream, ZipArchiveEntry.CompressionMethodValues method, long uncompressedSize = -1) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); @@ -41,7 +41,7 @@ public override bool CanRead { get { - if (_stream == null) + if (_stream is null) { return false; } @@ -141,7 +141,7 @@ public override int Read(byte[] array, int offset, int count) private void ValidateParameters(byte[] array, int offset, int count) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (offset < 0) @@ -156,7 +156,7 @@ private void ValidateParameters(byte[] array, int offset, int count) private void EnsureNotDisposed() { - if (_stream == null) + if (_stream is null) ThrowStreamClosedException(); } @@ -207,7 +207,7 @@ public override Task ReadAsync(byte[] array, int offset, int count, Cancell // If there is no data on the output buffer and we are not at // the end of the stream, we need to get more data from the base stream readTask = _stream!.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken); - if (readTask == null) + if (readTask is null) { throw new InvalidOperationException(SR.NotSupported_UnreadableStream); } @@ -217,7 +217,7 @@ public override Task ReadAsync(byte[] array, int offset, int count, Cancell finally { // if we haven't started any async work, decrement the counter to end the transaction - if (readTask == null) + if (readTask is null) { Interlocked.Decrement(ref _asyncOperations); } @@ -256,7 +256,7 @@ private async Task ReadAsyncCore(Task readTask, byte[] array, int offs // We could have read in head information and didn't get any data. // Read from the base stream again. readTask = _stream!.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken); - if (readTask == null) + if (readTask is null) { throw new InvalidOperationException(SR.NotSupported_UnreadableStream); } @@ -284,7 +284,7 @@ private void PurgeBuffers(bool disposing) if (!disposing) return; - if (_stream == null) + if (_stream is null) return; Flush(); @@ -303,7 +303,7 @@ protected override void Dispose(bool disposing) // In this case, we still need to clean up internal resources, hence the inner finally blocks. try { - if (disposing && _stream != null) + if (disposing && _stream is not null) _stream.Dispose(); } finally diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs index 4f1c36834a8bbf..9c04ec547bfb04 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs @@ -86,7 +86,7 @@ internal InflaterManaged(IFileFormatReader? reader, bool deflate64, long uncompr _codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; _deflate64 = deflate64; _uncompressedSize = uncompressedSize; - if (reader != null) + if (reader is not null) { _formatReader = reader; _hasFormatReader = true; @@ -139,7 +139,7 @@ public int Inflate(byte[] bytes, int offset, int length) { if (_hasFormatReader) { - Debug.Assert(_formatReader != null); + Debug.Assert(_formatReader is not null); _formatReader.UpdateWithBytesRead(bytes, offset, copied); } @@ -161,7 +161,7 @@ public int Inflate(byte[] bytes, int offset, int length) // But some data in output window might not be copied out. if (_output.AvailableBytes == 0) { - Debug.Assert(_formatReader != null); + Debug.Assert(_formatReader is not null); _formatReader.Validate(); } } @@ -202,7 +202,7 @@ private bool Decode() if (_hasFormatReader) { - Debug.Assert(_formatReader != null); + Debug.Assert(_formatReader is not null); if (_state == InflaterState.ReadingHeader) { if (!_formatReader.ReadHeader(_input)) @@ -400,7 +400,7 @@ private bool DecodeBlock(out bool end_of_block_code_seen) case InflaterState.DecodeTop: // decode an element from the literal tree - Debug.Assert(_literalLengthTree != null); + Debug.Assert(_literalLengthTree is not null); // TODO: optimize this!!! symbol = _literalLengthTree.GetNextSymbol(_input); if (symbol < 0) @@ -474,7 +474,7 @@ private bool DecodeBlock(out bool end_of_block_code_seen) case InflaterState.HaveFullLength: if (_blockType == BlockType.Dynamic) { - Debug.Assert(_distanceTree != null); + Debug.Assert(_distanceTree is not null); _distanceCode = _distanceTree.GetNextSymbol(_input); } else @@ -619,7 +619,7 @@ private bool DecodeDynamicBlockHeader() { if (_state == InflaterState.ReadingTreeCodesBefore) { - Debug.Assert(_codeLengthTree != null); + Debug.Assert(_codeLengthTree is not null); if ((_lengthCode = _codeLengthTree.GetNextSymbol(_input)) < 0) { return false; diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs index 7b5d2920b6bf06..1737b1ca822e66 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs @@ -43,7 +43,7 @@ public bool EnsureBitsAvailable(int count) { return false; } - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); // insert a byte to bitbuffer _bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer; _bitsInBuffer += 8; @@ -72,7 +72,7 @@ public bool EnsureBitsAvailable(int count) /// public uint TryLoad16Bits() { - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); if (_bitsInBuffer < 8) { if (_start < _end) @@ -125,7 +125,7 @@ public int GetBits(int count) /// Returns the number of bytes copied, 0 if no byte is available. public int CopyTo(byte[] output, int offset, int length) { - Debug.Assert(output != null); + Debug.Assert(output is not null); Debug.Assert(offset >= 0); Debug.Assert(length >= 0); Debug.Assert(offset <= output.Length - length); @@ -153,7 +153,7 @@ public int CopyTo(byte[] output, int offset, int length) length = avail; } - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); Array.Copy(_buffer, _start, output, offset, length); _start += length; return bytesFromBitBuffer + length; @@ -174,7 +174,7 @@ public int CopyTo(byte[] output, int offset, int length) /// public void SetInput(byte[] buffer, int offset, int length) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(offset >= 0); Debug.Assert(length >= 0); Debug.Assert(offset <= buffer.Length - length); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs index 4a34fe859a58b1..9f71c9a8be285b 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs @@ -51,7 +51,7 @@ public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leav /// internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int windowBits, long uncompressedSize = -1) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); switch (mode) @@ -80,7 +80,7 @@ internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int /// internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowBits) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); InitializeDeflater(stream, leaveOpen, windowBits, compressionLevel); @@ -92,7 +92,7 @@ internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool le [MemberNotNull(nameof(_stream))] internal void InitializeDeflater(Stream stream, bool leaveOpen, int windowBits, CompressionLevel compressionLevel) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); if (!stream.CanWrite) throw new ArgumentException(SR.NotSupported_UnwritableStream, nameof(stream)); @@ -106,13 +106,13 @@ internal void InitializeDeflater(Stream stream, bool leaveOpen, int windowBits, private void InitializeBuffer() { - Debug.Assert(_buffer == null); + Debug.Assert(_buffer is null); _buffer = ArrayPool.Shared.Rent(DefaultBufferSize); } private void EnsureBufferInitialized() { - if (_buffer == null) + if (_buffer is null) { InitializeBuffer(); } @@ -124,7 +124,7 @@ public override bool CanRead { get { - if (_stream == null) + if (_stream is null) { return false; } @@ -137,7 +137,7 @@ public override bool CanWrite { get { - if (_stream == null) + if (_stream is null) { return false; } @@ -182,7 +182,7 @@ private async Task FlushAsyncCore(CancellationToken cancellationToken) AsyncOperationStarting(); try { - Debug.Assert(_deflater != null && _buffer != null); + Debug.Assert(_deflater is not null && _buffer is not null); // Compress any bytes left: await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); @@ -223,7 +223,7 @@ public override int ReadByte() // Try to read a single byte from zlib without allocating an array, pinning an array, etc. // If zlib doesn't have any data, fall back to the base stream implementation, which will do that. byte b; - Debug.Assert(_inflater != null); + Debug.Assert(_inflater is not null); return _inflater.Inflate(out b) ? b : base.ReadByte(); } @@ -256,7 +256,7 @@ internal int ReadCore(Span buffer) int totalRead = 0; - Debug.Assert(_inflater != null); + Debug.Assert(_inflater is not null); while (true) { int bytesRead = _inflater.Inflate(buffer.Slice(totalRead)); @@ -277,7 +277,7 @@ internal int ReadCore(Span buffer) if (_inflater.NeedsInput()) { - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); int bytes = _stream.Read(_buffer, 0, _buffer.Length); if (bytes <= 0) { @@ -299,7 +299,7 @@ internal int ReadCore(Span buffer) private void ValidateParameters(byte[] array, int offset, int count) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (offset < 0) @@ -314,7 +314,7 @@ private void ValidateParameters(byte[] array, int offset, int count) private void EnsureNotDisposed() { - if (_stream == null) + if (_stream is null) ThrowStreamClosedException(); } @@ -388,7 +388,7 @@ internal ValueTask ReadAsyncMemory(Memory buffer, CancellationToken c AsyncOperationStarting(); try { - Debug.Assert(_inflater != null); + Debug.Assert(_inflater is not null); while (true) { // Finish inflating any bytes in the input buffer @@ -439,7 +439,7 @@ private async ValueTask FinishReadAsyncMemory( { try { - Debug.Assert(_inflater != null && _buffer != null); + Debug.Assert(_inflater is not null && _buffer is not null); while (true) { if (_inflater.NeedsInput()) @@ -528,7 +528,7 @@ internal void WriteCore(ReadOnlySpan buffer) EnsureCompressionMode(); EnsureNotDisposed(); - Debug.Assert(_deflater != null); + Debug.Assert(_deflater is not null); // Write compressed the bytes we already passed to the deflater: WriteDeflaterOutput(); @@ -546,7 +546,7 @@ internal void WriteCore(ReadOnlySpan buffer) private void WriteDeflaterOutput() { - Debug.Assert(_deflater != null && _buffer != null); + Debug.Assert(_deflater is not null && _buffer is not null); while (!_deflater.NeedsInput()) { int compressedBytes = _deflater.GetDeflateOutput(_buffer); @@ -566,7 +566,7 @@ private void FlushBuffers() // Compress any bytes left: WriteDeflaterOutput(); - Debug.Assert(_deflater != null && _buffer != null); + Debug.Assert(_deflater is not null && _buffer is not null); // Pull out any bytes left inside deflater: bool flushSuccessful; do @@ -588,13 +588,13 @@ private void PurgeBuffers(bool disposing) if (!disposing) return; - if (_stream == null) + if (_stream is null) return; if (_mode != CompressionMode.Compress) return; - Debug.Assert(_deflater != null && _buffer != null); + Debug.Assert(_deflater is not null && _buffer is not null); // Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs. // This round-trips and we should be ok with this, but our legacy managed deflater // always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry) @@ -636,13 +636,13 @@ private async ValueTask PurgeBuffersAsync() { // Same logic as PurgeBuffers, except with async counterparts. - if (_stream == null) + if (_stream is null) return; if (_mode != CompressionMode.Compress) return; - Debug.Assert(_deflater != null && _buffer != null); + Debug.Assert(_deflater is not null && _buffer is not null); // Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs. // This round-trips and we should be ok with this, but our legacy managed deflater // always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry) @@ -711,7 +711,7 @@ protected override void Dispose(bool disposing) _inflater = null; byte[]? buffer = _buffer; - if (buffer != null) + if (buffer is not null) { _buffer = null; if (!AsyncOperationIsActive) @@ -749,7 +749,7 @@ private async ValueTask DisposeAsyncCore() _stream = null!; try { - if (!_leaveOpen && stream != null) + if (!_leaveOpen && stream is not null) await stream.DisposeAsync().ConfigureAwait(false); } finally @@ -765,7 +765,7 @@ private async ValueTask DisposeAsyncCore() _inflater = null; byte[]? buffer = _buffer; - if (buffer != null) + if (buffer is not null) { _buffer = null; if (!AsyncOperationIsActive) @@ -822,7 +822,7 @@ private async ValueTask WriteAsyncMemoryCore(ReadOnlyMemory buffer, Cancel { await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); - Debug.Assert(_deflater != null); + Debug.Assert(_deflater is not null); // Pass new bytes through deflater _deflater.SetInput(buffer); @@ -841,7 +841,7 @@ private async ValueTask WriteAsyncMemoryCore(ReadOnlyMemory buffer, Cancel /// private async ValueTask WriteDeflaterOutputAsync(CancellationToken cancellationToken) { - Debug.Assert(_deflater != null && _buffer != null); + Debug.Assert(_deflater is not null && _buffer is not null); while (!_deflater.NeedsInput()) { int compressedBytes = _deflater.GetDeflateOutput(_buffer); @@ -896,8 +896,8 @@ public CopyToStream(DeflateStream deflateStream, Stream destination, int bufferS public CopyToStream(DeflateStream deflateStream, Stream destination, int bufferSize, CancellationToken cancellationToken) { - Debug.Assert(deflateStream != null); - Debug.Assert(destination != null); + Debug.Assert(deflateStream is not null); + Debug.Assert(destination is not null); Debug.Assert(bufferSize > 0); _deflateStream = deflateStream; @@ -911,7 +911,7 @@ public async Task CopyFromSourceToDestinationAsync() _deflateStream.AsyncOperationStarting(); try { - Debug.Assert(_deflateStream._inflater != null); + Debug.Assert(_deflateStream._inflater is not null); // Flush any existing data in the inflater to the destination stream. while (!_deflateStream._inflater.Finished()) { @@ -943,7 +943,7 @@ public void CopyFromSourceToDestination() { try { - Debug.Assert(_deflateStream._inflater != null); + Debug.Assert(_deflateStream._inflater is not null); // Flush any existing data in the inflater to the destination stream. while (!_deflateStream._inflater.Finished()) { @@ -985,7 +985,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int count, Canc throw new InvalidDataException(SR.GenericInvalidData); } - Debug.Assert(_deflateStream._inflater != null); + Debug.Assert(_deflateStream._inflater is not null); // Feed the data from base stream into the decompression engine. _deflateStream._inflater.SetInput(buffer, offset, count); @@ -1022,7 +1022,7 @@ public override void Write(byte[] buffer, int offset, int count) throw new InvalidDataException(SR.GenericInvalidData); } - Debug.Assert(_deflateStream._inflater != null); + Debug.Assert(_deflateStream._inflater is not null); // Feed the data from base stream into the decompression engine. _deflateStream._inflater.SetInput(buffer, offset, count); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs index 78302098aa08df..29943693000c33 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs @@ -134,7 +134,7 @@ internal unsafe void SetInput(ReadOnlyMemory inputBuffer) internal unsafe void SetInput(byte* inputBufferPtr, int count) { Debug.Assert(NeedsInput(), "We have something left in previous input!"); - Debug.Assert(inputBufferPtr != null); + Debug.Assert(inputBufferPtr is not null); if (count == 0) { @@ -150,7 +150,7 @@ internal unsafe void SetInput(byte* inputBufferPtr, int count) internal int GetDeflateOutput(byte[] outputBuffer) { - Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!"); + Debug.Assert(outputBuffer is not null, "Can't pass in a null output buffer!"); Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input"); try @@ -190,7 +190,7 @@ private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flus internal bool Finish(byte[] outputBuffer, out int bytesRead) { - Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!"); + Debug.Assert(outputBuffer is not null, "Can't pass in a null output buffer!"); Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!"); ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead); @@ -202,7 +202,7 @@ internal bool Finish(byte[] outputBuffer, out int bytesRead) /// internal bool Flush(byte[] outputBuffer, out int bytesRead) { - Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!"); + Debug.Assert(outputBuffer is not null, "Can't pass in a null output buffer!"); Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!"); Debug.Assert(NeedsInput(), "We have something left in previous input!"); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Inflater.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Inflater.cs index f6d17eb58559d2..c100ef484b2533 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Inflater.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Inflater.cs @@ -62,7 +62,7 @@ public unsafe int Inflate(byte[] bytes, int offset, int length) if (length == 0) return 0; - Debug.Assert(null != bytes, "Can't pass in a null output buffer!"); + Debug.Assert(bytes is not null, "Can't pass in a null output buffer!"); fixed (byte* bufPtr = bytes) { return InflateVerified(bufPtr + offset, length); @@ -178,7 +178,7 @@ private unsafe bool ResetStreamForLeftoverInput() public void SetInput(byte[] inputBuffer, int startIndex, int count) { Debug.Assert(NeedsInput(), "We have something left in previous input!"); - Debug.Assert(inputBuffer != null); + Debug.Assert(inputBuffer is not null); Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length); Debug.Assert(!_inputBufferHandle.IsAllocated); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/GZipStream.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/GZipStream.cs index bbdf8b3dfe62e9..e21bfe9bfaa0eb 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/GZipStream.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/GZipStream.cs @@ -137,7 +137,7 @@ protected override void Dispose(bool disposing) { try { - if (disposing && _deflateStream != null) + if (disposing && _deflateStream is not null) { _deflateStream.Dispose(); } @@ -157,7 +157,7 @@ public override ValueTask DisposeAsync() } DeflateStream? ds = _deflateStream; - if (ds != null) + if (ds is not null) { _deflateStream = null!; return ds.DisposeAsync(); @@ -226,7 +226,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio private void CheckDeflateStream() { - if (_deflateStream == null) + if (_deflateStream is null) { ThrowStreamClosedException(); } 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 5fbd00c47006c3..68738302c99d96 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 @@ -82,14 +82,14 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(str /// UTF-8 encoding for entry names.
/// This value is used as follows: /// Reading (opening) ZIP archive files: - /// If entryNameEncoding is not specified (== null): + /// If entryNameEncoding is not specified (is null): /// /// For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is not set, /// use the current system default code page (Encoding.Default) in order to decode the entry name. /// For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is set, /// use UTF-8 (Encoding.UTF8) in order to decode the entry name. /// - /// If entryNameEncoding is specified (!= null): + /// If entryNameEncoding is specified (is not null): /// /// For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is not set, /// use the specified entryNameEncoding in order to decode the entry name. @@ -97,7 +97,7 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(str /// use UTF-8 (Encoding.UTF8) in order to decode the entry name. /// /// Writing (saving) ZIP archive files: - /// If entryNameEncoding is not specified (== null): + /// If entryNameEncoding is not specified (is null): /// /// For entry names that contain characters outside the ASCII range, /// the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header, @@ -106,7 +106,7 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(str /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header, /// and the current system default code page (Encoding.Default) will be used to encode the entry names into bytes. /// - /// If entryNameEncoding is specified (!= null): + /// If entryNameEncoding is specified (is not null): /// /// The specified entryNameEncoding will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only @@ -118,7 +118,7 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(str /// If a Unicode encoding other than UTF-8 is specified for the entryNameEncoding. public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding? entryNameEncoding) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); EntryNameEncoding = entryNameEncoding; @@ -204,7 +204,7 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding? } catch { - if (extraTempStream != null) + if (extraTempStream is not null) extraTempStream.Dispose(); throw; @@ -328,7 +328,7 @@ public void Dispose() /// A wrapper for the file entry in the archive. If no entry in the archive exists with the specified name, null will be returned. public ZipArchiveEntry? GetEntry(string entryName) { - if (entryName == null) + if (entryName is null) throw new ArgumentNullException(nameof(entryName)); if (_mode == ZipArchiveMode.Create) @@ -351,7 +351,7 @@ internal Encoding? EntryNameEncoding private set { - // value == null is fine. This means the user does not want to overwrite default encoding picking logic. + // value is null is fine. This means the user does not want to overwrite default encoding picking logic. // The Zip file spec [http://www.pkware.com/documents/casestudies/APPNOTE.TXT] specifies a bit in the entry header // (specifically: the language encoding flag (EFS) in the general purpose bit flag of the local file header) that @@ -366,7 +366,7 @@ private set // for something other tools do not support. If we realise in future that "something else" should include non-UTF8 // Unicode encodings, we can remove this restriction. - if (value != null && + if (value is not null && (value.Equals(Encoding.BigEndianUnicode) || value.Equals(Encoding.Unicode))) { @@ -379,7 +379,7 @@ private set private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compressionLevel) { - if (entryName == null) + if (entryName is null) throw new ArgumentNullException(nameof(entryName)); if (string.IsNullOrEmpty(entryName)) @@ -403,7 +403,7 @@ private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compre internal void AcquireArchiveStream(ZipArchiveEntry entry) { // if a previous entry had held the stream but never wrote anything, we write their local header for them - if (_archiveStreamOwner != null) + if (_archiveStreamOwner is not null) { if (!_archiveStreamOwner.EverOpenedForWrite) { @@ -465,7 +465,7 @@ private void CloseStreams() // if _backingStream isn't null, that means we assigned the original stream they passed // us to _backingStream (which they requested we leave open), and _archiveStream was // the temporary copy that we needed - if (_backingStream != null) + if (_backingStream is not null) _archiveStream.Dispose(); } } @@ -489,7 +489,7 @@ private void ReadCentralDirectory() long numberOfEntries = 0; - Debug.Assert(_archiveReader != null); + Debug.Assert(_archiveReader is not null); //read the central directory ZipCentralDirectoryFileHeader currentHeader; bool saveExtraFieldsAndComments = Mode == ZipArchiveMode.Update; @@ -530,7 +530,7 @@ private void ReadEndOfCentralDirectory() long eocdStart = _archiveStream.Position; - Debug.Assert(_archiveReader != null); + Debug.Assert(_archiveReader is not null); // read the EOCD ZipEndOfCentralDirectoryBlock eocd; bool eocdProper = ZipEndOfCentralDirectoryBlock.TryReadBlock(_archiveReader, out eocd); @@ -590,7 +590,7 @@ private void TryReadZip64EndOfCentralDirectory(ZipEndOfCentralDirectoryBlock eoc Zip64EndOfCentralDirectoryLocator.SignatureConstant, Zip64EndOfCentralDirectoryLocator.SignatureSize)) { - Debug.Assert(_archiveReader != null); + Debug.Assert(_archiveReader is not null); // use locator to get to Zip64-EOCD Zip64EndOfCentralDirectoryLocator locator; diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs index 2e78b222c28f06..f5a40758d55ddc 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs @@ -188,7 +188,7 @@ public string FullName [MemberNotNull(nameof(_storedEntryName))] private set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(FullName)); bool isUTF8; @@ -262,7 +262,7 @@ public long Length /// The ZipArchive that this entry belongs to has been disposed. public void Delete() { - if (_archive == null) + if (_archive is null) return; if (_currentlyOpenForWrite) @@ -322,9 +322,9 @@ private long OffsetOfCompressedData { get { - if (_storedOffsetOfCompressedData == null) + if (_storedOffsetOfCompressedData is null) { - Debug.Assert(_archive.ArchiveReader != null); + Debug.Assert(_archive.ArchiveReader is not null); _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); // by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength // to find start of data, but still using central directory size information @@ -340,7 +340,7 @@ private MemoryStream UncompressedData { get { - if (_storedUncompressedData == null) + if (_storedUncompressedData is null) { // this means we have never opened it before @@ -398,12 +398,12 @@ private CompressionMethodValues CompressionMethod private string DecodeEntryName(byte[] entryNameBytes) { - Debug.Assert(entryNameBytes != null); + Debug.Assert(entryNameBytes is not null); Encoding readEntryNameEncoding; if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0) { - readEntryNameEncoding = _archive == null ? + readEntryNameEncoding = _archive is null ? Encoding.UTF8 : _archive.EntryNameEncoding ?? Encoding.UTF8; } @@ -417,10 +417,10 @@ private string DecodeEntryName(byte[] entryNameBytes) private byte[] EncodeEntryName(string entryName, out bool isUTF8) { - Debug.Assert(entryName != null); + Debug.Assert(entryName is not null); Encoding writeEntryNameEncoding; - if (_archive != null && _archive.EntryNameEncoding != null) + if (_archive is not null && _archive.EntryNameEncoding is not null) writeEntryNameEncoding = _archive.EntryNameEncoding; else writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName) ? Encoding.UTF8 : Encoding.ASCII; @@ -504,7 +504,7 @@ internal void WriteCentralDirectoryFileHeader() // determine if we can fit zip64 extra field and original extra fields all in int bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0) - + (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0); + + (_cdUnknownExtraFields is not null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0); ushort extraFieldLength; if (bigExtraFieldLength > ushort.MaxValue) { @@ -530,9 +530,9 @@ internal void WriteCentralDirectoryFileHeader() writer.Write(extraFieldLength); // Extra Field Length (2 bytes) // This should hold because of how we read it originally in ZipCentralDirectoryFileHeader: - Debug.Assert((_fileComment == null) || (_fileComment.Length <= ushort.MaxValue)); + Debug.Assert((_fileComment is null) || (_fileComment.Length <= ushort.MaxValue)); - writer.Write(_fileComment != null ? (ushort)_fileComment.Length : (ushort)0); // file comment length + writer.Write(_fileComment is not null ? (ushort)_fileComment.Length : (ushort)0); // file comment length writer.Write((ushort)0); // disk number start writer.Write((ushort)0); // internal file attributes writer.Write(_externalFileAttr); // external file attributes @@ -543,10 +543,10 @@ internal void WriteCentralDirectoryFileHeader() // write extra fields if (zip64Needed) zip64ExtraField.WriteBlock(_archive.ArchiveStream); - if (_cdUnknownExtraFields != null) + if (_cdUnknownExtraFields is not null) ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream); - if (_fileComment != null) + if (_fileComment is not null) writer.Write(_fileComment); } @@ -562,7 +562,7 @@ internal bool LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded() { _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); - Debug.Assert(_archive.ArchiveReader != null); + Debug.Assert(_archive.ArchiveReader is not null); _lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader); } @@ -748,7 +748,7 @@ private bool IsOpenable(bool needToUncompress, bool needToLoadIntoMemory, out st message = SR.LocalFileHeaderCorrupt; return false; } - Debug.Assert(_archive.ArchiveReader != null); + Debug.Assert(_archive.ArchiveReader is not null); _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader)) { @@ -854,7 +854,7 @@ private bool WriteLocalFileHeader(bool isEmptyFile) // calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important int bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0) - + (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0); + + (_lhUnknownExtraFields is not null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0); ushort extraFieldLength; if (bigExtraFieldLength > ushort.MaxValue) { @@ -882,7 +882,7 @@ private bool WriteLocalFileHeader(bool isEmptyFile) if (zip64Used) zip64ExtraField.WriteBlock(_archive.ArchiveStream); - if (_lhUnknownExtraFields != null) + if (_lhUnknownExtraFields is not null) ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream); return zip64Used; @@ -891,9 +891,9 @@ private bool WriteLocalFileHeader(bool isEmptyFile) private void WriteLocalFileHeaderAndDataIfNeeded() { // _storedUncompressedData gets frozen here, and is what gets written to the file - if (_storedUncompressedData != null || _compressedBytes != null) + if (_storedUncompressedData is not null || _compressedBytes is not null) { - if (_storedUncompressedData != null) + if (_storedUncompressedData is not null) { _uncompressedSize = _storedUncompressedData.Length; @@ -922,7 +922,7 @@ private void WriteLocalFileHeaderAndDataIfNeeded() // according to ZIP specs, zero-byte files MUST NOT include file data if (_uncompressedSize != 0) { - Debug.Assert(_compressedBytes != null); + Debug.Assert(_compressedBytes is not null); foreach (byte[] compressedBytes in _compressedBytes) { _archive.ArchiveStream.Write(compressedBytes, 0, compressedBytes.Length); @@ -1046,7 +1046,7 @@ private void WriteDataDescriptor() private void UnloadStreams() { - if (_storedUncompressedData != null) + if (_storedUncompressedData is not null) _storedUncompressedData.Dispose(); _compressedBytes = null; _outstandingWriteStream = null; @@ -1055,7 +1055,7 @@ private void UnloadStreams() private void CloseStreams() { // if the user left the stream open, close the underlying stream for them - if (_outstandingWriteStream != null) + if (_outstandingWriteStream is not null) { _outstandingWriteStream.Dispose(); } @@ -1075,7 +1075,7 @@ private void VersionToExtractAtLeast(ZipVersionNeededValues value) private void ThrowIfInvalidArchive() { - if (_archive == null) + if (_archive is null) throw new InvalidOperationException(SR.DeletedEntry); _archive.ThrowIfDisposed(); } @@ -1185,7 +1185,7 @@ public override void SetLength(long value) public override void Write(byte[] buffer, int offset, int count) { //we can't pass the argument checking down a level - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentNeedNonNegative); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipBlocks.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipBlocks.cs index 058a8617dea61c..73c501b69c5788 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipBlocks.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipBlocks.cs @@ -120,10 +120,10 @@ public long? LocalHeaderOffset private void UpdateSize() { _size = 0; - if (_uncompressedSize != null) _size += 8; - if (_compressedSize != null) _size += 8; - if (_localHeaderOffset != null) _size += 8; - if (_startDiskNumber != null) _size += 4; + if (_uncompressedSize is not null) _size += 8; + if (_compressedSize is not null) _size += 8; + if (_localHeaderOffset is not null) _size += 8; + if (_startDiskNumber is not null) _size += 4; } // There is a small chance that something very weird could happen here. The code calling into this function @@ -221,7 +221,7 @@ private static bool TryGetZip64BlockFromGenericExtraField(ZipGenericExtraField e } finally { - if (ms != null) + if (ms is not null) ms.Dispose(); } } @@ -278,10 +278,10 @@ public void WriteBlock(Stream stream) BinaryWriter writer = new BinaryWriter(stream); writer.Write(TagConstant); writer.Write(_size); - if (_uncompressedSize != null) writer.Write(_uncompressedSize.Value); - if (_compressedSize != null) writer.Write(_compressedSize.Value); - if (_localHeaderOffset != null) writer.Write(_localHeaderOffset.Value); - if (_startDiskNumber != null) writer.Write(_startDiskNumber.Value); + if (_uncompressedSize is not null) writer.Write(_uncompressedSize.Value); + if (_compressedSize is not null) writer.Write(_compressedSize.Value); + if (_localHeaderOffset is not null) writer.Write(_localHeaderOffset.Value); + if (_startDiskNumber is not null) writer.Write(_startDiskNumber.Value); } } @@ -521,16 +521,16 @@ public static bool TryReadBlock(BinaryReader reader, bool saveExtraFieldsAndComm header.FileComment = null; } - header.UncompressedSize = zip64.UncompressedSize == null + header.UncompressedSize = zip64.UncompressedSize is null ? uncompressedSizeSmall : zip64.UncompressedSize.Value; - header.CompressedSize = zip64.CompressedSize == null + header.CompressedSize = zip64.CompressedSize is null ? compressedSizeSmall : zip64.CompressedSize.Value; - header.RelativeOffsetOfLocalHeader = zip64.LocalHeaderOffset == null + header.RelativeOffsetOfLocalHeader = zip64.LocalHeaderOffset is null ? relativeOffsetOfLocalHeaderSmall : zip64.LocalHeaderOffset.Value; - header.DiskNumberStart = zip64.StartDiskNumber == null + header.DiskNumberStart = zip64.StartDiskNumber is null ? diskNumberStartSmall : zip64.StartDiskNumber.Value; @@ -580,10 +580,10 @@ public static void WriteBlock(Stream stream, long numberOfEntries, long startOfC writer.Write(startOfCentralDirectoryTruncated); // Should be valid because of how we read archiveComment in TryReadBlock: - Debug.Assert((archiveComment == null) || (archiveComment.Length <= ZipFileCommentMaxLength)); + Debug.Assert((archiveComment is null) || (archiveComment.Length <= ZipFileCommentMaxLength)); - writer.Write(archiveComment != null ? (ushort)archiveComment.Length : (ushort)0); // zip file comment length - if (archiveComment != null) + writer.Write(archiveComment is not null ? (ushort)archiveComment.Length : (ushort)0); // zip file comment length + if (archiveComment is not null) writer.Write(archiveComment); } diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipCustomStreams.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipCustomStreams.cs index dd85b890d925df..f048874e7e968c 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipCustomStreams.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipCustomStreams.cs @@ -397,7 +397,7 @@ public override void SetLength(long value) public override void Write(byte[] buffer, int offset, int count) { // we can't pass the argument checking down a level - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentNeedNonNegative); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipHelper.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipHelper.cs index 06954526dca29f..29662fc74a7fd8 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipHelper.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipHelper.cs @@ -19,7 +19,7 @@ internal static class ZipHelper internal static bool RequiresUnicode(string test) { - Debug.Assert(test != null); + Debug.Assert(test is not null); foreach (char c in test) { diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs index 51b3f926ba5196..1543a963a6c7de 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs @@ -12,7 +12,7 @@ public static partial class FileSystemAclExtensions { public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo) { - if (directoryInfo == null) + if (directoryInfo is null) { throw new ArgumentNullException(nameof(directoryInfo)); } @@ -22,7 +22,7 @@ public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInf public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo, AccessControlSections includeSections) { - if (directoryInfo == null) + if (directoryInfo is null) { throw new ArgumentNullException(nameof(directoryInfo)); } @@ -32,7 +32,7 @@ public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInf public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity) { - if (directorySecurity == null) + if (directorySecurity is null) { throw new ArgumentNullException(nameof(directorySecurity)); } @@ -43,7 +43,7 @@ public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectoryS public static FileSecurity GetAccessControl(this FileInfo fileInfo) { - if (fileInfo == null) + if (fileInfo is null) { throw new ArgumentNullException(nameof(fileInfo)); } @@ -53,7 +53,7 @@ public static FileSecurity GetAccessControl(this FileInfo fileInfo) public static FileSecurity GetAccessControl(this FileInfo fileInfo, AccessControlSections includeSections) { - if (fileInfo == null) + if (fileInfo is null) { throw new ArgumentNullException(nameof(fileInfo)); } @@ -63,12 +63,12 @@ public static FileSecurity GetAccessControl(this FileInfo fileInfo, AccessContro public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSecurity) { - if (fileInfo == null) + if (fileInfo is null) { throw new ArgumentNullException(nameof(fileInfo)); } - if (fileSecurity == null) + if (fileSecurity is null) { throw new ArgumentNullException(nameof(fileSecurity)); } @@ -86,7 +86,7 @@ public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSec /// The file stream is closed. public static FileSecurity GetAccessControl(this FileStream fileStream) { - if (fileStream == null) + if (fileStream is null) { throw new ArgumentNullException(nameof(fileStream)); } @@ -109,12 +109,12 @@ public static FileSecurity GetAccessControl(this FileStream fileStream) /// The file stream is closed. public static void SetAccessControl(this FileStream fileStream, FileSecurity fileSecurity) { - if (fileStream == null) + if (fileStream is null) { throw new ArgumentNullException(nameof(fileStream)); } - if (fileSecurity == null) + if (fileSecurity is null) { throw new ArgumentNullException(nameof(fileSecurity)); } @@ -137,12 +137,12 @@ public static void SetAccessControl(this FileStream fileStream, FileSecurity fil /// This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.DirectoryInfo.Create(System.Security.AccessControl.DirectorySecurity)` .NET Framework method. public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity) { - if (directoryInfo == null) + if (directoryInfo is null) { throw new ArgumentNullException(nameof(directoryInfo)); } - if (directorySecurity == null) + if (directorySecurity is null) { throw new ArgumentNullException(nameof(directorySecurity)); } @@ -172,12 +172,12 @@ public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity di /// This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.FileStream.#ctor(System.String,System.IO.FileMode,System.Security.AccessControl.FileSystemRights,System.IO.FileShare,System.Int32,System.IO.FileOptions,System.Security.AccessControl.FileSecurity)` .NET Framework constructor. public static FileStream Create(this FileInfo fileInfo, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity) { - if (fileInfo == null) + if (fileInfo is null) { throw new ArgumentNullException(nameof(fileInfo)); } - if (fileSecurity == null) + if (fileSecurity is null) { throw new ArgumentNullException(nameof(fileSecurity)); } @@ -234,12 +234,12 @@ public static FileStream Create(this FileInfo fileInfo, FileMode mode, FileSyste /// This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.Directory.CreateDirectory(System.String,System.Security.AccessControl.DirectorySecurity)` .NET Framework method. public static DirectoryInfo CreateDirectory(this DirectorySecurity directorySecurity, string path) { - if (directorySecurity == null) + if (directorySecurity is null) { throw new ArgumentNullException(nameof(directorySecurity)); } - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -276,7 +276,7 @@ private static FileAccess GetFileStreamFileAccess(FileSystemRights rights) private static unsafe SafeFileHandle CreateFileHandle(string fullPath, FileMode mode, FileSystemRights rights, FileShare share, FileOptions options, FileSecurity security) { - Debug.Assert(fullPath != null); + Debug.Assert(fullPath is not null); // Must use a valid Win32 constant if (mode == FileMode.Append) diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.net46.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.net46.cs index 5fdb118b406dae..88c01afb27f9d2 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.net46.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.net46.cs @@ -9,10 +9,10 @@ public static class FileSystemAclExtensions { public static FileStream Create(this FileInfo fileInfo, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity) { - if (fileInfo == null) + if (fileInfo is null) throw new ArgumentNullException(nameof(fileInfo)); - if (fileSecurity == null) + if (fileSecurity is null) throw new ArgumentNullException(nameof(fileSecurity)); return new FileStream(fileInfo.FullName, mode, rights, share, bufferSize, options, fileSecurity); @@ -20,10 +20,10 @@ public static FileStream Create(this FileInfo fileInfo, FileMode mode, FileSyste public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity) { - if (directoryInfo == null) + if (directoryInfo is null) throw new ArgumentNullException(nameof(directoryInfo)); - if (directorySecurity == null) + if (directorySecurity is null) throw new ArgumentNullException(nameof(directorySecurity)); directoryInfo.Create(directorySecurity); @@ -31,10 +31,10 @@ public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity di public static DirectoryInfo CreateDirectory(this DirectorySecurity directorySecurity, string path) { - if (directorySecurity == null) + if (directorySecurity is null) throw new ArgumentNullException(nameof(directorySecurity)); - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) @@ -45,7 +45,7 @@ public static DirectoryInfo CreateDirectory(this DirectorySecurity directorySecu public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo) { - if (directoryInfo == null) + if (directoryInfo is null) throw new ArgumentNullException(nameof(directoryInfo)); return directoryInfo.GetAccessControl(); @@ -53,7 +53,7 @@ public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInf public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo, AccessControlSections includeSections) { - if (directoryInfo == null) + if (directoryInfo is null) throw new ArgumentNullException(nameof(directoryInfo)); return directoryInfo.GetAccessControl(includeSections); @@ -61,10 +61,10 @@ public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInf public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity) { - if (directoryInfo == null) + if (directoryInfo is null) throw new ArgumentNullException(nameof(directoryInfo)); - if (directorySecurity == null) + if (directorySecurity is null) throw new ArgumentNullException(nameof(directorySecurity)); directoryInfo.SetAccessControl(directorySecurity); @@ -72,7 +72,7 @@ public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectoryS public static FileSecurity GetAccessControl(this FileInfo fileInfo) { - if (fileInfo == null) + if (fileInfo is null) throw new ArgumentNullException(nameof(fileInfo)); return fileInfo.GetAccessControl(); @@ -80,7 +80,7 @@ public static FileSecurity GetAccessControl(this FileInfo fileInfo) public static FileSecurity GetAccessControl(this FileInfo fileInfo, AccessControlSections includeSections) { - if (fileInfo == null) + if (fileInfo is null) throw new ArgumentNullException(nameof(fileInfo)); return fileInfo.GetAccessControl(includeSections); @@ -88,10 +88,10 @@ public static FileSecurity GetAccessControl(this FileInfo fileInfo, AccessContro public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSecurity) { - if (fileInfo == null) + if (fileInfo is null) throw new ArgumentNullException(nameof(fileInfo)); - if (fileSecurity == null) + if (fileSecurity is null) throw new ArgumentNullException(nameof(fileSecurity)); fileInfo.SetAccessControl(fileSecurity); @@ -99,7 +99,7 @@ public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSec public static FileSecurity GetAccessControl(this FileStream fileStream) { - if (fileStream == null) + if (fileStream is null) throw new ArgumentNullException(nameof(fileStream)); return fileStream.GetAccessControl(); @@ -107,10 +107,10 @@ public static FileSecurity GetAccessControl(this FileStream fileStream) public static void SetAccessControl(this FileStream fileStream, FileSecurity fileSecurity) { - if (fileStream == null) + if (fileStream is null) throw new ArgumentNullException(nameof(fileStream)); - if (fileSecurity == null) + if (fileSecurity is null) throw new ArgumentNullException(nameof(fileSecurity)); fileStream.SetAccessControl(fileSecurity); diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs index 6b1956aeb23520..f2f24a9cb557bc 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs @@ -20,7 +20,7 @@ protected DirectoryObjectSecurity() protected DirectoryObjectSecurity(CommonSecurityDescriptor securityDescriptor) : base(securityDescriptor) { - if (securityDescriptor == null) + if (securityDescriptor is null) { throw new ArgumentNullException(nameof(securityDescriptor)); } @@ -75,7 +75,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, } } - if (acl == null) + if (acl is null) { // // The required ACL was not present; return an empty collection. @@ -102,7 +102,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, // QualifiedAce? ace = acl[i] as QualifiedAce; - if (ace == null) + if (ace is null) { // // Only consider qualified ACEs @@ -152,10 +152,10 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, // QualifiedAce? ace = acl[i] as CommonAce; - if (ace == null) + if (ace is null) { ace = acl[i] as ObjectAce; - if (ace == null) + if (ace is null) { // // Only consider common or object ACEs @@ -212,7 +212,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, { CommonAce? commonAce = ace as CommonAce; - if (commonAce == null) + if (commonAce is null) { continue; } @@ -230,7 +230,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, { CommonAce? commonAce = ace as CommonAce; - if (commonAce == null) + if (commonAce is null) { continue; } @@ -256,7 +256,7 @@ private bool ModifyAccess(AccessControlModification modification, ObjectAccessRu { bool result = true; - if (SecurityDescriptor.DiscretionaryAcl == null) + if (SecurityDescriptor.DiscretionaryAcl is null) { if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || modification == AccessControlModification.RemoveSpecific) { @@ -289,7 +289,7 @@ private bool ModifyAccess(AccessControlModification modification, ObjectAccessRu SecurityIdentifier sid = (SecurityIdentifier)rule.IdentityReference.Translate(typeof(SecurityIdentifier)); - Debug.Assert(SecurityDescriptor.DiscretionaryAcl != null); + Debug.Assert(SecurityDescriptor.DiscretionaryAcl is not null); if (rule.AccessControlType == AccessControlType.Allow) { switch (modification) @@ -397,7 +397,7 @@ private bool ModifyAudit(AccessControlModification modification, ObjectAuditRule { bool result = true; - if (SecurityDescriptor.SystemAcl == null) + if (SecurityDescriptor.SystemAcl is null) { if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || modification == AccessControlModification.RemoveSpecific) { @@ -430,7 +430,7 @@ private bool ModifyAudit(AccessControlModification modification, ObjectAuditRule SecurityIdentifier sid = (SecurityIdentifier)rule.IdentityReference.Translate(typeof(SecurityIdentifier)); - Debug.Assert(SecurityDescriptor.SystemAcl != null); + Debug.Assert(SecurityDescriptor.SystemAcl is not null); switch (modification) { case AccessControlModification.Add: @@ -522,7 +522,7 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi protected void AddAccessRule(ObjectAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -544,7 +544,7 @@ protected void AddAccessRule(ObjectAccessRule rule) protected void SetAccessRule(ObjectAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -564,7 +564,7 @@ protected void SetAccessRule(ObjectAccessRule rule) protected void ResetAccessRule(ObjectAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -584,7 +584,7 @@ protected void ResetAccessRule(ObjectAccessRule rule) protected bool RemoveAccessRule(ObjectAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -593,7 +593,7 @@ protected bool RemoveAccessRule(ObjectAccessRule rule) try { - if (SecurityDescriptor == null) + if (SecurityDescriptor is null) { return true; } @@ -609,7 +609,7 @@ protected bool RemoveAccessRule(ObjectAccessRule rule) protected void RemoveAccessRuleAll(ObjectAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -618,7 +618,7 @@ protected void RemoveAccessRuleAll(ObjectAccessRule rule) try { - if (SecurityDescriptor == null) + if (SecurityDescriptor is null) { return; } @@ -634,12 +634,12 @@ protected void RemoveAccessRuleAll(ObjectAccessRule rule) protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } - if (SecurityDescriptor == null) + if (SecurityDescriptor is null) { return; } @@ -659,7 +659,7 @@ protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) protected void AddAuditRule(ObjectAuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -679,7 +679,7 @@ protected void AddAuditRule(ObjectAuditRule rule) protected void SetAuditRule(ObjectAuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -699,7 +699,7 @@ protected void SetAuditRule(ObjectAuditRule rule) protected bool RemoveAuditRule(ObjectAuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -719,7 +719,7 @@ protected bool RemoveAuditRule(ObjectAuditRule rule) protected void RemoveAuditRuleAll(ObjectAuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -739,7 +739,7 @@ protected void RemoveAuditRuleAll(ObjectAuditRule rule) protected void RemoveAuditRuleSpecific(ObjectAuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs index 27cd96a664a55b..092982b2748220 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs @@ -42,17 +42,17 @@ internal FileSystemSecurity(bool isContainer, SafeFileHandle? handle, AccessCont break; case Interop.Errors.ERROR_FILE_NOT_FOUND: - if ((context != null) && (context is bool) && ((bool)context)) + if ((context is not null) && (context is bool) && ((bool)context)) { // DirectorySecurity - if ((name != null) && (name.Length != 0)) + if ((name is not null) && (name.Length != 0)) exception = new DirectoryNotFoundException(name); else exception = new DirectoryNotFoundException(); } else { - if ((name != null) && (name.Length != 0)) + if ((name is not null) && (name.Length != 0)) exception = new FileNotFoundException(name); else exception = new FileNotFoundException(); @@ -164,7 +164,7 @@ public void ResetAccessRule(FileSystemAccessRule rule) public bool RemoveAccessRule(FileSystemAccessRule rule) { - if (rule == null) + if (rule is null) throw new ArgumentNullException(nameof(rule)); // If the rule to be removed matches what is there currently then @@ -208,7 +208,7 @@ public void RemoveAccessRuleAll(FileSystemAccessRule rule) public void RemoveAccessRuleSpecific(FileSystemAccessRule rule) { - if (rule == null) + if (rule is null) throw new ArgumentNullException(nameof(rule)); // If the rule to be removed matches what is there currently then diff --git a/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs b/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs index be8aaa27069ccc..582b6ae3ce9e28 100644 --- a/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs +++ b/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs @@ -11,7 +11,7 @@ public sealed partial class DriveInfo : ISerializable public DriveInfo(string driveName) { - if (driveName == null) + if (driveName is null) { throw new ArgumentNullException(nameof(driveName)); } diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs index ed4f1639d07a73..a8eb43e5670c11 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs @@ -26,7 +26,7 @@ private void StartRaisingEvents() } // If we already have a cancellation object, we're already running. - if (_cancellation != null) + if (_cancellation is not null) { return; } @@ -94,7 +94,7 @@ private void StopRaisingEvents() // The cancellation token and the processing task respond to cancellation // to handle all other cleanup. var cts = _cancellation; - if (cts != null) + if (cts is not null) { _cancellation = null; cts.Cancel(); @@ -273,15 +273,15 @@ internal RunningInstance( FileSystemWatcher watcher, SafeFileHandle inotifyHandle, string directoryPath, bool includeSubdirectories, NotifyFilters notifyFilters, CancellationToken cancellationToken) { - Debug.Assert(watcher != null); - Debug.Assert(inotifyHandle != null && !inotifyHandle.IsInvalid && !inotifyHandle.IsClosed); - Debug.Assert(directoryPath != null); + Debug.Assert(watcher is not null); + Debug.Assert(inotifyHandle is not null && !inotifyHandle.IsInvalid && !inotifyHandle.IsClosed); + Debug.Assert(directoryPath is not null); _weakWatcher = new WeakReference(watcher); _inotifyHandle = inotifyHandle; _directoryPath = directoryPath; _buffer = watcher.AllocateBuffer(); - Debug.Assert(_buffer != null && _buffer.Length > (c_INotifyEventSize + NAME_MAX + 1)); + Debug.Assert(_buffer is not null && _buffer.Length > (c_INotifyEventSize + NAME_MAX + 1)); _includeSubdirectories = includeSubdirectories; _notifyFilters = notifyFilters; _watchFilters = TranslateFilters(notifyFilters); @@ -321,9 +321,9 @@ private void AddDirectoryWatch(WatchedDirectory parent, string directoryName) // against the handle, so we'd deadlock if we relied on that approach. Instead, we want to follow // the approach of removing all watches when we're done, which means we also don't want to // add any new watches once the count hits zero. - if (parent == null || _wdToPathMap.Count > 0) + if (parent is null || _wdToPathMap.Count > 0) { - Debug.Assert(parent != null || _wdToPathMap.Count == 0); + Debug.Assert(parent is not null || _wdToPathMap.Count == 0); AddDirectoryWatchUnlocked(parent, directoryName); } } @@ -334,7 +334,7 @@ private void AddDirectoryWatch(WatchedDirectory parent, string directoryName) /// The new directory path to monitor, relative to the root. private void AddDirectoryWatchUnlocked(WatchedDirectory? parent, string directoryName) { - string fullPath = parent != null ? parent.GetPath(false, directoryName) : directoryName; + string fullPath = parent is not null ? parent.GetPath(false, directoryName) : directoryName; // inotify_add_watch will fail if this is a symlink, so check that we didn't get a symlink Interop.Sys.FileStatus status = default(Interop.Sys.FileStatus); @@ -391,13 +391,13 @@ private void AddDirectoryWatchUnlocked(WatchedDirectory? parent, string director if (directoryEntry.Parent != parent) { // Work around https://github.com/dotnet/csharplang/issues/3393 preventing Parent?.Children!. from behaving as expected - if (directoryEntry.Parent != null) + if (directoryEntry.Parent is not null) { directoryEntry.Parent.Children!.Remove(directoryEntry); } directoryEntry.Parent = parent; - if (parent != null) + if (parent is not null) { parent.InitializedChildren.Add (directoryEntry); } @@ -413,7 +413,7 @@ private void AddDirectoryWatchUnlocked(WatchedDirectory? parent, string director WatchDescriptor = wd, Name = directoryName }; - if (parent != null) + if (parent is not null) { parent.InitializedChildren.Add (directoryEntry); } @@ -449,7 +449,7 @@ private void RemoveWatchedDirectory(WatchedDirectory directoryEntry, bool remove lock (SyncObj) { // Work around https://github.com/dotnet/csharplang/issues/3393 preventing Parent?.Children!. from behaving as expected - if (directoryEntry.Parent != null) + if (directoryEntry.Parent is not null) { directoryEntry.Parent.Children!.Remove(directoryEntry); } @@ -464,7 +464,7 @@ private void RemoveWatchedDirectory(WatchedDirectory directoryEntry, bool remove private void RemoveWatchedDirectoryUnlocked(WatchedDirectory directoryEntry, bool removeInotify) { // If the directory has children, recursively remove them (see comments on recursion in AddDirectoryWatch). - if (directoryEntry.Children != null) + if (directoryEntry.Children is not null) { foreach (WatchedDirectory child in directoryEntry.Children) { @@ -598,7 +598,7 @@ private void ProcessEvents() // should be considered a deletion to match Win32 behavior. // But since we explicitly added watches on directories, if it's a directory it'll // still be watched, so we need to explicitly remove the watch. - if (previousEventParent != null && previousEventParent.Children != null) + if (previousEventParent is not null && previousEventParent.Children is not null) { // previousEventParent will be non-null iff the IN_MOVED_FROM // was for a directory, in which case previousEventParent is that directory's @@ -744,7 +744,7 @@ private void ProcessEvents() /// if event was read successfully, otherwise. private bool TryReadEvent(out NotifyEvent notifyEvent) { - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); Debug.Assert(_buffer.Length > 0); Debug.Assert(_bufferAvailable >= 0 && _bufferAvailable <= _buffer.Length); Debug.Assert(_bufferPos >= 0 && _bufferPos <= _bufferAvailable); @@ -889,7 +889,7 @@ internal string GetPath(bool relativeToRoot, string? additionalName = null) // Write the directory's path. Then if an additional filename was supplied, append it Write(builder, relativeToRoot); - if (additionalName != null) + if (additionalName is not null) { AppendSeparatorIfNeeded(builder); builder.Append(additionalName); @@ -913,7 +913,7 @@ private void Write(StringBuilder builder, bool relativeToRoot) // and max path limits. // First append the parent's path - if (Parent != null) + if (Parent is not null) { Parent.Write(builder, relativeToRoot); AppendSeparatorIfNeeded(builder); @@ -922,7 +922,7 @@ private void Write(StringBuilder builder, bool relativeToRoot) // Then append ours. In the case of the root directory // being watched, we only append its name if the caller // has asked for a full path. - if (Parent != null || !relativeToRoot) + if (Parent is not null || !relativeToRoot) { builder.Append(Name); } diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs index 3e07cea34d5467..8076b9b7d7d6cc 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs @@ -37,7 +37,7 @@ private void StartRaisingEvents() } // Don't start another instance if one is already runnings - if (_cancellation != null) + if (_cancellation is not null) { return; } @@ -67,7 +67,7 @@ private void StopRaisingEvents() return; CancellationTokenSource? token = _cancellation; - if (token != null) + if (token is not null) { _cancellation = null; token.Cancel(); @@ -264,7 +264,7 @@ private static void WatchForFileSystemEventsThreadStart(ManualResetEventSlim run private void CleanupEventStream() { SafeEventStreamHandle? eventStream = Interlocked.Exchange(ref _eventStream, null); - if (eventStream != null) + if (eventStream is not null) { _cancellationRegistration.Unregister(); try @@ -476,7 +476,7 @@ private unsafe void ProcessEvents(int numEvents, static ParsedEvent ParseEvent(byte* nativeEventPath) { int byteCount = 0; - Debug.Assert(nativeEventPath != null); + Debug.Assert(nativeEventPath is not null); byte* temp = nativeEventPath; // Finds the position of null character. diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs index 96d601de841b8b..7f87590f2f61a1 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs @@ -126,7 +126,7 @@ private void FinalizeDispose() private static bool IsHandleInvalid([NotNullWhen(false)] SafeFileHandle? handle) { - return handle == null || handle.IsInvalid || handle.IsClosed; + return handle is null || handle.IsInvalid || handle.IsClosed; } /// @@ -136,7 +136,7 @@ private static bool IsHandleInvalid([NotNullWhen(false)] SafeFileHandle? handle) /// private unsafe void Monitor(AsyncReadState state) { - Debug.Assert(state.PreAllocatedOverlapped != null); + Debug.Assert(state.PreAllocatedOverlapped is not null); // This method should only ever access the directory handle via the state object passed in, and not access it // via _directoryHandle. While this function is executing asynchronously, another thread could set @@ -183,7 +183,7 @@ private unsafe void Monitor(AsyncReadState state) if (!continueExecuting) { // Clean up the overlapped pointer created for this iteration - if (overlappedPointer != null) + if (overlappedPointer is not null) { state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); } @@ -372,10 +372,10 @@ private sealed class AsyncReadState { internal AsyncReadState(int session, byte[] buffer, SafeFileHandle handle, ThreadPoolBoundHandle binding, FileSystemWatcher parent) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(buffer.Length > 0); - Debug.Assert(handle != null); - Debug.Assert(binding != null); + Debug.Assert(handle is not null); + Debug.Assert(binding is not null); Session = session; Buffer = buffer; diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs index 16bdbb1074ce59..24fe760a4ffa95 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs @@ -248,7 +248,7 @@ public string Path } set { - value = (value == null) ? string.Empty : value; + value = (value is null) ? string.Empty : value; if (!string.Equals(_directory, value, PathInternal.StringComparison)) { if (value.Length == 0) @@ -370,7 +370,7 @@ protected override void Dispose(bool disposing) private static void CheckPathValidity(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); // Early check for directory parameter so that an exception can be thrown as early as possible. @@ -419,7 +419,7 @@ private void NotifyRenameEventArgs(WatcherChangeTypes action, ReadOnlySpan { // filter if there's no handler or neither new name or old name match a specified pattern RenamedEventHandler? handler = _onRenamedHandler; - if (handler != null && + if (handler is not null && (MatchPattern(name) || MatchPattern(oldName))) { handler(this, new RenamedEventArgs(action, _directory, name.IsEmpty ? null : name.ToString(), oldName.IsEmpty ? null : oldName.ToString())); @@ -449,7 +449,7 @@ private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, ReadOnlySp { FileSystemEventHandler? handler = GetHandler(changeType); - if (handler != null && MatchPattern(name.IsEmpty ? _directory : name)) + if (handler is not null && MatchPattern(name.IsEmpty ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name.IsEmpty ? null : name.ToString())); } @@ -462,7 +462,7 @@ private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string nam { FileSystemEventHandler? handler = GetHandler(changeType); - if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name)) + if (handler is not null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name)); } @@ -494,10 +494,10 @@ protected void OnDeleted(FileSystemEventArgs e) private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler? handler) { - if (handler != null) + if (handler is not null) { ISynchronizeInvoke? syncObj = SynchronizingObject; - if (syncObj != null && syncObj.InvokeRequired) + if (syncObj is not null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); @@ -510,10 +510,10 @@ private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler? handler) protected void OnError(ErrorEventArgs e) { ErrorEventHandler? handler = _onErrorHandler; - if (handler != null) + if (handler is not null) { ISynchronizeInvoke? syncObj = SynchronizingObject; - if (syncObj != null && syncObj.InvokeRequired) + if (syncObj is not null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); @@ -526,10 +526,10 @@ protected void OnError(ErrorEventArgs e) protected void OnRenamed(RenamedEventArgs e) { RenamedEventHandler? handler = _onRenamedHandler; - if (handler != null) + if (handler is not null) { ISynchronizeInvoke? syncObj = SynchronizingObject; - if (syncObj != null && syncObj.InvokeRequired) + if (syncObj is not null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); @@ -596,11 +596,11 @@ public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int ti finally { // Unregister the event handlers. - if (reh != null) + if (reh is not null) { Renamed -= reh; } - if (fseh != null) + if (fseh is not null) { if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh; @@ -650,7 +650,7 @@ public override ISite? Site // set EnableRaisingEvents to true at design time so the user // doesn't have to manually. - if (Site != null && Site.DesignMode) + if (Site is not null && Site.DesignMode) EnableRaisingEvents = true; } } diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/Directory.cs b/src/libraries/System.IO.FileSystem/src/System/IO/Directory.cs index 4139de67fb83b9..47b8bff1445ec8 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/Directory.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/Directory.cs @@ -20,7 +20,7 @@ public static partial class Directory { public static DirectoryInfo? GetParent(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) @@ -29,14 +29,14 @@ public static partial class Directory string fullPath = Path.GetFullPath(path); string? s = Path.GetDirectoryName(fullPath); - if (s == null) + if (s is null) return null; return new DirectoryInfo(s); } public static DirectoryInfo CreateDirectory(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); @@ -53,7 +53,7 @@ public static bool Exists(string? path) { try { - if (path == null) + if (path is null) return false; if (path.Length == 0) return false; @@ -171,9 +171,9 @@ internal static IEnumerable InternalEnumeratePaths( SearchTarget searchTarget, EnumerationOptions options) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (searchPattern == null) + if (searchPattern is null) throw new ArgumentNullException(nameof(searchPattern)); FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType); @@ -222,7 +222,7 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string public static string GetDirectoryRoot(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); string fullPath = Path.GetFullPath(path); @@ -235,7 +235,7 @@ public static string GetDirectoryRoot(string path) public static void SetCurrentDirectory(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); @@ -245,12 +245,12 @@ public static void SetCurrentDirectory(string path) public static void Move(string sourceDirName, string destDirName) { - if (sourceDirName == null) + if (sourceDirName is null) throw new ArgumentNullException(nameof(sourceDirName)); if (sourceDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceDirName)); - if (destDirName == null) + if (destDirName is null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs b/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs index 80a44bd3ad926c..c0b713e5c3d2fe 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs @@ -57,7 +57,7 @@ public DirectoryInfo? Parent // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. string? parentName = Path.GetDirectoryName(PathInternal.IsRoot(FullPath.AsSpan()) ? FullPath : Path.TrimEndingDirectorySeparator(FullPath)); - return parentName != null ? + return parentName is not null ? new DirectoryInfo(parentName, isNormalized: true) : null; } @@ -65,7 +65,7 @@ public DirectoryInfo? Parent public DirectoryInfo CreateSubdirectory(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); @@ -177,8 +177,8 @@ private IEnumerable InternalEnumerateInfos( SearchTarget searchTarget, EnumerationOptions options) { - Debug.Assert(path != null); - if (searchPattern == null) + Debug.Assert(path is not null); + if (searchPattern is null) throw new ArgumentNullException(nameof(searchPattern)); _isNormalized &= FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType); @@ -196,7 +196,7 @@ private IEnumerable InternalEnumerateInfos( public void MoveTo(string destDirName) { - if (destDirName == null) + if (destDirName is null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs b/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs index 95bb53f43ba8f6..1481ada45e2a00 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs @@ -107,7 +107,7 @@ public bool MoveNext() { do { - FindNextEntry(entryBufferPtr, _entryBuffer == null ? 0 : _entryBuffer.Length); + FindNextEntry(entryBufferPtr, _entryBuffer is null ? 0 : _entryBuffer.Length); if (_lastEntryFound) return false; @@ -147,7 +147,7 @@ public bool MoveNext() if (_options.RecurseSubdirectories && ShouldRecurseIntoEntry(ref entry)) { // Recursion is on and the directory was accepted, Queue it - if (_pending == null) + if (_pending is null) _pending = new Queue(); _pending.Enqueue(Path.Join(_currentPath, entry.FileName)); } @@ -167,7 +167,7 @@ private unsafe void FindNextEntry() { fixed (byte* entryBufferPtr = _entryBuffer) { - FindNextEntry(entryBufferPtr, _entryBuffer == null ? 0 : _entryBuffer.Length); + FindNextEntry(entryBufferPtr, _entryBuffer is null ? 0 : _entryBuffer.Length); } } @@ -212,7 +212,7 @@ private bool DequeueNextDirectory() while (_directoryHandle == IntPtr.Zero) { - if (_pending == null || _pending.Count == 0) + if (_pending is null || _pending.Count == 0) return false; _currentPath = _pending.Dequeue(); @@ -225,7 +225,7 @@ private bool DequeueNextDirectory() private void InternalDispose(bool disposing) { // It is possible to fail to allocate the lock, but the finalizer will still run - if (_lock != null) + if (_lock is not null) { lock (_lock) { @@ -234,10 +234,10 @@ private void InternalDispose(bool disposing) CloseDirectoryHandle(); - if (_pathBuffer != null) + if (_pathBuffer is not null) ArrayPool.Shared.Return(_pathBuffer); _pathBuffer = null; - if (_entryBuffer != null) + if (_entryBuffer is not null) ArrayPool.Shared.Return(_entryBuffer); _entryBuffer = null; } diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs b/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs index 32fd206ea897df..0343875a2134a2 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs @@ -170,7 +170,7 @@ public bool MoveNext() { try { - if (_pending == null) + if (_pending is null) _pending = new Queue<(IntPtr, string)>(); _pending.Enqueue((subDirectoryHandle, subDirectory)); } @@ -196,7 +196,7 @@ public bool MoveNext() private unsafe void FindNextEntry() { _entry = Interop.NtDll.FILE_FULL_DIR_INFORMATION.GetNextInfo(_entry); - if (_entry != null) + if (_entry is not null) return; // We need more data @@ -206,7 +206,7 @@ private unsafe void FindNextEntry() private bool DequeueNextDirectory() { - if (_pending == null || _pending.Count == 0) + if (_pending is null || _pending.Count == 0) return false; (_directoryHandle, _currentPath) = _pending.Dequeue(); @@ -216,7 +216,7 @@ private bool DequeueNextDirectory() private void InternalDispose(bool disposing) { // It is possible to fail to allocate the lock, but the finalizer will still run - if (_lock != null) + if (_lock is not null) { lock (_lock) { @@ -224,7 +224,7 @@ private void InternalDispose(bool disposing) CloseDirectoryHandle(); - if (_pending != null) + if (_pending is not null) { while (_pending.Count > 0) Interop.Kernel32.CloseHandle(_pending.Dequeue().Handle); diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/File.cs b/src/libraries/System.IO.FileSystem/src/System/IO/File.cs index 1b089a91ffc883..1bf4ad77c1e1f8 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/File.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/File.cs @@ -29,7 +29,7 @@ public static class File public static StreamReader OpenText(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); return new StreamReader(path); @@ -37,7 +37,7 @@ public static StreamReader OpenText(string path) public static StreamWriter CreateText(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); return new StreamWriter(path, append: false); @@ -45,7 +45,7 @@ public static StreamWriter CreateText(string path) public static StreamWriter AppendText(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); return new StreamWriter(path, append: true); @@ -65,9 +65,9 @@ public static void Copy(string sourceFileName, string destFileName) /// public static void Copy(string sourceFileName, string destFileName, bool overwrite) { - if (sourceFileName == null) + if (sourceFileName is null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); - if (destFileName == null) + if (destFileName is null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); @@ -104,7 +104,7 @@ public static FileStream Create(string path, int bufferSize, FileOptions options // or a file that is memory mapped. public static void Delete(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); FileSystem.DeleteFile(Path.GetFullPath(path)); @@ -118,7 +118,7 @@ public static bool Exists(string? path) { try { - if (path == null) + if (path is null) return false; if (path.Length == 0) return false; @@ -128,7 +128,7 @@ public static bool Exists(string? path) // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null - Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); + Debug.Assert(path is not null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return false; @@ -267,7 +267,7 @@ public static FileStream OpenWrite(string path) public static string ReadAllText(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -277,9 +277,9 @@ public static string ReadAllText(string path) public static string ReadAllText(string path, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -289,8 +289,8 @@ public static string ReadAllText(string path, Encoding encoding) private static string InternalReadAllText(string path, Encoding encoding) { - Debug.Assert(path != null); - Debug.Assert(encoding != null); + Debug.Assert(path is not null); + Debug.Assert(encoding is not null); Debug.Assert(path.Length > 0); using (StreamReader sr = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true)) @@ -299,7 +299,7 @@ private static string InternalReadAllText(string path, Encoding encoding) public static void WriteAllText(string path, string? contents) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -312,9 +312,9 @@ public static void WriteAllText(string path, string? contents) public static void WriteAllText(string path, string? contents, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -379,7 +379,7 @@ private static byte[] ReadAllBytesUnknownLength(FileStream fs) byte[] tmp = ArrayPool.Shared.Rent((int)newLength); buffer.CopyTo(tmp); - if (rentedArray != null) + if (rentedArray is not null) { ArrayPool.Shared.Return(rentedArray); } @@ -397,7 +397,7 @@ private static byte[] ReadAllBytesUnknownLength(FileStream fs) } finally { - if (rentedArray != null) + if (rentedArray is not null) { ArrayPool.Shared.Return(rentedArray); } @@ -407,11 +407,11 @@ private static byte[] ReadAllBytesUnknownLength(FileStream fs) public static void WriteAllBytes(string path, byte[] bytes) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes)); InternalWriteAllBytes(path, bytes); @@ -419,9 +419,9 @@ public static void WriteAllBytes(string path, byte[] bytes) private static void InternalWriteAllBytes(string path, byte[] bytes) { - Debug.Assert(path != null); + Debug.Assert(path is not null); Debug.Assert(path.Length != 0); - Debug.Assert(bytes != null); + Debug.Assert(bytes is not null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { @@ -430,7 +430,7 @@ private static void InternalWriteAllBytes(string path, byte[] bytes) } public static string[] ReadAllLines(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -440,9 +440,9 @@ public static string[] ReadAllLines(string path) public static string[] ReadAllLines(string path, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -452,15 +452,15 @@ public static string[] ReadAllLines(string path, Encoding encoding) private static string[] InternalReadAllLines(string path, Encoding encoding) { - Debug.Assert(path != null); - Debug.Assert(encoding != null); + Debug.Assert(path is not null); + Debug.Assert(encoding is not null); Debug.Assert(path.Length != 0); string? line; List lines = new List(); using (StreamReader sr = new StreamReader(path, encoding)) - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) lines.Add(line); return lines.ToArray(); @@ -468,7 +468,7 @@ private static string[] InternalReadAllLines(string path, Encoding encoding) public static IEnumerable ReadLines(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -478,9 +478,9 @@ public static IEnumerable ReadLines(string path) public static IEnumerable ReadLines(string path, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -495,9 +495,9 @@ public static void WriteAllLines(string path, string[] contents) public static void WriteAllLines(string path, IEnumerable contents) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (contents == null) + if (contents is null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -512,11 +512,11 @@ public static void WriteAllLines(string path, string[] contents, Encoding encodi public static void WriteAllLines(string path, IEnumerable contents, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (contents == null) + if (contents is null) throw new ArgumentNullException(nameof(contents)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -526,8 +526,8 @@ public static void WriteAllLines(string path, IEnumerable contents, Enco private static void InternalWriteAllLines(TextWriter writer, IEnumerable contents) { - Debug.Assert(writer != null); - Debug.Assert(contents != null); + Debug.Assert(writer is not null); + Debug.Assert(contents is not null); using (writer) { @@ -540,7 +540,7 @@ private static void InternalWriteAllLines(TextWriter writer, IEnumerable public static void AppendAllText(string path, string? contents) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -553,9 +553,9 @@ public static void AppendAllText(string path, string? contents) public static void AppendAllText(string path, string? contents, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -568,9 +568,9 @@ public static void AppendAllText(string path, string? contents, Encoding encodin public static void AppendAllLines(string path, IEnumerable contents) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (contents == null) + if (contents is null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -580,11 +580,11 @@ public static void AppendAllLines(string path, IEnumerable contents) public static void AppendAllLines(string path, IEnumerable contents, Encoding encoding) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (contents == null) + if (contents is null) throw new ArgumentNullException(nameof(contents)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -599,15 +599,15 @@ public static void Replace(string sourceFileName, string destinationFileName, st public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors) { - if (sourceFileName == null) + if (sourceFileName is null) throw new ArgumentNullException(nameof(sourceFileName)); - if (destinationFileName == null) + if (destinationFileName is null) throw new ArgumentNullException(nameof(destinationFileName)); FileSystem.ReplaceFile( Path.GetFullPath(sourceFileName), Path.GetFullPath(destinationFileName), - destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null, + destinationBackupFileName is not null ? Path.GetFullPath(destinationBackupFileName) : null, ignoreMetadataErrors); } @@ -626,9 +626,9 @@ public static void Move(string sourceFileName, string destFileName) public static void Move(string sourceFileName, string destFileName, bool overwrite) { - if (sourceFileName == null) + if (sourceFileName is null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); - if (destFileName == null) + if (destFileName is null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); @@ -686,9 +686,9 @@ private static StreamWriter AsyncStreamWriter(string path, Encoding encoding, bo public static Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -701,7 +701,7 @@ private static StreamWriter AsyncStreamWriter(string path, Encoding encoding, bo private static async Task InternalReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); - Debug.Assert(encoding != null); + Debug.Assert(encoding is not null); char[]? buffer = null; StreamReader sr = AsyncStreamReader(path, encoding); @@ -728,7 +728,7 @@ private static async Task InternalReadAllTextAsync(string path, Encoding finally { sr.Dispose(); - if (buffer != null) + if (buffer is not null) { ArrayPool.Shared.Return(buffer); } @@ -740,9 +740,9 @@ private static async Task InternalReadAllTextAsync(string path, Encoding public static Task WriteAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -868,11 +868,11 @@ private static async Task InternalReadAllBytesUnknownLengthAsync(FileStr public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes)); return cancellationToken.IsCancellationRequested @@ -883,7 +883,7 @@ private static async Task InternalReadAllBytesUnknownLengthAsync(FileStr private static async Task InternalWriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); - Debug.Assert(bytes != null); + Debug.Assert(bytes is not null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) { @@ -901,9 +901,9 @@ private static async Task InternalWriteAllBytesAsync(string path, byte[] bytes, public static Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -916,14 +916,14 @@ private static async Task InternalWriteAllBytesAsync(string path, byte[] bytes, private static async Task InternalReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); - Debug.Assert(encoding != null); + Debug.Assert(encoding is not null); using (StreamReader sr = AsyncStreamReader(path, encoding)) { cancellationToken.ThrowIfCancellationRequested(); string? line; List lines = new List(); - while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null) + while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) is not null) { lines.Add(line); cancellationToken.ThrowIfCancellationRequested(); @@ -938,11 +938,11 @@ private static async Task InternalReadAllLinesAsync(string path, Encod public static Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (contents == null) + if (contents is null) throw new ArgumentNullException(nameof(contents)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -954,8 +954,8 @@ private static async Task InternalReadAllLinesAsync(string path, Encod private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumerable contents, CancellationToken cancellationToken) { - Debug.Assert(writer != null); - Debug.Assert(contents != null); + Debug.Assert(writer is not null); + Debug.Assert(contents is not null); using (writer) { @@ -996,7 +996,7 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont finally { sw.Dispose(); - if (buffer != null) + if (buffer is not null) { ArrayPool.Shared.Return(buffer); } @@ -1008,9 +1008,9 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont public static Task AppendAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); @@ -1035,11 +1035,11 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont public static Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); - if (contents == null) + if (contents is null) throw new ArgumentNullException(nameof(contents)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/FileInfo.cs b/src/libraries/System.IO.FileSystem/src/System/IO/FileInfo.cs index fc391cdf814755..c7d7ffd782db49 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/FileInfo.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/FileInfo.cs @@ -55,7 +55,7 @@ public DirectoryInfo? Directory get { string? dirName = DirectoryName; - if (dirName == null) + if (dirName is null) return null; return new DirectoryInfo(dirName); } @@ -89,7 +89,7 @@ public StreamWriter AppendText() public FileInfo CopyTo(string destFileName, bool overwrite) { - if (destFileName == null) + if (destFileName is null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); @@ -139,7 +139,7 @@ public void MoveTo(string destFileName) // This method does work across volumes. public void MoveTo(string destFileName, bool overwrite) { - if (destFileName == null) + if (destFileName is null) throw new ArgumentNullException(nameof(destFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); @@ -171,13 +171,13 @@ public FileInfo Replace(string destinationFileName, string? destinationBackupFil public FileInfo Replace(string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors) { - if (destinationFileName == null) + if (destinationFileName is null) throw new ArgumentNullException(nameof(destinationFileName)); FileSystem.ReplaceFile( FullPath, Path.GetFullPath(destinationFileName), - destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null, + destinationBackupFileName is not null ? Path.GetFullPath(destinationBackupFileName) : null, ignoreMetadataErrors); return new FileInfo(destinationFileName); diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs b/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs index b91936824fbc36..37926a7639ff93 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs @@ -97,7 +97,7 @@ private static void LinkOrCopyFile (string sourceFullPath, string destFullPath) public static void ReplaceFile(string sourceFullPath, string destFullPath, string? destBackupFullPath, bool ignoreMetadataErrors) { - if (destBackupFullPath != null) + if (destBackupFullPath is not null) { // We're backing up the destination file to the backup file, so we need to first delete the backup // file, if it exists. If deletion fails for a reason other than the file not existing, fail. @@ -204,7 +204,7 @@ public static void DeleteFile(string fullPath) case Interop.Error.ENOENT: // In order to match Windows behavior string? directoryName = Path.GetDirectoryName(fullPath); - Debug.Assert(directoryName != null); + Debug.Assert(directoryName is not null); if (directoryName.Length > 0 && !Directory.Exists(directoryName)) { throw Interop.GetExceptionForIoErrno(errorInfo, fullPath, true); @@ -429,7 +429,7 @@ private static void RemoveDirectoryInternal(DirectoryInfo directory, bool recurs } catch (Exception exc) { - if (firstException != null) + if (firstException is not null) { firstException = exc; } @@ -439,13 +439,13 @@ private static void RemoveDirectoryInternal(DirectoryInfo directory, bool recurs } catch (Exception exc) { - if (firstException != null) + if (firstException is not null) { firstException = exc; } } - if (firstException != null) + if (firstException is not null) { throw firstException; } diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Windows.cs b/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Windows.cs index 5b5f9a86bc7446..28444c6c1a5261 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Windows.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/FileSystem.Windows.cs @@ -246,7 +246,7 @@ private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel { // File string fileName = findData.cFileName.GetStringFromFixedBuffer(); - if (!Interop.Kernel32.DeleteFile(Path.Combine(fullPath, fileName)) && exception == null) + if (!Interop.Kernel32.DeleteFile(Path.Combine(fullPath, fileName)) && exception is null) { errorCode = Marshal.GetLastWin32Error(); @@ -277,7 +277,7 @@ private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel } catch (Exception e) { - if (exception == null) + if (exception is null) exception = e; } } @@ -290,7 +290,7 @@ private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel // Mount point. Unmount using full path plus a trailing '\'. // (Note: This doesn't remove the underlying directory) string mountPoint = Path.Join(fullPath, fileName, PathInternal.DirectorySeparatorCharAsString); - if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint) && exception == null) + if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint) && exception is null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && @@ -302,7 +302,7 @@ private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel } // Note that RemoveDirectory on a symbolic link will remove the link itself. - if (!Interop.Kernel32.RemoveDirectory(Path.Combine(fullPath, fileName)) && exception == null) + if (!Interop.Kernel32.RemoveDirectory(Path.Combine(fullPath, fileName)) && exception is null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) @@ -314,7 +314,7 @@ private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel } } while (Interop.Kernel32.FindNextFile(handle, ref findData)); - if (exception != null) + if (exception is not null) throw exception; errorCode = Marshal.GetLastWin32Error(); diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/ReadLinesIterator.cs b/src/libraries/System.IO.FileSystem/src/System/IO/ReadLinesIterator.cs index 349526cc8bb8e5..124ed25eac8de3 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/ReadLinesIterator.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/ReadLinesIterator.cs @@ -33,10 +33,10 @@ internal class ReadLinesIterator : Iterator private ReadLinesIterator(string path, Encoding encoding, StreamReader reader) { - Debug.Assert(path != null); + Debug.Assert(path is not null); Debug.Assert(path.Length > 0); - Debug.Assert(encoding != null); - Debug.Assert(reader != null); + Debug.Assert(encoding is not null); + Debug.Assert(reader is not null); _path = path; _encoding = encoding; @@ -45,10 +45,10 @@ private ReadLinesIterator(string path, Encoding encoding, StreamReader reader) public override bool MoveNext() { - if (this._reader != null) + if (this._reader is not null) { this.current = _reader.ReadLine(); - if (this.current != null) + if (this.current is not null) return true; // To maintain 4.0 behavior we Dispose @@ -76,7 +76,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_reader != null) + if (_reader is not null) { _reader.Dispose(); } diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32Unix.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32Unix.cs index 33e611115fa28e..d2e9fa55881397 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32Unix.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32Unix.cs @@ -50,7 +50,7 @@ internal static void GetDefaultIdentityAndHash(out object identity, out string h Assembly? assembly = Assembly.GetEntryAssembly(); - if (assembly == null) + if (assembly is null) throw new IsolatedStorageException(SR.IsolatedStorage_Init); AssemblyName assemblyName = assembly.GetName(); @@ -59,7 +59,7 @@ internal static void GetDefaultIdentityAndHash(out object identity, out string h #pragma warning restore SYSLIB0012 hash = IdentityHelper.GetNormalizedStrongNameHash(assemblyName)!; - if (hash != null) + if (hash is not null) { hash = "StrongName" + separator + hash; identity = assemblyName; diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs index 9213aae615d4a0..c3db9faf968ca5 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs @@ -118,7 +118,7 @@ public void Close() public void DeleteFile(string file) { - if (file == null) + if (file is null) throw new ArgumentNullException(nameof(file)); EnsureStoreIsValid(); @@ -136,7 +136,7 @@ public void DeleteFile(string file) public bool FileExists(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -148,7 +148,7 @@ public bool FileExists(string path) public bool DirectoryExists(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); EnsureStoreIsValid(); @@ -158,7 +158,7 @@ public bool DirectoryExists(string path) public void CreateDirectory(string dir) { - if (dir == null) + if (dir is null) throw new ArgumentNullException(nameof(dir)); EnsureStoreIsValid(); @@ -194,7 +194,7 @@ public void CreateDirectory(string dir) public void DeleteDirectory(string dir) { - if (dir == null) + if (dir is null) throw new ArgumentNullException(nameof(dir)); EnsureStoreIsValid(); @@ -218,7 +218,7 @@ public string[] GetFileNames() // foo\abc*.txt will give all abc*.txt files in foo directory public string[] GetFileNames(string searchPattern) { - if (searchPattern == null) + if (searchPattern is null) throw new ArgumentNullException(nameof(searchPattern)); EnsureStoreIsValid(); @@ -243,7 +243,7 @@ public string[] GetDirectoryNames() // foo\data* will give all directory names in foo directory that starts with data public string[] GetDirectoryNames(string searchPattern) { - if (searchPattern == null) + if (searchPattern is null) throw new ArgumentNullException(nameof(searchPattern)); EnsureStoreIsValid(); @@ -288,7 +288,7 @@ public IsolatedStorageFileStream CreateFile(string path) public DateTimeOffset GetCreationTime(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) @@ -310,7 +310,7 @@ public DateTimeOffset GetCreationTime(string path) public DateTimeOffset GetLastAccessTime(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) @@ -332,7 +332,7 @@ public DateTimeOffset GetLastAccessTime(string path) public DateTimeOffset GetLastWriteTime(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) @@ -354,10 +354,10 @@ public DateTimeOffset GetLastWriteTime(string path) public void CopyFile(string sourceFileName, string destinationFileName) { - if (sourceFileName == null) + if (sourceFileName is null) throw new ArgumentNullException(nameof(sourceFileName)); - if (destinationFileName == null) + if (destinationFileName is null) throw new ArgumentNullException(nameof(destinationFileName)); if (sourceFileName.Length == 0) @@ -375,10 +375,10 @@ public void CopyFile(string sourceFileName, string destinationFileName) public void CopyFile(string sourceFileName, string destinationFileName, bool overwrite) { - if (sourceFileName == null) + if (sourceFileName is null) throw new ArgumentNullException(nameof(sourceFileName)); - if (destinationFileName == null) + if (destinationFileName is null) throw new ArgumentNullException(nameof(destinationFileName)); if (sourceFileName.Length == 0) @@ -416,10 +416,10 @@ public void CopyFile(string sourceFileName, string destinationFileName, bool ove public void MoveFile(string sourceFileName, string destinationFileName) { - if (sourceFileName == null) + if (sourceFileName is null) throw new ArgumentNullException(nameof(sourceFileName)); - if (destinationFileName == null) + if (destinationFileName is null) throw new ArgumentNullException(nameof(destinationFileName)); if (sourceFileName.Length == 0) @@ -457,10 +457,10 @@ public void MoveFile(string sourceFileName, string destinationFileName) public void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { - if (sourceDirectoryName == null) + if (sourceDirectoryName is null) throw new ArgumentNullException(nameof(sourceDirectoryName)); - if (destinationDirectoryName == null) + if (destinationDirectoryName is null) throw new ArgumentNullException(nameof(destinationDirectoryName)); if (sourceDirectoryName.Length == 0) @@ -639,30 +639,30 @@ private static IsolatedStorageFile GetStore(IsolatedStorageScope scope) public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Type? applicationEvidenceType) { // Scope MUST be Application - return (applicationEvidenceType == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 + return (applicationEvidenceType is null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, object? applicationIdentity) { // Scope MUST be Application - return (applicationIdentity == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 + return (applicationIdentity is null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Type? domainEvidenceType, Type? assemblyEvidenceType) { // Scope MUST NOT be Application (assembly is assumed otherwise) - return (domainEvidenceType == null && assemblyEvidenceType == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 + return (domainEvidenceType is null && assemblyEvidenceType is null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, object? domainIdentity, object? assemblyIdentity) { // Scope MUST NOT be Application (assembly is assumed otherwise) - return (domainIdentity == null && assemblyIdentity == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 + return (domainIdentity is null && assemblyIdentity is null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/runtime/issues/18208 } internal string GetFullPath(string partialPath) { - Debug.Assert(partialPath != null, "partialPath should be non null"); + Debug.Assert(partialPath is not null, "partialPath should be non null"); int i; @@ -730,7 +730,7 @@ public override void Remove() Close(); string? parentDirectory = Path.GetDirectoryName(RootDirectory.TrimEnd(Path.DirectorySeparatorChar)); - Debug.Assert(parentDirectory != null); + Debug.Assert(parentDirectory is not null); if (ContainsUnknownFiles(parentDirectory)) return; @@ -749,7 +749,7 @@ public override void Remove() if (Helper.IsDomain(Scope)) { parentDirectory = Path.GetDirectoryName(parentDirectory); - Debug.Assert(parentDirectory != null); + Debug.Assert(parentDirectory is not null); if (ContainsUnknownFiles(parentDirectory)) return; diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs index 54f0f83375d442..775092cdea6795 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs @@ -82,7 +82,7 @@ private struct InitialiationData // If IsolatedStorageFile is null, then we default to using a file that is scoped by user, appdomain, and assembly. private static InitialiationData InitializeFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile? isf) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if ((path.Length == 0) || path.Equals(BackSlash)) @@ -90,7 +90,7 @@ private static InitialiationData InitializeFileStream(string path, FileMode mode SR.IsolatedStorage_Path); bool createdStore = false; - if (isf == null) + if (isf is null) { isf = IsolatedStorageFile.GetUserStoreForDomain(); createdStore = true; @@ -206,7 +206,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_fs != null) + if (_fs is not null) _fs.Dispose(); } } @@ -220,7 +220,7 @@ public override ValueTask DisposeAsync() { return GetType() != typeof(IsolatedStorageFileStream) ? base.DisposeAsync() : - _fs != null ? _fs.DisposeAsync() : + _fs is not null ? _fs.DisposeAsync() : default; } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs index 3892e6189ace63..b5296f12409dab 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs @@ -49,7 +49,7 @@ internal SafeMemoryMappedFileHandle( long capacity) : base(ownsHandle: true) { - Debug.Assert(!ownsFileStream || fileStream != null, "We can only own a FileStream we're actually given."); + Debug.Assert(!ownsFileStream || fileStream is not null, "We can only own a FileStream we're actually given."); // Store the arguments. We'll actually open the map when the view is created. _fileStream = fileStream; diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs index abe63639a4eb0e..efd9f2c977896c 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs @@ -12,7 +12,7 @@ private static void VerifyMemoryMappedFileAccess(MemoryMappedFileAccess access, { fileSize = -1; - if (fileStream != null) + if (fileStream is not null) { Interop.Sys.FileStatus status; @@ -59,7 +59,7 @@ private static unsafe SafeMemoryMappedFileHandle CreateCore( { VerifyMemoryMappedFileAccess(access, capacity, fileStream, out long fileSize); - if (mapName != null) + if (mapName is not null) { // Named maps are not supported in our Unix implementation. We could support named maps on Linux using // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due @@ -74,7 +74,7 @@ private static unsafe SafeMemoryMappedFileHandle CreateCore( } bool ownsFileStream = false; - if (fileStream != null) + if (fileStream is not null) { if (fileSize >= 0 && capacity > fileSize) { @@ -123,7 +123,7 @@ private static SafeMemoryMappedFileHandle CreateOrOpenCore( HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { - // Since we don't support mapName != null, CreateOrOpenCore can't + // Since we don't support mapName is not null, CreateOrOpenCore can't // be used to Open an existing map, and thus is identical to CreateCore. return CreateCore(null, mapName, inheritability, access, options, capacity); } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs index ad08669e8e008c..14cd4e2c6bfad1 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs @@ -34,16 +34,16 @@ private static SafeMemoryMappedFileHandle CreateCore( FileStream? fileStream, string? mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { - SafeFileHandle? fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; + SafeFileHandle? fileHandle = fileStream is not null ? fileStream.SafeFileHandle : null; Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); - if (fileStream != null) + if (fileStream is not null) { VerifyMemoryMappedFileAccess(access, capacity, fileStream); } - SafeMemoryMappedFileHandle handle = fileHandle != null ? + SafeMemoryMappedFileHandle handle = fileHandle is not null ? Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) : Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); @@ -167,7 +167,7 @@ private static SafeMemoryMappedFileHandle CreateOrOpenCore( } // finished retrying but couldn't create or open - if (handle == null || handle.IsInvalid) + if (handle is null || handle.IsInvalid) { throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping); } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs index d2f04e84d27ef9..1342c7d30bc659 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs @@ -17,7 +17,7 @@ public partial class MemoryMappedFile : IDisposable // Private constructors to be used by the factory methods. private MemoryMappedFile(SafeMemoryMappedFileHandle handle) { - Debug.Assert(handle != null); + Debug.Assert(handle is not null); Debug.Assert(!handle.IsClosed); Debug.Assert(!handle.IsInvalid); @@ -27,10 +27,10 @@ private MemoryMappedFile(SafeMemoryMappedFileHandle handle) private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen) { - Debug.Assert(handle != null); + Debug.Assert(handle is not null); Debug.Assert(!handle.IsClosed); Debug.Assert(!handle.IsInvalid); - Debug.Assert(fileStream != null); + Debug.Assert(fileStream is not null); _handle = handle; _fileStream = fileStream; @@ -60,7 +60,7 @@ public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRigh public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability) { - if (mapName == null) + if (mapName is null) { throw new ArgumentNullException(nameof(mapName), SR.ArgumentNull_MapName); } @@ -114,12 +114,12 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string? mapName, long capacity, MemoryMappedFileAccess access) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } - if (mapName != null && mapName.Length == 0) + if (mapName is not null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } @@ -174,7 +174,7 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string throw; } - Debug.Assert(handle != null); + Debug.Assert(handle is not null); Debug.Assert(!handle.IsInvalid); return new MemoryMappedFile(handle, fileStream, false); } @@ -183,12 +183,12 @@ public static MemoryMappedFile CreateFromFile(FileStream fileStream, string? map MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { - if (fileStream == null) + if (fileStream is null) { throw new ArgumentNullException(nameof(fileStream), SR.ArgumentNull_FileStream); } - if (mapName != null && mapName.Length == 0) + if (mapName is not null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } @@ -234,7 +234,7 @@ public static MemoryMappedFile CreateFromFile(FileStream fileStream, string? map } // Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal - // for IPC, when mapName != null. + // for IPC, when mapName is not null. public static MemoryMappedFile CreateNew(string? mapName, long capacity) { return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, @@ -251,7 +251,7 @@ public static MemoryMappedFile CreateNew(string? mapName, long capacity, MemoryM MemoryMappedFileOptions options, HandleInheritability inheritability) { - if (mapName != null && mapName.Length == 0) + if (mapName is not null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } @@ -314,7 +314,7 @@ public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { - if (mapName == null) + if (mapName is null) { throw new ArgumentNullException(nameof(mapName), SR.ArgumentNull_MapName); } @@ -454,7 +454,7 @@ protected virtual void Dispose(bool disposing) } finally { - if (_fileStream != null && _leaveOpen == false) + if (_fileStream is not null && _leaveOpen == false) { _fileStream.Dispose(); } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs index b5e97b23518b45..4f1e61e574c2a5 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs @@ -56,7 +56,7 @@ public static unsafe MemoryMappedView CreateView( // If we have a file handle, get the file descriptor from it. If the handle is null, // we'll use an anonymous backing store for the map. SafeFileHandle fd; - if (memMappedFileHandle._fileStream != null) + if (memMappedFileHandle._fileStream is not null) { // Get the file descriptor from the SafeFileHandle fd = memMappedFileHandle._fileStream.SafeFileHandle; @@ -152,7 +152,7 @@ public unsafe void Flush(UIntPtr capacity) } finally { - if (ptr != null) + if (ptr is not null) { _viewHandle.ReleasePointer(); } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs index 4e6e6259a7aee5..fef1e269e72ea0 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs @@ -140,7 +140,7 @@ public void Flush(UIntPtr capacity) } finally { - if (firstPagePtr != null) + if (firstPagePtr is not null) { _viewHandle.ReleasePointer(); } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs index 0f677f257f0995..fc394ce1f564a5 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs @@ -16,7 +16,7 @@ internal partial class MemoryMappedView : IDisposable private unsafe MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, long pointerOffset, long size, MemoryMappedFileAccess access) { - Debug.Assert(viewHandle != null); + Debug.Assert(viewHandle is not null); _viewHandle = viewHandle; _pointerOffset = pointerOffset; diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs index 5bef12efb4bacd..2e1d7b4f94e31d 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs @@ -12,7 +12,7 @@ public sealed class MemoryMappedViewAccessor : UnmanagedMemoryAccessor internal MemoryMappedViewAccessor(MemoryMappedView view) { - Debug.Assert(view != null, "view is null"); + Debug.Assert(view is not null, "view is null"); _view = view; Initialize(_view.ViewHandle, _view.PointerOffset, _view.Size, MemoryMappedFile.GetFileAccess(_view.Access)); diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs index 1a51c7e2814b69..d61da5e9e2538e 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs @@ -12,7 +12,7 @@ public sealed class MemoryMappedViewStream : UnmanagedMemoryStream internal unsafe MemoryMappedViewStream(MemoryMappedView view) { - Debug.Assert(view != null, "view is null"); + Debug.Assert(view is not null, "view is null"); _view = view; Initialize(_view.ViewHandle, _view.PointerOffset, _view.Size, MemoryMappedFile.GetFileAccess(_view.Access)); diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/BufferSegment.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/BufferSegment.cs index 65379ef68f9a30..3d0c6f92e15dfd 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/BufferSegment.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/BufferSegment.cs @@ -62,14 +62,14 @@ public void SetOwnedMemory(byte[] arrayPoolBuffer) public void ResetMemory() { IMemoryOwner? memoryOwner = _memoryOwner; - if (memoryOwner != null) + if (memoryOwner is not null) { _memoryOwner = null; memoryOwner.Dispose(); } else { - Debug.Assert(_array != null); + Debug.Assert(_array is not null); ArrayPool.Shared.Return(_array); _array = null; } @@ -97,16 +97,16 @@ public int WritableBytes public void SetNext(BufferSegment segment) { - Debug.Assert(segment != null); - Debug.Assert(Next == null); + Debug.Assert(segment is not null); + Debug.Assert(Next is null); NextSegment = segment; segment = this; - while (segment.Next != null) + while (segment.Next is not null) { - Debug.Assert(segment.NextSegment != null); + Debug.Assert(segment.NextSegment is not null); segment.NextSegment.RunningIndex = segment.RunningIndex + segment.Length; segment = segment.NextSegment; } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/Pipe.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/Pipe.cs index 90964cd4389be8..0f66ceb94c1dc3 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/Pipe.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/Pipe.cs @@ -97,7 +97,7 @@ public Pipe() : this(PipeOptions.Default) /// public Pipe(PipeOptions options) { - if (options == null) + if (options is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options); } @@ -189,7 +189,7 @@ private void AllocateWriteHeadSynchronized(int sizeHint) { _operationState.BeginWrite(); - if (_writingHead == null) + if (_writingHead is null) { // We need to allocate memory to write since nobody has written before BufferSegment newSegment = AllocateSegment(sizeHint); @@ -285,7 +285,7 @@ internal bool CommitUnsynchronized() } // Update the writing head - Debug.Assert(_writingHead != null); + Debug.Assert(_writingHead is not null); _writingHead.End += _writingHeadBytesBuffered; // Always move the read tail to the write head @@ -409,7 +409,7 @@ internal void CompleteWriter(Exception? exception) CompletePipe(); } - if (completionCallbacks != null) + if (completionCallbacks is not null) { ScheduleCallbacks(_readerScheduler, completionCallbacks); } @@ -438,7 +438,7 @@ internal void AdvanceReader(in SequencePosition consumed, in SequencePosition ex private void AdvanceReader(BufferSegment? consumedSegment, int consumedIndex, BufferSegment? examinedSegment, int examinedIndex) { // Throw if examined < consumed - if (consumedSegment != null && examinedSegment != null && BufferSegment.GetLength(consumedSegment, consumedIndex, examinedSegment, examinedIndex) < 0) + if (consumedSegment is not null && examinedSegment is not null && BufferSegment.GetLength(consumedSegment, consumedIndex, examinedSegment, examinedIndex) < 0) { ThrowHelper.ThrowInvalidOperationException_InvalidExaminedOrConsumedPosition(); } @@ -456,7 +456,7 @@ private void AdvanceReader(BufferSegment? consumedSegment, int consumedIndex, Bu examinedEverything = examinedIndex == _readTailIndex; } - if (examinedSegment != null && _lastExaminedIndex >= 0) + if (examinedSegment is not null && _lastExaminedIndex >= 0) { long examinedBytes = BufferSegment.GetLength(_lastExaminedIndex, examinedSegment, examinedIndex); long oldLength = _unconsumedBytes; @@ -480,9 +480,9 @@ private void AdvanceReader(BufferSegment? consumedSegment, int consumedIndex, Bu } } - if (consumedSegment != null) + if (consumedSegment is not null) { - if (_readHead == null) + if (_readHead is null) { ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor(); return; @@ -546,7 +546,7 @@ void MoveReturnEndToNextBlock() _readerAwaitable.SetUncompleted(); } - while (returnStart != null && returnStart != returnEnd) + while (returnStart is not null && returnStart != returnEnd) { BufferSegment? next = returnStart.NextSegment; returnStart.ResetMemory(); @@ -587,7 +587,7 @@ internal void CompleteReader(Exception? exception) CompletePipe(); } - if (completionCallbacks != null) + if (completionCallbacks is not null) { ScheduleCallbacks(_writerScheduler, completionCallbacks); } @@ -608,7 +608,7 @@ internal void OnWriterCompleted(Action callback, object? st completionCallbacks = _writerCompletion.AddCallback(callback, state); } - if (completionCallbacks != null) + if (completionCallbacks is not null) { ScheduleCallbacks(_readerScheduler, completionCallbacks); } @@ -647,7 +647,7 @@ internal void OnReaderCompleted(Action callback, object? st completionCallbacks = _readerCompletion.AddCallback(callback, state); } - if (completionCallbacks != null) + if (completionCallbacks is not null) { ScheduleCallbacks(_writerScheduler, completionCallbacks); } @@ -709,7 +709,7 @@ internal bool TryRead(out ReadResult result) private static void ScheduleCallbacks(PipeScheduler scheduler, PipeCompletionCallbacks completionCallbacks) { - Debug.Assert(completionCallbacks != null); + Debug.Assert(completionCallbacks is not null); scheduler.UnsafeSchedule(s_invokeCompletionCallbacks, completionCallbacks); } @@ -743,7 +743,7 @@ private static void TrySchedule(PipeScheduler scheduler, in CompletionData compl [MethodImpl(MethodImplOptions.NoInlining)] private static void ScheduleWithContext(PipeScheduler scheduler, in CompletionData completionData) { - Debug.Assert(completionData.SynchronizationContext != null || completionData.ExecutionContext != null); + Debug.Assert(completionData.SynchronizationContext is not null || completionData.ExecutionContext is not null); if (completionData.SynchronizationContext is null) { @@ -775,7 +775,7 @@ private static void ExecuteWithoutExecutionContext(object state) private static void ExecuteWithExecutionContext(object state) { CompletionData completionData = (CompletionData)state; - Debug.Assert(completionData.ExecutionContext != null); + Debug.Assert(completionData.ExecutionContext is not null); ExecutionContext.Run(completionData.ExecutionContext, s_executionContextRawCallback, state); } @@ -793,7 +793,7 @@ private void CompletePipe() // if _readHead is null we need to try return _commitHead // because there might be a block allocated for writing BufferSegment? segment = _readHead ?? _readTail; - while (segment != null) + while (segment is not null) { BufferSegment returnSegment = segment; segment = segment.NextSegment; @@ -875,9 +875,9 @@ private void GetReadResult(out ReadResult result) // No need to read end if there is no head BufferSegment? head = _readHead; - if (head != null) + if (head is not null) { - Debug.Assert(_readTail != null); + Debug.Assert(_readTail is not null); // Reading commit head shared with writer var readOnlySequence = new ReadOnlySequence(head, _readHeadIndex, _readTail, _readTailIndex); result = new ReadResult(readOnlySequence, isCanceled, isCompleted); @@ -995,7 +995,7 @@ internal ValueTask WriteAsync(ReadOnlyMemory source, Cancella private void WriteMultiSegment(ReadOnlySpan source) { - Debug.Assert(_writingHead != null); + Debug.Assert(_writingHead is not null); Span destination = _writingHeadMemory.Span; while (true) diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeAwaitable.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeAwaitable.cs index dab70646c1df49..4a992646cd23ce 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeAwaitable.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeAwaitable.cs @@ -81,7 +81,7 @@ private void ExtractCompletion(out CompletionData completionData) _synchronizationContext = null; _executionContext = null; - completionData = currentCompletion != null ? + completionData = currentCompletion is not null ? new CompletionData(currentCompletion, currentState, executionContext, synchronizationContext) : default; } @@ -89,10 +89,10 @@ private void ExtractCompletion(out CompletionData completionData) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetUncompleted() { - Debug.Assert(_completion == null); - Debug.Assert(_completionState == null); - Debug.Assert(_synchronizationContext == null); - Debug.Assert(_executionContext == null); + Debug.Assert(_completion is null); + Debug.Assert(_completionState is null); + Debug.Assert(_synchronizationContext is null); + Debug.Assert(_executionContext is null); _awaitableState &= ~AwaitableState.Completed; } @@ -116,7 +116,7 @@ public void OnCompleted(Action continuation, object? state, ValueTaskSo (flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext? sc = SynchronizationContext.Current; - if (sc != null && sc.GetType() != typeof(SynchronizationContext)) + if (sc is not null && sc.GetType() != typeof(SynchronizationContext)) { _synchronizationContext = sc; } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletion.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletion.cs index a37292d52a44e6..4a8062a77b2ce9 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletion.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletion.cs @@ -24,14 +24,14 @@ internal struct PipeCompletion public bool IsCompleted => _isCompleted; - public bool IsFaulted => _exceptionInfo != null; + public bool IsFaulted => _exceptionInfo is not null; public PipeCompletionCallbacks? TryComplete(Exception? exception = null) { if (!_isCompleted) { _isCompleted = true; - if (exception != null) + if (exception is not null) { _exceptionInfo = ExceptionDispatchInfo.Capture(exception); } @@ -53,7 +53,7 @@ internal struct PipeCompletion // -1 to adjust for _firstCallback var callbackIndex = _callbackCount - 1; _callbackCount++; - Debug.Assert(_callbacks != null); + Debug.Assert(_callbacks is not null); _callbacks[callbackIndex] = new PipeCompletionCallback(callback, state); } @@ -67,7 +67,7 @@ internal struct PipeCompletion private void EnsureSpace() { - if (_callbacks == null) + if (_callbacks is null) { _callbacks = s_completionCallbackPool.Rent(InitialCallbacksSize); } @@ -91,7 +91,7 @@ public bool IsCompletedOrThrow() return false; } - if (_exceptionInfo != null) + if (_exceptionInfo is not null) { ThrowLatchedException(); } @@ -122,7 +122,7 @@ public bool IsCompletedOrThrow() public void Reset() { Debug.Assert(IsCompleted); - Debug.Assert(_callbacks == null); + Debug.Assert(_callbacks is null); _isCompleted = false; _exceptionInfo = null; } @@ -130,7 +130,7 @@ public void Reset() [MethodImpl(MethodImplOptions.NoInlining)] private void ThrowLatchedException() { - Debug.Assert(_exceptionInfo != null); + Debug.Assert(_exceptionInfo is not null); _exceptionInfo.Throw(); } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs index 9bba043440c021..603b776129e713 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs @@ -34,7 +34,7 @@ public void Execute() Execute(_firstCallback, ref exceptions); - if (_callbacks != null) + if (_callbacks is not null) { try { @@ -50,7 +50,7 @@ public void Execute() } } - if (exceptions != null) + if (exceptions is not null) { throw new AggregateException(exceptions); } @@ -64,7 +64,7 @@ private void Execute(PipeCompletionCallback callback, ref List? excep } catch (Exception ex) { - if (exceptions == null) + if (exceptions is null) { exceptions = new List(); } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs index 9febce0fbb57cc..c26bc3629fc1a3 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs @@ -58,7 +58,7 @@ public abstract partial class PipeReader /// The . public virtual Stream AsStream(bool leaveOpen = false) { - if (_stream == null) + if (_stream is null) { _stream = new PipeReaderStream(this, leaveOpen); } @@ -127,7 +127,7 @@ public static PipeReader Create(Stream stream, StreamPipeReaderOptions? readerOp /// A task that represents the asynchronous copy operation. public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default) { - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } @@ -157,7 +157,7 @@ public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancel /// A task that represents the asynchronous copy operation. public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default) { - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs index e654113a6fecda..589009499f387f 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs @@ -15,7 +15,7 @@ internal sealed class PipeReaderStream : Stream public PipeReaderStream(PipeReader pipeReader, bool leaveOpen) { - Debug.Assert(pipeReader != null); + Debug.Assert(pipeReader is not null); _pipeReader = pipeReader; LeaveOpen = leaveOpen; } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriter.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriter.cs index 88627c81acb6ab..d5dc8e7b906564 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriter.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriter.cs @@ -72,7 +72,7 @@ public virtual void OnReaderCompleted(Action callback, obje /// The . public virtual Stream AsStream(bool leaveOpen = false) { - if (_stream == null) + if (_stream is null) { _stream = new PipeWriterStream(this, leaveOpen); } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs index 915927f264c11b..341896a3c11f98 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs @@ -13,7 +13,7 @@ internal sealed class PipeWriterStream : Stream public PipeWriterStream(PipeWriter pipeWriter, bool leaveOpen) { - Debug.Assert(pipeWriter != null); + Debug.Assert(pipeWriter is not null); _pipeWriter = pipeWriter; LeaveOpen = leaveOpen; } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs index 090325017a8a75..fe240acbf79165 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs @@ -17,12 +17,12 @@ public static class StreamPipeExtensions /// A task that represents the asynchronous copy operation. public static Task CopyToAsync(this Stream source, PipeWriter destination, CancellationToken cancellationToken = default) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs index b283ad406afeb7..76f2b4de6957e6 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs @@ -42,7 +42,7 @@ public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options) { InnerStream = readingStream ?? throw new ArgumentNullException(nameof(readingStream)); - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -50,7 +50,7 @@ public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options) _bufferSegmentPool = new BufferSegmentStack(InitialSegmentPoolSize); _minimumReadThreshold = Math.Min(options.MinimumReadSize, options.BufferSize); _pool = options.Pool == MemoryPool.Shared ? null : options.Pool; - _bufferSize = _pool == null ? options.BufferSize : Math.Min(options.BufferSize, _pool.MaxBufferSize); + _bufferSize = _pool is null ? options.BufferSize : Math.Min(options.BufferSize, _pool.MaxBufferSize); _leaveOpen = options.LeaveOpen; } @@ -71,7 +71,7 @@ private CancellationTokenSource InternalTokenSource { lock (_lock) { - if (_internalTokenSource == null) + if (_internalTokenSource is null) { _internalTokenSource = new CancellationTokenSource(); } @@ -90,12 +90,12 @@ public override void AdvanceTo(SequencePosition consumed, SequencePosition exami private void AdvanceTo(BufferSegment? consumedSegment, int consumedIndex, BufferSegment? examinedSegment, int examinedIndex) { - if (consumedSegment == null || examinedSegment == null) + if (consumedSegment is null || examinedSegment is null) { return; } - if (_readHead == null) + if (_readHead is null) { ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor(); } @@ -172,7 +172,7 @@ public override void Complete(Exception? exception = null) _isReaderCompleted = true; BufferSegment? segment = _readHead; - while (segment != null) + while (segment is not null) { BufferSegment returnSegment = segment; segment = segment.NextSegment; @@ -284,7 +284,7 @@ private bool TryReadInternal(CancellationTokenSource source, out ReadResult resu ClearCancellationToken(); } - ReadOnlySequence buffer = _readHead == null ? default : GetCurrentReadOnlySequence(); + ReadOnlySequence buffer = _readHead is null ? default : GetCurrentReadOnlySequence(); result = new ReadResult(buffer, isCancellationRequested, _isStreamCompleted); return true; @@ -296,21 +296,21 @@ private bool TryReadInternal(CancellationTokenSource source, out ReadResult resu private ReadOnlySequence GetCurrentReadOnlySequence() { - Debug.Assert(_readHead != null &&_readTail != null); + Debug.Assert(_readHead is not null &&_readTail is not null); return new ReadOnlySequence(_readHead, _readIndex, _readTail, _readTail.End); } private void AllocateReadTail() { - if (_readHead == null) + if (_readHead is null) { - Debug.Assert(_readTail == null); + Debug.Assert(_readTail is null); _readHead = AllocateSegment(); _readTail = _readHead; } else { - Debug.Assert(_readTail != null); + Debug.Assert(_readTail is not null); if (_readTail.WritableBytes < _minimumReadThreshold) { BufferSegment nextSegment = AllocateSegment(); diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs index d84229317f96f9..ea78a1ee1d6b3a 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs @@ -37,7 +37,7 @@ private CancellationTokenSource InternalTokenSource { lock (_lockObject) { - if (_internalTokenSource == null) + if (_internalTokenSource is null) { _internalTokenSource = new CancellationTokenSource(); } @@ -50,7 +50,7 @@ public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options) { InnerStream = writingStream ?? throw new ArgumentNullException(nameof(writingStream)); - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -118,7 +118,7 @@ public override Span GetSpan(int sizeHint = 0) private void AllocateMemory(int sizeHint) { - if (_head == null) + if (_head is null) { // We need to allocate memory to write since nobody has written before BufferSegment newSegment = AllocateSegment(sizeHint); @@ -129,7 +129,7 @@ private void AllocateMemory(int sizeHint) } else { - Debug.Assert(_tail != null); + Debug.Assert(_tail is not null); int bytesLeftInBuffer = _tailMemory.Length; if (bytesLeftInBuffer == 0 || bytesLeftInBuffer < sizeHint) @@ -215,7 +215,7 @@ public override void Complete(Exception? exception = null) _isCompleted = true; - FlushInternal(writeToStream: exception == null); + FlushInternal(writeToStream: exception is null); _internalTokenSource?.Dispose(); @@ -234,7 +234,7 @@ public override async ValueTask CompleteAsync(Exception? exception = null) _isCompleted = true; - await FlushAsyncInternal(writeToStream: exception == null).ConfigureAwait(false); + await FlushAsyncInternal(writeToStream: exception is null).ConfigureAwait(false); _internalTokenSource?.Dispose(); @@ -276,7 +276,7 @@ private async ValueTask FlushAsyncInternal(bool writeToStream, Canc if (_tailBytesBuffered > 0) { - Debug.Assert(_tail != null); + Debug.Assert(_tail is not null); // Update any buffered data _tail.End += _tailBytesBuffered; @@ -289,7 +289,7 @@ private async ValueTask FlushAsyncInternal(bool writeToStream, Canc try { BufferSegment? segment = _head; - while (segment != null) + while (segment is not null) { BufferSegment returnSegment = segment; segment = segment.NextSegment; @@ -344,7 +344,7 @@ private void FlushInternal(bool writeToStream) // and flush the result. if (_tailBytesBuffered > 0) { - Debug.Assert(_tail != null); + Debug.Assert(_tail is not null); // Update any buffered data _tail.End += _tailBytesBuffered; @@ -352,7 +352,7 @@ private void FlushInternal(bool writeToStream) } BufferSegment? segment = _head; - while (segment != null) + while (segment is not null) { BufferSegment returnSegment = segment; segment = segment.NextSegment; diff --git a/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Unix.cs b/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Unix.cs index 238aeabca6cf9f..c16cb7ef86875a 100644 --- a/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Unix.cs @@ -27,7 +27,7 @@ public sealed partial class SafePipeHandle : SafeHandleZeroOrMinusOneIsInvalid internal SafePipeHandle(Socket namedPipeSocket) : base(ownsHandle: true) { - Debug.Assert(namedPipeSocket != null); + Debug.Assert(namedPipeSocket is not null); _namedPipeSocket = namedPipeSocket; _namedPipeSocketHandle = namedPipeSocket.SafeHandle; @@ -43,7 +43,7 @@ internal SafePipeHandle(Socket namedPipeSocket) : base(ownsHandle: true) protected override void Dispose(bool disposing) { base.Dispose(disposing); // must be called before trying to Dispose the socket - if (disposing && _namedPipeSocket != null) + if (disposing && _namedPipeSocket is not null) { _namedPipeSocket.Dispose(); _namedPipeSocket = null; @@ -55,7 +55,7 @@ protected override bool ReleaseHandle() Debug.Assert(!IsInvalid); // Clean up resources for named handles - if (_namedPipeSocketHandle != null) + if (_namedPipeSocketHandle is not null) { SetHandle(DefaultInvalidHandle); _namedPipeSocketHandle.DangerousRelease(); @@ -71,7 +71,7 @@ protected override bool ReleaseHandle() public override bool IsInvalid { - get { return (long)handle < 0 && _namedPipeSocket == null; } + get { return (long)handle < 0 && _namedPipeSocket is null; } } } } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs index 0c904b33c7c867..55c5d453a985c6 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs @@ -24,7 +24,7 @@ public AnonymousPipeClientStream(PipeDirection direction, string pipeHandleAsStr { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } - if (pipeHandleAsString == null) + if (pipeHandleAsString is null) { throw new ArgumentNullException(nameof(pipeHandleAsString)); } @@ -54,7 +54,7 @@ public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePip { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } - if (safePipeHandle == null) + if (safePipeHandle is null) { throw new ArgumentNullException(nameof(safePipeHandle)); } @@ -69,7 +69,7 @@ public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePip private void Init(PipeDirection direction, SafePipeHandle safePipeHandle) { Debug.Assert(direction != PipeDirection.InOut, "anonymous pipes are unidirectional, caller should have verified before calling Init"); - Debug.Assert(safePipeHandle != null && !safePipeHandle.IsInvalid, "safePipeHandle must be valid"); + Debug.Assert(safePipeHandle is not null && !safePipeHandle.IsInvalid, "safePipeHandle must be valid"); ValidateHandleIsPipe(safePipeHandle); InitializeHandle(safePipeHandle, true, false); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs index bbebf3d79d993d..af40fecdf97ad4 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs @@ -37,11 +37,11 @@ public AnonymousPipeServerStream(PipeDirection direction, SafePipeHandle serverS { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } - if (serverSafePipeHandle == null) + if (serverSafePipeHandle is null) { throw new ArgumentNullException(nameof(serverSafePipeHandle)); } - if (clientSafePipeHandle == null) + if (clientSafePipeHandle is null) { throw new ArgumentNullException(nameof(clientSafePipeHandle)); } @@ -116,7 +116,7 @@ public SafePipeHandle ClientSafePipeHandle // know the client has been passed the handle and so the connection is live. public void DisposeLocalCopyOfClientHandle() { - if (_clientHandle != null && !_clientHandle.IsClosed) + if (_clientHandle is not null && !_clientHandle.IsClosed) { _clientHandle.Dispose(); } @@ -127,7 +127,7 @@ protected override void Dispose(bool disposing) try { // We should dispose of the client handle if it was not exposed. - if (!_clientHandleExposed && _clientHandle != null && !_clientHandle.IsClosed) + if (!_clientHandleExposed && _clientHandle is not null && !_clientHandle.IsClosed) { _clientHandle.Dispose(); } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index a03b5f1eaa524a..6a14fbec0c49f6 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -56,11 +56,11 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability) : base(direction, 0) { - if (pipeName == null) + if (pipeName is null) { throw new ArgumentNullException(nameof(pipeName)); } - if (serverName == null) + if (serverName is null) { throw new ArgumentNullException(nameof(serverName), SR.ArgumentNull_ServerName); } @@ -100,7 +100,7 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, 0) { - if (safePipeHandle == null) + if (safePipeHandle is null) { throw new ArgumentNullException(nameof(safePipeHandle)); } 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 7f0d62611bc447..e120b268481f0a 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 @@ -25,7 +25,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(pipeName is not null && pipeName.Length != 0, "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"); @@ -135,13 +135,13 @@ public string GetImpersonationUserName() CheckWriteOperations(); SafeHandle? handle = InternalHandle?.NamedPipeSocketHandle; - if (handle == null) + if (handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } string name = Interop.Sys.GetPeerUserName(handle); - if (name != null) + if (name is not null) { return name; } @@ -174,7 +174,7 @@ public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker) { CheckWriteOperations(); SafeHandle? handle = InternalHandle?.NamedPipeSocketHandle; - if (handle == null) + if (handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } 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 8168691c9a93ff..9b25c4ffbf3176 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 @@ -33,7 +33,7 @@ internal NamedPipeServerStream( { ValidateParameters(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability); - if (pipeSecurity != null && IsCurrentUserOnly) + if (pipeSecurity is not null && IsCurrentUserOnly) { throw new ArgumentException(SR.NotSupported_PipeSecurityIsCurrentUserOnly, nameof(pipeSecurity)); } @@ -54,7 +54,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(pipeName is not null && pipeName.Length != 0, "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"); @@ -71,7 +71,7 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer if (IsCurrentUserOnly) { - Debug.Assert(pipeSecurity == null); + Debug.Assert(pipeSecurity is null); using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent()) { @@ -341,7 +341,7 @@ private unsafe Task WaitForConnectionCoreAsync(CancellationToken cancellationTok private void CheckConnectOperationsServerWithHandle() { - if (InternalHandle == null) + if (InternalHandle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs index 596f3504c49f7d..3f75060a39a989 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs @@ -94,7 +94,7 @@ private void ValidateParameters( int outBufferSize, HandleInheritability inheritability) { - if (pipeName == null) + if (pipeName is null) { throw new ArgumentNullException(nameof(pipeName)); } @@ -148,7 +148,7 @@ private void ValidateParameters( public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, PipeTransmissionMode.Byte, 0) { - if (safePipeHandle == null) + if (safePipeHandle is null) { throw new ArgumentNullException(nameof(safePipeHandle)); } @@ -193,7 +193,7 @@ private void CheckConnectOperationsServer() { throw Error.GetPipeNotOpen(); } - if (InternalHandle != null && InternalHandle.IsClosed) // only check IsClosed if we have a handle + if (InternalHandle is not null && InternalHandle.IsClosed) // only check IsClosed if we have a handle { throw Error.GetPipeNotOpen(); } @@ -214,11 +214,11 @@ private void CheckDisconnectOperations() { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyDisconnected); } - if (InternalHandle == null && CheckOperationsRequiresSetHandle) + if (InternalHandle is null && CheckOperationsRequiresSetHandle) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } - if ((State == PipeState.Closed) || (InternalHandle != null && InternalHandle.IsClosed)) + if ((State == PipeState.Closed) || (InternalHandle is not null && InternalHandle.IsClosed)) { throw Error.GetPipeNotOpen(); } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs index 118463c35d0f7f..f024bcf7e644da 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs @@ -34,7 +34,7 @@ internal abstract unsafe class PipeCompletionSource : TaskCompletionSou protected PipeCompletionSource(ThreadPoolBoundHandle handle, ReadOnlyMemory bufferToPin) : base(TaskCreationOptions.RunContinuationsAsynchronously) { - Debug.Assert(handle != null, "handle is null"); + Debug.Assert(handle is not null, "handle is null"); _threadPoolBinding = handle; _state = NoResult; @@ -62,7 +62,7 @@ internal void RegisterForCancellation(CancellationToken cancellationToken) #endif // Quick check to make sure that the cancellation token supports cancellation, and that the IO hasn't completed - if (cancellationToken.CanBeCanceled && Overlapped != null) + if (cancellationToken.CanBeCanceled && Overlapped is not null) { // Register the cancellation only if the IO hasn't completed int state = Interlocked.CompareExchange(ref _state, RegisteringCancellation, NoResult); @@ -96,7 +96,7 @@ internal void ReleaseResources() // NOTE: The cancellation must *NOT* be running at this point, or it may observe freed memory // (this is why we disposed the registration above) - if (_overlapped != null) + if (_overlapped is not null) { _threadPoolBinding.FreeNativeOverlapped(Overlapped); _overlapped = null; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs index c37f180e35df93..383187e3700916 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs @@ -19,7 +19,7 @@ internal PipeSecurity(SafePipeHandle safeHandle, AccessControlSections includeSe public void AddAccessRule(PipeAccessRule rule) { - if (rule == null) + if (rule is null) throw new ArgumentNullException(nameof(rule)); base.AddAccessRule(rule); @@ -27,7 +27,7 @@ public void AddAccessRule(PipeAccessRule rule) public void SetAccessRule(PipeAccessRule rule) { - if (rule == null) + if (rule is null) throw new ArgumentNullException(nameof(rule)); base.SetAccessRule(rule); @@ -35,7 +35,7 @@ public void SetAccessRule(PipeAccessRule rule) public void ResetAccessRule(PipeAccessRule rule) { - if (rule == null) + if (rule is null) throw new ArgumentNullException(nameof(rule)); base.ResetAccessRule(rule); @@ -43,7 +43,7 @@ public void ResetAccessRule(PipeAccessRule rule) public bool RemoveAccessRule(PipeAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -56,7 +56,7 @@ public bool RemoveAccessRule(PipeAccessRule rule) { PipeAccessRule? fsrule = rules[i] as PipeAccessRule; - if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) + if ((fsrule is not null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { @@ -84,7 +84,7 @@ public bool RemoveAccessRule(PipeAccessRule rule) public void RemoveAccessRuleSpecific(PipeAccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -98,7 +98,7 @@ public void RemoveAccessRuleSpecific(PipeAccessRule rule) { PipeAccessRule? fsrule = rules[i] as PipeAccessRule; - if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) + if ((fsrule is not null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs index 6e6fa8a5c1385f..97b43228022535 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs @@ -80,7 +80,7 @@ internal static string GetPipePath(string serverName, string pipeName) /// The handle to validate. internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { - if (safePipeHandle.NamedPipeSocket == null) + if (safePipeHandle.NamedPipeSocket is null) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); @@ -109,12 +109,12 @@ internal virtual void DisposeCore(bool disposing) private unsafe int ReadCore(Span buffer) { - Debug.Assert(_handle != null); + Debug.Assert(_handle is not null); DebugAssertHandleValid(_handle); // For named pipes, receive on the socket. Socket? socket = _handle.NamedPipeSocket; - if (socket != null) + if (socket is not null) { // For a blocking socket, we could simply use the same Read syscall as is done // for reading an anonymous pipe. However, for a non-blocking socket, Read could @@ -141,12 +141,12 @@ private unsafe int ReadCore(Span buffer) private unsafe void WriteCore(ReadOnlySpan buffer) { - Debug.Assert(_handle != null); + Debug.Assert(_handle is not null); DebugAssertHandleValid(_handle); // For named pipes, send to the socket. Socket? socket = _handle.NamedPipeSocket; - if (socket != null) + if (socket is not null) { // For a blocking socket, we could simply use the same Write syscall as is done // for writing to anonymous pipe. However, for a non-blocking socket, Write could @@ -378,7 +378,7 @@ private int GetPipeBufferSize() // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction). // If we don't, just return the buffer size that was passed to the constructor. - return _handle != null ? + return _handle is not null ? CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) : (int)_outBufferSize; } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs index b221c9880b6cfa..8872b1e8190abb 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs @@ -320,7 +320,7 @@ public virtual PipeTransmissionMode ReadMode private unsafe int ReadFileNative(SafePipeHandle handle, Span buffer, NativeOverlapped* overlapped, out int errorCode) { DebugAssertHandleValid(handle); - Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative."); + Debug.Assert((_isAsync && overlapped is not null) || (!_isAsync && overlapped is null), "Async IO parameter screwup in call to ReadFileNative."); // You can't use the fixed statement on an array of length 0. Note that async callers // check to avoid calling this first, so they can call user's callback @@ -358,7 +358,7 @@ private unsafe int ReadFileNative(SafePipeHandle handle, Span buffer, Nati private unsafe int WriteFileNative(SafePipeHandle handle, ReadOnlySpan buffer, NativeOverlapped* overlapped, out int errorCode) { DebugAssertHandleValid(handle); - Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative."); + Debug.Assert((_isAsync && overlapped is not null) || (!_isAsync && overlapped is null), "Async IO parameter screwup in call to WriteFileNative."); // You can't use the fixed statement on an array of length 0. Note that async callers // check to avoid calling this first, so they can call user's callback @@ -405,7 +405,7 @@ internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleIn { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); - if (pipeSecurity != null) + if (pipeSecurity is not null) { byte[] securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(securityDescriptor, GCHandleType.Pinned); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs index e01f10b8161cc8..5e84d3add0dd6b 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs @@ -95,7 +95,7 @@ private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode // This method may also be called to uninitialize a handle, setting it to null. protected void InitializeHandle(SafePipeHandle? handle, bool isExposed, bool isAsync) { - if (isAsync && handle != null) + if (isAsync && handle is not null) { InitializeAsyncHandle(handle); } @@ -322,7 +322,7 @@ public override void EndWrite(IAsyncResult asyncResult) private void CheckReadWriteArgs(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -335,7 +335,7 @@ private void CheckReadWriteArgs(byte[] buffer, int offset, int count) [Conditional("DEBUG")] private static void DebugAssertHandleValid(SafePipeHandle handle) { - Debug.Assert(handle != null, "handle is null"); + Debug.Assert(handle is not null, "handle is null"); Debug.Assert(!handle.IsClosed, "handle is closed"); } @@ -382,7 +382,7 @@ protected override void Dispose(bool disposing) { // Nothing will be done differently based on whether we are // disposing vs. finalizing. - if (_handle != null && !_handle.IsClosed) + if (_handle is not null && !_handle.IsClosed) { _handle.Dispose(); } @@ -434,12 +434,12 @@ public bool IsMessageComplete { throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected); } - if (CheckOperationsRequiresSetHandle && _handle == null) + if (CheckOperationsRequiresSetHandle && _handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } - if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed)) + if ((_state == PipeState.Closed) || (_handle is not null && _handle.IsClosed)) { throw Error.GetPipeNotOpen(); } @@ -465,7 +465,7 @@ public SafePipeHandle SafePipeHandle { get { - if (_handle == null) + if (_handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } @@ -553,13 +553,13 @@ public override long Seek(long offset, SeekOrigin origin) // or connected. Named client overrides protected internal virtual void CheckPipePropertyOperations() { - if (CheckOperationsRequiresSetHandle && _handle == null) + if (CheckOperationsRequiresSetHandle && _handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } // these throw object disposed - if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed)) + if ((_state == PipeState.Closed) || (_handle is not null && _handle.IsClosed)) { throw Error.GetPipeNotOpen(); } @@ -578,13 +578,13 @@ protected internal void CheckReadOperations() { throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected); } - if (CheckOperationsRequiresSetHandle && _handle == null) + if (CheckOperationsRequiresSetHandle && _handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } // these throw object disposed - if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed)) + if ((_state == PipeState.Closed) || (_handle is not null && _handle.IsClosed)) { throw Error.GetPipeNotOpen(); } @@ -602,7 +602,7 @@ protected internal void CheckWriteOperations() { throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected); } - if (CheckOperationsRequiresSetHandle && _handle == null) + if (CheckOperationsRequiresSetHandle && _handle is null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } @@ -614,7 +614,7 @@ protected internal void CheckWriteOperations() } // these throw object disposed - if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed)) + if ((_state == PipeState.Closed) || (_handle is not null && _handle.IsClosed)) { throw Error.GetPipeNotOpen(); } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs index 6ebcb91b312920..0b3de770574ac0 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs @@ -19,7 +19,7 @@ public static PipeSecurity GetAccessControl(this PipeStream stream) public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity) { - if (pipeSecurity == null) + if (pipeSecurity is null) { throw new ArgumentNullException(nameof(pipeSecurity)); } diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SafeSerialDeviceHandle.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SafeSerialDeviceHandle.Unix.cs index 7f3f02b47f947f..740bdcedcfdbaf 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SafeSerialDeviceHandle.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SafeSerialDeviceHandle.Unix.cs @@ -18,7 +18,7 @@ private SafeSerialDeviceHandle() : base(ownsHandle: true) internal static SafeSerialDeviceHandle Open(string portName) { - Debug.Assert(portName != null); + Debug.Assert(portName is not null); SafeSerialDeviceHandle handle = Interop.Serial.SerialPortOpen(portName); if (handle.IsInvalid) diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Win32.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Win32.cs index ac930c78a1a1d5..1b0c2e2aab80ee 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Win32.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Win32.cs @@ -25,7 +25,7 @@ public static string[] GetPortNames() using (RegistryKey serialKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM")) { - if (serialKey != null) + if (serialKey is not null) { string[] result = serialKey.GetValueNames(); for (int i = 0; i < result.Length; i++) diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs index 9f05c3a14919b2..390da39d70854c 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs @@ -74,12 +74,12 @@ public event SerialDataReceivedEventHandler DataReceived { add { - bool wasNull = _dataReceived == null; + bool wasNull = _dataReceived is null; _dataReceived += value; if (wasNull) { - if (_internalSerialStream != null) + if (_internalSerialStream is not null) { _internalSerialStream.DataReceived += _dataReceivedHandler; } @@ -89,9 +89,9 @@ public event SerialDataReceivedEventHandler DataReceived { _dataReceived -= value; - if (_dataReceived == null) + if (_dataReceived is null) { - if (_internalSerialStream != null) + if (_internalSerialStream is not null) { _internalSerialStream.DataReceived -= _dataReceivedHandler; } @@ -267,7 +267,7 @@ public Encoding Encoding } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(Encoding)); // Limit the encodings we support to some known ones. The code pages < 50000 represent all of the single-byte @@ -307,7 +307,7 @@ public Handshake Handshake public bool IsOpen { // true only if the Open() method successfully called on this SerialPort object, without Close() being called more recently. - get { return (_internalSerialStream != null && _internalSerialStream.IsOpen); } + get { return (_internalSerialStream is not null && _internalSerialStream.IsOpen); } } public string NewLine @@ -315,7 +315,7 @@ public string NewLine get { return _newLine; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(NewLine)); if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(NewLine)), nameof(NewLine)); @@ -362,7 +362,7 @@ public string PortName } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(PortName)); if (value.Length == 0) throw new ArgumentException(SR.PortNameEmpty_String, nameof(PortName)); @@ -603,7 +603,7 @@ public void Open() _internalSerialStream.ErrorReceived += new SerialErrorReceivedEventHandler(CatchErrorEvents); _internalSerialStream.PinChanged += new SerialPinChangedEventHandler(CatchPinChangedEvents); - if (_dataReceived != null) + if (_dataReceived is not null) { _internalSerialStream.DataReceived += _dataReceivedHandler; } @@ -622,7 +622,7 @@ public int Read(byte[] buffer, int offset, int count) { if (!IsOpen) throw new InvalidOperationException(SR.Port_not_open); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); @@ -763,7 +763,7 @@ public int Read(char[] buffer, int offset, int count) { if (!IsOpen) throw new InvalidOperationException(SR.Port_not_open); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); @@ -778,7 +778,7 @@ public int Read(char[] buffer, int offset, int count) private int InternalRead(char[] buffer, int offset, int count, int timeout, bool countMultiByteCharsAsOne) { Debug.Assert(IsOpen, "port not open!"); - Debug.Assert(buffer != null, "invalid buffer!"); + Debug.Assert(buffer is not null, "invalid buffer!"); Debug.Assert(offset >= 0, "invalid offset!"); Debug.Assert(count >= 0, "invalid count!"); Debug.Assert(buffer.Length - offset >= count, "invalid offset/count!"); @@ -857,7 +857,7 @@ private int ReadBufferIntoChars(char[] buffer, int offset, int count, bool count // funky fallbacks that would make it not single byte DecoderReplacementFallback fallback = _encoding.DecoderFallback as DecoderReplacementFallback; if (_encoding.IsSingleByte && _encoding.GetMaxCharCount(bytesToRead) == bytesToRead && - fallback != null && fallback.MaxCharCount == 1) + fallback is not null && fallback.MaxCharCount == 1) { // kill ASCII/ANSI encoding easily. // read at least one and at most *count* characters @@ -1006,7 +1006,7 @@ public string ReadTo(string value) { if (!IsOpen) throw new InvalidOperationException(SR.Port_not_open); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(value)), nameof(value)); @@ -1024,7 +1024,7 @@ public string ReadTo(string value) _readLen += _internalSerialStream.Read(_inBuffer, _readLen, bytesInStream); - if (_singleCharBuffer == null) + if (_singleCharBuffer is null) { // This is somewhat of an approximate guesstimate to get the max char[] size needed to encode a single character _singleCharBuffer = new char[_maxByteCountForSingleChar]; @@ -1127,7 +1127,7 @@ public void Write(string text) { if (!IsOpen) throw new InvalidOperationException(SR.Port_not_open); - if (text == null) + if (text is null) throw new ArgumentNullException(nameof(text)); if (text.Length == 0) return; byte[] bytesToWrite; @@ -1143,7 +1143,7 @@ public void Write(char[] buffer, int offset, int count) { if (!IsOpen) throw new InvalidOperationException(SR.Port_not_open); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); @@ -1163,7 +1163,7 @@ public void Write(byte[] buffer, int offset, int count) { if (!IsOpen) throw new InvalidOperationException(SR.Port_not_open); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); @@ -1191,7 +1191,7 @@ private void CatchErrorEvents(object src, SerialErrorReceivedEventArgs e) SerialErrorReceivedEventHandler eventHandler = ErrorReceived; SerialStream stream = _internalSerialStream; - if ((eventHandler != null) && (stream != null)) + if ((eventHandler is not null) && (stream is not null)) { lock (stream) { @@ -1206,7 +1206,7 @@ private void CatchPinChangedEvents(object src, SerialPinChangedEventArgs e) SerialPinChangedEventHandler eventHandler = PinChanged; SerialStream stream = _internalSerialStream; - if ((eventHandler != null) && (stream != null)) + if ((eventHandler is not null) && (stream is not null)) { lock (stream) { @@ -1221,7 +1221,7 @@ private void CatchReceivedEvents(object src, SerialDataReceivedEventArgs e) SerialDataReceivedEventHandler eventHandler = _dataReceived; SerialStream stream = _internalSerialStream; - if ((eventHandler != null) && (stream != null)) + if ((eventHandler is not null) && (stream is not null)) { lock (stream) { diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index 65f7fd62b1bff8..3aa3b6cb3af4d5 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -44,7 +44,7 @@ internal event SerialDataReceivedEventHandler DataReceived { add { - bool wasNull = _dataReceived == null; + bool wasNull = _dataReceived is null; _dataReceived += value; if (wasNull) @@ -64,7 +64,7 @@ internal event SerialPinChangedEventHandler PinChanged { add { - bool wasNull = _pinChanged == null; + bool wasNull = _pinChanged is null; _pinChanged += value; if (wasNull) @@ -91,7 +91,7 @@ public override int ReadTimeout { if (value < 0 && value != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException(nameof(ReadTimeout), SR.ArgumentOutOfRange_Timeout); - if (_handle == null) { + if (_handle is null) { InternalResources.FileNotOpen(); } _readTimeout = value; @@ -105,7 +105,7 @@ public override int WriteTimeout { if (value < 0 && value != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException(nameof(ReadTimeout), SR.ArgumentOutOfRange_Timeout); - if (_handle == null) { + if (_handle is null) { InternalResources.FileNotOpen(); } _writeTimeout = value; @@ -353,26 +353,26 @@ internal byte ParityReplace internal void DiscardInBuffer() { - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); // This may or may not work depending on hardware. Interop.Termios.TermiosDiscard(_handle, Interop.Termios.Queue.ReceiveQueue); } internal void DiscardOutBuffer() { - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); // This may or may not work depending on hardware. Interop.Termios.TermiosDiscard(_handle, Interop.Termios.Queue.SendQueue); } internal void SetBufferSizes(int readBufferSize, int writeBufferSize) { - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); // Ignore for now. } - internal bool IsOpen => _handle != null; + internal bool IsOpen => _handle is not null; // Flush dumps the contents of the serial driver's internal read and write buffers. @@ -381,7 +381,7 @@ internal void SetBufferSizes(int readBufferSize, int writeBufferSize) // Note: Serial driver's write buffer is *already* attempting to write it, so we can only wait until it finishes. public override void Flush() { - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); SpinWait sw = default; while (!_writeQueue.IsEmpty) @@ -535,7 +535,7 @@ private int EndReadWrite(IAsyncResult asyncResult) internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) { - if (portName == null) + if (portName is null) { throw new ArgumentNullException(nameof(portName)); } @@ -596,9 +596,9 @@ private void EnsureIOLoopRunning() { lock (_ioLoopLock) { - if (_ioLoop == null) + if (_ioLoop is null) { - Debug.Assert(_handle != null); + Debug.Assert(_handle is not null); _ioLoop = Task.Factory.StartNew( IOLoop, CancellationToken.None, @@ -638,7 +638,7 @@ protected override void Dispose(bool disposing) FinishPendingIORequests(); - if (_handle != null) + if (_handle is not null) { _handle.Dispose(); _handle = null; @@ -652,7 +652,7 @@ protected override void Dispose(bool disposing) // but are currently split to avoid allocation related to context private void RaiseDataReceivedChars() { - if (_dataReceived != null) + if (_dataReceived is not null) { ThreadPool.QueueUserWorkItem(s => { var thisRef = (SerialStream)s; @@ -663,7 +663,7 @@ private void RaiseDataReceivedChars() private void RaisePinChanged(SerialPinChange pinChanged) { - if (_pinChanged != null) + if (_pinChanged is not null) { ThreadPool.QueueUserWorkItem(s => { var thisRef = (SerialStream)s; @@ -674,12 +674,12 @@ private void RaisePinChanged(SerialPinChange pinChanged) private void RaiseDataReceivedEof() { - if (_dataReceived != null) + if (_dataReceived is not null) { ThreadPool.QueueUserWorkItem(s => { var thisRef = (SerialStream)s; SerialDataReceivedEventHandler dataReceived = thisRef._dataReceived; - if (dataReceived != null) + if (dataReceived is not null) { dataReceived(thisRef, new SerialDataReceivedEventArgs(SerialData.Eof)); } @@ -794,9 +794,9 @@ private unsafe void IOLoop() bool lastIsIdle = false; int ticksWhenIdleStarted = 0; - Signals lastSignals = _pinChanged != null ? Interop.Termios.TermiosGetAllSignals(_handle) : Signals.Error; + Signals lastSignals = _pinChanged is not null ? Interop.Termios.TermiosGetAllSignals(_handle) : Signals.Error; - bool IsNoEventRegistered() => _dataReceived == null && _pinChanged == null; + bool IsNoEventRegistered() => _dataReceived is null && _pinChanged is null; while (IsOpen && !eofReceived && !_ioLoopFinished) { @@ -883,7 +883,7 @@ private unsafe void IOLoop() RaiseDataReceivedChars(); } - if (_pinChanged != null) + if (_pinChanged is not null) { // Checking for changes could technically speaking be done by waiting with ioctl+TIOCMIWAIT // This would require spinning new thread and also would potentially trigger events when diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs index 7385ca885910b8..060c6882eb867a 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs @@ -236,7 +236,7 @@ internal Handshake Handshake } } - internal bool IsOpen => _handle != null && !_eventRunner.ShutdownLoop; + internal bool IsOpen => _handle is not null && !_eventRunner.ShutdownLoop; internal Parity Parity { @@ -345,7 +345,7 @@ public override int ReadTimeout { if (value < 0 && value != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException(nameof(ReadTimeout), SR.ArgumentOutOfRange_Timeout); - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); int oldReadConstant = _commTimeouts.ReadTotalTimeoutConstant; int oldReadInterval = _commTimeouts.ReadIntervalTimeout; @@ -470,7 +470,7 @@ public override int WriteTimeout { if (value <= 0 && value != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException(nameof(WriteTimeout), SR.ArgumentOutOfRange_WriteTimeout); - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); int oldWriteConstant = _commTimeouts.WriteTotalTimeoutConstant; _commTimeouts.WriteTotalTimeoutConstant = ((value == SerialPort.InfiniteTimeout) ? 0 : value); @@ -558,7 +558,7 @@ internal int BytesToWrite internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) { - if (portName == null) + if (portName is null) { throw new ArgumentNullException(nameof(portName)); } @@ -700,7 +700,7 @@ protected override void Dispose(bool disposing) { // Signal the other side that we're closing. Should do regardless of whether we've called // Close() or not Dispose() - if (_handle != null && !_handle.IsInvalid) + if (_handle is not null && !_handle.IsInvalid) { try { @@ -751,7 +751,7 @@ protected override void Dispose(bool disposing) DiscardOutBuffer(); } - if (disposing && _eventRunner != null && _waitForComEventTask != null) + if (disposing && _eventRunner is not null && _waitForComEventTask is not null) { _waitForComEventTask.GetAwaiter().GetResult(); _eventRunner.waitCommEventWaitHandle.Close(); @@ -855,11 +855,11 @@ public unsafe override int EndRead(IAsyncResult asyncResult) if (!_isAsync) return base.EndRead(asyncResult); - if (asyncResult == null) + if (asyncResult is null) throw new ArgumentNullException(nameof(asyncResult)); SerialStreamAsyncResult afsar = asyncResult as SerialStreamAsyncResult; - if (afsar == null || afsar._isWrite) + if (afsar is null || afsar._isWrite) InternalResources.WrongAsyncResult(); // This sidesteps race conditions, avoids memory corruption after freeing the @@ -872,7 +872,7 @@ public unsafe override int EndRead(IAsyncResult asyncResult) // Obtain the WaitHandle, but don't use public property in case we // delay initialize the manual reset event in the future. WaitHandle wh = afsar._waitHandle; - if (wh != null) + if (wh is not null) { // We must block to ensure that AsyncFSCallback has completed, // and we should close the WaitHandle in here. @@ -903,7 +903,7 @@ public unsafe override int EndRead(IAsyncResult asyncResult) // Free memory, GC handles. NativeOverlapped* overlappedPtr = afsar._overlapped; - if (overlappedPtr != null) + if (overlappedPtr is not null) { // Legacy behavior as indicated by tests (e.g.: System.IO.Ports.Tests.SerialStream_EndRead.EndReadAfterClose) // expects to be able to call EndRead after Close/Dispose - even if disposed _threadPoolBinding can free the @@ -935,11 +935,11 @@ public unsafe override void EndWrite(IAsyncResult asyncResult) if (_inBreak) throw new InvalidOperationException(SR.In_Break_State); - if (asyncResult == null) + if (asyncResult is null) throw new ArgumentNullException(nameof(asyncResult)); SerialStreamAsyncResult afsar = asyncResult as SerialStreamAsyncResult; - if (afsar == null || !afsar._isWrite) + if (afsar is null || !afsar._isWrite) InternalResources.WrongAsyncResult(); // This sidesteps race conditions, avoids memory corruption after freeing the @@ -950,7 +950,7 @@ public unsafe override void EndWrite(IAsyncResult asyncResult) // Obtain the WaitHandle, but don't use public property in case we // delay initialize the manual reset event in the future. WaitHandle wh = afsar._waitHandle; - if (wh != null) + if (wh is not null) { // We must block to ensure that AsyncFSCallback has completed, // and we should close the WaitHandle in here. @@ -967,7 +967,7 @@ public unsafe override void EndWrite(IAsyncResult asyncResult) // Free memory, GC handles. NativeOverlapped* overlappedPtr = afsar._overlapped; - if (overlappedPtr != null) + if (overlappedPtr is not null) { // Legacy behavior as indicated by tests (e.g.: System.IO.Ports.Tests.SerialStream_EndWrite.EndWriteAfterSerialStreamClose) // expects to be able to call EndWrite after Close/Dispose - even if disposed _threadPoolBinding can free the @@ -988,7 +988,7 @@ public unsafe override void EndWrite(IAsyncResult asyncResult) // Note: Serial driver's write buffer is *already* attempting to write it, so we can only wait until it finishes. public override void Flush() { - if (_handle == null) throw new ObjectDisposedException(SR.Port_not_open); + if (_handle is null) throw new ObjectDisposedException(SR.Port_not_open); Interop.Kernel32.FlushFileBuffers(_handle); } @@ -1031,7 +1031,7 @@ internal unsafe int Read(byte[] array, int offset, int count, int timeout) internal unsafe int ReadByte(int timeout) { - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); int numBytes = 0; if (_isAsync) @@ -1057,7 +1057,7 @@ internal unsafe int ReadByte(int timeout) internal void SetBufferSizes(int readBufferSize, int writeBufferSize) { - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); if (!Interop.Kernel32.SetupComm(_handle, readBufferSize, writeBufferSize)) throw Win32Marshal.GetExceptionForLastWin32Error(); @@ -1078,7 +1078,7 @@ internal unsafe void Write(byte[] array, int offset, int count, int timeout) EndWrite(result); SerialStreamAsyncResult afsar = result as SerialStreamAsyncResult; - Debug.Assert(afsar != null, "afsar should be a SerialStreamAsyncResult and should not be null"); + Debug.Assert(afsar is not null, "afsar should be a SerialStreamAsyncResult and should not be null"); numBytes = afsar._numBytes; } else @@ -1110,7 +1110,7 @@ internal unsafe void WriteByte(byte value, int timeout) if (_inBreak) throw new InvalidOperationException(SR.In_Break_State); - if (_handle == null) InternalResources.FileNotOpen(); + if (_handle is null) InternalResources.FileNotOpen(); _tempBuf[0] = value; @@ -1122,7 +1122,7 @@ internal unsafe void WriteByte(byte value, int timeout) EndWrite(result); SerialStreamAsyncResult afsar = result as SerialStreamAsyncResult; - Debug.Assert(afsar != null, "afsar should be a SerialStreamAsyncResult and should not be null"); + Debug.Assert(afsar is not null, "afsar should be a SerialStreamAsyncResult and should not be null"); numBytes = afsar._numBytes; } else @@ -1524,7 +1524,7 @@ private static unsafe void AsyncFSCallback(uint errorCode, uint numBytes, Native // But don't close it if the user callback called EndXxx, // which then closed the manual reset event already. ManualResetEvent wh = asyncResult._waitHandle; - if (wh != null) + if (wh is not null) { bool r = wh.Set(); if (!r) throw Win32Marshal.GetExceptionForLastWin32Error(); @@ -1738,10 +1738,10 @@ private void CallErrorEvents(object state) { int errors = (int)state; SerialStream stream = (SerialStream)streamWeakReference.Target; - if (stream == null) + if (stream is null) return; - if (stream.ErrorReceived != null) + if (stream.ErrorReceived is not null) { if ((errors & (int)SerialError.TXFull) != 0) stream.ErrorReceived(stream, new SerialErrorReceivedEventArgs(SerialError.TXFull)); @@ -1766,10 +1766,10 @@ private void CallReceiveEvents(object state) { int nativeEvents = (int)state; SerialStream stream = (SerialStream)streamWeakReference.Target; - if (stream == null) + if (stream is null) return; - if (stream.DataReceived != null) + if (stream.DataReceived is not null) { if ((nativeEvents & (int)SerialData.Chars) != 0) stream.DataReceived(stream, new SerialDataReceivedEventArgs(SerialData.Chars)); @@ -1785,10 +1785,10 @@ private void CallPinEvents(object state) int nativeEvents = (int)state; SerialStream stream = (SerialStream)streamWeakReference.Target; - if (stream == null) + if (stream is null) return; - if (stream.PinChanged != null) + if (stream.PinChanged is not null) { if ((nativeEvents & (int)SerialPinChange.CtsChanged) != 0) stream.PinChanged(stream, new SerialPinChangedEventArgs(SerialPinChange.CtsChanged)); @@ -1854,9 +1854,9 @@ public WaitHandle AsyncWaitHandle // reason to create a synchronization primitive here. Fixing // this will save us some perf, assuming we can correctly // initialize the ManualResetEvent. - if (_waitHandle == null) { + if (_waitHandle is null) { ManualResetEvent mre = new ManualResetEvent(false); - if (_overlapped != null && _overlapped->EventHandle != IntPtr.Zero) + if (_overlapped is not null && _overlapped->EventHandle != IntPtr.Zero) mre.Handle = _overlapped->EventHandle; if (_isComplete) mre.Set(); diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs index cec491596eff31..ed82e42d2fffb1 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs @@ -32,7 +32,7 @@ internal sealed partial class SerialStream : Stream // are not usefully queried by applications which know they have a SerialStream, etc... public override bool CanRead { - get { return (_handle != null); } + get { return (_handle is not null); } } public override bool CanSeek @@ -42,12 +42,12 @@ public override bool CanSeek public override bool CanTimeout { - get { return (_handle != null); } + get { return (_handle is not null); } } public override bool CanWrite { - get { return (_handle != null); } + get { return (_handle is not null); } } public override long Length @@ -88,7 +88,7 @@ public override void Write(byte[] array, int offset, int count) private void CheckReadWriteArguments(byte[] array, int offset, int count) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); @@ -96,7 +96,7 @@ private void CheckReadWriteArguments(byte[] array, int offset, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNumRequired); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - if (_handle == null) + if (_handle is null) InternalResources.FileNotOpen(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs index 97846a853545f6..d5bfd0de261184 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs @@ -74,8 +74,8 @@ public static BindingRestrictions GetTypeRestriction(Expression expression, Type /// internal static BindingRestrictions GetTypeRestriction(DynamicMetaObject obj) { - Debug.Assert(obj != null); - if (obj.Value == null && obj.HasValue) + Debug.Assert(obj is not null); + if (obj.Value is null && obj.HasValue) { return GetInstanceRestriction(obj.Expression, null); } @@ -122,11 +122,11 @@ public static BindingRestrictions GetExpressionRestriction(Expression expression public static BindingRestrictions Combine(IList? contributingObjects) { BindingRestrictions res = Empty; - if (contributingObjects != null) + if (contributingObjects is not null) { foreach (DynamicMetaObject mo in contributingObjects) { - if (mo != null) + if (mo is not null) { res = res.Merge(mo.Restrictions); } @@ -238,7 +238,7 @@ private sealed class CustomRestriction : BindingRestrictions internal CustomRestriction(Expression expression) { - Debug.Assert(expression != null); + Debug.Assert(expression is not null); _expression = expression; } @@ -259,8 +259,8 @@ private sealed class TypeRestriction : BindingRestrictions internal TypeRestriction(Expression parameter, Type type) { - Debug.Assert(parameter != null); - Debug.Assert(type != null); + Debug.Assert(parameter is not null); + Debug.Assert(type is not null); _expression = parameter; _type = type; } @@ -282,7 +282,7 @@ private sealed class InstanceRestriction : BindingRestrictions internal InstanceRestriction(Expression parameter, object? instance) { - Debug.Assert(parameter != null); + Debug.Assert(parameter is not null); _expression = parameter; _instance = instance; } @@ -297,7 +297,7 @@ public override int GetHashCode() internal override Expression GetExpression() { - if (_instance == null) + if (_instance is null) { return Expression.Equal( Expression.Convert(_expression, typeof(object)), diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs index ec1d4b89ef4f48..39621802403abc 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs @@ -60,7 +60,7 @@ public DynamicMetaObject FallbackConvert(DynamicMetaObject target) public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[]? args) { ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); + ContractUtils.Requires(args is null || args.Length == 0, nameof(args)); return target.BindConvert(this); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs index 4215864b85b7f9..a6f17cb1269977 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs @@ -65,7 +65,7 @@ public DynamicMetaObject FallbackDeleteMember(DynamicMetaObject target) public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[]? args) { ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); + ContractUtils.Requires(args is null || args.Length == 0, nameof(args)); return target.BindDeleteMember(this); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs index 1a7a115cd94981..c56ef2c34005c4 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs @@ -261,7 +261,7 @@ internal static Expression[] GetExpressions(DynamicMetaObject[] objects) DynamicMetaObject mo = objects[i]; ContractUtils.RequiresNotNull(mo, nameof(objects)); Expression expr = mo.Expression; - Debug.Assert(expr != null, "Unexpected null expression; ctor should have caught this."); + Debug.Assert(expr is not null, "Unexpected null expression; ctor should have caught this."); res[i] = expr; } @@ -286,9 +286,9 @@ public static DynamicMetaObject Create(object value, Expression expression) { var idoMetaObject = ido.GetMetaObject(expression); - if (idoMetaObject == null || + if (idoMetaObject is null || !idoMetaObject.HasValue || - idoMetaObject.Value == null || + idoMetaObject.Value is null || (object)idoMetaObject.Expression != (object)expression) { throw System.Linq.Expressions.Error.InvalidMetaObjectCreated(ido.GetType()); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs index 824c7845515e1f..542e49e17419f3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs @@ -89,7 +89,7 @@ public sealed override Expression Bind(object[] args, ReadOnlyCollection(); block.Add( @@ -481,7 +481,7 @@ private static Expression ReferenceArgAssign(Expression callArgs, Expression[] a } } - if (block != null) + if (block is not null) return Expression.Block(block); else return AstUtils.Empty; @@ -497,9 +497,9 @@ private static Expression[] BuildCallArgs(TBinder binder, Expression[] where TBinder : DynamicMetaObjectBinder { if (!object.ReferenceEquals(parameters, s_noArgs)) - return arg1 != null ? new Expression[] { Constant(binder), arg0, arg1 } : new Expression[] { Constant(binder), arg0 }; + return arg1 is not null ? new Expression[] { Constant(binder), arg0, arg1 } : new Expression[] { Constant(binder), arg0 }; else - return arg1 != null ? new Expression[] { Constant(binder), arg1 } : new Expression[] { Constant(binder) }; + return arg1 is not null ? new Expression[] { Constant(binder), arg1 } : new Expression[] { Constant(binder) }; } private static ConstantExpression Constant(TBinder binder) @@ -575,11 +575,11 @@ private DynamicMetaObject BuildCallMethodWithResult(MethodInfo method, // Need to add a conversion if calling TryConvert if (binder.ReturnType != typeof(object)) { - Debug.Assert(binder is ConvertBinder && fallbackInvoke == null); + Debug.Assert(binder is ConvertBinder && fallbackInvoke is null); UnaryExpression convert = Expression.Convert(resultMO.Expression, binder.ReturnType); // will always be a cast or unbox - Debug.Assert(convert.Method == null); + Debug.Assert(convert.Method is null); // Prepare a good exception message in case the convert will fail string convertFailed = System.Linq.Expressions.Strings.DynamicObjectResultNotAssignable( @@ -591,7 +591,7 @@ private DynamicMetaObject BuildCallMethodWithResult(MethodInfo method, Expression condition; // If the return type can not be assigned null then just check for type assignability otherwise allow null. - if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType(binder.ReturnType) == null) + if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType(binder.ReturnType) is null) { condition = Expression.TypeIs(resultMO.Expression, binder.ReturnType); } @@ -637,7 +637,7 @@ private DynamicMetaObject BuildCallMethodWithResult(MethodInfo method, resultMO = new DynamicMetaObject(checkedConvert, resultMO.Restrictions); } - if (fallbackInvoke != null) + if (fallbackInvoke is not null) { resultMO = fallbackInvoke(this, binder, resultMO); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs index 1f3439e380562f..c68bf2af971ba6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs @@ -58,7 +58,7 @@ internal ExpandoClass FindNewClass(string newKey) for (int i = 0; i < infos.Count; i++) { ExpandoClass? klass = infos[i].Target as ExpandoClass; - if (klass == null) + if (klass is null) { infos.RemoveAt(i); i--; @@ -89,7 +89,7 @@ internal ExpandoClass FindNewClass(string newKey) /// private List GetTransitionList(int hashCode) { - if (_transitions == null) + if (_transitions is null) { _transitions = new Dictionary>(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs index 5a6b72d3087742..eb641bbd4f16d3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs @@ -172,7 +172,7 @@ internal void TrySetValue(object? indexClass, int index, object? value, string n // Notify property changed outside the lock PropertyChangedEventHandler? propertyChanged = _propertyChanged; - if (propertyChanged != null && value != oldValue) + if (propertyChanged is not null && value != oldValue) { propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[index])); } @@ -688,7 +688,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Notify property changed for all properties. var propertyChanged = _propertyChanged; - if (propertyChanged != null) + if (propertyChanged is not null) { for (int i = 0, n = data.Class.Keys.Length; i < n; i++) { @@ -800,7 +800,7 @@ private DynamicMetaObject BindGetOrInvokeMember(DynamicMetaObjectBinder binder, ); var result = new DynamicMetaObject(value, BindingRestrictions.Empty); - if (fallbackInvoke != null) + if (fallbackInvoke is not null) { result = fallbackInvoke(result); } @@ -921,7 +921,7 @@ public override IEnumerable GetDynamicMemberNames() private DynamicMetaObject AddDynamicTestAndDefer(DynamicMetaObjectBinder binder, ExpandoClass klass, ExpandoClass? originalClass, DynamicMetaObject succeeds) { Expression ifTestSucceeds = succeeds.Expression; - if (originalClass != null) + if (originalClass is not null) { // we are accessing a member which has not yet been defined on this class. // We force a class promotion after the type check. If the class changes the diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs index 420f5919975415..86cd921a759bec 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs @@ -65,7 +65,7 @@ public DynamicMetaObject FallbackGetMember(DynamicMetaObject target) public sealed override DynamicMetaObject Bind(DynamicMetaObject target, params DynamicMetaObject[]? args) { ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); + ContractUtils.Requires(args is null || args.Length == 0, nameof(args)); return target.BindGetMember(this); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs index 9eddf145c28798..523fd24261bb83 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs @@ -71,7 +71,7 @@ public DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target) public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[]? args) { ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); + ContractUtils.Requires(args is null || args.Length == 0, nameof(args)); return target.BindUnaryOperation(this); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/UpdateDelegates.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/UpdateDelegates.Generated.cs index f54a21adb7a4f3..e3c0163c7f04e5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/UpdateDelegates.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/UpdateDelegates.Generated.cs @@ -28,7 +28,7 @@ internal static TRet UpdateAndExecute1(CallSite site, T0 arg0) // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -173,7 +173,7 @@ internal static TRet UpdateAndExecute2(CallSite site, T0 arg0, T1 // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -318,7 +318,7 @@ internal static TRet UpdateAndExecute3(CallSite site, T0 arg0, // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -463,7 +463,7 @@ internal static TRet UpdateAndExecute4(CallSite site, T0 a // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -608,7 +608,7 @@ internal static TRet UpdateAndExecute5(CallSite site, // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -753,7 +753,7 @@ internal static TRet UpdateAndExecute6(CallSite si // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -898,7 +898,7 @@ internal static TRet UpdateAndExecute7(CallSit // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -1043,7 +1043,7 @@ internal static TRet UpdateAndExecute8(Cal // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -1188,7 +1188,7 @@ internal static TRet UpdateAndExecute9 // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -1333,7 +1333,7 @@ internal static TRet UpdateAndExecute10(CallSite site, T0 arg0) // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -1621,7 +1621,7 @@ internal static void UpdateAndExecuteVoid2(CallSite site, T0 arg0, T1 ar // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -1765,7 +1765,7 @@ internal static void UpdateAndExecuteVoid3(CallSite site, T0 arg0, T // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -1909,7 +1909,7 @@ internal static void UpdateAndExecuteVoid4(CallSite site, T0 arg // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -2053,7 +2053,7 @@ internal static void UpdateAndExecuteVoid5(CallSite site, T0 // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -2197,7 +2197,7 @@ internal static void UpdateAndExecuteVoid6(CallSite site // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -2341,7 +2341,7 @@ internal static void UpdateAndExecuteVoid7(CallSite // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -2485,7 +2485,7 @@ internal static void UpdateAndExecuteVoid8(CallS // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -2629,7 +2629,7 @@ internal static void UpdateAndExecuteVoid9(C // // Level 1 cache lookup // - if ((applicable = CallSiteOps.GetRules(@this)) != null) + if ((applicable = CallSiteOps.GetRules(@this)) is not null) { for (int i = 0; i < applicable.Length; i++) { @@ -2773,7 +2773,7 @@ internal static void UpdateAndExecuteVoid10(this T[] array) /// public static ReadOnlyCollection ToReadOnly(this IEnumerable? enumerable) { - if (enumerable == null) + if (enumerable is null) { return EmptyReadOnlyCollection.Instance; } @@ -85,7 +85,7 @@ public static int ListHashCode(this ReadOnlyCollection list) int h = 6551; foreach (T t in list) { - if (t != null) + if (t is not null) { h ^= (h << 5) ^ cmp.GetHashCode(t); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs index 8125fc9ac1159a..e1a052bb6d7763 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs @@ -62,7 +62,7 @@ public static void RequiresNotNull(object value, string paramName) { Debug.Assert(!string.IsNullOrEmpty(paramName)); - if (value == null) + if (value is null) { throw new ArgumentNullException(paramName); } @@ -88,7 +88,7 @@ public static void RequiresNotNull(object value, string paramName, int index) { Debug.Assert(!string.IsNullOrEmpty(paramName)); - if (value == null) + if (value is null) { throw new ArgumentNullException(GetParamName(paramName, index)); } @@ -134,7 +134,7 @@ public static void RequiresNotNullItems(IList array, string arrayName) for (int i = 0, n = array.Count; i < n; i++) { - if (array[i] == null) + if (array[i] is null) { throw new ArgumentNullException(GetParamName(arrayName, i)); } @@ -158,7 +158,7 @@ public static void RequiresArrayRange(IList array, int offset, int count, { Debug.Assert(!string.IsNullOrEmpty(offsetName)); Debug.Assert(!string.IsNullOrEmpty(countName)); - Debug.Assert(array != null); + Debug.Assert(array is not null); if (count < 0) throw new ArgumentOutOfRangeException(countName); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs index 8e2c32aeb3bc5c..8f5d683901fc47 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs @@ -163,7 +163,7 @@ private static Delegate CreateObjectArrayDelegateRefEmit(Type delegateType, Func thunkMethod = GetCSharpThunk(returnType, hasReturnValue, parameters); - if (thunkMethod == null) + if (thunkMethod is null) { int thunkIndex = Interlocked.Increment(ref s_ThunksCreated); Type[] paramTypes = new Type[parameters.Length + 1]; diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs index 83be5cf584b926..8e2781a0da49fd 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs @@ -112,7 +112,7 @@ public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeK ParameterInfo pi = pis[i]; arg = ValidateOneArgument(method, nodeKind, arg, pi, methodParamName, nameof(arguments), i); - if (newArgs == null && arg != arguments[i]) + if (newArgs is null && arg != arguments[i]) { newArgs = new Expression[arguments.Count]; for (int j = 0; j < i; j++) @@ -120,12 +120,12 @@ public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeK newArgs[j] = arguments[j]; } } - if (newArgs != null) + if (newArgs is not null) { newArgs[i] = arg; } } - if (newArgs != null) + if (newArgs is not null) { arguments = new TrueReadOnlyCollection(newArgs); } @@ -197,7 +197,7 @@ public static void RequiresCanRead(Expression expression, string paramName, int { case ExpressionType.Index: IndexExpression index = (IndexExpression)expression; - if (index.Indexer != null && !index.Indexer.CanRead) + if (index.Indexer is not null && !index.Indexer.CanRead) { throw Error.ExpressionMustBeReadable(paramName, idx); } @@ -245,13 +245,13 @@ internal static ParameterInfo[] GetParametersForValidation(MethodBase method, Ex internal static bool SameElements(ICollection? replacement, IReadOnlyList current) where T : class { - Debug.Assert(current != null); + Debug.Assert(current is not null); if (replacement == current) // Relatively common case, so particularly useful to take the short-circuit. { return true; } - if (replacement == null) // Treat null as empty. + if (replacement is null) // Treat null as empty. { return current.Count == 0; } @@ -261,13 +261,13 @@ internal static bool SameElements(ICollection? replacement, IReadOnlyList< internal static bool SameElements(ref IEnumerable? replacement, IReadOnlyList current) where T : class { - Debug.Assert(current != null); + Debug.Assert(current is not null); if (replacement == current) // Relatively common case, so particularly useful to take the short-circuit. { return true; } - if (replacement == null) // Treat null as empty. + if (replacement is null) // Treat null as empty. { return current.Count == 0; } @@ -276,7 +276,7 @@ internal static bool SameElements(ref IEnumerable? replacement, IReadOnlyL // If we have to build a collection, build a TrueReadOnlyCollection // so it won't be built a second time if used. ICollection? replacementCol = replacement as ICollection; - if (replacementCol == null) + if (replacementCol is null) { replacement = replacementCol = replacement.ToReadOnly(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionVisitorUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionVisitorUtils.cs index 7405a9f4e104d7..fbad2b53b08ad6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionVisitorUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionVisitorUtils.cs @@ -15,7 +15,7 @@ internal static class ExpressionVisitorUtils Expression curNode = block.GetExpression(i); Expression node = visitor.Visit(curNode); - if (newNodes != null) + if (newNodes is not null) { newNodes[i] = node; } @@ -40,7 +40,7 @@ internal static class ExpressionVisitorUtils ParameterExpression curNode = nodes.GetParameter(i); ParameterExpression node = visitor.VisitAndConvert(curNode, callerName); - if (newNodes != null) + if (newNodes is not null) { newNodes[i] = node; } @@ -65,7 +65,7 @@ internal static class ExpressionVisitorUtils Expression curNode = nodes.GetArgument(i); Expression node = visitor.Visit(curNode); - if (newNodes != null) + if (newNodes is not null) { newNodes[i] = node; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/Helpers.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/Helpers.cs index 95e2dfda6b89eb..aaab8691b6a431 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/Helpers.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/Helpers.cs @@ -17,11 +17,11 @@ internal static class Helpers return first; } var set = new HashSet(cmp); - for (T t = first; t != null; t = parent(t)) + for (T t = first; t is not null; t = parent(t)) { set.Add(t); } - for (T t = second; t != null; t = parent(t)) + for (T t = second; t is not null; t = parent(t)) { if (set.Contains(t)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeExtensions.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeExtensions.cs index 5d5390a874351c..e319a7afc6b7bb 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeExtensions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeExtensions.cs @@ -17,7 +17,7 @@ internal static class TypeExtensions /// public static MethodInfo? GetAnyStaticMethodValidated(this Type type, string name, Type[] types) { - Debug.Assert(types != null); + Debug.Assert(types is not null); MethodInfo? method = type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly, null, types, null); return method.MatchesArgumentTypes(types) ? method : null; } @@ -33,9 +33,9 @@ internal static class TypeExtensions /// private static bool MatchesArgumentTypes(this MethodInfo? mi, Type[] argTypes) { - Debug.Assert(argTypes != null); + Debug.Assert(argTypes is not null); - if (mi == null) + if (mi is null) { return false; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeUtils.cs index c31dc3b7454d07..b5ab5805752fea 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeUtils.cs @@ -19,7 +19,7 @@ internal static class TypeUtils public static Type GetNullableType(this Type type) { - Debug.Assert(type != null, "type cannot be null"); + Debug.Assert(type is not null, "type cannot be null"); if (type.IsValueType && !IsNullableType(type)) { return typeof(Nullable<>).MakeGenericType(type); @@ -165,7 +165,7 @@ public static bool IsIntegerOrBool(this Type type) public static bool IsValidInstanceType(MemberInfo member, Type instanceType) { Type? targetType = member.DeclaringType; - if (targetType == null) + if (targetType is null) { return false; } @@ -211,7 +211,7 @@ public static bool IsValidInstanceType(MemberInfo member, Type instanceType) public static bool HasIdentityPrimitiveOrNullableConversionTo(this Type source, Type dest) { - Debug.Assert(source != null && dest != null); + Debug.Assert(source is not null && dest is not null); // Identity conversion if (AreEquivalent(source, dest)) @@ -242,7 +242,7 @@ public static bool HasIdentityPrimitiveOrNullableConversionTo(this Type source, public static bool HasReferenceConversionTo(this Type source, Type dest) { - Debug.Assert(source != null && dest != null); + Debug.Assert(source is not null && dest is not null); // void -> void conversion is handled elsewhere // (it's an identity conversion) @@ -416,31 +416,31 @@ private static bool HasInterfaceToArrayConversion(Type source, Type dest) private static bool IsCovariant(Type t) { - Debug.Assert(t != null); + Debug.Assert(t is not null); return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Covariant); } private static bool IsContravariant(Type t) { - Debug.Assert(t != null); + Debug.Assert(t is not null); return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Contravariant); } private static bool IsInvariant(Type t) { - Debug.Assert(t != null); + Debug.Assert(t is not null); return 0 == (t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask); } private static bool IsDelegate(Type t) { - Debug.Assert(t != null); + Debug.Assert(t is not null); return t.IsSubclassOf(typeof(MulticastDelegate)); } public static bool IsLegalExplicitVariantDelegateConversion(Type source, Type dest) { - Debug.Assert(source != null && dest != null); + Debug.Assert(source is not null && dest is not null); // There *might* be a legal conversion from a generic delegate type S to generic delegate type T, // provided all of the follow are true: @@ -468,9 +468,9 @@ public static bool IsLegalExplicitVariantDelegateConversion(Type source, Type de Type[] sourceArguments = source.GetGenericArguments(); Type[] destArguments = dest.GetGenericArguments(); - Debug.Assert(genericParameters != null); - Debug.Assert(sourceArguments != null); - Debug.Assert(destArguments != null); + Debug.Assert(genericParameters is not null); + Debug.Assert(sourceArguments is not null); + Debug.Assert(destArguments is not null); Debug.Assert(genericParameters.Length == sourceArguments.Length); Debug.Assert(genericParameters.Length == destArguments.Length); @@ -479,7 +479,7 @@ public static bool IsLegalExplicitVariantDelegateConversion(Type source, Type de Type sourceArgument = sourceArguments[iParam]; Type destArgument = destArguments[iParam]; - Debug.Assert(sourceArgument != null && destArgument != null); + Debug.Assert(sourceArgument is not null && destArgument is not null); // If the arguments are identical then this one is automatically good, so skip it. if (AreEquivalent(sourceArgument, destArgument)) @@ -489,7 +489,7 @@ public static bool IsLegalExplicitVariantDelegateConversion(Type source, Type de Type genericParameter = genericParameters[iParam]; - Debug.Assert(genericParameter != null); + Debug.Assert(genericParameter is not null); if (IsInvariant(genericParameter)) { @@ -615,7 +615,7 @@ public static bool IsImplicitlyConvertibleTo(this Type source, Type destination) MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo? method = FindConversionOperator(eMethods, convertFrom, convertToType); - if (method != null) + if (method is not null) { return method; } @@ -623,7 +623,7 @@ public static bool IsImplicitlyConvertibleTo(this Type source, Type destination) MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType); - if (method != null) + if (method is not null) { return method; } @@ -798,7 +798,7 @@ private static bool IsImplicitNullableConversion(Type source, Type destination) foreach (Type itype in type.GetTypeInfo().ImplementedInterfaces) { Type? found = FindGenericType(definition, itype); - if (found != null) + if (found is not null) { return found; } @@ -825,20 +825,20 @@ private static bool IsImplicitNullableConversion(Type source, Type destination) do { MethodInfo? result = type.GetAnyStaticMethodValidated(name, new[] { type }); - if (result != null && result.IsSpecialName && !result.ContainsGenericParameters) + if (result is not null && result.IsSpecialName && !result.ContainsGenericParameters) { return result; } type = type.BaseType!; - } while (type != null); + } while (type is not null); return null; } public static Type GetNonRefType(this Type type) => type.IsByRef ? type.GetElementType()! : type; - public static bool AreEquivalent(Type? t1, Type? t2) => t1 != null && t1.IsEquivalentTo(t2); + public static bool AreEquivalent(Type? t1, Type? t2) => t1 is not null && t1.IsEquivalentTo(t2); public static bool AreReferenceAssignable(Type dest, Type src) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BinaryExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BinaryExpression.cs index 81b28e528f53db..6bce0bfbc07da8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BinaryExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BinaryExpression.cs @@ -162,7 +162,7 @@ private Expression ReduceVariable() ExpressionType op = GetBinaryOpFromAssignmentOp(NodeType); Expression r = Expression.MakeBinary(op, Left, Right, false, Method); LambdaExpression? conversion = GetConversion(); - if (conversion != null) + if (conversion is not null) { r = Expression.Invoke(conversion, r); } @@ -173,7 +173,7 @@ private Expression ReduceMember() { MemberExpression member = (MemberExpression)Left; - if (member.Expression == null) + if (member.Expression is null) { // static member, reduce the same as variable return ReduceVariable(); @@ -195,7 +195,7 @@ private Expression ReduceMember() ExpressionType op = GetBinaryOpFromAssignmentOp(NodeType); Expression e2 = Expression.MakeBinary(op, Expression.MakeMemberAccess(temp1, member.Member), Right, false, Method); LambdaExpression? conversion = GetConversion(); - if (conversion != null) + if (conversion is not null) { e2 = Expression.Invoke(conversion, e2); } @@ -254,7 +254,7 @@ private Expression ReduceIndex() ExpressionType binaryOp = GetBinaryOpFromAssignmentOp(NodeType); Expression op = Expression.MakeBinary(binaryOp, tempIndex, Right, false, Method); LambdaExpression? conversion = GetConversion(); - if (conversion != null) + if (conversion is not null) { op = Expression.Invoke(conversion, op); } @@ -289,7 +289,7 @@ public bool IsLifted if (Left.Type.IsNullableType()) { MethodInfo? method = GetMethod(); - return method == null || + return method is null || !TypeUtils.AreEquivalent(method.GetParametersCached()[0].ParameterType.GetNonRefType(), Left.Type); } return false; @@ -312,12 +312,12 @@ protected internal override Expression Accept(ExpressionVisitor visitor) internal static BinaryExpression Create(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo? method, LambdaExpression? conversion) { Debug.Assert(nodeType != ExpressionType.Assign); - if (conversion != null) + if (conversion is not null) { - Debug.Assert(method == null && TypeUtils.AreEquivalent(type, right.Type) && nodeType == ExpressionType.Coalesce); + Debug.Assert(method is null && TypeUtils.AreEquivalent(type, right.Type) && nodeType == ExpressionType.Coalesce); return new CoalesceConversionBinaryExpression(left, right, conversion); } - if (method != null) + if (method is not null) { return new MethodBinaryExpression(nodeType, left, right, type, method); } @@ -341,7 +341,7 @@ internal bool IsLiftedLogical (kind == ExpressionType.AndAlso || kind == ExpressionType.OrElse) && TypeUtils.AreEquivalent(right, left) && left.IsNullableType() && - method != null && + method is not null && TypeUtils.AreEquivalent(method.ReturnType, left.GetNonNullableType()); } } @@ -356,7 +356,7 @@ internal bool IsReferenceComparison ExpressionType kind = NodeType; return (kind == ExpressionType.Equal || kind == ExpressionType.NotEqual) && - method == null && !left.IsValueType && !right.IsValueType; + method is null && !left.IsValueType && !right.IsValueType; } } @@ -397,7 +397,7 @@ internal Expression ReduceUserdefinedLifted() ParameterExpression right = Parameter(Right.Type, "right"); string opName = NodeType == ExpressionType.AndAlso ? "op_False" : "op_True"; MethodInfo? opTrueFalse = TypeUtils.GetBooleanOperator(Method!.DeclaringType!, opName); - Debug.Assert(opTrueFalse != null); + Debug.Assert(opTrueFalse is not null); return Block( new TrueReadOnlyCollection(left), @@ -584,7 +584,7 @@ public static BinaryExpression Assign(Expression left, Expression right) { // try exact match first MethodInfo? method = GetUserDefinedBinaryOperator(binaryType, left.Type, right.Type, name); - if (method != null) + if (method is not null) { return new MethodBinaryExpression(binaryType, left, right, method.ReturnType, method); } @@ -594,7 +594,7 @@ public static BinaryExpression Assign(Expression left, Expression right) Type nnLeftType = left.Type.GetNonNullableType(); Type nnRightType = right.Type.GetNonNullableType(); method = GetUserDefinedBinaryOperator(binaryType, nnLeftType, nnRightType, name); - if (method != null && method.ReturnType.IsValueType && !method.ReturnType.IsNullableType()) + if (method is not null && method.ReturnType.IsValueType && !method.ReturnType.IsNullableType()) { if (method.ReturnType != typeof(bool) || liftToNull) { @@ -611,7 +611,7 @@ public static BinaryExpression Assign(Expression left, Expression right) private static BinaryExpression GetMethodBasedBinaryOperator(ExpressionType binaryType, Expression left, Expression right, MethodInfo method, bool liftToNull) { - System.Diagnostics.Debug.Assert(method != null); + System.Diagnostics.Debug.Assert(method is not null); ValidateOperator(method); ParameterInfo[] pms = method.GetParametersCached(); if (pms.Length != 2) @@ -643,7 +643,7 @@ private static BinaryExpression GetMethodBasedBinaryOperator(ExpressionType bina private static BinaryExpression GetMethodBasedAssignOperator(ExpressionType binaryType, Expression left, Expression right, MethodInfo method, LambdaExpression? conversion, bool liftToNull) { BinaryExpression b = GetMethodBasedBinaryOperator(binaryType, left, right, method, liftToNull); - if (conversion == null) + if (conversion is null) { // return type must be assignable back to the left type if (!TypeUtils.AreReferenceAssignable(left.Type, b.Type)) @@ -663,7 +663,7 @@ private static BinaryExpression GetMethodBasedAssignOperator(ExpressionType bina private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow(ExpressionType binaryType, string name, Expression left, Expression right, bool liftToNull) { BinaryExpression? b = GetUserDefinedBinaryOperator(binaryType, name, left, right, liftToNull); - if (b != null) + if (b is not null) { ParameterInfo[] pis = b.Method!.GetParametersCached(); ValidateParamswithOperandsOrThrow(pis[0].ParameterType, left.Type, binaryType, name); @@ -676,7 +676,7 @@ private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow(ExpressionTy private static BinaryExpression GetUserDefinedAssignOperatorOrThrow(ExpressionType binaryType, string name, Expression left, Expression right, LambdaExpression? conversion, bool liftToNull) { BinaryExpression b = GetUserDefinedBinaryOperatorOrThrow(binaryType, name, left, right, liftToNull); - if (conversion == null) + if (conversion is null) { // return type must be assignable back to the left type if (!TypeUtils.AreReferenceAssignable(left.Type, b.Type)) @@ -701,7 +701,7 @@ private static BinaryExpression GetUserDefinedAssignOperatorOrThrow(ExpressionTy Type nnLeftType = leftType.GetNonNullableType(); Type nnRightType = rightType.GetNonNullableType(); MethodInfo? method = nnLeftType.GetAnyStaticMethodValidated(name, types); - if (method == null && !TypeUtils.AreEquivalent(leftType, rightType)) + if (method is null && !TypeUtils.AreEquivalent(leftType, rightType)) { method = nnRightType.GetAnyStaticMethodValidated(name, types); } @@ -717,7 +717,7 @@ private static bool IsLiftingConditionalLogicalOperator(Type left, Type right, M { return right.IsNullableType() && left.IsNullableType() && - method == null && + method is null && (binaryType == ExpressionType.AndAlso || binaryType == ExpressionType.OrElse); } @@ -739,7 +739,7 @@ private static void ValidateParamswithOperandsOrThrow(Type paramType, Type opera private static void ValidateOperator(MethodInfo method) { - Debug.Assert(method != null); + Debug.Assert(method is not null); ValidateMethodInfo(method, nameof(method)); if (!method.IsStatic) throw Error.UserDefinedOperatorMustBeStatic(method, nameof(method)); @@ -772,7 +772,7 @@ private static bool IsNullComparison(Expression left, Expression right) private static bool IsNullConstant(Expression e) { var c = e as ConstantExpression; - return c != null && c.Value == null; + return c is not null && c.Value is null; } private static void ValidateUserDefinedConditionalLogicOperator(ExpressionType nodeType, Type left, Type right, MethodInfo method) @@ -804,14 +804,14 @@ private static void ValidateUserDefinedConditionalLogicOperator(ExpressionType n left = left.GetNonNullableType(); } Type? declaringType = method.DeclaringType; - if (declaringType == null) + if (declaringType is null) { throw Error.LogicalOperatorMustHaveBooleanOperators(nodeType, method.Name); } MethodInfo? opTrue = TypeUtils.GetBooleanOperator(declaringType, "op_True"); MethodInfo? opFalse = TypeUtils.GetBooleanOperator(declaringType, "op_False"); - if (opTrue == null || opTrue.ReturnType != typeof(bool) || - opFalse == null || opFalse.ReturnType != typeof(bool)) + if (opTrue is null || opTrue.ReturnType != typeof(bool) || + opFalse is null || opFalse.ReturnType != typeof(bool)) { throw Error.LogicalOperatorMustHaveBooleanOperators(nodeType, method.Name); } @@ -949,7 +949,7 @@ public static BinaryExpression Equal(Expression left, Expression right, bool lif { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { return GetEqualityComparisonOperator(ExpressionType.Equal, "op_Equality", left, right, liftToNull); } @@ -1001,7 +1001,7 @@ public static BinaryExpression NotEqual(Expression left, Expression right, bool { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { return GetEqualityComparisonOperator(ExpressionType.NotEqual, "op_Inequality", left, right, liftToNull); } @@ -1046,7 +1046,7 @@ private static BinaryExpression GetEqualityComparisonOperator(ExpressionType bin } // look for user defined operator BinaryExpression? b = GetUserDefinedBinaryOperator(binaryType, opName, left, right, liftToNull); - if (b != null) + if (b is not null) { return b; } @@ -1094,7 +1094,7 @@ public static BinaryExpression GreaterThan(Expression left, Expression right, bo { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { return GetComparisonOperator(ExpressionType.GreaterThan, "op_GreaterThan", left, right, liftToNull); } @@ -1128,7 +1128,7 @@ public static BinaryExpression LessThan(Expression left, Expression right, bool { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { return GetComparisonOperator(ExpressionType.LessThan, "op_LessThan", left, right, liftToNull); } @@ -1161,7 +1161,7 @@ public static BinaryExpression GreaterThanOrEqual(Expression left, Expression ri { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { return GetComparisonOperator(ExpressionType.GreaterThanOrEqual, "op_GreaterThanOrEqual", left, right, liftToNull); } @@ -1194,7 +1194,7 @@ public static BinaryExpression LessThanOrEqual(Expression left, Expression right { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { return GetComparisonOperator(ExpressionType.LessThanOrEqual, "op_LessThanOrEqual", left, right, liftToNull); } @@ -1247,7 +1247,7 @@ public static BinaryExpression AndAlso(Expression left, Expression right, Method ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); Type returnType; - if (method == null) + if (method is null) { if (left.Type == right.Type) { @@ -1261,7 +1261,7 @@ public static BinaryExpression AndAlso(Expression left, Expression right, Method } } method = GetUserDefinedBinaryOperator(ExpressionType.AndAlso, left.Type, right.Type, "op_BitwiseAnd"); - if (method != null) + if (method is not null) { ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.Type, right.Type, method); returnType = (left.Type.IsNullableType() && TypeUtils.AreEquivalent(method.ReturnType, left.Type.GetNonNullableType())) ? left.Type : method.ReturnType; @@ -1300,7 +1300,7 @@ public static BinaryExpression OrElse(Expression left, Expression right, MethodI ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); Type returnType; - if (method == null) + if (method is null) { if (left.Type == right.Type) { @@ -1314,7 +1314,7 @@ public static BinaryExpression OrElse(Expression left, Expression right, MethodI } } method = GetUserDefinedBinaryOperator(ExpressionType.OrElse, left.Type, right.Type, "op_BitwiseOr"); - if (method != null) + if (method is not null) { ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.Type, right.Type, method); returnType = (left.Type.IsNullableType() && method.ReturnType == left.Type.GetNonNullableType()) ? left.Type : method.ReturnType; @@ -1357,7 +1357,7 @@ public static BinaryExpression Coalesce(Expression left, Expression right, Lambd ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (conversion == null) + if (conversion is null) { Type resultType = ValidateCoalesceArgTypes(left.Type, right.Type); return new SimpleBinaryExpression(ExpressionType.Coalesce, left, right, resultType); @@ -1453,7 +1453,7 @@ public static BinaryExpression Add(Expression left, Expression right, MethodInfo { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -1506,12 +1506,12 @@ public static BinaryExpression AddAssign(Expression left, Expression right, Meth ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -1537,7 +1537,7 @@ private static void ValidateOpAssignConversionLambda(LambdaExpression conversion { throw Error.OperandTypesDoNotMatchParameters(nodeType, conversion.ToString()); } - Debug.Assert(method != null); + Debug.Assert(method is not null); // The parameter type of conversion lambda must be the same as the return type of the overload method if (!TypeUtils.AreEquivalent(pms[0].ParameterType, method.ReturnType)) { @@ -1590,12 +1590,12 @@ public static BinaryExpression AddAssignChecked(Expression left, Expression righ RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -1631,7 +1631,7 @@ public static BinaryExpression AddChecked(Expression left, Expression right, Met { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -1667,7 +1667,7 @@ public static BinaryExpression Subtract(Expression left, Expression right, Metho { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -1720,12 +1720,12 @@ public static BinaryExpression SubtractAssign(Expression left, Expression right, ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -1778,12 +1778,12 @@ public static BinaryExpression SubtractAssignChecked(Expression left, Expression ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -1819,7 +1819,7 @@ public static BinaryExpression SubtractChecked(Expression left, Expression right { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -1855,7 +1855,7 @@ public static BinaryExpression Divide(Expression left, Expression right, MethodI { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -1908,12 +1908,12 @@ public static BinaryExpression DivideAssign(Expression left, Expression right, M ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -1949,7 +1949,7 @@ public static BinaryExpression Modulo(Expression left, Expression right, MethodI { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -2002,12 +2002,12 @@ public static BinaryExpression ModuloAssign(Expression left, Expression right, M ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2043,7 +2043,7 @@ public static BinaryExpression Multiply(Expression left, Expression right, Metho { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -2096,12 +2096,12 @@ public static BinaryExpression MultiplyAssign(Expression left, Expression right, ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2154,12 +2154,12 @@ public static BinaryExpression MultiplyAssignChecked(Expression left, Expression ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2195,7 +2195,7 @@ public static BinaryExpression MultiplyChecked(Expression left, Expression right { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { @@ -2247,7 +2247,7 @@ public static BinaryExpression LeftShift(Expression left, Expression right, Meth { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (IsSimpleShift(left.Type, right.Type)) { @@ -2301,12 +2301,12 @@ public static BinaryExpression LeftShiftAssign(Expression left, Expression right ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (IsSimpleShift(left.Type, right.Type)) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2343,7 +2343,7 @@ public static BinaryExpression RightShift(Expression left, Expression right, Met { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (IsSimpleShift(left.Type, right.Type)) { @@ -2397,12 +2397,12 @@ public static BinaryExpression RightShiftAssign(Expression left, Expression righ ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (IsSimpleShift(left.Type, right.Type)) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2439,7 +2439,7 @@ public static BinaryExpression And(Expression left, Expression right, MethodInfo { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsIntegerOrBool()) { @@ -2492,12 +2492,12 @@ public static BinaryExpression AndAssign(Expression left, Expression right, Meth ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsIntegerOrBool()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2533,7 +2533,7 @@ public static BinaryExpression Or(Expression left, Expression right, MethodInfo? { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsIntegerOrBool()) { @@ -2586,12 +2586,12 @@ public static BinaryExpression OrAssign(Expression left, Expression right, Metho ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsIntegerOrBool()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2627,7 +2627,7 @@ public static BinaryExpression ExclusiveOr(Expression left, Expression right, Me { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsIntegerOrBool()) { @@ -2680,12 +2680,12 @@ public static BinaryExpression ExclusiveOrAssign(Expression left, Expression rig ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsIntegerOrBool()) { // conversion is not supported for binary ops on arithmetic types without operator overloading - if (conversion != null) + if (conversion is not null) { throw Error.ConversionIsNotSupportedForArithmeticTypes(); } @@ -2721,12 +2721,12 @@ public static BinaryExpression Power(Expression left, Expression right, MethodIn { ExpressionUtils.RequiresCanRead(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { if (left.Type == right.Type && left.Type.IsArithmetic()) { method = Math_Pow_Double_Double; - Debug.Assert(method != null); + Debug.Assert(method is not null); } else { @@ -2734,11 +2734,11 @@ public static BinaryExpression Power(Expression left, Expression right, MethodIn // test for either. string name = "op_Exponent"; BinaryExpression? b = GetUserDefinedBinaryOperator(ExpressionType.Power, name, left, right, liftToNull: true); - if (b == null) + if (b is null) { name = "op_Exponentiation"; b = GetUserDefinedBinaryOperator(ExpressionType.Power, name, left, right, liftToNull: true); - if (b == null) + if (b is null) { throw Error.BinaryOperatorNotDefined(ExpressionType.Power, left.Type, right.Type); } @@ -2796,10 +2796,10 @@ public static BinaryExpression PowerAssign(Expression left, Expression right, Me ExpressionUtils.RequiresCanRead(left, nameof(left)); RequiresCanWrite(left, nameof(left)); ExpressionUtils.RequiresCanRead(right, nameof(right)); - if (method == null) + if (method is null) { method = Math_Pow_Double_Double; - if (method == null) + if (method is null) { throw Error.BinaryOperatorNotDefined(ExpressionType.PowerAssign, left.Type, right.Type); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs index c8f12524bead5d..44bfffddd9e615 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs @@ -66,19 +66,19 @@ protected internal override Expression Accept(ExpressionVisitor visitor) /// This expression if no children changed, or an expression with the updated children. public BlockExpression Update(IEnumerable? variables, IEnumerable expressions) { - if (expressions != null) + if (expressions is not null) { // Ensure variables is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection? vars; - if (variables == null) + if (variables is null) { vars = null; } else { vars = variables as ICollection; - if (vars == null) + if (vars is null) { variables = vars = variables.ToReadOnly(); } @@ -89,7 +89,7 @@ public BlockExpression Update(IEnumerable? variables, IEnum // Ensure expressions is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection? exps = expressions as ICollection; - if (exps == null) + if (exps is null) { expressions = exps = expressions.ToReadOnly(); } @@ -104,7 +104,7 @@ public BlockExpression Update(IEnumerable? variables, IEnum } internal virtual bool SameVariables(ICollection? variables) => - variables == null || variables.Count == 0; + variables is null || variables.Count == 0; [ExcludeFromCodeCoverage(Justification = "Unreachable")] internal virtual bool SameExpressions(ICollection expressions) @@ -207,7 +207,7 @@ internal override Expression GetExpression(int index) => internal override bool SameExpressions(ICollection expressions) { - Debug.Assert(expressions != null); + Debug.Assert(expressions is not null); if (expressions.Count == 2) { if (_arg0 is ReadOnlyCollection alreadyCollection) @@ -238,9 +238,9 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[] args) { - Debug.Assert(args != null); + Debug.Assert(args is not null); Debug.Assert(args.Length == 2); - Debug.Assert(variables == null || variables.Count == 0); + Debug.Assert(variables is null || variables.Count == 0); return new Block2(args[0], args[1]); } @@ -260,7 +260,7 @@ internal Block3(Expression arg0, Expression arg1, Expression arg2) internal override bool SameExpressions(ICollection expressions) { - Debug.Assert(expressions != null); + Debug.Assert(expressions is not null); if (expressions.Count == 3) { if (_arg0 is ReadOnlyCollection alreadyCollection) @@ -304,9 +304,9 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[] args) { - Debug.Assert(args != null); + Debug.Assert(args is not null); Debug.Assert(args.Length == 3); - Debug.Assert(variables == null || variables.Count == 0); + Debug.Assert(variables is null || variables.Count == 0); return new Block3(args[0], args[1], args[2]); } @@ -327,7 +327,7 @@ internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression ar internal override bool SameExpressions(ICollection expressions) { - Debug.Assert(expressions != null); + Debug.Assert(expressions is not null); if (expressions.Count == 4) { if (_arg0 is ReadOnlyCollection alreadyCollection) @@ -376,9 +376,9 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[] args) { - Debug.Assert(args != null); + Debug.Assert(args is not null); Debug.Assert(args.Length == 4); - Debug.Assert(variables == null || variables.Count == 0); + Debug.Assert(variables is null || variables.Count == 0); return new Block4(args[0], args[1], args[2], args[3]); } @@ -411,7 +411,7 @@ internal override Expression GetExpression(int index) => internal override bool SameExpressions(ICollection expressions) { - Debug.Assert(expressions != null); + Debug.Assert(expressions is not null); if (expressions.Count == 5) { if (_arg0 is ReadOnlyCollection alreadyCollection) @@ -454,9 +454,9 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[] args) { - Debug.Assert(args != null); + Debug.Assert(args is not null); Debug.Assert(args.Length == 5); - Debug.Assert(variables == null || variables.Count == 0); + Debug.Assert(variables is null || variables.Count == 0); return new Block5(args[0], args[1], args[2], args[3], args[4]); } @@ -492,8 +492,8 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[] args) { - Debug.Assert(variables == null || variables.Count == 0); - Debug.Assert(args != null); + Debug.Assert(variables is null || variables.Count == 0); + Debug.Assert(args is not null); return new BlockN(args); } @@ -521,7 +521,7 @@ internal override ReadOnlyCollection GetOrMakeVariables() // Used for rewrite of the nodes to either reuse existing set of variables if not rewritten. internal IReadOnlyList ReuseOrValidateVariables(ReadOnlyCollection? variables) { - if (variables != null && variables != VariablesList) + if (variables is not null && variables != VariablesList) { // Need to validate the new variables (uniqueness, not byref) ValidateVariables(variables, nameof(variables)); @@ -551,7 +551,7 @@ private Scope1(IReadOnlyList variables, object body) internal override bool SameExpressions(ICollection expressions) { - Debug.Assert(expressions != null); + Debug.Assert(expressions is not null); if (expressions.Count == 1) { if (_body is ReadOnlyCollection alreadyCollection) @@ -585,14 +585,14 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[]? args) { - if (args == null) + if (args is null) { Debug.Assert(variables!.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new Scope1(variables, _body); } Debug.Assert(args.Length == 1); - Debug.Assert(variables == null || variables.Count == Variables.Count); + Debug.Assert(variables is null || variables.Count == Variables.Count); return new Scope1(ReuseOrValidateVariables(variables), args[0]); } @@ -624,14 +624,14 @@ internal override ReadOnlyCollection GetOrMakeExpressions() internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[]? args) { - if (args == null) + if (args is null) { Debug.Assert(variables!.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new ScopeN(variables, _body); } Debug.Assert(args.Length == ExpressionCount); - Debug.Assert(variables == null || variables.Count == Variables.Count); + Debug.Assert(variables is null || variables.Count == Variables.Count); return new ScopeN(ReuseOrValidateVariables(variables), args); } @@ -649,14 +649,14 @@ internal ScopeWithType(IReadOnlyList variables, IReadOnlyLi internal override BlockExpression Rewrite(ReadOnlyCollection? variables, Expression[]? args) { - if (args == null) + if (args is null) { Debug.Assert(variables!.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new ScopeWithType(variables, Body, Type); } Debug.Assert(args.Length == ExpressionCount); - Debug.Assert(variables == null || variables.Count == Variables.Count); + Debug.Assert(variables is null || variables.Count == Variables.Count); return new ScopeWithType(ReuseOrValidateVariables(variables), args, Type); } @@ -1028,7 +1028,7 @@ private static BlockExpression BlockCore(Type? type, ReadOnlyCollection ((ConstantExpression)e).Value == null, + ExpressionType.Constant => ((ConstantExpression)e).Value is null, ExpressionType.Default => e.Type.IsNullableOrReferenceType(), _ => false, diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs index a0287218278353..14ccf9266c1a98 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs @@ -22,7 +22,7 @@ private static AssemblyGen Assembly { get { - if (s_assembly == null) + if (s_assembly is null) { Interlocked.CompareExchange(ref s_assembly, new AssemblyGen(), comparand: null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/CompilerScope.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/CompilerScope.cs index a866e7b7a779e7..b6fd12d0dc806c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/CompilerScope.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/CompilerScope.cs @@ -124,7 +124,7 @@ internal CompilerScope Enter(LambdaCompiler lc, CompilerScope? parent) AllocateLocals(lc); - if (IsMethod && _closureHoistedLocals != null) + if (IsMethod && _closureHoistedLocals is not null) { EmitClosureAccess(lc, _closureHoistedLocals); } @@ -168,7 +168,7 @@ internal CompilerScope Enter(LambdaCompiler lc, CompilerScope? parent) internal void EmitVariableAccess(LambdaCompiler lc, ReadOnlyCollection vars) { - if (NearestHoistedLocals != null && vars.Count > 0) + if (NearestHoistedLocals is not null && vars.Count > 0) { // Find what array each variable is on & its index var indexes = new ArrayBuilder(vars.Count); @@ -182,7 +182,7 @@ internal void EmitVariableAccess(LambdaCompiler lc, ReadOnlyCollection GetVariables() => - MergedScopes == null ? GetVariables(Node) : GetVariablesIncludingMerged(); + MergedScopes is null ? GetVariables(Node) : GetVariablesIncludingMerged(); private IEnumerable GetVariablesIncludingMerged() { @@ -494,7 +494,7 @@ private string? CurrentLambdaName get { CompilerScope? s = this; - while (s != null) + while (s is not null) { if (s.Node is LambdaExpression lambda) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs index 8a359790b890bf..082b91ec01d9bc 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs @@ -27,7 +27,7 @@ internal static Type MakeDelegateType(Type[] types) } // see if we have the delegate already - if (curTypeInfo.DelegateType == null) + if (curTypeInfo.DelegateType is null) { // clone because MakeCustomDelegate can hold onto the array. curTypeInfo.DelegateType = MakeNewDelegate((Type[])types.Clone()); @@ -67,7 +67,7 @@ private static TypeInfo NextTypeInfo(Type initialArg, TypeInfo curTypeInfo) { Type lookingUp = initialArg; TypeInfo nextTypeInfo; - if (curTypeInfo.TypeChain == null) + if (curTypeInfo.TypeChain is null) { curTypeInfo.TypeChain = new Dictionary(); } @@ -136,7 +136,7 @@ private static Type TryMakeVBStyledCallSite(Type[] types) /// internal static Type MakeNewDelegate(Type[] types) { - Debug.Assert(types != null && types.Length > 0); + Debug.Assert(types is not null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> @@ -180,7 +180,7 @@ internal static Type MakeNewDelegate(Type[] types) result = GetFuncType(types); } - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.cs index f1cb6e844bb901..550f2db75fbcee 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.cs @@ -37,7 +37,7 @@ internal static Type MakeCallSiteDelegate(ReadOnlyCollection types, curTypeInfo = NextTypeInfo(returnType, curTypeInfo); // see if we have the delegate already - if (curTypeInfo.DelegateType == null) + if (curTypeInfo.DelegateType is null) { curTypeInfo.MakeDelegateType(returnType, types); } @@ -77,7 +77,7 @@ internal static Type MakeDeferredSiteDelegate(DynamicMetaObject[] args, Type ret curTypeInfo = NextTypeInfo(returnType, curTypeInfo); // see if we have the delegate already - if (curTypeInfo.DelegateType == null) + if (curTypeInfo.DelegateType is null) { // nope, go ahead and create it and spend the // cost of creating the array. diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/HoistedLocals.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/HoistedLocals.cs index afa13bb72794c8..de91ce6fa4b070 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/HoistedLocals.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/HoistedLocals.cs @@ -58,7 +58,7 @@ internal sealed class HoistedLocals internal HoistedLocals(HoistedLocals? parent, ReadOnlyCollection vars) { - if (parent != null) + if (parent is not null) { // Add the parent locals array as the 0th element in the array vars = vars.AddFirst(parent.SelfVariable); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/ILGen.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/ILGen.cs index 21e914fd7e72b7..256a13f79dd5a7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/ILGen.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/ILGen.cs @@ -57,7 +57,7 @@ internal static void EmitStoreArg(this ILGenerator il, int index) /// internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); switch (type.GetTypeCode()) { @@ -110,7 +110,7 @@ internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) /// internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); switch (type.GetTypeCode()) { @@ -155,7 +155,7 @@ internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) internal static void EmitLoadElement(this ILGenerator il, Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); if (!type.IsValueType) { @@ -207,7 +207,7 @@ internal static void EmitLoadElement(this ILGenerator il, Type type) /// internal static void EmitStoreElement(this ILGenerator il, Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); switch (type.GetTypeCode()) { @@ -250,7 +250,7 @@ internal static void EmitStoreElement(this ILGenerator il, Type type) internal static void EmitType(this ILGenerator il, Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); @@ -262,28 +262,28 @@ internal static void EmitType(this ILGenerator il, Type type) internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { - Debug.Assert(fi != null); + Debug.Assert(fi is not null); il.Emit(fi.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda, fi); } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { - Debug.Assert(fi != null); + Debug.Assert(fi is not null); il.Emit(fi.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, fi); } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { - Debug.Assert(fi != null); + Debug.Assert(fi is not null); il.Emit(fi.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fi); } internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { - Debug.Assert(ci != null); + Debug.Assert(ci is not null); Debug.Assert(!ci.DeclaringType!.ContainsGenericParameters); il.Emit(OpCodes.Newobj, ci); @@ -300,7 +300,7 @@ internal static void EmitNull(this ILGenerator il) internal static void EmitString(this ILGenerator il, string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); il.Emit(OpCodes.Ldstr, value); } @@ -355,7 +355,7 @@ private static void EmitPrimitive(this ILGenerator il, float value) // matches TryEmitConstant internal static bool CanEmitConstant(object? value, Type type) { - if (value == null || CanEmitILConstant(type)) + if (value is null || CanEmitILConstant(type)) { return true; } @@ -398,7 +398,7 @@ private static bool CanEmitILConstant(Type type) // Linq does internal static bool TryEmitConstant(this ILGenerator il, object? value, Type type, ILocalCache locals) { - if (value == null) + if (value is null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and @@ -434,7 +434,7 @@ internal static bool TryEmitConstant(this ILGenerator il, object? value, Type ty { il.Emit(OpCodes.Ldtoken, mb); Type? dt = mb.DeclaringType; - if (dt != null && dt.IsGenericType) + if (dt is not null && dt.IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle); @@ -471,12 +471,12 @@ internal static bool ShouldLdtoken(MethodBase mb) } Type? dt = mb.DeclaringType; - return dt == null || ShouldLdtoken(dt); + return dt is null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { - Debug.Assert(value != null); + Debug.Assert(value is not null); if (type.IsNullableType()) { @@ -934,7 +934,7 @@ internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableTyp /// internal static void EmitArray(this ILGenerator il, T[] items, ILocalCache locals) { - Debug.Assert(items != null); + Debug.Assert(items is not null); il.EmitPrimitive(items.Length); il.Emit(OpCodes.Newarr, typeof(T)); @@ -953,7 +953,7 @@ internal static void EmitArray(this ILGenerator il, T[] items, ILocalCache lo /// internal static void EmitArray(this ILGenerator il, Type elementType, int count) { - Debug.Assert(elementType != null); + Debug.Assert(elementType is not null); Debug.Assert(count >= 0); il.EmitPrimitive(count); @@ -967,7 +967,7 @@ internal static void EmitArray(this ILGenerator il, Type elementType, int count) /// internal static void EmitArray(this ILGenerator il, Type arrayType) { - Debug.Assert(arrayType != null); + Debug.Assert(arrayType is not null); Debug.Assert(arrayType.IsArray); if (arrayType.IsSZArray) @@ -982,7 +982,7 @@ internal static void EmitArray(this ILGenerator il, Type arrayType) types[i] = typeof(int); } ConstructorInfo? ci = arrayType.GetConstructor(types); - Debug.Assert(ci != null); + Debug.Assert(ci is not null); il.EmitNew(ci); } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs index 427db15858146f..90e3dfa2859bba 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs @@ -89,7 +89,7 @@ internal void Define(LabelScopeInfo block) // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) - for (LabelScopeInfo? j = block; j != null; j = j.Parent) + for (LabelScopeInfo? j = block; j is not null; j = j.Parent) { if (j.ContainsTarget(_node!)) { @@ -130,7 +130,7 @@ private void ValidateJump(LabelScopeInfo reference) _opCode = _canReturn ? OpCodes.Ret : OpCodes.Br; // look for a simple jump out - for (LabelScopeInfo? j = reference; j != null; j = j.Parent) + for (LabelScopeInfo? j = reference; j is not null; j = j.Parent) { if (_definitions.Contains(j)) { @@ -150,7 +150,7 @@ private void ValidateJump(LabelScopeInfo reference) } _acrossBlockJump = true; - if (_node != null && _node.Type != typeof(void)) + if (_node is not null && _node.Type != typeof(void)) { throw Error.NonLocalJumpWithValue(_node.Name); } @@ -228,7 +228,7 @@ internal void EmitJump() private void StoreValue() { EnsureLabelAndValue(); - if (_value != null) + if (_value is not null) { _ilg.Emit(OpCodes.Stloc, _value); } @@ -268,7 +268,7 @@ internal void Mark() internal void MarkWithEmptyStack() { _ilg.MarkLabel(Label); - if (_value != null) + if (_value is not null) { // We always read the value from a local, because we don't know // if there will be a "leave" instruction targeting it ("branch" @@ -283,7 +283,7 @@ private void EnsureLabelAndValue() { _labelDefined = true; _label = _ilg.DefineLabel(); - if (_node != null && _node.Type != typeof(void)) + if (_node is not null && _node.Type != typeof(void)) { _value = _ilg.DeclareLocal(_node.Type); } @@ -358,7 +358,7 @@ internal bool CanJumpInto internal bool ContainsTarget(LabelTarget target) { - if (_labels == null) + if (_labels is null) { return false; } @@ -368,7 +368,7 @@ internal bool ContainsTarget(LabelTarget target) internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo? info) { - if (_labels == null) + if (_labels is null) { info = null; return false; @@ -381,7 +381,7 @@ internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); - if (_labels == null) + if (_labels is null) { _labels = new Dictionary(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Address.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Address.cs index 29b5b832286621..f2386066c834e7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Address.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Address.cs @@ -21,7 +21,7 @@ private void EmitAddress(Expression node, Type type) // boxed value) private void EmitAddress(Expression node, Type type, CompilationFlags flags) { - Debug.Assert(node != null); + Debug.Assert(node is not null); bool emitStart = (flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart; CompilationFlags startEmitted = emitStart ? EmitExpressionStart(node) : CompilationFlags.EmitNoExpressionStart; @@ -65,7 +65,7 @@ private void EmitAddress(Expression node, Type type, CompilationFlags flags) private void AddressOf(BinaryExpression node, Type type) { - Debug.Assert(node.NodeType == ExpressionType.ArrayIndex && node.Method == null); + Debug.Assert(node.NodeType == ExpressionType.ArrayIndex && node.Method is null); if (TypeUtils.AreEquivalent(type, node.Type)) { @@ -115,7 +115,7 @@ private void AddressOf(MemberExpression node, Type type) { // emit "this", if any Type? objectType = null; - if (node.Expression != null) + if (node.Expression is not null) { EmitInstance(node.Expression, out objectType); } @@ -186,7 +186,7 @@ private void AddressOf(MethodCallExpression node, Type type) private void AddressOf(IndexExpression node, Type type) { - if (!TypeUtils.AreEquivalent(type, node.Type) || node.Indexer != null) + if (!TypeUtils.AreEquivalent(type, node.Type) || node.Indexer is not null) { EmitExpressionAddress(node, type); return; @@ -247,7 +247,7 @@ private void EmitExpressionAddress(Expression node, Type type) break; } } - if (result == null) + if (result is null) { EmitAddress(node, type, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); } @@ -273,7 +273,7 @@ private WriteBack AddressOfWriteBackCore(MemberExpression node) // emit instance, if any LocalBuilder? instanceLocal = null; Type? instanceType = null; - if (node.Expression != null) + if (node.Expression is not null) { EmitInstance(node.Expression, out instanceType); @@ -296,7 +296,7 @@ private WriteBack AddressOfWriteBackCore(MemberExpression node) // don't re-evaluate anything return @this => { - if (instanceLocal != null) + if (instanceLocal is not null) { @this._ilg.Emit(OpCodes.Ldloc, instanceLocal); @this.FreeLocal(instanceLocal); @@ -309,7 +309,7 @@ private WriteBack AddressOfWriteBackCore(MemberExpression node) private WriteBack? AddressOfWriteBack(IndexExpression node) { - if (node.Indexer == null || !node.Indexer.CanWrite) + if (node.Indexer is null || !node.Indexer.CanWrite) { return null; } @@ -322,7 +322,7 @@ private WriteBack AddressOfWriteBackCore(IndexExpression node) // emit instance, if any LocalBuilder? instanceLocal = null; Type? instanceType = null; - if (node.Object != null) + if (node.Object is not null) { EmitInstance(node.Object, out instanceType); @@ -358,7 +358,7 @@ private WriteBack AddressOfWriteBackCore(IndexExpression node) // don't re-evaluate anything return @this => { - if (instanceLocal != null) + if (instanceLocal is not null) { @this._ilg.Emit(OpCodes.Ldloc, instanceLocal); @this.FreeLocal(instanceLocal); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Binary.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Binary.cs index c28f740d7f9136..755b2be8a0ac60 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Binary.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Binary.cs @@ -22,7 +22,7 @@ private void EmitBinaryExpression(Expression expr, CompilationFlags flags) Debug.Assert(b.NodeType != ExpressionType.AndAlso && b.NodeType != ExpressionType.OrElse && b.NodeType != ExpressionType.Coalesce); - if (b.Method != null) + if (b.Method is not null) { EmitBinaryMethod(b, flags); return; @@ -516,7 +516,7 @@ private void EmitLiftedBooleanAnd() _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Or); - // if !(left != null | right == true) + // if !(left is not null | right == true) _ilg.Emit(OpCodes.Brfalse_S, returnRight); _ilg.Emit(OpCodes.Ldloc, locLeft); FreeLocal(locLeft); @@ -547,7 +547,7 @@ private void EmitLiftedBooleanOr() _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Or); - // if !(right == true | left != null) + // if !(right == true | left is not null) _ilg.Emit(OpCodes.Brfalse_S, returnLeft); _ilg.Emit(OpCodes.Ldloc, locRight); FreeLocal(locRight); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs index 3e6033504fa84c..6aa195ad530061 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs @@ -28,7 +28,7 @@ private LabelInfo ReferenceLabel(LabelTarget node) private LabelInfo DefineLabel(LabelTarget? node) { - if (node == null) + if (node is null) { return new LabelInfo(_ilg, null, false); } @@ -44,14 +44,14 @@ private void PushLabelBlock(LabelScopeKind type) private void PopLabelBlock(LabelScopeKind kind) { - Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind); + Debug.Assert(_labelBlock is not null && _labelBlock.Kind == kind); _labelBlock = _labelBlock.Parent!; } private void EmitLabelExpression(Expression expr, CompilationFlags flags) { var node = (LabelExpression)expr; - Debug.Assert(node.Target != null); + Debug.Assert(node.Target is not null); // If we're an immediate child of a block, our label will already // be defined. If not, we need to define our own block so this @@ -63,21 +63,21 @@ private void EmitLabelExpression(Expression expr, CompilationFlags flags) _labelBlock.TryGetLabelInfo(node.Target, out label); // We're in a block but didn't find our label, try switch - if (label == null && _labelBlock.Parent!.Kind == LabelScopeKind.Switch) + if (label is null && _labelBlock.Parent!.Kind == LabelScopeKind.Switch) { _labelBlock.Parent.TryGetLabelInfo(node.Target, out label); } // if we're in a switch or block, we should've found the label - Debug.Assert(label != null); + Debug.Assert(label is not null); } - if (label == null) + if (label is null) { label = DefineLabel(node.Target); } - if (node.DefaultValue != null) + if (node.DefaultValue is not null) { if (node.Target.Type == typeof(void)) { @@ -109,7 +109,7 @@ private void EmitGotoExpression(Expression expr, CompilationFlags flags) flags = UpdateEmitAsTailCallFlag(flags, tailCall); } - if (node.Value != null) + if (node.Value is not null) { if (node.Target.Type == typeof(void)) { @@ -224,7 +224,7 @@ private bool TryPushLabelBlock(Expression node) private void DefineBlockLabels(Expression? node) { var block = node as BlockExpression; - if (block == null || block is SpilledExpressionBlock) + if (block is null || block is SpilledExpressionBlock) { return; } @@ -233,7 +233,7 @@ private void DefineBlockLabels(Expression? node) Expression e = block.GetExpression(i); var label = e as LabelExpression; - if (label != null) + if (label is not null) { DefineLabel(label.Target); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs index aab1e749747cc2..521ca2b5e786bb 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs @@ -79,7 +79,7 @@ private void EmitExpressionAsVoid(Expression node) private void EmitExpressionAsVoid(Expression node, CompilationFlags flags) { - Debug.Assert(node != null); + Debug.Assert(node is not null); CompilationFlags startEmitted = EmitExpressionStart(node); @@ -173,7 +173,7 @@ private void EmitInvocationExpression(Expression expr, CompilationFlags flags) // This is worth it because otherwise we end up with an extra call // to DynamicMethod.CreateDelegate, which is expensive. // - if (node.LambdaOperand != null) + if (node.LambdaOperand is not null) { EmitInlinedInvoke(node, flags); return; @@ -206,7 +206,7 @@ private void EmitInlinedInvoke(InvocationExpression invoke, CompilationFlags fla // 3. Emit the body // if the inlined lambda is the last expression of the whole lambda, // tail call can be applied. - if (wb != null) + if (wb is not null) { Debug.Assert(wb.Count > 0); flags = UpdateEmitAsTailCallFlag(flags, CompilationFlags.EmitAsNoTail); @@ -227,7 +227,7 @@ private void EmitIndexExpression(Expression expr) // Emit instance, if calling an instance method Type? objectType = null; - if (node.Object != null) + if (node.Object is not null) { EmitInstance(node.Object, out objectType); } @@ -253,7 +253,7 @@ private void EmitIndexAssignment(AssignBinaryExpression node, CompilationFlags f // Emit instance, if calling an instance method Type? objectType = null; - if (index.Object != null) + if (index.Object is not null) { EmitInstance(index.Object, out objectType); } @@ -289,7 +289,7 @@ private void EmitIndexAssignment(AssignBinaryExpression node, CompilationFlags f private void EmitGetIndexCall(IndexExpression node, Type? objectType) { - if (node.Indexer != null) + if (node.Indexer is not null) { // For indexed properties, just call the getter MethodInfo method = node.Indexer.GetGetMethod(nonPublic: true)!; @@ -317,7 +317,7 @@ private void EmitGetArrayElement(Type arrayType) private void EmitSetIndexCall(IndexExpression node, Type? objectType) { - if (node.Indexer != null) + if (node.Indexer is not null) { // For indexed properties, just call the setter MethodInfo method = node.Indexer.GetSetMethod(nonPublic: true)!; @@ -370,12 +370,12 @@ private void EmitMethodCall(Expression? obj, MethodInfo method, IArgumentProvide Type? objectType = null; if (!method.IsStatic) { - Debug.Assert(obj != null); + Debug.Assert(obj is not null); EmitInstance(obj, out objectType); } // if the obj has a value type, its address is passed to the method call so we cannot destroy the // stack by emitting a tail call - if (obj != null && obj.Type.IsValueType) + if (obj is not null && obj.Type.IsValueType) { EmitMethodCall(method, methodCallExpr, objectType); } @@ -524,9 +524,9 @@ private static bool UseVirtual(MethodInfo mi) type = type.GetElementType()!; WriteBack? wb = EmitAddressWriteBack(argument, type); - if (wb != null) + if (wb is not null) { - if (writeBacks == null) + if (writeBacks is null) { writeBacks = new List(); } @@ -544,7 +544,7 @@ private static bool UseVirtual(MethodInfo mi) private void EmitWriteBack(List? writeBacks) { - if (writeBacks != null) + if (writeBacks is not null) { foreach (WriteBack wb in writeBacks) { @@ -564,7 +564,7 @@ private void EmitConstantExpression(Expression expr) private void EmitConstant(object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); EmitConstant(value, value.GetType()); } @@ -615,7 +615,7 @@ private void EmitNewExpression(Expression expr) { NewExpression node = (NewExpression)expr; - if (node.Constructor != null) + if (node.Constructor is not null) { if (node.Constructor.DeclaringType!.IsAbstract) throw Error.NonAbstractConstructorRequired(); @@ -785,7 +785,7 @@ private void EmitMemberAssignment(AssignBinaryExpression node, CompilationFlags // emit "this", if any Type? objectType = null; - if (lvalue.Expression != null) + if (lvalue.Expression is not null) { EmitInstance(lvalue.Expression, out objectType); } @@ -828,7 +828,7 @@ private void EmitMemberExpression(Expression expr) // emit "this", if any Type? instanceType = null; - if (node.Expression != null) + if (node.Expression is not null) { EmitInstance(node.Expression, out instanceType); } @@ -1013,8 +1013,8 @@ private void EmitMemberInit(MemberInitExpression init) _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); } - EmitMemberInit(init.Bindings, loc == null, init.NewExpression.Type); - if (loc != null) + EmitMemberInit(init.Bindings, loc is null, init.NewExpression.Type); + if (loc is not null) { _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); @@ -1057,8 +1057,8 @@ private void EmitListInit(ListInitExpression init) _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); } - EmitListInit(init.Initializers, loc == null, init.NewExpression.Type); - if (loc != null) + EmitListInit(init.Initializers, loc is null, init.NewExpression.Type); + if (loc is not null) { _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs index 6d476f90037711..82c16e506f4254 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs @@ -21,7 +21,7 @@ private void EmitExpression(Expression node, CompilationFlags flags) return; } - Debug.Assert(node != null); + Debug.Assert(node is not null); bool emitStart = (flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Lambda.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Lambda.cs index 65b987c4565021..fa19470ac4c271 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Lambda.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Lambda.cs @@ -31,7 +31,7 @@ internal void EmitConstantArray(T[] array) EmitConstant(array, typeof(T[])); } #if FEATURE_COMPILE_TO_METHODBUILDER - else if (_typeBuilder != null) + else if (_typeBuilder is not null) { // store into field in our type builder, we will initialize // the value only once. @@ -94,9 +94,9 @@ private void EmitDelegateConstruction(LambdaCompiler inner) Type delegateType = inner._lambda.Type; DynamicMethod? dynamicMethod = inner._method as DynamicMethod; #if FEATURE_COMPILE_TO_METHODBUILDER - if (dynamicMethod != null) + if (dynamicMethod is not null) #else - Debug.Assert(dynamicMethod != null); + Debug.Assert(dynamicMethod is not null); #endif { // Emit MethodInfo.CreateDelegate instead because DynamicMethod is not in Windows 8 Profile @@ -160,7 +160,7 @@ private static Type[] GetParameterTypes(LambdaExpression lambda, Type firstType) Type[] result; int i; - if (firstType != null) + if (firstType is not null) { result = new Type[count + 1]; result[0] = firstType; @@ -243,7 +243,7 @@ private void EmitLambdaBody(CompilerScope? parent, bool inlined, CompilationFlag _scope.Exit(); // Validate labels - Debug.Assert(_labelBlock.Parent == null && _labelBlock.Kind == LabelScopeKind.Lambda); + Debug.Assert(_labelBlock.Parent is null && _labelBlock.Kind == LabelScopeKind.Lambda); foreach (LabelInfo label in _labelInfo.Values) { label.ValidateFinish(); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs index b20bff13069216..f5c0a8e018219d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs @@ -49,7 +49,7 @@ private void EmitConditionalExpression(Expression expr, CompilationFlags flags) private static bool NotEmpty(Expression node) { var empty = node as DefaultExpression; - if (empty == null || empty.Type != typeof(void)) + if (empty is null || empty.Type != typeof(void)) { return true; } @@ -64,7 +64,7 @@ private static bool NotEmpty(Expression node) private static bool Significant(Expression node) { var block = node as BlockExpression; - if (block != null) + if (block is not null) { for (int i = 0; i < block.ExpressionCount; i++) { @@ -86,7 +86,7 @@ private static bool Significant(Expression node) private void EmitCoalesceBinaryExpression(Expression expr) { BinaryExpression b = (BinaryExpression)expr; - Debug.Assert(b.Method == null); + Debug.Assert(b.Method is null); if (b.Left.Type.IsNullableType()) { @@ -95,7 +95,7 @@ private void EmitCoalesceBinaryExpression(Expression expr) else { Debug.Assert(!b.Left.Type.IsValueType); - if (b.Conversion != null) + if (b.Conversion is not null) { EmitLambdaReferenceCoalesce(b); } @@ -109,7 +109,7 @@ private void EmitCoalesceBinaryExpression(Expression expr) private void EmitNullableCoalesce(BinaryExpression b) { - Debug.Assert(b.Method == null); + Debug.Assert(b.Method is null); LocalBuilder loc = GetLocal(b.Left.Type); Label labIfNull = _ilg.DefineLabel(); @@ -121,7 +121,7 @@ private void EmitNullableCoalesce(BinaryExpression b) _ilg.Emit(OpCodes.Brfalse, labIfNull); Type nnLeftType = b.Left.Type.GetNonNullableType(); - if (b.Conversion != null) + if (b.Conversion is not null) { Debug.Assert(b.Conversion.ParameterCount == 1); ParameterExpression p = b.Conversion.GetParameter(0); @@ -281,7 +281,7 @@ private void EmitMethodAndAlso(BinaryExpression b, CompilationFlags flags) EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); MethodInfo? opFalse = TypeUtils.GetBooleanOperator(b.Method.DeclaringType!, "op_False"); - Debug.Assert(opFalse != null, "factory should check that the method exists"); + Debug.Assert(opFalse is not null, "factory should check that the method exists"); _ilg.Emit(OpCodes.Call, opFalse); _ilg.Emit(OpCodes.Brtrue, labEnd); @@ -311,7 +311,7 @@ private void EmitAndAlsoBinaryExpression(Expression expr, CompilationFlags flags { BinaryExpression b = (BinaryExpression)expr; - if (b.Method != null) + if (b.Method is not null) { if (b.IsLiftedLogical) { @@ -356,7 +356,7 @@ private void EmitLiftedOrElse(BinaryExpression b) _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Or); - // if !(right == true | left != null) + // if !(right == true | left is not null) _ilg.Emit(OpCodes.Brfalse_S, returnLeft); _ilg.Emit(OpCodes.Ldloc, locRight); FreeLocal(locRight); @@ -387,7 +387,7 @@ private void EmitMethodOrElse(BinaryExpression b, CompilationFlags flags) EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); MethodInfo? opTrue = TypeUtils.GetBooleanOperator(b.Method.DeclaringType!, "op_True"); - Debug.Assert(opTrue != null, "factory should check that the method exists"); + Debug.Assert(opTrue is not null, "factory should check that the method exists"); _ilg.Emit(OpCodes.Call, opTrue); _ilg.Emit(OpCodes.Brtrue, labEnd); @@ -405,7 +405,7 @@ private void EmitOrElseBinaryExpression(Expression expr, CompilationFlags flags) { BinaryExpression b = (BinaryExpression)expr; - if (b.Method != null) + if (b.Method is not null) { if (b.IsLiftedLogical) { @@ -441,7 +441,7 @@ private void EmitOrElseBinaryExpression(Expression expr, CompilationFlags flags) /// operators to avoid double-branching, minimize instruction count, /// and generate similar IL to the C# compiler. This is important for /// the JIT to optimize patterns like: - /// x != null AndAlso x.GetType() == typeof(SomeType) + /// x is not null AndAlso x.GetType() == typeof(SomeType) /// /// One optimization we don't do: we always emits at least one /// conditional branch to the label, and always possibly falls through, @@ -493,7 +493,7 @@ private void EmitBranchOp(bool branch, Label label) private void EmitBranchNot(bool branch, UnaryExpression node, Label label) { - if (node.Method != null) + if (node.Method is not null) { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); EmitBranchOp(branch, label); @@ -511,7 +511,7 @@ private void EmitBranchComparison(bool branch, BinaryExpression node, Label labe // To share code paths, we want to treat NotEqual as an inverted Equal bool branchWhenEqual = branch == (node.NodeType == ExpressionType.Equal); - if (node.Method != null) + if (node.Method is not null) { EmitBinaryMethod(node, CompilationFlags.EmitAsNoTail); // EmitBinaryMethod takes into account the Equal/NotEqual @@ -583,7 +583,7 @@ private void EmitBranchLogical(bool branch, BinaryExpression node, Label label) Debug.Assert(node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse); Debug.Assert(!node.IsLiftedToNull); - if (node.Method != null || node.IsLifted) + if (node.Method is not null || node.IsLifted) { EmitExpression(node); EmitBranchOp(branch, label); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs index 8c86aa80376976..012453d8bc0dc1 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs @@ -43,7 +43,7 @@ private void Emit(BlockExpression node, CompilationFlags flags) if (tailCall != CompilationFlags.EmitAsNoTail) { var g = next as GotoExpression; - if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) + if (g is not null && (g.Value is null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) { // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted // as Ret. Therefore we can emit the current expression with tail call. @@ -84,7 +84,7 @@ private void Emit(BlockExpression node, CompilationFlags flags) private void EnterScope(object node) { if (HasVariables(node) && - (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) + (_scope.MergedScopes is null || !_scope.MergedScopes.Contains(node))) { if (!_tree.Scopes.TryGetValue(node, out CompilerScope? scope)) { @@ -110,11 +110,11 @@ private void EnterScope(object node) private static bool HasVariables(object node) { var block = node as BlockExpression; - if (block != null) + if (block is not null) { return block.Variables.Count > 0; } - return ((CatchBlock)node).Variable != null; + return ((CatchBlock)node).Variable is not null; } private void ExitScope(object node) @@ -167,7 +167,7 @@ private void EmitSwitchExpression(Expression expr, CompilationFlags flags) EmitExpressionAsVoid(node.SwitchValue); // Now if there is a default body, it happens unconditionally. - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { EmitExpressionAsType(node.DefaultBody, node.Type, flags); } @@ -225,7 +225,7 @@ private void EmitSwitchExpression(Expression expr, CompilationFlags flags) // Define labels Label end = _ilg.DefineLabel(); - Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); + Label @default = (node.DefaultBody is null) ? end : _ilg.DefineLabel(); // Emit the case and default bodies EmitSwitchCases(node, labels, isGoto, @default, end, flags); @@ -236,7 +236,7 @@ private void EmitSwitchExpression(Expression expr, CompilationFlags flags) /// private static Type GetTestValueType(SwitchExpression node) { - if (node.Comparison == null) + if (node.Comparison is null) { // If we have no comparison, all right side types must be the // same. @@ -362,7 +362,7 @@ private static bool CanOptimizeSwitchType(Type valueType) private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) { // If we have a comparison, bail - if (node.Comparison != null) + if (node.Comparison is not null) { return false; } @@ -429,7 +429,7 @@ private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags fl // Create end label, and default label if needed Label end = _ilg.DefineLabel(); - Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); + Label @default = (node.DefaultBody is null) ? end : _ilg.DefineLabel(); // Emit the switch var info = new SwitchInfo(node, value, @default); @@ -460,7 +460,7 @@ private void DefineSwitchCaseLabel(SwitchCase @case, out Label label, out bool i { var jump = @case.Body as GotoExpression; // if it's a goto with no value - if (jump != null && jump.Value == null) + if (jump is not null && jump.Value is null) { // Reference the label from the switch. This will cause us to // analyze the jump target and determine if it is safe. @@ -500,7 +500,7 @@ private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGot EmitExpressionAsType(node.Cases[i].Body, node.Type, flags); // Last case doesn't need branch - if (node.DefaultBody != null || i < n - 1) + if (node.DefaultBody is not null || i < n - 1) { if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { @@ -516,7 +516,7 @@ private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGot } // Default value - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { _ilg.MarkLabel(@default); EmitExpressionAsType(node.DefaultBody, node.Type, flags); @@ -671,7 +671,7 @@ private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flag { foreach (ConstantExpression t in node.Cases[i].TestValues) { - if (t.Value != null) + if (t.Value is not null) { initializers.Add(Expression.ElementInit(add, new TrueReadOnlyCollection(t, Utils.Constant(i)))); } @@ -710,10 +710,10 @@ private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flag // Create a tree like: // // switchValue = switchValueExpression; - // if (switchValue == null) { + // if (switchValue is null) { // switchIndex = nullCase; // } else { - // if (_dictField == null) { + // if (_dictField is null) { // _dictField = new Dictionary(count) { { ... }, ... }; // } // if (!_dictField.TryGetValue(switchValue, out switchIndex)) { @@ -755,7 +755,7 @@ private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flag private void CheckRethrow() { // Rethrow is only valid inside a catch. - for (LabelScopeInfo? j = _labelBlock; j != null; j = j.Parent) + for (LabelScopeInfo? j = _labelBlock; j is not null; j = j.Parent) { if (j.Kind == LabelScopeKind.Catch) { @@ -775,7 +775,7 @@ private void CheckRethrow() private void CheckTry() { // Try inside a filter is not verifiable - for (LabelScopeInfo? j = _labelBlock; j != null; j = j.Parent) + for (LabelScopeInfo? j = _labelBlock; j is not null; j = j.Parent) { if (j.Kind == LabelScopeKind.Filter) { @@ -786,7 +786,7 @@ private void CheckTry() private void EmitSaveExceptionOrPop(CatchBlock cb) { - if (cb.Variable != null) + if (cb.Variable is not null) { // If the variable is present, store the exception // in the variable. @@ -835,7 +835,7 @@ private void EmitTryExpression(Expression expr) PushLabelBlock(LabelScopeKind.Catch); // Begin the strongly typed exception block - if (cb.Filter == null) + if (cb.Filter is null) { _ilg.BeginCatchBlock(cb.Test); } @@ -867,11 +867,11 @@ private void EmitTryExpression(Expression expr) // 4. Emit the finally block //****************************************************************** - if (node.Finally != null || node.Fault != null) + if (node.Finally is not null || node.Fault is not null) { PushLabelBlock(LabelScopeKind.Finally); - if (node.Finally != null) + if (node.Finally is not null) { _ilg.BeginFinallyBlock(); } @@ -906,7 +906,7 @@ private void EmitTryExpression(Expression expr) /// private void EmitCatchStart(CatchBlock cb) { - if (cb.Filter == null) + if (cb.Filter is null) { EmitSaveExceptionOrPop(cb); return; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Unary.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Unary.cs index c764b7827609b9..1f0eb1286eb6af 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Unary.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Unary.cs @@ -24,7 +24,7 @@ private void EmitQuote(UnaryExpression quote) // Heuristic: only emit the tree rewrite logic if we have hoisted // locals. - if (_scope.NearestHoistedLocals != null) + if (_scope.NearestHoistedLocals is not null) { // HoistedLocals is internal so emit as System.Object EmitConstant(_scope.NearestHoistedLocals, typeof(object)); @@ -43,7 +43,7 @@ private void EmitThrowUnaryExpression(Expression expr) private void EmitThrow(UnaryExpression expr, CompilationFlags flags) { - if (expr.Operand == null) + if (expr.Operand is null) { CheckRethrow(); @@ -65,7 +65,7 @@ private void EmitUnaryExpression(Expression expr, CompilationFlags flags) private void EmitUnary(UnaryExpression node, CompilationFlags flags) { - if (node.Method != null) + if (node.Method is not null) { EmitUnaryMethod(node, flags); } @@ -285,7 +285,7 @@ private void EmitConvertUnaryExpression(Expression expr, CompilationFlags flags) private void EmitConvert(UnaryExpression node, CompilationFlags flags) { - if (node.Method != null) + if (node.Method is not null) { // User-defined conversions are only lifted if both source and // destination types are value types. The C# compiler gets this wrong. @@ -306,7 +306,7 @@ private void EmitConvert(UnaryExpression node, CompilationFlags flags) if (node.IsLifted && (!node.Type.IsValueType || !node.Operand.Type.IsValueType)) { ParameterInfo[] pis = node.Method.GetParametersCached(); - Debug.Assert(pis != null && pis.Length == 1); + Debug.Assert(pis is not null && pis.Length == 1); Type paramType = pis[0].ParameterType; if (paramType.IsByRef) { @@ -314,11 +314,11 @@ private void EmitConvert(UnaryExpression node, CompilationFlags flags) } UnaryExpression operand = Expression.Convert(node.Operand, paramType); - Debug.Assert(operand.Method == null); + Debug.Assert(operand.Method is null); node = Expression.Convert(Expression.Call(node.Method, operand), node.Type); - Debug.Assert(node.Method == null); + Debug.Assert(node.Method is null); } else { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.cs index c647214c170d9a..379d93e9a44c3e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.cs @@ -226,7 +226,7 @@ private static AnalyzedTree AnalyzeLambda(ref LambdaExpression lambda) public void FreeLocal(LocalBuilder local) { - Debug.Assert(local != null); + Debug.Assert(local is not null); _freeLocals.Push(local.LocalType, local); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs index be140e2748e96d..df5cae86410cf5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs @@ -121,7 +121,7 @@ internal void Add(Expression? expression) { Debug.Assert(!_done); - if (expression == null) + if (expression is null) { _expressions[_expressionsCount++] = null; return; @@ -232,7 +232,7 @@ private void EnsureDone() /// private static bool ShouldSaveToTemp(Expression? expression) { - if (expression == null) + if (expression is null) return false; // Some expressions have no side-effects and don't have to be @@ -265,7 +265,7 @@ private static bool ShouldSaveToTemp(Expression? expression) case ExpressionType.MemberAccess: var member = (MemberExpression)expression; var field = member.Member as FieldInfo; - if (field != null) + if (field is not null) { // Emits ldc for the raw value of the field if (field.IsLiteral) @@ -350,7 +350,7 @@ internal void MarkRefArgs(MethodBase method, int startIndex) /// private void MarkRef(int index) { - if (_byRefs == null) + if (_byRefs is null) { _byRefs = new bool[_expressions.Length]; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Generated.cs index 703c00425f5a81..1b6f7d1ece8d9b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Generated.cs @@ -15,7 +15,7 @@ internal partial class StackSpiller /// Rewritten expression. private Result RewriteExpression(Expression node, Stack stack) { - if (node == null) + if (node is null) { return new Result(RewriteAction.None, null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs index 41222f5af4d050..00462e07900244 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs @@ -110,7 +110,7 @@ internal ParameterExpression Temp(Type type) { ParameterExpression temp; - if (_freeTemps != null) + if (_freeTemps is not null) { // Recycle from the free-list if possible. for (int i = _freeTemps.Count - 1; i >= 0; i--) @@ -140,10 +140,10 @@ internal ParameterExpression Temp(Type type) /// The original temporary variable. private ParameterExpression UseTemp(ParameterExpression temp) { - Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); - Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); + Debug.Assert(_freeTemps is null || !_freeTemps.Contains(temp)); + Debug.Assert(_usedTemps is null || !_usedTemps.Contains(temp)); - if (_usedTemps == null) + if (_usedTemps is null) { _usedTemps = new Stack(); } @@ -160,9 +160,9 @@ private ParameterExpression UseTemp(ParameterExpression temp) /// The temporary variable to mark as no longer in use. private void FreeTemp(ParameterExpression temp) { - Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); + Debug.Assert(_freeTemps is null || !_freeTemps.Contains(temp)); - if (_freeTemps == null) + if (_freeTemps is null) { _freeTemps = new List(); } @@ -192,12 +192,12 @@ private void FreeTemp(ParameterExpression temp) /// internal void Free(int mark) { - // (_usedTemps != null) ==> (mark <= _usedTemps.Count) - Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count); - // (_usedTemps == null) ==> (mark == 0) - Debug.Assert(mark == 0 || _usedTemps != null); + // (_usedTemps is not null) ==> (mark <= _usedTemps.Count) + Debug.Assert(_usedTemps is null || mark <= _usedTemps.Count); + // (_usedTemps is null) ==> (mark == 0) + Debug.Assert(mark == 0 || _usedTemps is not null); - if (_usedTemps != null) + if (_usedTemps is not null) { while (mark < _usedTemps.Count) { @@ -214,7 +214,7 @@ internal void Free(int mark) [Conditional("DEBUG")] internal void VerifyTemps() { - Debug.Assert(_usedTemps == null || _usedTemps.Count == 0); + Debug.Assert(_usedTemps is null || _usedTemps.Count == 0); } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs index 86d20134e217ca..3c7505984c4a34 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs @@ -130,7 +130,7 @@ internal Expression Rewrite(Expression lambda) [Conditional("DEBUG")] private static void VerifyRewrite(Result result, Expression node) { - Debug.Assert(result.Node != null); + Debug.Assert(result.Node is not null); // (result.Action == RewriteAction.None) if and only if (node == result.Node) Debug.Assert((result.Action == RewriteAction.None) ^ (node != result.Node), "rewrite action does not match node object identity"); @@ -449,7 +449,7 @@ private Result RewriteMethodCallExpression(Expression expr, Stack stack) if (cr.Rewrite) { - if (node.Object != null) + if (node.Object is not null) { expr = new InstanceMethodCallExpressionN(node.Method, cr[0]!, cr[1, -1]!); } @@ -498,7 +498,7 @@ private Result RewriteInvocationExpression(Expression expr, Stack stack) // See if the lambda will be inlined. LambdaExpression? lambda = node.LambdaOperand; - if (lambda != null) + if (lambda is not null) { // Arguments execute on current stack. cr = new ChildRewriter(this, stack, node.ArgumentCount); @@ -786,12 +786,12 @@ private Result RewriteBlockExpression(Expression expr, Stack stack) Result rewritten = RewriteExpression(expression, stack); action |= rewritten.Action; - if (clone == null && rewritten.Action != RewriteAction.None) + if (clone is null && rewritten.Action != RewriteAction.None) { clone = Clone(node.Expressions, i); } - if (clone != null) + if (clone is not null) { clone[i] = rewritten.Node; } @@ -895,12 +895,12 @@ private Result RewriteSwitchExpression(Expression expr, Stack stack) Result test = RewriteExpression(testValues[j], stack); action |= test.Action; - if (cloneTests == null && test.Action != RewriteAction.None) + if (cloneTests is null && test.Action != RewriteAction.None) { cloneTests = Clone(testValues, j); } - if (cloneTests != null) + if (cloneTests is not null) { cloneTests[j] = test.Node; } @@ -910,22 +910,22 @@ private Result RewriteSwitchExpression(Expression expr, Stack stack) Result body = RewriteExpression(@case.Body, stack); action |= body.Action; - if (body.Action != RewriteAction.None || cloneTests != null) + if (body.Action != RewriteAction.None || cloneTests is not null) { - if (cloneTests != null) + if (cloneTests is not null) { testValues = new ReadOnlyCollection(cloneTests); } @case = new SwitchCase(body.Node, testValues); - if (clone == null) + if (clone is null) { clone = Clone(cases, i); } } - if (clone != null) + if (clone is not null) { clone[i] = @case; } @@ -937,7 +937,7 @@ private Result RewriteSwitchExpression(Expression expr, Stack stack) if (action != RewriteAction.None) { - if (clone != null) + if (clone is not null) { // okay to wrap because we aren't modifying the array cases = new ReadOnlyCollection(clone); @@ -960,7 +960,7 @@ private Result RewriteTryExpression(Expression expr, Stack stack) CatchBlock[]? clone = null; RewriteAction action = body.Action; - if (handlers != null) + if (handlers is not null) { for (int i = 0; i < handlers.Count; i++) { @@ -969,7 +969,7 @@ private Result RewriteTryExpression(Expression expr, Stack stack) CatchBlock handler = handlers[i]; Expression? filter = handler.Filter; - if (handler.Filter != null) + if (handler.Filter is not null) { // Our code gen saves the incoming filter value and provides it as a variable so the stack is empty Result rfault = RewriteExpression(handler.Filter, Stack.Empty); @@ -987,13 +987,13 @@ private Result RewriteTryExpression(Expression expr, Stack stack) { handler = Expression.MakeCatchBlock(handler.Test, handler.Variable, rbody.Node, filter); - if (clone == null) + if (clone is null) { clone = Clone(handlers, i); } } - if (clone != null) + if (clone is not null) { clone[i] = handler; } @@ -1014,7 +1014,7 @@ private Result RewriteTryExpression(Expression expr, Stack stack) if (action != RewriteAction.None) { - if (clone != null) + if (clone is not null) { // Okay to wrap because we aren't modifying the array. handlers = new ReadOnlyCollection(clone); @@ -1044,7 +1044,7 @@ private Result RewriteExtensionExpression(Expression expr, Stack stack) /// The cloned array. private static T[] Clone(ReadOnlyCollection original, int max) { - Debug.Assert(original != null); + Debug.Assert(original is not null); Debug.Assert(max < original.Count); T[] clone = new T[original.Count]; @@ -1073,7 +1073,7 @@ private static T[] Clone(ReadOnlyCollection original, int max) /// private static void RequireNoRefArgs(MethodBase? method) { - if (method != null && method.GetParametersCached().Any(p => p.ParameterType.IsByRef)) + if (method is not null && method.GetParametersCached().Any(p => p.ParameterType.IsByRef)) { throw Error.TryNotSupportedForMethodsWithRefArgs(method); } @@ -1102,7 +1102,7 @@ private static bool IsRefInstance([NotNullWhen(true)] Expression? instance) // Primitive value types are okay because they are all read-only, // but we can't rely on this for non-primitive types. So we have // to either throw NotSupported or use ref locals. - return instance != null && instance.Type.IsValueType && instance.Type.GetTypeCode() == TypeCode.Object; + return instance is not null && instance.Type.IsValueType && instance.Type.GetTypeCode() == TypeCode.Object; } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs index 47ae039a607a2a..c936ce3fa5ea67 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs @@ -96,7 +96,7 @@ protected internal override Expression VisitInvocation(InvocationExpression node LambdaExpression? lambda = node.LambdaOperand; // optimization: inline code for literal lambda's directly - if (lambda != null) + if (lambda is not null) { // visit the lambda, but treat it like a scope associated with invocation _scopes.Push(_tree.Scopes[node] = new CompilerScope(lambda, false)); @@ -128,7 +128,7 @@ protected internal override Expression VisitBlock(BlockExpression node) protected override CatchBlock VisitCatchBlock(CatchBlock node) { - if (node.Variable == null) + if (node.Variable is null) { Visit(node.Filter); Visit(node.Body); @@ -148,7 +148,7 @@ private ReadOnlyCollection MergeScopes(Expression node) { ReadOnlyCollection body; var lambda = node as LambdaExpression; - if (lambda != null) + if (lambda is not null) { body = new ReadOnlyCollection(new[] { lambda.Body }); } @@ -178,7 +178,7 @@ private ReadOnlyCollection MergeScopes(Expression node) } // Otherwise, merge it - if (currentScope.MergedScopes == null) + if (currentScope.MergedScopes is null) { currentScope.MergedScopes = new HashSet(ReferenceEqualityComparer.Instance); } @@ -220,8 +220,8 @@ protected internal override Expression VisitParameter(ParameterExpression node) } } - Debug.Assert(referenceScope != null); - if (referenceScope.ReferenceCount == null) + Debug.Assert(referenceScope is not null); + if (referenceScope.ReferenceCount is null) { referenceScope.ReferenceCount = new Dictionary(); } @@ -256,7 +256,7 @@ private void Reference(ParameterExpression node, VariableStorageKind storage) storage = VariableStorageKind.Hoisted; } } - if (definition == null) + if (definition is null) { throw Error.UndefinedVariable(node.Name, node.Type, CurrentLambdaName); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs index 515c41c23c8d02..fe4daa77f5322b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs @@ -25,7 +25,7 @@ public override Type Type { get { - if (Value == null) + if (Value is null) { return typeof(object); } @@ -96,7 +96,7 @@ public static ConstantExpression Constant(object? value, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); TypeUtils.ValidateType(type, nameof(type)); - if (value == null) + if (value is null) { if (type == typeof(object)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs index 96de71810676ba..e3f345d25a6a1b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs @@ -79,7 +79,7 @@ private void NewLine() private static int GetId(T e, ref Dictionary? ids) where T : notnull { - if (ids == null) + if (ids is null) { ids = new Dictionary(); ids.Add(e, 1); @@ -121,8 +121,8 @@ private int GetLabelTargetId(LabelTarget target) /// internal static void WriteTo(Expression node, TextWriter writer) { - Debug.Assert(node != null); - Debug.Assert(writer != null); + Debug.Assert(node is not null); + Debug.Assert(writer is not null); new DebugViewWriter(writer).WriteTo(node); } @@ -143,7 +143,7 @@ private void WriteTo(Expression node) // Output all lambda expression definitions. // in the order of their appearances in the tree. // - while (_lambdas != null && _lambdas.Count > 0) + while (_lambdas is not null && _lambdas.Count > 0) { WriteLine(); WriteLine(); @@ -255,7 +255,7 @@ private void VisitExpressions(char open, char separator, IReadOnlyList exp { Out(open.ToString()); - if (expressions != null) + if (expressions is not null) { Indent(); bool isFirst = true; @@ -409,7 +409,7 @@ protected internal override Expression VisitLambda(Expression node) ) ); - if (_lambdas == null) + if (_lambdas is null) { _lambdas = new Queue(); } @@ -426,7 +426,7 @@ protected internal override Expression VisitLambda(Expression node) private static bool IsSimpleExpression(Expression node) { var binary = node as BinaryExpression; - if (binary != null) + if (binary is not null) { return !(binary.Left is BinaryExpression || binary.Right is BinaryExpression); } @@ -465,7 +465,7 @@ protected internal override Expression VisitConstant(ConstantExpression node) { object? value = node.Value; - if (value == null) + if (value is null) { Out("null"); } @@ -491,7 +491,7 @@ protected internal override Expression VisitConstant(ConstantExpression node) else { string? suffix = GetConstantValueSuffix(node.Type); - if (suffix != null) + if (suffix is not null) { Out(value.ToString()!); Out(suffix); @@ -547,7 +547,7 @@ protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExp // Prints ".instanceField" or "declaringType.staticField" private void OutMember(Expression node, Expression? instance, MemberInfo member) { - if (instance != null) + if (instance is not null) { ParenthesizedVisit(node, instance); Out("." + member.Name); @@ -575,8 +575,8 @@ protected internal override Expression VisitInvocation(InvocationExpression node private static bool NeedsParentheses(Expression parent, Expression? child) { - Debug.Assert(parent != null); - if (child == null) + Debug.Assert(parent is not null); + if (child is null) { return false; } @@ -631,7 +631,7 @@ private static bool NeedsParentheses(Expression parent, Expression? child) case ExpressionType.Divide: case ExpressionType.Modulo: BinaryExpression? binary = parent as BinaryExpression; - Debug.Assert(binary != null); + Debug.Assert(binary is not null); // Need to have parenthesis for the right operand. return child == binary.Right; } @@ -640,7 +640,7 @@ private static bool NeedsParentheses(Expression parent, Expression? child) // Special case: negate of a constant needs parentheses, to // disambiguate it from a negative constant. - if (child != null && child.NodeType == ExpressionType.Constant && + if (child is not null && child.NodeType == ExpressionType.Constant && (parent.NodeType == ExpressionType.Negate || parent.NodeType == ExpressionType.NegateChecked)) { return true; @@ -788,11 +788,11 @@ private void ParenthesizedVisit(Expression parent, Expression? nodeToVisit) protected internal override Expression VisitMethodCall(MethodCallExpression node) { Out(".Call "); - if (node.Object != null) + if (node.Object is not null) { ParenthesizedVisit(node, node.Object); } - else if (node.Method.DeclaringType != null) + else if (node.Method.DeclaringType is not null) { Out(node.Method.DeclaringType.ToString()); } @@ -930,7 +930,7 @@ protected internal override Expression VisitUnary(UnaryExpression node) Out("'"); break; case ExpressionType.Throw: - if (node.Operand == null) + if (node.Operand is null) { Out(".Rethrow"); } @@ -1035,7 +1035,7 @@ protected internal override Expression VisitGoto(GotoExpression node) protected internal override Expression VisitLoop(LoopExpression node) { Out(".Loop", Flow.Space); - if (node.ContinueLabel != null) + if (node.ContinueLabel is not null) { DumpLabel(node.ContinueLabel); } @@ -1044,7 +1044,7 @@ protected internal override Expression VisitLoop(LoopExpression node) Visit(node.Body); Dedent(); Out(Flow.NewLine, "}"); - if (node.BreakLabel != null) + if (node.BreakLabel is not null) { Out("", Flow.NewLine); DumpLabel(node.BreakLabel); @@ -1074,7 +1074,7 @@ protected internal override Expression VisitSwitch(SwitchExpression node) Visit(node.SwitchValue); Out(") {", Flow.NewLine); Visit(node.Cases, VisitSwitchCase); - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { Out(".Default:", Flow.NewLine); Indent(); Indent(); @@ -1089,12 +1089,12 @@ protected internal override Expression VisitSwitch(SwitchExpression node) protected override CatchBlock VisitCatchBlock(CatchBlock node) { Out(Flow.NewLine, "} .Catch (" + node.Test.ToString()); - if (node.Variable != null) + if (node.Variable is not null) { Out(Flow.Space, ""); VisitParameter(node.Variable); } - if (node.Filter != null) + if (node.Filter is not null) { Out(") .If (", Flow.Break); Visit(node.Filter); @@ -1113,14 +1113,14 @@ protected internal override Expression VisitTry(TryExpression node) Visit(node.Body); Dedent(); Visit(node.Handlers, VisitCatchBlock); - if (node.Finally != null) + if (node.Finally is not null) { Out(Flow.NewLine, "} .Finally {", Flow.NewLine); Indent(); Visit(node.Finally); Dedent(); } - else if (node.Fault != null) + else if (node.Fault is not null) { Out(Flow.NewLine, "} .Fault {", Flow.NewLine); Indent(); @@ -1134,7 +1134,7 @@ protected internal override Expression VisitTry(TryExpression node) protected internal override Expression VisitIndex(IndexExpression node) { - if (node.Indexer != null) + if (node.Indexer is not null) { OutMember(node, node.Object, node.Indexer); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs index 689586b6a48470..39db68568189a5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs @@ -176,14 +176,14 @@ internal virtual DynamicExpression Rewrite(Expression[] args) public DynamicExpression Update(IEnumerable? arguments) { ICollection? args; - if (arguments == null) + if (arguments is null) { args = null; } else { args = arguments as ICollection; - if (args == null) + if (args is null) { arguments = args = arguments.ToReadOnly(); } @@ -542,7 +542,7 @@ Expression IArgumentProvider.GetArgument(int index) => internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 1) + if (arguments is not null && arguments.Count == 1) { using (IEnumerator en = arguments.GetEnumerator()) { @@ -602,7 +602,7 @@ Expression IArgumentProvider.GetArgument(int index) => internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 2) + if (arguments is not null && arguments.Count == 2) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -673,7 +673,7 @@ Expression IArgumentProvider.GetArgument(int index) => internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 3) + if (arguments is not null && arguments.Count == 3) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -750,7 +750,7 @@ Expression IArgumentProvider.GetArgument(int index) => internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 4) + if (arguments is not null && arguments.Count == 4) { if (_arg0 is ReadOnlyCollection alreadyCollection) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpressionVisitor.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpressionVisitor.cs index 6a509e7fdc9537..e27a9af6ddae60 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpressionVisitor.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpressionVisitor.cs @@ -16,7 +16,7 @@ public class DynamicExpressionVisitor : ExpressionVisitor protected internal override Expression VisitDynamic(DynamicExpression node) { Expression[]? a = ExpressionVisitorUtils.VisitArguments(this, node); - if (a == null) + if (a is null) { return node; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs index c24ba7d4a5d9b7..93e1ab8e28b2de 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs @@ -50,7 +50,7 @@ public ExtensionInfo(ExpressionType nodeType, Type type) protected Expression(ExpressionType nodeType, Type type) { // Can't enforce anything that V1 didn't - if (s_legacyCtorSupportTable == null) + if (s_legacyCtorSupportTable is null) { Interlocked.CompareExchange( ref s_legacyCtorSupportTable, @@ -76,7 +76,7 @@ public virtual ExpressionType NodeType { get { - if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out ExtensionInfo? extInfo)) + if (s_legacyCtorSupportTable is not null && s_legacyCtorSupportTable.TryGetValue(this, out ExtensionInfo? extInfo)) { return extInfo.NodeType; } @@ -94,7 +94,7 @@ public virtual Type Type { get { - if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out ExtensionInfo? extInfo)) + if (s_legacyCtorSupportTable is not null && s_legacyCtorSupportTable.TryGetValue(this, out ExtensionInfo? extInfo)) { return extInfo.Type; } @@ -177,7 +177,7 @@ public Expression ReduceAndCheck() // 1. Reduction must return a new, non-null node // 2. Reduction must return a new node whose result type can be assigned to the type of the original node - if (newNode == null || newNode == this) throw Error.MustReduceToDifferent(); + if (newNode is null || newNode == this) throw Error.MustReduceToDifferent(); if (!TypeUtils.AreReferenceAssignable(Type, newNode.Type)) throw Error.ReducedNotCompatible(); return newNode; } @@ -226,7 +226,7 @@ private string DebugView private static void RequiresCanRead(IReadOnlyList items, string paramName) { - Debug.Assert(items != null); + Debug.Assert(items is not null); // this is called a lot, avoid allocating an enumerator if we can... for (int i = 0, n = items.Count; i < n; i++) { @@ -236,7 +236,7 @@ private static void RequiresCanRead(IReadOnlyList items, string para private static void RequiresCanWrite(Expression expression, string paramName) { - if (expression == null) + if (expression is null) { throw new ArgumentNullException(paramName); } @@ -245,7 +245,7 @@ private static void RequiresCanWrite(Expression expression, string paramName) { case ExpressionType.Index: PropertyInfo? indexer = ((IndexExpression)expression).Indexer; - if (indexer == null || indexer.CanWrite) + if (indexer is null || indexer.CanWrite) { return; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs index 2fd6089db5c513..551595f411af1b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs @@ -34,7 +34,7 @@ public override string ToString() private int GetId(object o) { - if (_ids == null) + if (_ids is null) { _ids = new Dictionary(); } @@ -70,7 +70,7 @@ private void Out(char c) /// internal static string ExpressionToString(Expression node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.Visit(node); return esb.ToString(); @@ -78,7 +78,7 @@ internal static string ExpressionToString(Expression node) internal static string CatchBlockToString(CatchBlock node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitCatchBlock(node); return esb.ToString(); @@ -86,7 +86,7 @@ internal static string CatchBlockToString(CatchBlock node) internal static string SwitchCaseToString(SwitchCase node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitSwitchCase(node); return esb.ToString(); @@ -97,7 +97,7 @@ internal static string SwitchCaseToString(SwitchCase node) /// internal static string MemberBindingToString(MemberBinding node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitMemberBinding(node); return esb.ToString(); @@ -108,7 +108,7 @@ internal static string MemberBindingToString(MemberBinding node) /// internal static string ElementInitBindingToString(ElementInit node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); ExpressionStringBuilder esb = new ExpressionStringBuilder(); esb.VisitElementInit(node); return esb.ToString(); @@ -122,7 +122,7 @@ private void VisitExpressions(char open, ReadOnlyCollection expressions, c private void VisitExpressions(char open, ReadOnlyCollection expressions, char close, string seperator) where T : Expression { Out(open); - if (expressions != null) + if (expressions is not null) { bool isFirst = true; foreach (T e in expressions) @@ -351,7 +351,7 @@ protected internal override Expression VisitConditional(ConditionalExpression no protected internal override Expression VisitConstant(ConstantExpression node) { - if (node.Value != null) + if (node.Value is not null) { string? sValue = node.Value.ToString(); if (node.Value is string) @@ -402,7 +402,7 @@ protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExp // Prints ".instanceField" or "declaringType.staticField" private void OutMember(Expression? instance, MemberInfo member) { - if (instance != null) + if (instance is not null) { Visit(instance); } @@ -524,13 +524,13 @@ protected internal override Expression VisitMethodCall(MethodCallExpression node int start = 0; Expression? ob = node.Object; - if (node.Method.GetCustomAttribute(typeof(ExtensionAttribute)) != null) + if (node.Method.GetCustomAttribute(typeof(ExtensionAttribute)) is not null) { start = 1; ob = node.GetArgument(0); } - if (ob != null) + if (ob is not null) { Visit(ob); Out('.'); @@ -578,7 +578,7 @@ protected internal override Expression VisitNew(NewExpression node) { Out(", "); } - if (members != null) + if (members is not null) { string name = members[i].Name; Out(name); @@ -706,7 +706,7 @@ protected internal override Expression VisitGoto(GotoExpression node) Out(op); Out(' '); DumpLabel(node.Target); - if (node.Value != null) + if (node.Value is not null) { Out(" ("); Visit(node.Value); @@ -759,16 +759,16 @@ protected internal override Expression VisitTry(TryExpression node) protected internal override Expression VisitIndex(IndexExpression node) { - if (node.Object != null) + if (node.Object is not null) { Visit(node.Object); } else { - Debug.Assert(node.Indexer != null); + Debug.Assert(node.Indexer is not null); Out(node.Indexer.DeclaringType!.Name); } - if (node.Indexer != null) + if (node.Indexer is not null) { Out('.'); Out(node.Indexer.Name); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs index 92e210f97690bb..8029102bf1f853 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs @@ -48,7 +48,7 @@ public ReadOnlyCollection Visit(ReadOnlyCollection nodes { Expression node = Visit(nodes[i]); - if (newNodes != null) + if (newNodes is not null) { newNodes[i] = node; } @@ -62,7 +62,7 @@ public ReadOnlyCollection Visit(ReadOnlyCollection nodes newNodes[i] = node; } } - if (newNodes == null) + if (newNodes is null) { return nodes; } @@ -96,7 +96,7 @@ public static ReadOnlyCollection Visit(ReadOnlyCollection nodes, Func Visit(ReadOnlyCollection nodes, Func Visit(ReadOnlyCollection nodes, Func(T? node, string? callerName) where T : Expression { - if (node == null) + if (node is null) { return null; } node = (Visit(node) as T); - if (node == null) + if (node is null) { throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName); } @@ -157,12 +157,12 @@ public ReadOnlyCollection VisitAndConvert(ReadOnlyCollection nodes, str for (int i = 0, n = nodes.Count; i < n; i++) { T? node = Visit(nodes[i]) as T; - if (node == null) + if (node is null) { throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName); } - if (newNodes != null) + if (newNodes is not null) { newNodes[i] = node; } @@ -176,7 +176,7 @@ public ReadOnlyCollection VisitAndConvert(ReadOnlyCollection nodes, str newNodes[i] = node; } } - if (newNodes == null) + if (newNodes is null) { return nodes; } @@ -213,7 +213,7 @@ protected internal virtual Expression VisitBlock(BlockExpression node) Expression[]? nodes = ExpressionVisitorUtils.VisitBlockExpressions(this, node); ReadOnlyCollection v = VisitAndConvert(node.Variables, "VisitBlock"); - if (v == node.Variables && nodes == null) + if (v == node.Variables && nodes is null) { return node; } @@ -303,7 +303,7 @@ protected internal virtual Expression VisitInvocation(InvocationExpression node) { Expression e = Visit(node.Expression); Expression[]? a = VisitArguments(node); - if (e == node.Expression && a == null) + if (e == node.Expression && a is null) { return node; } @@ -346,7 +346,7 @@ protected internal virtual Expression VisitLambda(Expression node) Expression body = Visit(node.Body); ParameterExpression[]? parameters = VisitParameters(node, nameof(VisitLambda)); - if (body == node.Body && parameters == null) + if (body == node.Body && parameters is null) { return node; } @@ -386,7 +386,7 @@ protected internal virtual Expression VisitIndex(IndexExpression node) { Expression o = Visit(node.Object)!; Expression[]? a = VisitArguments(node); - if (o == node.Object && a == null) + if (o == node.Object && a is null) { return node; } @@ -404,7 +404,7 @@ protected internal virtual Expression VisitMethodCall(MethodCallExpression node) { Expression o = Visit(node.Object)!; Expression[]? a = VisitArguments(node); - if (o == node.Object && a == null) + if (o == node.Object && a is null) { return node; } @@ -432,7 +432,7 @@ protected internal virtual Expression VisitNewArray(NewArrayExpression node) protected internal virtual Expression VisitNew(NewExpression node) { Expression[]? a = VisitArguments(node); - if (a == null) + if (a is null) { return node; } @@ -638,15 +638,15 @@ protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding nod // private static UnaryExpression ValidateUnary(UnaryExpression before, UnaryExpression after) { - if (before != after && before.Method == null) + if (before != after && before.Method is null) { - if (after.Method != null) + if (after.Method is not null) { throw Error.MustRewriteWithoutMethod(after.Method, nameof(VisitUnary)); } // rethrow has null operand - if (before.Operand != null && after.Operand != null) + if (before.Operand is not null && after.Operand is not null) { ValidateChildType(before.Operand.Type, after.Operand.Type, nameof(VisitUnary)); } @@ -656,9 +656,9 @@ private static UnaryExpression ValidateUnary(UnaryExpression before, UnaryExpres private static BinaryExpression ValidateBinary(BinaryExpression before, BinaryExpression after) { - if (before != after && before.Method == null) + if (before != after && before.Method is null) { - if (after.Method != null) + if (after.Method is not null) { throw Error.MustRewriteWithoutMethod(after.Method, nameof(VisitBinary)); } @@ -674,7 +674,7 @@ private static SwitchExpression ValidateSwitch(SwitchExpression before, SwitchEx { // If we did not have a method, we don't want to bind to one, // it might not be the right thing. - if (before.Comparison == null && after.Comparison != null) + if (before.Comparison is null && after.Comparison is not null) { throw Error.MustRewriteWithoutMethod(after.Comparison, nameof(VisitSwitch)); } @@ -712,7 +712,7 @@ private static void ValidateChildType(Type before, Type after, string methodName protected internal virtual Expression VisitDynamic(DynamicExpression node) { Expression[]? a = VisitArguments((IArgumentProvider)node); - if (a == null) + if (a is null) { return node; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs index 9c1a38f9a8a458..0c2afb969f4202 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs @@ -339,11 +339,11 @@ public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget targe private static void ValidateGoto(LabelTarget target, ref Expression? value, string targetParameter, string valueParameter, Type? type) { ContractUtils.RequiresNotNull(target, targetParameter); - if (value == null) + if (value is null) { if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression(nameof(target)); - if (type != null) + if (type is not null) { TypeUtils.ValidateType(type, nameof(type)); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs index 6d131fbfcc00c5..485d513b3caecc 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs @@ -24,9 +24,9 @@ internal IndexExpression( PropertyInfo? indexer, IReadOnlyList arguments) { - if (indexer == null) + if (indexer is null) { - Debug.Assert(instance != null && instance.Type.IsArray); + Debug.Assert(instance is not null && instance.Type.IsArray); Debug.Assert(instance.Type.GetArrayRank() == arguments.Count); } @@ -49,7 +49,7 @@ public sealed override Type Type { get { - if (Indexer != null) + if (Indexer is not null) { return Indexer.PropertyType; } @@ -85,7 +85,7 @@ public ReadOnlyCollection Arguments /// This expression if no children changed, or an expression with the updated children. public IndexExpression Update(Expression @object, IEnumerable? arguments) { - if (@object == Object && arguments != null) + if (@object == Object && arguments is not null) { if (ExpressionUtils.SameElements(ref arguments, Arguments)) { @@ -118,8 +118,8 @@ protected internal override Expression Accept(ExpressionVisitor visitor) internal Expression Rewrite(Expression instance, Expression[]? arguments) { - Debug.Assert(instance != null); - Debug.Assert(arguments == null || arguments.Length == _arguments.Count); + Debug.Assert(instance is not null); + Debug.Assert(arguments is null || arguments.Length == _arguments.Count); return Expression.MakeIndex(instance, Indexer, arguments ?? _arguments); } @@ -136,7 +136,7 @@ public partial class Expression /// The created . public static IndexExpression MakeIndex(Expression instance, PropertyInfo? indexer, IEnumerable? arguments) { - if (indexer != null) + if (indexer is not null) { return Property(instance, indexer, arguments); } @@ -227,14 +227,14 @@ private static PropertyInfo FindInstanceProperty(Type type, string propertyName, // bind to public names first BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; PropertyInfo? pi = FindProperty(type, propertyName, arguments, flags); - if (pi == null) + if (pi is null) { flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; pi = FindProperty(type, propertyName, arguments, flags); } - if (pi == null) + if (pi is null) { - if (arguments == null || arguments.Length == 0) + if (arguments is null || arguments.Length == 0) { throw Error.InstancePropertyWithoutParameterNotDefinedForType(propertyName, type); } @@ -270,7 +270,7 @@ private static string GetArgTypesString(Expression[] arguments) { if (pi.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase) && IsCompatible(pi, arguments)) { - if (property == null) + if (property is null) { property = pi; } @@ -288,14 +288,14 @@ private static bool IsCompatible(PropertyInfo pi, Expression[]? args) { MethodInfo? mi = pi.GetGetMethod(nonPublic: true); ParameterInfo[] parms; - if (mi != null) + if (mi is not null) { parms = mi.GetParametersCached(); } else { mi = pi.GetSetMethod(nonPublic: true); - if (mi == null) + if (mi is null) { return false; } @@ -309,7 +309,7 @@ private static bool IsCompatible(PropertyInfo pi, Expression[]? args) parms = parms.RemoveLast(); } - if (args == null) + if (args is null) { return parms.Length == 0; } @@ -318,7 +318,7 @@ private static bool IsCompatible(PropertyInfo pi, Expression[]? args) return false; for (int i = 0; i < args.Length; i++) { - if (args[i] == null) return false; + if (args[i] is null) return false; if (!TypeUtils.AreReferenceAssignable(parms[i].ParameterType, args[i].Type)) { return false; @@ -381,7 +381,7 @@ private static void ValidateIndexedProperty(Expression? instance, PropertyInfo i ParameterInfo[]? getParameters = null; MethodInfo? getter = indexer.GetGetMethod(nonPublic: true); - if (getter != null) + if (getter is not null) { if (getter.ReturnType != indexer.PropertyType) { @@ -393,7 +393,7 @@ private static void ValidateIndexedProperty(Expression? instance, PropertyInfo i } MethodInfo? setter = indexer.GetSetMethod(nonPublic: true); - if (setter != null) + if (setter is not null) { ParameterInfo[] setParameters = setter.GetParametersCached(); if (setParameters.Length == 0) @@ -416,7 +416,7 @@ private static void ValidateIndexedProperty(Expression? instance, PropertyInfo i throw Error.PropertyTypeMustMatchSetter(paramName); } - if (getter != null) + if (getter is not null) { if (getter.IsStatic ^ setter.IsStatic) { @@ -440,7 +440,7 @@ private static void ValidateIndexedProperty(Expression? instance, PropertyInfo i ValidateAccessor(instance, setter, setParameters.RemoveLast(), ref argList, paramName); } } - else if (getter == null) + else if (getter is null) { throw Error.PropertyDoesNotHaveAccessor(indexer, paramName); } @@ -458,14 +458,14 @@ private static void ValidateAccessor(Expression? instance, MethodInfo method, Pa if (method.IsStatic) { - if (instance != null) + if (instance is not null) { throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(instance)); } } else { - if (instance == null) + if (instance is null) { throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(instance)); } @@ -503,7 +503,7 @@ private static void ValidateAccessorArgumentTypes(MethodInfo method, ParameterIn throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method, nameof(arguments), i); } } - if (newArgs == null && arg != arguments[i]) + if (newArgs is null && arg != arguments[i]) { newArgs = new Expression[arguments.Count]; for (int j = 0; j < i; j++) @@ -511,12 +511,12 @@ private static void ValidateAccessorArgumentTypes(MethodInfo method, ParameterIn newArgs[j] = arguments[j]; } } - if (newArgs != null) + if (newArgs is not null) { newArgs[i] = arg; } } - if (newArgs != null) + if (newArgs is not null) { arguments = new TrueReadOnlyCollection(newArgs); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AddInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AddInstruction.cs index e853c0a7785624..1e17565ceca254 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AddInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AddInstruction.cs @@ -23,10 +23,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left + (short)right)); + stack[index - 2] = right is null ? null : (object)unchecked((short)((short)left + (short)right)); } frame.StackIndex = index - 1; @@ -41,10 +41,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left + (int)right)); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left + (int)right)); } frame.StackIndex = index - 1; @@ -59,10 +59,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((long)left + (long)right); + stack[index - 2] = right is null ? null : (object)unchecked((long)left + (long)right); } frame.StackIndex = index - 1; @@ -77,10 +77,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left + (ushort)right)); + stack[index - 2] = right is null ? null : (object)unchecked((ushort)((ushort)left + (ushort)right)); } frame.StackIndex = index - 1; @@ -95,10 +95,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((uint)left + (uint)right); + stack[index - 2] = right is null ? null : (object)unchecked((uint)left + (uint)right); } frame.StackIndex = index - 1; @@ -113,10 +113,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ulong)left + (ulong)right); + stack[index - 2] = right is null ? null : (object)unchecked((ulong)left + (ulong)right); } frame.StackIndex = index - 1; @@ -131,10 +131,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((float)left + (float)right); + stack[index - 2] = right is null ? null : (object)((float)left + (float)right); } frame.StackIndex = index - 1; @@ -149,10 +149,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((double)left + (double)right); + stack[index - 2] = right is null ? null : (object)((double)left + (double)right); } frame.StackIndex = index - 1; @@ -195,10 +195,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((short)((short)left + (short)right)); + stack[index - 2] = right is null ? null : (object)checked((short)((short)left + (short)right)); } frame.StackIndex = index - 1; @@ -213,10 +213,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left + (int)right)); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left + (int)right)); } frame.StackIndex = index - 1; @@ -231,10 +231,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((long)left + (long)right); + stack[index - 2] = right is null ? null : (object)checked((long)left + (long)right); } frame.StackIndex = index - 1; @@ -249,10 +249,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((ushort)((ushort)left + (ushort)right)); + stack[index - 2] = right is null ? null : (object)checked((ushort)((ushort)left + (ushort)right)); } frame.StackIndex = index - 1; @@ -267,10 +267,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((uint)left + (uint)right); + stack[index - 2] = right is null ? null : (object)checked((uint)left + (uint)right); } frame.StackIndex = index - 1; @@ -285,10 +285,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((ulong)left + (ulong)right); + stack[index - 2] = right is null ? null : (object)checked((ulong)left + (ulong)right); } frame.StackIndex = index - 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AndInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AndInstruction.cs index 98d941e41d5cfb..8f8f74eab3875f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AndInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/AndInstruction.cs @@ -21,7 +21,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -37,7 +37,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -53,7 +53,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -69,7 +69,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -85,7 +85,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -117,7 +117,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -133,7 +133,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -149,9 +149,9 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - if (right == null) + if (right is null) { frame.Push(null); } @@ -161,7 +161,7 @@ public override int Run(InterpretedFrame frame) } return 1; } - else if (right == null) + else if (right is null) { frame.Push((bool)left ? null : Utils.BoxedFalse); return 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs index ba16d0998d4ab9..0661cc40a0fbf0 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs @@ -152,7 +152,7 @@ public static int ToInt32NoNull(object? val) { // If the value is null, unbox and cast to throw an InvalidOperationException // that .NET Framework throws. - return (val == null) ? (int)(int?)val! : Convert.ToInt32(val); + return (val is null) ? (int)(int?)val! : Convert.ToInt32(val); } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs index 0c3ef9769ae444..fdacd23e0db594 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs @@ -57,7 +57,7 @@ internal void Mark(InstructionList instructions) _continuationStackDepth = instructions.CurrentContinuationsDepth; _targetIndex = instructions.Count; - if (_forwardBranchFixups != null) + if (_forwardBranchFixups is not null) { foreach (int branchIndex in _forwardBranchFixups) { @@ -74,7 +74,7 @@ internal void AddBranch(InstructionList instructions, int branchIndex) if (_targetIndex == UnknownIndex) { - if (_forwardBranchFixups == null) + if (_forwardBranchFixups is null) { _forwardBranchFixups = new List(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.Generated.cs index e9855aebed6348..7317e215073459 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.Generated.cs @@ -37,7 +37,7 @@ internal partial class CallInstruction private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 0); - if (t == null) + if (t is null) { return new ActionCallInstruction(target); } @@ -76,7 +76,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 1); - if (t == null) + if (t is null) { if (target.ReturnType == typeof(void)) { @@ -119,7 +119,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 2); - if (t == null) + if (t is null) { if (target.ReturnType == typeof(void)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs index c222f01151c40b..687aca5f4d5988 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs @@ -42,7 +42,7 @@ public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters // A workaround for CLR behavior (Unable to create delegates for Array.Get/Set): // T[]::Address - not supported by ETs due to T& return value - if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) + if (info.DeclaringType is not null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) { return GetArrayAccessor(info, argumentCount); } @@ -267,7 +267,7 @@ protected static bool TryGetLightLambdaTarget(object? instance, [NotNullWhen(tru if (thunk is not null) { lightLambda = thunk.Target as LightLambda; - if (lightLambda != null) + if (lightLambda is not null) { return true; } @@ -459,7 +459,7 @@ public sealed override int Run(InterpretedFrame frame) } finally { - if (args != null) + if (args is not null) { foreach (ByRefUpdater arg in _byrefArgs) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs index dc058e63c469f4..aef8f11db479b7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs @@ -26,7 +26,7 @@ public Instruction Fixup(int offset) _offset = offset; Instruction[] cache = Cache; - if (cache != null && offset >= 0 && offset < cache.Length) + if (cache is not null && offset >= 0 && offset < cache.Length) { return cache[offset] ?? (cache[offset] = this); } @@ -53,7 +53,7 @@ public override Instruction[] Cache { get { - if (s_cache == null) + if (s_cache is null) { s_cache = new Instruction[CacheSize]; } @@ -85,7 +85,7 @@ public override Instruction[] Cache { get { - if (s_cache == null) + if (s_cache is null) { s_cache = new Instruction[CacheSize]; } @@ -117,7 +117,7 @@ public override Instruction[] Cache { get { - if (s_cache == null) + if (s_cache is null) { s_cache = new Instruction[CacheSize]; } @@ -133,7 +133,7 @@ public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); - if (frame.Peek() != null) + if (frame.Peek() is not null) { return _offset; } @@ -150,7 +150,7 @@ public override Instruction[] Cache { get { - if (s_caches == null) + if (s_caches is null) { s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; } @@ -297,7 +297,7 @@ internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction internal void SetTryHandler(TryCatchFinallyHandler tryHandler) { - Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once"); + Debug.Assert(_tryHandler is null && tryHandler is not null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } @@ -323,7 +323,7 @@ internal static EnterTryCatchFinallyInstruction CreateTryCatch() public override int Run(InterpretedFrame frame) { - Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); + Debug.Assert(_tryHandler is not null, "the tryHandler must be set already"); if (_hasFinally) { @@ -361,7 +361,7 @@ public override int Run(InterpretedFrame frame) #if FEATURE_THREAD_ABORT // stay in the current catch so that ThreadAbortException is not rethrown by CLR: var abort = exception as ThreadAbortException; - if (abort != null) + if (abort is not null) { Interpreter.AnyAbortException = abort; frame.CurrentAbortHandler = exHandler; @@ -445,14 +445,14 @@ internal EnterTryFaultInstruction(int targetIndex) internal void SetTryHandler(TryFaultHandler tryHandler) { - Debug.Assert(tryHandler != null); - Debug.Assert(_tryHandler == null, "the tryHandler can be set only once"); + Debug.Assert(tryHandler is not null); + Debug.Assert(_tryHandler is null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } public override int Run(InterpretedFrame frame) { - Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); + Debug.Assert(_tryHandler is not null, "the tryHandler must be set already"); // Push fault. frame.PushContinuation(_labelIndex); @@ -766,7 +766,7 @@ public override int Run(InterpretedFrame frame) } private static Exception? WrapThrownObject(object? thrown) => - thrown == null ? null : (thrown as Exception ?? new RuntimeWrappedException(thrown)); + thrown is null ? null : (thrown as Exception ?? new RuntimeWrappedException(thrown)); } internal sealed class IntSwitchInstruction : Instruction where T : notnull @@ -809,7 +809,7 @@ public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { return _nullCase.Value; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DecrementInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DecrementInstruction.cs index e5c156cdcea105..7be65cf70f96a0 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DecrementInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DecrementInstruction.cs @@ -21,7 +21,7 @@ private sealed class DecrementInt16 : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -38,7 +38,7 @@ private sealed class DecrementInt32 : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -55,7 +55,7 @@ private sealed class DecrementInt64 : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -72,7 +72,7 @@ private sealed class DecrementUInt16 : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -89,7 +89,7 @@ private sealed class DecrementUInt32 : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -106,7 +106,7 @@ private sealed class DecrementUInt64 : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -123,7 +123,7 @@ private sealed class DecrementSingle : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -140,7 +140,7 @@ private sealed class DecrementDouble : DecrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DivInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DivInstruction.cs index 682fd18034aeb9..ec2f36700b2e45 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DivInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/DivInstruction.cs @@ -23,10 +23,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left / (short)right)); + stack[index - 2] = right is null ? null : (object)unchecked((short)((short)left / (short)right)); } frame.StackIndex = index - 1; @@ -41,10 +41,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject((int)left / (int)right); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject((int)left / (int)right); } frame.StackIndex = index - 1; @@ -59,10 +59,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((long)left / (long)right); + stack[index - 2] = right is null ? null : (object)((long)left / (long)right); } frame.StackIndex = index - 1; @@ -77,10 +77,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left / (ushort)right)); + stack[index - 2] = right is null ? null : (object)unchecked((ushort)((ushort)left / (ushort)right)); } frame.StackIndex = index - 1; @@ -95,10 +95,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((uint)left / (uint)right); + stack[index - 2] = right is null ? null : (object)((uint)left / (uint)right); } frame.StackIndex = index - 1; @@ -113,10 +113,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((ulong)left / (ulong)right); + stack[index - 2] = right is null ? null : (object)((ulong)left / (ulong)right); } frame.StackIndex = index - 1; @@ -131,10 +131,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((float)left / (float)right); + stack[index - 2] = right is null ? null : (object)((float)left / (float)right); } frame.StackIndex = index - 1; @@ -149,10 +149,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((double)left / (double)right); + stack[index - 2] = right is null ? null : (object)((double)left / (double)right); } frame.StackIndex = index - 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/EqualInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/EqualInstruction.cs index 531a8a1908de4d..b585f833bd548a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/EqualInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/EqualInstruction.cs @@ -24,11 +24,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -46,11 +46,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -68,11 +68,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -90,11 +90,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -112,11 +112,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -134,11 +134,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -156,11 +156,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -178,11 +178,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -200,11 +200,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -222,11 +222,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -244,11 +244,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -266,11 +266,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right == null); + frame.Push(right is null); } - else if (right == null) + else if (right is null) { frame.Push(false); } @@ -297,7 +297,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -315,7 +315,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -333,7 +333,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -351,7 +351,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -369,7 +369,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -387,7 +387,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -405,7 +405,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -423,7 +423,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -441,7 +441,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -459,7 +459,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -477,7 +477,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -495,7 +495,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ExclusiveOrInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ExclusiveOrInstruction.cs index d7fdbe08522a93..7b55ef73c05d6e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ExclusiveOrInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ExclusiveOrInstruction.cs @@ -21,7 +21,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -37,7 +37,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -53,7 +53,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -69,7 +69,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -85,7 +85,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -117,7 +117,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -133,7 +133,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -149,7 +149,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanInstruction.cs index aab0a3094ec9ef..bb9298c1e2d1c8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanInstruction.cs @@ -32,7 +32,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -55,7 +55,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -78,7 +78,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -124,7 +124,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -147,7 +147,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -170,7 +170,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -193,7 +193,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -216,7 +216,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -239,7 +239,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -262,7 +262,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanOrEqualInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanOrEqualInstruction.cs index a7d9360a227641..e1b012032b232a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanOrEqualInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/GreaterThanOrEqualInstruction.cs @@ -32,7 +32,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -55,7 +55,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -78,7 +78,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -124,7 +124,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -147,7 +147,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -170,7 +170,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -193,7 +193,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -216,7 +216,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -239,7 +239,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -262,7 +262,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/IncrementInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/IncrementInstruction.cs index 96e223f696001f..218e1ed88b6199 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/IncrementInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/IncrementInstruction.cs @@ -21,7 +21,7 @@ private sealed class IncrementInt16 : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -38,7 +38,7 @@ private sealed class IncrementInt32 : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -55,7 +55,7 @@ private sealed class IncrementInt64 : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -72,7 +72,7 @@ private sealed class IncrementUInt16 : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -89,7 +89,7 @@ private sealed class IncrementUInt32 : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -106,7 +106,7 @@ private sealed class IncrementUInt64 : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -123,7 +123,7 @@ private sealed class IncrementSingle : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -140,7 +140,7 @@ private sealed class IncrementDouble : IncrementInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Instruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Instruction.cs index ddf76de9b145b9..e7cd5240ca0bef 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Instruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Instruction.cs @@ -30,7 +30,7 @@ internal abstract class Instruction // throws NRE when o is null protected static void NullCheck(object? o) { - if (o == null) + if (o is null) { o!.GetType(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs index 0fbabd6289f36a..71326cbbdf1d3c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs @@ -341,13 +341,13 @@ public void EmitLoad(bool value) public void EmitLoad(object? value, Type? type) { - if (value == null) + if (value is null) { Emit(s_null ?? (s_null = new LoadObjectInstruction(null))); return; } - if (type == null || type.IsValueType) + if (type is null || type.IsValueType) { if (value is bool) { @@ -360,7 +360,7 @@ public void EmitLoad(object? value, Type? type) int i = (int)value; if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { - if (s_Ints == null) + if (s_Ints is null) { s_Ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; } @@ -371,10 +371,10 @@ public void EmitLoad(object? value, Type? type) } } - if (_objects == null) + if (_objects is null) { _objects = new List(); - if (s_loadObjectCached == null) + if (s_loadObjectCached is null) { s_loadObjectCached = new Instruction[CachedObjectCount]; } @@ -411,7 +411,7 @@ internal void SwitchToBoxed(int index, int instructionIndex) if (_instructions[instructionIndex] is IBoxableInstruction instruction) { Instruction? newInstruction = instruction.BoxIfIndexMatches(index); - if (newInstruction != null) + if (newInstruction is not null) { _instructions[instructionIndex] = newInstruction; } @@ -432,7 +432,7 @@ internal void SwitchToBoxed(int index, int instructionIndex) public void EmitLoadLocal(int index) { - if (s_loadLocal == null) + if (s_loadLocal is null) { s_loadLocal = new Instruction[LocalInstrCacheSize]; } @@ -454,7 +454,7 @@ public void EmitLoadLocalBoxed(int index) internal static Instruction LoadLocalBoxed(int index) { - if (s_loadLocalBoxed == null) + if (s_loadLocalBoxed is null) { s_loadLocalBoxed = new Instruction[LocalInstrCacheSize]; } @@ -471,7 +471,7 @@ internal static Instruction LoadLocalBoxed(int index) public void EmitLoadLocalFromClosure(int index) { - if (s_loadLocalFromClosure == null) + if (s_loadLocalFromClosure is null) { s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; } @@ -488,7 +488,7 @@ public void EmitLoadLocalFromClosure(int index) public void EmitLoadLocalFromClosureBoxed(int index) { - if (s_loadLocalFromClosureBoxed == null) + if (s_loadLocalFromClosureBoxed is null) { s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; } @@ -505,7 +505,7 @@ public void EmitLoadLocalFromClosureBoxed(int index) public void EmitAssignLocal(int index) { - if (s_assignLocal == null) + if (s_assignLocal is null) { s_assignLocal = new Instruction[LocalInstrCacheSize]; } @@ -522,7 +522,7 @@ public void EmitAssignLocal(int index) public void EmitStoreLocal(int index) { - if (s_storeLocal == null) + if (s_storeLocal is null) { s_storeLocal = new Instruction[LocalInstrCacheSize]; } @@ -544,7 +544,7 @@ public void EmitAssignLocalBoxed(int index) internal static Instruction AssignLocalBoxed(int index) { - if (s_assignLocalBoxed == null) + if (s_assignLocalBoxed is null) { s_assignLocalBoxed = new Instruction[LocalInstrCacheSize]; } @@ -566,7 +566,7 @@ public void EmitStoreLocalBoxed(int index) internal static Instruction StoreLocalBoxed(int index) { - if (s_storeLocalBoxed == null) + if (s_storeLocalBoxed is null) { s_storeLocalBoxed = new Instruction[LocalInstrCacheSize]; } @@ -583,7 +583,7 @@ internal static Instruction StoreLocalBoxed(int index) public void EmitAssignLocalToClosure(int index) { - if (s_assignLocalToClosure == null) + if (s_assignLocalToClosure is null) { s_assignLocalToClosure = new Instruction[LocalInstrCacheSize]; } @@ -607,7 +607,7 @@ public void EmitStoreLocalToClosure(int index) public void EmitInitializeLocal(int index, Type type) { object? value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); - if (value != null) + if (value is not null) { Emit(new InitializeLocalInstruction.ImmutableValue(index, value)); } @@ -967,7 +967,7 @@ private RuntimeLabel[] BuildRuntimeLabels() public BranchLabel MakeLabel() { - if (_labels == null) + if (_labels is null) { _labels = new List(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs index a8d9ccac62b5b8..dcf7de1a31f7dc 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs @@ -137,12 +137,12 @@ public IEnumerable GetStackTraceDebugInfo() { yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex)); frame = frame.Parent; - } while (frame != null); + } while (frame is not null); } internal void SaveTraceToException(Exception exception) { - if (exception.Data[typeof(InterpretedFrameInfo)] == null) + if (exception.Data[typeof(InterpretedFrameInfo)] is null) { exception.Data[typeof(InterpretedFrameInfo)] = new List(GetStackTraceDebugInfo()).ToArray(); } @@ -164,7 +164,7 @@ internal string[] Trace { trace.Add(frame.Name!); frame = frame.Parent; - } while (frame != null); + } while (frame is not null); return trace.ToArray(); } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs index 3fbc68ec476893..377da712c4927c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs @@ -58,7 +58,7 @@ internal void Define(LabelScopeInfo block) // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) - for (LabelScopeInfo? j = block; j != null; j = j.Parent) + for (LabelScopeInfo? j = block; j is not null; j = j.Parent) { if (j.ContainsTarget(_node!)) { @@ -96,7 +96,7 @@ internal void Define(LabelScopeInfo block) private void ValidateJump(LabelScopeInfo reference) { // look for a simple jump out - for (LabelScopeInfo? j = reference; j != null; j = j.Parent) + for (LabelScopeInfo? j = reference; j is not null; j = j.Parent) { if (DefinedIn(j)) { @@ -110,7 +110,7 @@ private void ValidateJump(LabelScopeInfo reference) } _acrossBlockJump = true; - if (_node != null && _node.Type != typeof(void)) + if (_node is not null && _node.Type != typeof(void)) { throw Error.NonLocalJumpWithValue(_node.Name); } @@ -165,7 +165,7 @@ internal void ValidateFinish() private void EnsureLabel(LightCompiler compiler) { - if (_label == null) + if (_label is null) { _label = compiler.Instructions.MakeLabel(); } @@ -185,7 +185,7 @@ private bool DefinedIn(LabelScopeInfo scope) return false; } - private bool HasDefinitions => _definitions != null; + private bool HasDefinitions => _definitions is not null; private LabelScopeInfo FirstDefinition() { @@ -202,14 +202,14 @@ private LabelScopeInfo FirstDefinition() private void AddDefinition(LabelScopeInfo scope) { - if (_definitions == null) + if (_definitions is null) { _definitions = scope; } else { HashSet? set = _definitions as HashSet; - if (set == null) + if (set is null) { _definitions = set = new HashSet() { (LabelScopeInfo)_definitions }; } @@ -227,11 +227,11 @@ private void AddDefinition(LabelScopeInfo scope) return first; } var set = new HashSet(cmp); - for (T t = first; t != null; t = parent(t)) + for (T t = first; t is not null; t = parent(t)) { set.Add(t); } - for (T t = second; t != null; t = parent(t)) + for (T t = second; t is not null; t = parent(t)) { if (set.Contains(t)) { @@ -308,7 +308,7 @@ internal bool CanJumpInto internal bool ContainsTarget(LabelTarget target) { - if (_labels == null) + if (_labels is null) { return false; } @@ -318,7 +318,7 @@ internal bool ContainsTarget(LabelTarget target) internal bool TryGetLabelInfo(LabelTarget target, [NotNullWhen(true)] out LabelInfo? info) { - if (_labels == null) + if (_labels is null) { info = null; return false; @@ -331,7 +331,7 @@ internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); - if (_labels == null) + if (_labels is null) { _labels = new HybridReferenceDictionary(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LeftShiftInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LeftShiftInstruction.cs index a7ab8c1e02d634..ff0bc4153c11a2 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LeftShiftInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LeftShiftInstruction.cs @@ -21,7 +21,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -39,7 +39,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -57,7 +57,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -75,7 +75,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -93,7 +93,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -111,7 +111,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -129,7 +129,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -147,7 +147,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanInstruction.cs index 0adf30dbe53c4f..25087d1b74ad5e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanInstruction.cs @@ -32,7 +32,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -55,7 +55,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -78,7 +78,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -124,7 +124,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -147,7 +147,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -170,7 +170,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -193,7 +193,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -216,7 +216,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -239,7 +239,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -262,7 +262,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanOrEqualInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanOrEqualInstruction.cs index d06208a62578b7..b74b290791fd7e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanOrEqualInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LessThanOrEqualInstruction.cs @@ -32,7 +32,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -55,7 +55,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -78,7 +78,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -124,7 +124,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -147,7 +147,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -170,7 +170,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -193,7 +193,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -216,7 +216,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -239,7 +239,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } @@ -262,7 +262,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(_nullValue); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs index 534a3f73698872..fe04878396f1f3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs @@ -40,7 +40,7 @@ internal sealed class ExceptionHandler internal ExceptionHandler(int labelIndex, int handlerStartIndex, int handlerEndIndex, Type exceptionType, ExceptionFilter? filter) { - Debug.Assert(exceptionType != null); + Debug.Assert(exceptionType is not null); LabelIndex = labelIndex; _exceptionType = exceptionType; HandlerStartIndex = handlerStartIndex; @@ -75,7 +75,7 @@ internal bool IsFinallyBlockExist internal ExceptionHandler[]? Handlers => _handlers; - internal bool IsCatchBlockExist => _handlers != null; + internal bool IsCatchBlockExist => _handlers is not null; /// /// No finally block @@ -83,7 +83,7 @@ internal bool IsFinallyBlockExist internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndTargetIndex, ExceptionHandler[] handlers) : this(tryStart, tryEnd, gotoEndTargetIndex, Instruction.UnknownInstrIndex, Instruction.UnknownInstrIndex, handlers) { - Debug.Assert(handlers != null, "catch blocks should exist"); + Debug.Assert(handlers is not null, "catch blocks should exist"); } /// @@ -117,11 +117,11 @@ internal bool HasHandler(InterpretedFrame frame, Exception exception, [NotNullWh if (IsCatchBlockExist) { RuntimeWrappedException? rwe = exception as RuntimeWrappedException; - unwrappedException = rwe != null ? rwe.WrappedException : exception; + unwrappedException = rwe is not null ? rwe.WrappedException : exception; Type exceptionType = unwrappedException.GetType(); foreach (ExceptionHandler candidate in _handlers!) { - if (candidate.Matches(exceptionType) && (candidate.Filter == null || FilterPasses(frame, ref unwrappedException, candidate.Filter))) + if (candidate.Matches(exceptionType) && (candidate.Filter is null || FilterPasses(frame, ref unwrappedException, candidate.Filter))) { handler = candidate; return true; @@ -216,7 +216,7 @@ private class DebugInfoComparer : IComparer //We allow comparison between int and DebugInfo here int IComparer.Compare(DebugInfo? d1, DebugInfo? d2) { - Debug.Assert(d1 != null && d2 != null); + Debug.Assert(d1 is not null && d2 is not null); if (d1.Index > d2.Index) return 1; else if (d1.Index == d2.Index) return 0; else return -1; @@ -272,7 +272,7 @@ public InterpretedFrameInfo(string? methodName, DebugInfo? info) _debugInfo = info; } - public override string? ToString() => _debugInfo != null ? _methodName + ": " + _debugInfo : _methodName; + public override string? ToString() => _debugInfo is not null ? _methodName + ": " + _debugInfo : _methodName; } internal sealed class LightCompiler @@ -362,7 +362,7 @@ private void CompileDefaultExpression(Type type) else { object? value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); - if (value != null) + if (value is not null) { _instructions.EmitLoad(value); } @@ -384,7 +384,7 @@ private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) } return local; } - else if (_parent != null) + else if (_parent is not null) { _parent.EnsureAvailableForClosure(expr); return _locals.AddClosureVariable(expr); @@ -571,7 +571,7 @@ private void CompileIndexExpression(Expression expr) var index = (IndexExpression)expr; // instance: - if (index.Object != null) + if (index.Object is not null) { EmitThisForMethodCall(index.Object); } @@ -587,7 +587,7 @@ private void CompileIndexExpression(Expression expr) private void EmitIndexGet(IndexExpression index) { - if (index.Indexer != null) + if (index.Indexer is not null) { _instructions.EmitCall(index.Indexer.GetGetMethod(nonPublic: true)!); } @@ -606,7 +606,7 @@ private void CompileIndexAssignment(BinaryExpression node, bool asVoid) var index = (IndexExpression)node.Left; // instance: - if (index.Object != null) + if (index.Object is not null) { EmitThisForMethodCall(index.Object); } @@ -626,7 +626,7 @@ private void CompileIndexAssignment(BinaryExpression node, bool asVoid) _instructions.EmitAssignLocal(local.Index); } - if (index.Indexer != null) + if (index.Indexer is not null) { _instructions.EmitCall(index.Indexer.GetSetMethod(nonPublic: true)!); } @@ -650,7 +650,7 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { var member = (MemberExpression)node.Left; Expression? expr = member.Expression; - if (expr != null) + if (expr is not null) { EmitThisForMethodCall(expr); } @@ -688,7 +688,7 @@ private void CompileMemberAssignment(bool asVoid, MemberInfo refMember, Expressi { // other types inherited from MemberInfo (EventInfo\MethodBase\Type) cannot be used in MemberAssignment var fi = (FieldInfo)refMember; - Debug.Assert(fi != null); + Debug.Assert(fi is not null); if (fi.IsLiteral) { throw Error.NotSupported(); @@ -753,7 +753,7 @@ private void CompileBinaryExpression(Expression expr) { var node = (BinaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { if (node.IsLifted) { @@ -778,9 +778,9 @@ private void CompileBinaryExpression(Expression expr) case ExpressionType.Equal: case ExpressionType.NotEqual: /* generating (equal/not equal): - * if (left == null) { - * right == null/right != null - * }else if (right == null) { + * if (left is null) { + * right is null/right is not null + * }else if (right is null) { * False/True * }else{ * op_Equality(left, right)/op_Inequality(left, right) @@ -969,7 +969,7 @@ private static bool IsNullComparison(Expression left, Expression right) private static bool IsNullConstant(Expression e) { var c = e as ConstantExpression; - return c != null && c.Value == null; + return c is not null && c.Value is null; } #endif private void CompileEqual(Expression left, Expression right, bool liftedToNull) @@ -1033,7 +1033,7 @@ private void CompileArithmetic(ExpressionType nodeType, Expression left, Express private void CompileConvertUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { BranchLabel end = _instructions.MakeLabel(); BranchLabel loadDefault = _instructions.MakeLabel(); @@ -1079,7 +1079,7 @@ private void CompileConvertUnaryExpression(Expression expr) _instructions.Emit(NullableMethodCallInstruction.CreateGetValue()); } - if (updater == null) + if (updater is null) { _instructions.EmitCall(method); } @@ -1225,7 +1225,7 @@ private void CompileUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { EmitUnaryMethodCall(node); } @@ -1331,7 +1331,7 @@ private void CompileOrElseBinaryExpression(Expression expr) private void CompileLogicalBinaryExpression(BinaryExpression b, bool andAlso) { - if (b.Method != null && !b.IsLiftedLogical) + if (b.Method is not null && !b.IsLiftedLogical) { CompileMethodLogicalBinaryExpression(b, andAlso); } @@ -1356,7 +1356,7 @@ private void CompileMethodLogicalBinaryExpression(BinaryExpression expr, bool an _instructions.EmitDup(); MethodInfo? opTrue = TypeUtils.GetBooleanOperator(expr.Method!.DeclaringType!, andAlso ? "op_False" : "op_True"); - Debug.Assert(opTrue != null, "factory should check that the method exists"); + Debug.Assert(opTrue is not null, "factory should check that the method exists"); _instructions.EmitCall(opTrue); _instructions.EmitBranchTrue(labEnd); @@ -1536,7 +1536,7 @@ private void CompileSwitchExpression(Expression expr) CompileAsVoid(node.SwitchValue); // Now if there is a default body, it happens unconditionally. - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { Compile(node.DefaultBody); } @@ -1551,7 +1551,7 @@ private void CompileSwitchExpression(Expression expr) TypeCode switchType = node.SwitchValue.Type.GetTypeCode(); - if (node.Comparison == null) + if (node.Comparison is null) { switch (switchType) { @@ -1582,7 +1582,7 @@ private void CompileSwitchExpression(Expression expr) { // If we have a comparison other than string equality, bail MethodInfo? equality = String_op_Equality_String_String; - if (equality != null && !equality.IsStatic) + if (equality is not null && !equality.IsStatic) { equality = null; } @@ -1634,7 +1634,7 @@ private void CompileIntSwitchExpression(SwitchExpression node) where T : notn int switchIndex = _instructions.Count; _instructions.EmitIntSwitch(caseDict); - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { Compile(node.DefaultBody, !hasValue); } @@ -1678,7 +1678,7 @@ private void CompileStringSwitchExpression(SwitchExpression node) var nullCase = new StrongBox(1); _instructions.EmitStringSwitch(caseDict, nullCase); - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { Compile(node.DefaultBody, !hasValue); } @@ -1696,7 +1696,7 @@ private void CompileStringSwitchExpression(SwitchExpression node) foreach (ConstantExpression testValue in switchCase.TestValues) { var key = (string?)testValue.Value; - if (key == null) + if (key is null) { if (nullCase.Value == 1) { @@ -1734,21 +1734,21 @@ private void CompileLabelExpression(Expression expr) _labelBlock.TryGetLabelInfo(node.Target, out label); // We're in a block but didn't find our label, try switch - if (label == null && _labelBlock.Parent!.Kind == LabelScopeKind.Switch) + if (label is null && _labelBlock.Parent!.Kind == LabelScopeKind.Switch) { _labelBlock.Parent.TryGetLabelInfo(node.Target, out label); } // if we're in a switch or block, we should've found the label - Debug.Assert(label != null); + Debug.Assert(label is not null); } - if (label == null) + if (label is null) { label = DefineLabel(node.Target); } - if (node.DefaultValue != null) + if (node.DefaultValue is not null) { if (node.Target.Type == typeof(void)) { @@ -1768,14 +1768,14 @@ private void CompileGotoExpression(Expression expr) var node = (GotoExpression)expr; LabelInfo labelInfo = ReferenceLabel(node.Target); - if (node.Value != null) + if (node.Value is not null) { Compile(node.Value); } _instructions.EmitGoto(labelInfo.GetLabel(this), node.Type != typeof(void), - node.Value != null && node.Value.Type != typeof(void), + node.Value is not null && node.Value.Type != typeof(void), node.Target.Type != typeof(void)); } @@ -1786,7 +1786,7 @@ private void PushLabelBlock(LabelScopeKind type) private void PopLabelBlock(LabelScopeKind kind) { - Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind); + Debug.Assert(_labelBlock is not null && _labelBlock.Kind == kind); _labelBlock = _labelBlock.Parent!; } @@ -1808,7 +1808,7 @@ private LabelInfo ReferenceLabel(LabelTarget node) private LabelInfo DefineLabel(LabelTarget? node) { - if (node == null) + if (node is null) { return new LabelInfo(null); } @@ -1896,7 +1896,7 @@ private bool TryPushLabelBlock(Expression node) private void DefineBlockLabels(Expression? node) { var block = node as BlockExpression; - if (block == null) + if (block is null) { return; } @@ -1906,7 +1906,7 @@ private void DefineBlockLabels(Expression? node) Expression e = block.Expressions[i]; var label = e as LabelExpression; - if (label != null) + if (label is not null) { DefineLabel(label.Target); } @@ -1916,7 +1916,7 @@ private void DefineBlockLabels(Expression? node) private void CheckRethrow() { // Rethrow is only valid inside a catch. - for (LabelScopeInfo? j = _labelBlock; j != null; j = j.Parent) + for (LabelScopeInfo? j = _labelBlock; j is not null; j = j.Parent) { if (j.Kind == LabelScopeKind.Catch) { @@ -1935,7 +1935,7 @@ private void CompileThrowUnaryExpression(Expression expr, bool asVoid) { var node = (UnaryExpression)expr; - if (node.Operand == null) + if (node.Operand is null) { CheckRethrow(); @@ -1966,7 +1966,7 @@ private void CompileThrowUnaryExpression(Expression expr, bool asVoid) private void CompileTryExpression(Expression expr) { var node = (TryExpression)expr; - if (node.Fault != null) + if (node.Fault is not null) { CompileTryFaultExpression(node); } @@ -1977,7 +1977,7 @@ private void CompileTryExpression(Expression expr) int tryStart = _instructions.Count; BranchLabel? startOfFinally = null; - if (node.Finally != null) + if (node.Finally is not null) { startOfFinally = _instructions.MakeLabel(); _instructions.EmitEnterTryFinally(startOfFinally); @@ -1989,7 +1989,7 @@ private void CompileTryExpression(Expression expr) List? exHandlers = null; var enterTryInstr = _instructions.GetInstruction(tryStart) as EnterTryCatchFinallyInstruction; - Debug.Assert(enterTryInstr != null); + Debug.Assert(enterTryInstr is not null); PushLabelBlock(LabelScopeKind.Try); bool hasValue = node.Type != typeof(void); @@ -2015,7 +2015,7 @@ private void CompileTryExpression(Expression expr) ExceptionFilter? filter = null; - if (handler.Filter != null) + if (handler.Filter is not null) { PushLabelBlock(LabelScopeKind.Filter); @@ -2068,9 +2068,9 @@ private void CompileTryExpression(Expression expr) } } - if (node.Finally != null) + if (node.Finally is not null) { - Debug.Assert(startOfFinally != null); + Debug.Assert(startOfFinally is not null); PushLabelBlock(LabelScopeKind.Finally); _instructions.MarkLabel(startOfFinally); @@ -2086,7 +2086,7 @@ private void CompileTryExpression(Expression expr) } else { - Debug.Assert(exHandlers != null); + Debug.Assert(exHandlers is not null); enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, exHandlers.ToArray())); } @@ -2099,7 +2099,7 @@ private void CompileTryExpression(Expression expr) private void CompileTryFaultExpression(TryExpression expr) { - Debug.Assert(expr.Finally == null); + Debug.Assert(expr.Finally is null); Debug.Assert(expr.Handlers.Count == 0); // Mark where we begin. @@ -2147,7 +2147,7 @@ private void CompileMethodCallExpression(Expression @object, MethodInfo method, if (!method.IsStatic) { ByRefUpdater? updater = CompileAddress(@object, -1); - if (updater != null) + if (updater is not null) { updaters = new List() { updater }; } @@ -2164,9 +2164,9 @@ private void CompileMethodCallExpression(Expression @object, MethodInfo method, if (parameters[i].ParameterType.IsByRef) { ByRefUpdater? updater = CompileAddress(arg, i); - if (updater != null) + if (updater is not null) { - if (updaters == null) + if (updaters is null) { updaters = new List(); } @@ -2189,7 +2189,7 @@ private void CompileMethodCallExpression(Expression @object, MethodInfo method, } else { - if (updaters == null) + if (updaters is null) { _instructions.EmitCall(method, parameters); } @@ -2267,10 +2267,10 @@ private static bool ShouldWritebackNode(Expression node) return CompileArrayIndexAddress(array.Left, array.Right, index); case ExpressionType.Index: var indexNode = (IndexExpression)node; - if (/*!TypeUtils.AreEquivalent(type, node.Type) || */indexNode.Indexer != null) + if (/*!TypeUtils.AreEquivalent(type, node.Type) || */indexNode.Indexer is not null) { LocalDefinition? objTmp = null; - if (indexNode.Object != null) + if (indexNode.Object is not null) { objTmp = _locals.DefineLocal(Expression.Parameter(indexNode.Object.Type), _instructions.Count); EmitThisForMethodCall(indexNode.Object); @@ -2308,7 +2308,7 @@ private static bool ShouldWritebackNode(Expression node) var member = (MemberExpression)node; LocalDefinition? memberTemp = null; - if (member.Expression != null) + if (member.Expression is not null) { memberTemp = _locals.DefineLocal(Expression.Parameter(member.Expression.Type, "member"), _instructions.Count); EmitThisForMethodCall(member.Expression); @@ -2317,7 +2317,7 @@ private static bool ShouldWritebackNode(Expression node) } var field = member.Member as FieldInfo; - if (field != null) + if (field is not null) { _instructions.EmitLoadField(field); if (!field.IsLiteral && !field.IsInitOnly) @@ -2389,7 +2389,7 @@ private void CompileNewExpression(Expression expr) { var node = (NewExpression)expr; - if (node.Constructor != null) + if (node.Constructor is not null) { if (node.Constructor.DeclaringType!.IsAbstract) throw Error.NonAbstractConstructorRequired(); @@ -2404,9 +2404,9 @@ private void CompileNewExpression(Expression expr) if (parameters[i].ParameterType.IsByRef) { ByRefUpdater? updater = CompileAddress(arg, i); - if (updater != null) + if (updater is not null) { - if (updaters == null) + if (updaters is null) { updaters = new List(); } @@ -2419,7 +2419,7 @@ private void CompileNewExpression(Expression expr) } } - if (updaters != null) + if (updaters is not null) { _instructions.EmitByRefNew(node.Constructor, parameters, updaters.ToArray()); } @@ -2477,7 +2477,7 @@ private void CompileMember(Expression? from, MemberInfo member, bool forBinding) } else { - if (from != null) + if (from is not null) { EmitThisForMethodCall(from); } @@ -2489,7 +2489,7 @@ private void CompileMember(Expression? from, MemberInfo member, bool forBinding) { // MemberExpression can use either FieldInfo or PropertyInfo - other types derived from MemberInfo are not permitted var pi = (PropertyInfo)member; - if (pi != null) + if (pi is not null) { MethodInfo method = pi.GetGetMethod(nonPublic: true)!; if (forBinding && method.IsStatic) @@ -2497,13 +2497,13 @@ private void CompileMember(Expression? from, MemberInfo member, bool forBinding) throw Error.InvalidProgram(); } - if (from != null) + if (from is not null) { EmitThisForMethodCall(from); } if (!method.IsStatic && - (from != null && from.Type.IsNullableType())) + (from is not null && from.Type.IsNullableType())) { // reflection doesn't let us call methods on Nullable when the value // is null... so we get to special case those methods! @@ -2581,7 +2581,7 @@ private void CompileLambdaExpression(Expression expr) var compiler = new LightCompiler(this); LightDelegateCreator creator = compiler.CompileTop(node); - if (compiler._locals.ClosureVariables != null) + if (compiler._locals.ClosureVariables is not null) { foreach (ParameterExpression variable in compiler._locals.ClosureVariables.Keys) { @@ -2596,7 +2596,7 @@ private void CompileCoalesceBinaryExpression(Expression expr) { var node = (BinaryExpression)expr; - bool hasConversion = node.Conversion != null; + bool hasConversion = node.Conversion is not null; bool hasImplicitConversion = false; if (!hasConversion && node.Left.Type.IsNullableType()) { @@ -2641,7 +2641,7 @@ private void CompileCoalesceBinaryExpression(Expression expr) _instructions.MarkLabel(leftNotNull); - if (node.Conversion != null) + if (node.Conversion is not null) { ParameterExpression temp = Expression.Parameter(node.Left.Type, "temp"); LocalDefinition local = _locals.DefineLocal(temp, _instructions.Count); @@ -2763,9 +2763,9 @@ private void CompileMemberInit(ReadOnlyCollection bindings) private static Type GetMemberType(MemberInfo member) { var fi = member as FieldInfo; - if (fi != null) return fi.FieldType; + if (fi is not null) return fi.FieldType; var pi = member as PropertyInfo; - if (pi != null) return pi.PropertyType; + if (pi is not null) return pi.PropertyType; throw new InvalidOperationException("MemberNotFieldOrProperty"); } @@ -2814,13 +2814,13 @@ protected internal override Expression VisitBlock(BlockExpression node) protected override CatchBlock VisitCatchBlock(CatchBlock node) { - if (node.Variable != null) + if (node.Variable is not null) { PushParameters(new[] { node.Variable }); } Visit(node.Body); Visit(node.Filter); - if (node.Variable != null) + if (node.Variable is not null) { PopParameters(new[] { node.Variable }); } @@ -3198,13 +3198,13 @@ public FieldByRefUpdater(LocalDefinition? obj, FieldInfo field, int argumentInde public override void Update(InterpretedFrame frame, object? value) { - object? obj = _object == null ? null : frame.Data[_object.GetValueOrDefault().Index]; + object? obj = _object is null ? null : frame.Data[_object.GetValueOrDefault().Index]; _field.SetValue(obj, value); } public override void UndefineTemps(InstructionList instructions, LocalVariables locals) { - if (_object != null) + if (_object is not null) { locals.UndefineLocal(_object.GetValueOrDefault(), instructions.Count); } @@ -3225,7 +3225,7 @@ public PropertyByRefUpdater(LocalDefinition? obj, PropertyInfo property, int arg public override void Update(InterpretedFrame frame, object? value) { - object? obj = _object == null ? null : frame.Data[_object.GetValueOrDefault().Index]; + object? obj = _object is null ? null : frame.Data[_object.GetValueOrDefault().Index]; try { @@ -3240,7 +3240,7 @@ public override void Update(InterpretedFrame frame, object? value) public override void UndefineTemps(InstructionList instructions, LocalVariables locals) { - if (_object != null) + if (_object is not null) { locals.UndefineLocal(_object.GetValueOrDefault(), instructions.Count); } @@ -3270,7 +3270,7 @@ public override void Update(InterpretedFrame frame, object? value) } args[args.Length - 1] = value; - object? instance = _obj == null ? null : frame.Data[_obj.GetValueOrDefault().Index]; + object? instance = _obj is null ? null : frame.Data[_obj.GetValueOrDefault().Index]; try { @@ -3285,7 +3285,7 @@ public override void Update(InterpretedFrame frame, object? value) public override void UndefineTemps(InstructionList instructions, LocalVariables locals) { - if (_obj != null) + if (_obj is not null) { locals.UndefineLocal(_obj.GetValueOrDefault(), instructions.Count); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightDelegateCreator.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightDelegateCreator.cs index eb99a0007c5f23..b2277a103c7646 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightDelegateCreator.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightDelegateCreator.cs @@ -15,8 +15,8 @@ internal sealed class LightDelegateCreator internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda) { - Debug.Assert(interpreter != null); - Debug.Assert(lambda != null); + Debug.Assert(interpreter is not null); + Debug.Assert(lambda is not null); Interpreter = interpreter; _lambda = lambda; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs index 770bc872d1ef3b..c7b72ca1b26607 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs @@ -75,7 +75,7 @@ private void Analyze() AddHandlerExit(catchHandler.HandlerEndIndex); ExceptionFilter? filter = catchHandler.Filter; - if (filter != null) + if (filter is not null) { _handlerEnter.Add(filter.StartIndex - 1 /* include EnterExceptionFilter instruction */, "filter"); AddHandlerExit(filter.EndIndex); @@ -366,7 +366,7 @@ internal Delegate MakeDelegate(Type delegateType) } #else Func fastCtor = GetRunDelegateCtor(delegateType); - if (fastCtor != null) + if (fastCtor is not null) { return fastCtor(this); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalAccess.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalAccess.cs index 8cc0bf98ee0f04..1365b62668675c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalAccess.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalAccess.cs @@ -25,7 +25,7 @@ protected LocalAccessInstruction(int index) public override string ToDebugString(int instructionIndex, object? cookie, Func labelIndexer, IReadOnlyList? objects) { - return cookie == null ? + return cookie is null ? InstructionName + "(" + _index + ")" : InstructionName + "(" + cookie + ": " + _index + ")"; } @@ -225,7 +225,7 @@ internal sealed class ValueTypeCopyInstruction : Instruction public override int Run(InterpretedFrame frame) { object? o = frame.Pop(); - frame.Push(o == null ? o : RuntimeHelpers.GetObjectValue(o)); + frame.Push(o is null ? o : RuntimeHelpers.GetObjectValue(o)); return 1; } } @@ -269,7 +269,7 @@ internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstr internal ImmutableValue(int index, object defaultValue) : base(index) { - Debug.Assert(defaultValue != null); + Debug.Assert(defaultValue is not null); _defaultValue = defaultValue; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs index 60c4a4c4c54aea..8ec7f4085b84da 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs @@ -70,7 +70,7 @@ public override bool Equals(object? obj) public override int GetHashCode() { - if (Parameter == null) + if (Parameter is null) { return 0; } @@ -94,7 +94,7 @@ public LocalDefinition DefineLocal(ParameterExpression variable, int start) if (_variables.TryGetValue(variable, out existing)) { newScope = new VariableScope(result, start, existing); - if (existing.ChildScopes == null) + if (existing.ChildScopes is null) { existing.ChildScopes = new List(); } @@ -113,7 +113,7 @@ public void UndefineLocal(LocalDefinition definition, int end) { VariableScope scope = _variables[definition.Parameter]; scope.Stop = end; - if (scope.Parent != null) + if (scope.Parent is not null) { _variables[definition.Parameter] = scope.Parent; } @@ -136,7 +136,7 @@ internal void Box(ParameterExpression variable, InstructionList instructions) int curChild = 0; for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++) { - if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i) + if (scope.ChildScopes is not null && scope.ChildScopes[curChild].Start == i) { // skip boxing in the child scope VariableScope child = scope.ChildScopes[curChild]; @@ -159,7 +159,7 @@ public bool TryGetLocalOrClosure(ParameterExpression var, [NotNullWhen(true)] ou local = scope.Variable; return true; } - if (_closureVariables != null && _closureVariables.TryGetValue(var, out local)) + if (_closureVariables is not null && _closureVariables.TryGetValue(var, out local)) { return true; } @@ -175,7 +175,7 @@ public bool TryGetLocalOrClosure(ParameterExpression var, [NotNullWhen(true)] ou internal LocalVariable AddClosureVariable(ParameterExpression variable) { - if (_closureVariables == null) + if (_closureVariables is null) { _closureVariables = new Dictionary(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ModuloInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ModuloInstruction.cs index 669d9db2cd1f42..07938adafc1304 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ModuloInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ModuloInstruction.cs @@ -23,10 +23,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left % (short)right)); + stack[index - 2] = right is null ? null : (object)unchecked((short)((short)left % (short)right)); } frame.StackIndex = index - 1; @@ -41,10 +41,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject((int)left % (int)right); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject((int)left % (int)right); } frame.StackIndex = index - 1; @@ -59,10 +59,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((long)left % (long)right); + stack[index - 2] = right is null ? null : (object)((long)left % (long)right); } frame.StackIndex = index - 1; @@ -77,10 +77,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left % (ushort)right)); + stack[index - 2] = right is null ? null : (object)unchecked((ushort)((ushort)left % (ushort)right)); } frame.StackIndex = index - 1; @@ -95,10 +95,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((uint)left % (uint)right); + stack[index - 2] = right is null ? null : (object)((uint)left % (uint)right); } frame.StackIndex = index - 1; @@ -113,10 +113,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((ulong)left % (ulong)right); + stack[index - 2] = right is null ? null : (object)((ulong)left % (ulong)right); } frame.StackIndex = index - 1; @@ -131,10 +131,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((float)left % (float)right); + stack[index - 2] = right is null ? null : (object)((float)left % (float)right); } frame.StackIndex = index - 1; @@ -149,10 +149,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((double)left % (double)right); + stack[index - 2] = right is null ? null : (object)((double)left % (double)right); } frame.StackIndex = index - 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/MulInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/MulInstruction.cs index d872d3a5e5e110..d096ebf09a69b4 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/MulInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/MulInstruction.cs @@ -23,10 +23,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left * (short)right)); + stack[index - 2] = right is null ? null : (object)unchecked((short)((short)left * (short)right)); } frame.StackIndex = index - 1; @@ -41,10 +41,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left * (int)right)); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left * (int)right)); } frame.StackIndex = index - 1; @@ -59,10 +59,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((long)left * (long)right); + stack[index - 2] = right is null ? null : (object)unchecked((long)left * (long)right); } frame.StackIndex = index - 1; @@ -77,10 +77,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left * (ushort)right)); + stack[index - 2] = right is null ? null : (object)unchecked((ushort)((ushort)left * (ushort)right)); } frame.StackIndex = index - 1; @@ -95,10 +95,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((uint)left * (uint)right); + stack[index - 2] = right is null ? null : (object)unchecked((uint)left * (uint)right); } frame.StackIndex = index - 1; @@ -113,10 +113,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ulong)left * (ulong)right); + stack[index - 2] = right is null ? null : (object)unchecked((ulong)left * (ulong)right); } frame.StackIndex = index - 1; @@ -131,10 +131,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((float)left * (float)right); + stack[index - 2] = right is null ? null : (object)((float)left * (float)right); } frame.StackIndex = index - 1; @@ -149,10 +149,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((double)left * (double)right); + stack[index - 2] = right is null ? null : (object)((double)left * (double)right); } frame.StackIndex = index - 1; @@ -196,10 +196,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((short)((short)left * (short)right)); + stack[index - 2] = right is null ? null : (object)checked((short)((short)left * (short)right)); } frame.StackIndex = index - 1; @@ -214,10 +214,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left * (int)right)); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left * (int)right)); } frame.StackIndex = index - 1; @@ -232,10 +232,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((long)left * (long)right); + stack[index - 2] = right is null ? null : (object)checked((long)left * (long)right); } frame.StackIndex = index - 1; @@ -250,10 +250,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((ushort)((ushort)left * (ushort)right)); + stack[index - 2] = right is null ? null : (object)checked((ushort)((ushort)left * (ushort)right)); } frame.StackIndex = index - 1; @@ -268,10 +268,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((uint)left * (uint)right); + stack[index - 2] = right is null ? null : (object)checked((uint)left * (uint)right); } frame.StackIndex = index - 1; @@ -286,10 +286,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((ulong)left * (ulong)right); + stack[index - 2] = right is null ? null : (object)checked((ulong)left * (ulong)right); } frame.StackIndex = index - 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NegateInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NegateInstruction.cs index 8a85abd65c390b..c74bdbc5a93d02 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NegateInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NegateInstruction.cs @@ -21,7 +21,7 @@ private sealed class NegateInt16 : NegateInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -38,7 +38,7 @@ private sealed class NegateInt32 : NegateInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -55,7 +55,7 @@ private sealed class NegateInt64 : NegateInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -72,7 +72,7 @@ private sealed class NegateSingle : NegateInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -89,7 +89,7 @@ private sealed class NegateDouble : NegateInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -131,7 +131,7 @@ private sealed class NegateCheckedInt32 : NegateCheckedInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -148,7 +148,7 @@ private sealed class NegateCheckedInt16 : NegateCheckedInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } @@ -165,7 +165,7 @@ private sealed class NegateCheckedInt64 : NegateCheckedInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotEqualInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotEqualInstruction.cs index a77e770817a22d..9c603fb8148df7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotEqualInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotEqualInstruction.cs @@ -24,11 +24,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -46,11 +46,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -68,11 +68,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -90,11 +90,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -112,11 +112,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -134,11 +134,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -156,11 +156,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -178,11 +178,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -200,11 +200,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -222,11 +222,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -244,11 +244,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -266,11 +266,11 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - frame.Push(right != null); + frame.Push(right is not null); } - else if (right == null) + else if (right is null) { frame.Push(true); } @@ -297,7 +297,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -315,7 +315,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -333,7 +333,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -351,7 +351,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -369,7 +369,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -387,7 +387,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -405,7 +405,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -423,7 +423,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -441,7 +441,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -459,7 +459,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } @@ -477,7 +477,7 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotInstruction.cs index 75632c9c4e7105..5d692f4351700b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NotInstruction.cs @@ -20,7 +20,7 @@ private sealed class NotBoolean : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -37,7 +37,7 @@ private sealed class NotInt64 : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -54,7 +54,7 @@ private sealed class NotInt32 : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -71,7 +71,7 @@ private sealed class NotInt16 : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -88,7 +88,7 @@ private sealed class NotUInt64 : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -105,7 +105,7 @@ private sealed class NotUInt32 : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -122,7 +122,7 @@ private sealed class NotUInt16 : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -139,7 +139,7 @@ private sealed class NotByte : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } @@ -156,7 +156,7 @@ private sealed class NotSByte : NotInstruction public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value == null) + if (value is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NumericConvertInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NumericConvertInstruction.cs index e7814cefcee9e6..0c8e7e1b0228c6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NumericConvertInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/NumericConvertInstruction.cs @@ -21,7 +21,7 @@ public sealed override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); object? converted; - if (obj == null) + if (obj is null) { if (_isLiftedToNull) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/OrInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/OrInstruction.cs index a50b065faed651..02d9ca493e5668 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/OrInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/OrInstruction.cs @@ -21,7 +21,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -37,7 +37,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -53,7 +53,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -69,7 +69,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -85,7 +85,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -101,7 +101,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -117,7 +117,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -133,7 +133,7 @@ public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); - if (left == null || right == null) + if (left is null || right is null) { frame.Push(null); return 1; @@ -149,9 +149,9 @@ public override int Run(InterpretedFrame frame) { object? right = frame.Pop(); object? left = frame.Pop(); - if (left == null) + if (left is null) { - if (right == null) + if (right is null) { frame.Push(null); } @@ -162,7 +162,7 @@ public override int Run(InterpretedFrame frame) return 1; } - if (right == null) + if (right is null) { frame.Push((bool)left ? Utils.BoxedTrue : null); return 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/RightShiftInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/RightShiftInstruction.cs index 0c52669042f6eb..0ab34c59eeae55 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/RightShiftInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/RightShiftInstruction.cs @@ -21,7 +21,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -39,7 +39,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -57,7 +57,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -75,7 +75,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -93,7 +93,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -111,7 +111,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -129,7 +129,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } @@ -147,7 +147,7 @@ public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); - if (value == null || shift == null) + if (value is null || shift is null) { frame.Push(null); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/SubInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/SubInstruction.cs index 70fb95dc02b2c0..cdc42f54297196 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/SubInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/SubInstruction.cs @@ -23,10 +23,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left - (short)right)); + stack[index - 2] = right is null ? null : (object)unchecked((short)((short)left - (short)right)); } frame.StackIndex = index - 1; @@ -41,10 +41,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left - (int)right)); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left - (int)right)); } frame.StackIndex = index - 1; @@ -59,10 +59,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((long)left - (long)right); + stack[index - 2] = right is null ? null : (object)unchecked((long)left - (long)right); } frame.StackIndex = index - 1; @@ -77,10 +77,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left - (ushort)right)); + stack[index - 2] = right is null ? null : (object)unchecked((ushort)((ushort)left - (ushort)right)); } frame.StackIndex = index - 1; @@ -95,10 +95,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((uint)left - (uint)right); + stack[index - 2] = right is null ? null : (object)unchecked((uint)left - (uint)right); } frame.StackIndex = index - 1; @@ -113,10 +113,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)unchecked((ulong)left - (ulong)right); + stack[index - 2] = right is null ? null : (object)unchecked((ulong)left - (ulong)right); } frame.StackIndex = index - 1; @@ -131,10 +131,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((float)left - (float)right); + stack[index - 2] = right is null ? null : (object)((float)left - (float)right); } frame.StackIndex = index - 1; @@ -149,10 +149,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)((double)left - (double)right); + stack[index - 2] = right is null ? null : (object)((double)left - (double)right); } frame.StackIndex = index - 1; @@ -195,10 +195,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((short)((short)left - (short)right)); + stack[index - 2] = right is null ? null : (object)checked((short)((short)left - (short)right)); } frame.StackIndex = index - 1; @@ -213,10 +213,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left - (int)right)); + stack[index - 2] = right is null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left - (int)right)); } frame.StackIndex = index - 1; @@ -231,10 +231,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((long)left - (long)right); + stack[index - 2] = right is null ? null : (object)checked((long)left - (long)right); } frame.StackIndex = index - 1; @@ -249,10 +249,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((ushort)((ushort)left - (ushort)right)); + stack[index - 2] = right is null ? null : (object)checked((ushort)((ushort)left - (ushort)right)); } frame.StackIndex = index - 1; @@ -267,10 +267,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((uint)left - (uint)right); + stack[index - 2] = right is null ? null : (object)checked((uint)left - (uint)right); } frame.StackIndex = index - 1; @@ -285,10 +285,10 @@ public override int Run(InterpretedFrame frame) int index = frame.StackIndex; object?[] stack = frame.Data; object? left = stack[index - 2]; - if (left != null) + if (left is not null) { object? right = stack[index - 1]; - stack[index - 2] = right == null ? null : (object)checked((ulong)left - (ulong)right); + stack[index - 2] = right is null ? null : (object)checked((ulong)left - (ulong)right); } frame.StackIndex = index - 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/TypeOperations.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/TypeOperations.cs index 96c851e9becf93..2de7b8fc426dde 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/TypeOperations.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/TypeOperations.cs @@ -124,7 +124,7 @@ private sealed class HasValue : NullableMethodCallInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - frame.Push(obj != null); + frame.Push(obj is not null); return 1; } } @@ -133,7 +133,7 @@ private sealed class GetValue : NullableMethodCallInstruction { public override int Run(InterpretedFrame frame) { - if (frame.Peek() == null) + if (frame.Peek() is null) { // Trigger InvalidOperationException with same localized method as if we'd called the Value getter. return (int)default(int?)!; @@ -154,7 +154,7 @@ public GetValueOrDefault(MethodInfo mi) public override int Run(InterpretedFrame frame) { - if (frame.Peek() == null) + if (frame.Peek() is null) { frame.Pop(); frame.Push(Activator.CreateInstance(_defaultValueType)); @@ -184,11 +184,11 @@ public override int Run(InterpretedFrame frame) { object? other = frame.Pop(); object? obj = frame.Pop(); - if (obj == null) + if (obj is null) { - frame.Push(other == null); + frame.Push(other is null); } - else if (other == null) + else if (other is null) { frame.Push(Utils.BoxedFalse); } @@ -205,7 +205,7 @@ private sealed class ToStringClass : NullableMethodCallInstruction public override int Run(InterpretedFrame frame) { object? obj = frame.Pop(); - frame.Push(obj == null ? "" : obj.ToString()); + frame.Push(obj is null ? "" : obj.ToString()); return 1; } } @@ -292,7 +292,7 @@ protected CastInstructionNoT(Type t) public override int Run(InterpretedFrame frame) { object? value = frame.Pop(); - if (value != null) + if (value is not null) { Type valueType = value.GetType(); @@ -390,7 +390,7 @@ public override int Run(InterpretedFrame frame) TypeCode.Empty, TypeCode.Int32, TypeCode.SByte, TypeCode.Int16, TypeCode.Int64, TypeCode.UInt32, TypeCode.Byte, TypeCode.UInt16, TypeCode.UInt64, TypeCode.Char, TypeCode.Boolean }.Contains(Convert.GetTypeCode(from))); - frame.Push(from == null ? null : Enum.ToObject(_t, from)); + frame.Push(from is null ? null : Enum.ToObject(_t, from)); return 1; } } @@ -408,7 +408,7 @@ public CastReferenceToEnumInstruction(Type t) public override int Run(InterpretedFrame frame) { object? from = frame.Pop(); - Debug.Assert(from != null); + Debug.Assert(from is not null); // If from is neither a T nor a type assignable to T (viz. an T-backed enum) // this will cause an InvalidCastException, which is what this operation should @@ -474,7 +474,7 @@ public QuoteInstruction(Expression operand, Dictionary { node.Variable }); } Expression? b = Visit(node.Body); Expression? f = Visit(node.Filter); - if (node.Variable != null) + if (node.Variable is not null) { _shadowedVars.Pop(); } @@ -575,7 +575,7 @@ protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExp for (int i = 0; i < indexes.Length; i++) { IStrongBox? box = GetBox(node.Variables[i]); - if (box == null) + if (box is null) { indexes[i] = vars.Count; vars.Add(node.Variables[i]); @@ -617,7 +617,7 @@ private static IRuntimeVariables MergeRuntimeVariables(IRuntimeVariables first, protected internal override Expression VisitParameter(ParameterExpression node) { IStrongBox? box = GetBox(node); - if (box == null) + if (box is null) { return node; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Utilities.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Utilities.cs index 7b757e955d2322..3238e55842dcab 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Utilities.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/Utilities.cs @@ -17,7 +17,7 @@ internal static partial class DelegateHelpers internal static Type MakeDelegate(Type[] types) { - Debug.Assert(types != null && types.Length > 0); + Debug.Assert(types is not null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> @@ -175,13 +175,13 @@ internal class HybridReferenceDictionary where TKey : class public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { return _dict.TryGetValue(key, out value); } - else if (_keysAndValues != null) + else if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { @@ -198,13 +198,13 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) public void Remove(TKey key) { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { _dict.Remove(key); } - else if (_keysAndValues != null) + else if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { @@ -219,15 +219,15 @@ public void Remove(TKey key) public bool ContainsKey(TKey key) { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { return _dict.ContainsKey(key); } KeyValuePair[]? keysAndValues = _keysAndValues; - if (keysAndValues != null) + if (keysAndValues is not null) { for (int i = 0; i < keysAndValues.Length; i++) { @@ -243,7 +243,7 @@ public bool ContainsKey(TKey key) public IEnumerator> GetEnumerator() { - if (_dict != null) + if (_dict is not null) { return _dict.GetEnumerator(); } @@ -253,11 +253,11 @@ public IEnumerator> GetEnumerator() private IEnumerator> GetEnumeratorWorker() { - if (_keysAndValues != null) + if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { - if (_keysAndValues[i].Key != null) + if (_keysAndValues[i].Key is not null) { yield return _keysAndValues[i]; } @@ -269,7 +269,7 @@ public TValue this[TKey key] { get { - Debug.Assert(key != null); + Debug.Assert(key is not null); TValue res; if (TryGetValue(key, out res)) @@ -281,16 +281,16 @@ public TValue this[TKey key] } set { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { _dict[key] = value; } else { int index; - if (_keysAndValues != null) + if (_keysAndValues is not null) { index = -1; for (int i = 0; i < _keysAndValues.Length; i++) @@ -300,7 +300,7 @@ public TValue this[TKey key] _keysAndValues[i] = new KeyValuePair(key, value); return; } - else if (_keysAndValues[i].Key == null) + else if (_keysAndValues[i].Key is null) { index = i; } @@ -337,7 +337,7 @@ internal static class Assert [Conditional("DEBUG")] public static void NotNull(object var) { - Debug.Assert(var != null); + Debug.Assert(var is not null); } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/InvocationExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/InvocationExpression.cs index a77ff636f8cf29..9a69bfea6fb72b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/InvocationExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/InvocationExpression.cs @@ -55,7 +55,7 @@ internal InvocationExpression(Expression expression, Type returnType) /// This expression if no children changed, or an expression with the updated children. public InvocationExpression Update(Expression expression, IEnumerable? arguments) { - if (expression == Expression && arguments != null) + if (expression == Expression && arguments is not null) { if (ExpressionUtils.SameElements(ref arguments, Arguments)) { @@ -143,8 +143,8 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == _arguments.Count); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == _arguments.Count); return Expression.Invoke(lambda, arguments ?? _arguments); } @@ -171,8 +171,8 @@ public override Expression GetArgument(int index) internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == 0); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == 0); return Expression.Invoke(lambda); } @@ -204,10 +204,10 @@ public override Expression GetArgument(int index) => internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == 1); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == 1); - if (arguments != null) + if (arguments is not null) { return Expression.Invoke(lambda, arguments[0]); } @@ -244,10 +244,10 @@ public override Expression GetArgument(int index) => internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == 2); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == 2); - if (arguments != null) + if (arguments is not null) { return Expression.Invoke(lambda, arguments[0], arguments[1]); } @@ -287,10 +287,10 @@ public override Expression GetArgument(int index) => internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == 3); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == 3); - if (arguments != null) + if (arguments is not null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2]); } @@ -333,10 +333,10 @@ public override Expression GetArgument(int index) => internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == 4); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == 4); - if (arguments != null) + if (arguments is not null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3]); } @@ -382,10 +382,10 @@ public override Expression GetArgument(int index) => internal override InvocationExpression Rewrite(Expression lambda, Expression[]? arguments) { - Debug.Assert(lambda != null); - Debug.Assert(arguments == null || arguments.Length == 5); + Debug.Assert(lambda is not null); + Debug.Assert(arguments is null || arguments.Length == 5); - if (arguments != null) + if (arguments is not null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); } @@ -746,7 +746,7 @@ internal static MethodInfo GetInvokeMethod(Expression expression) if (!expression.Type.IsSubclassOf(typeof(MulticastDelegate))) { Type? exprType = TypeUtils.FindGenericType(typeof(Expression<>), expression.Type); - if (exprType == null) + if (exprType is null) { throw Error.ExpressionTypeNotInvocable(expression.Type, nameof(expression)); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs index 30ccac84af7184..740355d84400dd 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs @@ -141,7 +141,7 @@ public void CompileToMethod(System.Reflection.Emit.MethodBuilder method) ContractUtils.RequiresNotNull(method, nameof(method)); ContractUtils.Requires(method.IsStatic, nameof(method)); var type = method.DeclaringType as System.Reflection.Emit.TypeBuilder; - if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder(); + if (type is null) throw Error.MethodBuilderDoesNotHaveTypeBuilder(); Compiler.LambdaCompiler.Compile(this, method); } @@ -226,14 +226,14 @@ internal Expression(Expression body) // Ensure parameters is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection? pars; - if (parameters == null) + if (parameters is null) { pars = null; } else { pars = parameters as ICollection; - if (pars == null) + if (pars is null) { parameters = pars = parameters.ToReadOnly(); } @@ -276,7 +276,7 @@ internal override LambdaExpression Accept(Compiler.StackSpiller spiller) internal static Expression Create(Expression body, string? name, bool tailCall, IReadOnlyList parameters) { - if (name == null && !tailCall) + if (name is null && !tailCall) { return parameters.Count switch { @@ -309,7 +309,7 @@ public class ExpressionCreator { public static Expression CreateExpressionFunc(Expression body, string? name, bool tailCall, ReadOnlyCollection parameters) { - if (name == null && !tailCall) + if (name is null && !tailCall) { switch (parameters.Count) { @@ -336,7 +336,7 @@ public Expression0(Expression body) internal override int ParameterCount => 0; internal override bool SameParameters(ICollection? parameters) => - parameters == null || parameters.Count == 0; + parameters is null || parameters.Count == 0; internal override ParameterExpression GetParameter(int index) { @@ -347,8 +347,8 @@ internal override ParameterExpression GetParameter(int index) internal override Expression Rewrite(Expression body, ParameterExpression[]? parameters) { - Debug.Assert(body != null); - Debug.Assert(parameters == null || parameters.Length == 0); + Debug.Assert(body is not null); + Debug.Assert(parameters is null || parameters.Length == 0); return Expression.Lambda(body, parameters); } @@ -375,7 +375,7 @@ internal override ParameterExpression GetParameter(int index) => internal override bool SameParameters(ICollection? parameters) { - if (parameters != null && parameters.Count == 1) + if (parameters is not null && parameters.Count == 1) { using (IEnumerator en = parameters.GetEnumerator()) { @@ -391,10 +391,10 @@ internal override bool SameParameters(ICollection? paramete internal override Expression Rewrite(Expression body, ParameterExpression[]? parameters) { - Debug.Assert(body != null); - Debug.Assert(parameters == null || parameters.Length == 1); + Debug.Assert(body is not null); + Debug.Assert(parameters is null || parameters.Length == 1); - if (parameters != null) + if (parameters is not null) { return Expression.Lambda(body, parameters); } @@ -427,7 +427,7 @@ internal override ParameterExpression GetParameter(int index) => internal override bool SameParameters(ICollection? parameters) { - if (parameters != null && parameters.Count == 2) + if (parameters is not null && parameters.Count == 2) { if (_par0 is ReadOnlyCollection alreadyCollection) { @@ -453,10 +453,10 @@ internal override bool SameParameters(ICollection? paramete internal override Expression Rewrite(Expression body, ParameterExpression[]? parameters) { - Debug.Assert(body != null); - Debug.Assert(parameters == null || parameters.Length == 2); + Debug.Assert(body is not null); + Debug.Assert(parameters is null || parameters.Length == 2); - if (parameters != null) + if (parameters is not null) { return Expression.Lambda(body, parameters); } @@ -492,7 +492,7 @@ internal override ParameterExpression GetParameter(int index) => internal override bool SameParameters(ICollection? parameters) { - if (parameters != null && parameters.Count == 3) + if (parameters is not null && parameters.Count == 3) { if (_par0 is ReadOnlyCollection alreadyCollection) { @@ -521,10 +521,10 @@ internal override bool SameParameters(ICollection? paramete internal override Expression Rewrite(Expression body, ParameterExpression[]? parameters) { - Debug.Assert(body != null); - Debug.Assert(parameters == null || parameters.Length == 3); + Debug.Assert(body is not null); + Debug.Assert(parameters is null || parameters.Length == 3); - if (parameters != null) + if (parameters is not null) { return Expression.Lambda(body, parameters); } @@ -554,8 +554,8 @@ internal override bool SameParameters(ICollection? paramete internal override Expression Rewrite(Expression body, ParameterExpression[]? parameters) { - Debug.Assert(body != null); - Debug.Assert(parameters == null || parameters.Length == _parameters.Count); + Debug.Assert(body is not null); + Debug.Assert(parameters is null || parameters.Length == _parameters.Count); return Expression.Lambda(body, Name, TailCall, parameters ?? _parameters); } @@ -587,7 +587,7 @@ internal static LambdaExpression CreateLambda(Type delegateType, Expression body // delegate type Func, LambdaExpression>? fastPath; CacheDict, LambdaExpression>>? factories = s_lambdaFactories; - if (factories == null) + if (factories is null) { s_lambdaFactories = factories = new CacheDict, LambdaExpression>>(50); } @@ -950,7 +950,7 @@ private enum TryGetFuncActionArgsResult private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[]? typeArgs) { - if (typeArgs == null) + if (typeArgs is null) { return TryGetFuncActionArgsResult.ArgumentNull; } @@ -958,7 +958,7 @@ private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[]? t for (int i = 0; i < typeArgs.Length; i++) { Type a = typeArgs[i]; - if (a == null) + if (a is null) { return TryGetFuncActionArgsResult.ArgumentNull; } @@ -996,7 +996,7 @@ public static Type GetFuncType(params Type[]? typeArgs) // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs); - if (result == null) + if (result is null) { throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs)); } @@ -1016,7 +1016,7 @@ public static bool TryGetFuncType(Type[] typeArgs, [NotNullWhen(true)] out Type? { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { - return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null; + return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) is not null; } funcType = null; @@ -1041,7 +1041,7 @@ public static Type GetActionType(params Type[]? typeArgs) // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetActionType(typeArgs); - if (result == null) + if (result is null) { throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs)); } @@ -1060,7 +1060,7 @@ public static bool TryGetActionType(Type[] typeArgs, [NotNullWhen(true)] out Typ { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { - return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null; + return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) is not null; } actionType = null; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs index eddba885dd9c1b..9ccb7cb63f3ebe 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs @@ -83,7 +83,7 @@ public override Expression Reduce() /// This expression if no children changed, or an expression with the updated children. public ListInitExpression Update(NewExpression newExpression, IEnumerable initializers) { - if (newExpression == NewExpression && initializers != null) + if (newExpression == NewExpression && initializers is not null) { if (ExpressionUtils.SameElements(ref initializers!, Initializers)) { @@ -150,7 +150,7 @@ public static ListInitExpression ListInit(NewExpression newExpression, MethodInf /// A that has the property equal to and the property set to the specified value. public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo? addMethod, IEnumerable initializers) { - if (addMethod == null) + if (addMethod is null) { return ListInit(newExpression, initializers); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LoopExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LoopExpression.cs index 3587b940c7ef70..56e197698ca4b1 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LoopExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LoopExpression.cs @@ -23,7 +23,7 @@ internal LoopExpression(Expression body, LabelTarget? @break, LabelTarget? @cont /// Gets the static type of the expression that this represents. /// /// The that represents the static type of the expression. - public sealed override Type Type => BreakLabel == null ? typeof(void) : BreakLabel.Type; + public sealed override Type Type => BreakLabel is null ? typeof(void) : BreakLabel.Type; /// /// Returns the node type of this Expression. Extension nodes should return @@ -107,7 +107,7 @@ public static LoopExpression Loop(Expression body, LabelTarget? @break) public static LoopExpression Loop(Expression body, LabelTarget? @break, LabelTarget? @continue) { ExpressionUtils.RequiresCanRead(body, nameof(body)); - if (@continue != null && @continue.Type != typeof(void)) throw Error.LabelTypeMustBeVoid(nameof(@continue)); + if (@continue is not null && @continue.Type != typeof(void)) throw Error.LabelTypeMustBeVoid(nameof(@continue)); return new LoopExpression(body, @break, @continue); } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs index d3d4d3196067c5..1c55628fa2dd10 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs @@ -85,7 +85,7 @@ public static MemberAssignment Bind(MethodInfo propertyAccessor, Expression expr private static void ValidateSettableFieldOrPropertyMember(MemberInfo member, out Type memberType) { Type? decType = member.DeclaringType; - if (decType == null) + if (decType is null) { throw Error.NotAMemberOfAnyType(member, nameof(member)); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs index 43594d96a74a8a..3e5a22385792dd 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs @@ -32,20 +32,20 @@ internal MemberExpression(Expression? expression) internal static PropertyExpression Make(Expression? expression, PropertyInfo property) { - Debug.Assert(property != null); + Debug.Assert(property is not null); return new PropertyExpression(expression, property); } internal static FieldExpression Make(Expression? expression, FieldInfo field) { - Debug.Assert(field != null); + Debug.Assert(field is not null); return new FieldExpression(expression, field); } internal static MemberExpression Make(Expression? expression, MemberInfo member) { FieldInfo? fi = member as FieldInfo; - return fi == null ? (MemberExpression)Make(expression, (PropertyInfo)member) : Make(expression, fi); + return fi is null ? (MemberExpression)Make(expression, (PropertyInfo)member) : Make(expression, fi); } /// @@ -130,11 +130,11 @@ public static MemberExpression Field(Expression? expression, FieldInfo field) if (field.IsStatic) { - if (expression != null) throw Error.OnlyStaticFieldsHaveNullInstance(nameof(expression)); + if (expression is not null) throw Error.OnlyStaticFieldsHaveNullInstance(nameof(expression)); } else { - if (expression == null) throw Error.OnlyStaticFieldsHaveNullInstance(nameof(field)); + if (expression is null) throw Error.OnlyStaticFieldsHaveNullInstance(nameof(field)); ExpressionUtils.RequiresCanRead(expression, nameof(expression)); if (!TypeUtils.AreReferenceAssignable(field.DeclaringType!, expression.Type)) { @@ -158,7 +158,7 @@ public static MemberExpression Field(Expression expression, string fieldName) // bind to public names first FieldInfo? fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) ?? expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (fi == null) + if (fi is null) { throw Error.InstanceFieldNotDefinedForType(fieldName, expression.Type); } @@ -182,7 +182,7 @@ public static MemberExpression Field(Expression? expression, Type type, string f FieldInfo? fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) ?? type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (fi == null) + if (fi is null) { throw Error.FieldNotDefinedForType(fieldName, type); } @@ -206,7 +206,7 @@ public static MemberExpression Property(Expression expression, string propertyNa // bind to public names first PropertyInfo? pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) ?? expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (pi == null) + if (pi is null) { throw Error.InstancePropertyNotDefinedForType(propertyName, expression.Type, nameof(propertyName)); } @@ -227,7 +227,7 @@ public static MemberExpression Property(Expression? expression, Type type, strin // bind to public names first PropertyInfo? pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) ?? type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (pi == null) + if (pi is null) { throw Error.PropertyNotDefinedForType(propertyName, type, nameof(propertyName)); } @@ -246,11 +246,11 @@ public static MemberExpression Property(Expression? expression, PropertyInfo pro MethodInfo? mi = property.GetGetMethod(nonPublic: true); - if (mi == null) + if (mi is null) { mi = property.GetSetMethod(nonPublic: true); - if (mi == null) + if (mi is null) { throw Error.PropertyDoesNotHaveAccessor(property, nameof(property)); } @@ -266,11 +266,11 @@ public static MemberExpression Property(Expression? expression, PropertyInfo pro if (mi.IsStatic) { - if (expression != null) throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(expression)); + if (expression is not null) throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(expression)); } else { - if (expression == null) throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(property)); + if (expression is null) throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(property)); ExpressionUtils.RequiresCanRead(expression, nameof(expression)); if (!TypeUtils.IsValidInstanceType(property, expression.Type)) { @@ -299,7 +299,7 @@ public static MemberExpression Property(Expression? expression, MethodInfo prope private static PropertyInfo GetProperty(MethodInfo mi, string? paramName, int index = -1) { Type? type = mi.DeclaringType; - if (type != null) + if (type is not null) { BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic; flags |= (mi.IsStatic) ? BindingFlags.Static : BindingFlags.Instance; @@ -350,16 +350,16 @@ public static MemberExpression PropertyOrField(Expression expression, string pro ExpressionUtils.RequiresCanRead(expression, nameof(expression)); // bind to public names first PropertyInfo? pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (pi != null) + if (pi is not null) return Property(expression, pi); FieldInfo? fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (fi != null) + if (fi is not null) return Field(expression, fi); pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (pi != null) + if (pi is not null) return Property(expression, pi); fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); - if (fi != null) + if (fi is not null) return Field(expression, fi); throw Error.NotAMemberOfType(propertyOrFieldName, expression.Type, nameof(propertyOrFieldName)); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs index 9785b5d2844cbd..ab879b45d3c62c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs @@ -121,7 +121,7 @@ internal static Expression ReduceMemberBinding(ParameterExpression objVar, Membe /// This expression if no children changed, or an expression with the updated children. public MemberInitExpression Update(NewExpression newExpression, IEnumerable bindings) { - if (newExpression == NewExpression && bindings != null) + if (newExpression == NewExpression && bindings is not null) { if (ExpressionUtils.SameElements(ref bindings!, Bindings)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs index 0ba41cd6f55c3e..2cd56c8f39d17e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs @@ -37,7 +37,7 @@ internal MemberListBinding(MemberInfo member, ReadOnlyCollection in /// This expression if no children changed, or an expression with the updated children. public MemberListBinding Update(IEnumerable initializers) { - if (initializers != null) + if (initializers is not null) { if (ExpressionUtils.SameElements(ref initializers!, Initializers)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs index 49574c0b32077e..767d1b73a9a0a2 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs @@ -40,7 +40,7 @@ internal MemberMemberBinding(MemberInfo member, ReadOnlyCollectionThis expression if no children changed, or an expression with the updated children. public MemberMemberBinding Update(IEnumerable bindings) { - if (bindings != null) + if (bindings is not null) { if (ExpressionUtils.SameElements(ref bindings!, Bindings)) { @@ -120,7 +120,7 @@ public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, IEnume private static void ValidateGettableFieldOrPropertyMember(MemberInfo member, out Type memberType) { Type? decType = member.DeclaringType; - if (decType == null) + if (decType is null) { throw Error.NotAMemberOfAnyType(member, nameof(member)); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs index 9217c5efbf98cf..5ad4826c3d3daa 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs @@ -66,14 +66,14 @@ public MethodCallExpression Update(Expression @object, IEnumerable? // Ensure arguments is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection? args; - if (arguments == null) + if (arguments is null) { args = null; } else { args = arguments as ICollection; - if (args == null) + if (args is null) { arguments = args = arguments.ToReadOnly(); } @@ -156,7 +156,7 @@ internal class InstanceMethodCallExpression : MethodCallExpression, IArgumentPro public InstanceMethodCallExpression(MethodInfo method, Expression instance) : base(method) { - Debug.Assert(instance != null); + Debug.Assert(instance is not null); _instance = instance; } @@ -188,8 +188,8 @@ internal override bool SameArguments(ICollection? arguments) => internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == _arguments.Count); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == _arguments.Count); return Expression.Call(Method, args ?? _arguments); } @@ -219,8 +219,8 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression instance, IReadOnlyList? args) { - Debug.Assert(instance != null); - Debug.Assert(args == null || args.Count == _arguments.Count); + Debug.Assert(instance is not null); + Debug.Assert(args is null || args.Count == _arguments.Count); return Expression.Call(instance, Method, args ?? _arguments); } @@ -246,12 +246,12 @@ internal override ReadOnlyCollection GetOrMakeArguments() } internal override bool SameArguments(ICollection? arguments) => - arguments == null || arguments.Count == 0; + arguments is null || arguments.Count == 0; internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == 0); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == 0); return Expression.Call(Method); } @@ -283,7 +283,7 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 1) + if (arguments is not null && arguments.Count == 1) { using (IEnumerator en = arguments.GetEnumerator()) { @@ -297,10 +297,10 @@ internal override bool SameArguments(ICollection? arguments) internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == 1); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == 1); - if (args != null) + if (args is not null) { return Expression.Call(Method, args[0]); } @@ -335,7 +335,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 2) + if (arguments is not null && arguments.Count == 2) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -363,10 +363,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == 2); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == 2); - if (args != null) + if (args is not null) { return Expression.Call(Method, args[0], args[1]); } @@ -402,7 +402,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 3) + if (arguments is not null && arguments.Count == 3) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -434,10 +434,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == 3); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == 3); - if (args != null) + if (args is not null) { return Expression.Call(Method, args[0], args[1], args[2]); } @@ -475,7 +475,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 4) + if (arguments is not null && arguments.Count == 4) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -511,10 +511,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == 4); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == 4); - if (args != null) + if (args is not null) { return Expression.Call(Method, args[0], args[1], args[2], args[3]); } @@ -554,7 +554,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 5) + if (arguments is not null && arguments.Count == 5) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -594,10 +594,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression? instance, IReadOnlyList? args) { - Debug.Assert(instance == null); - Debug.Assert(args == null || args.Count == 5); + Debug.Assert(instance is null); + Debug.Assert(args is null || args.Count == 5); - if (args != null) + if (args is not null) { return Expression.Call(Method, args[0], args[1], args[2], args[3], args[4]); } @@ -626,12 +626,12 @@ internal override ReadOnlyCollection GetOrMakeArguments() } internal override bool SameArguments(ICollection? arguments) => - arguments == null || arguments.Count == 0; + arguments is null || arguments.Count == 0; internal override MethodCallExpression Rewrite(Expression instance, IReadOnlyList? args) { - Debug.Assert(instance != null); - Debug.Assert(args == null || args.Count == 0); + Debug.Assert(instance is not null); + Debug.Assert(args is null || args.Count == 0); return Expression.Call(instance, Method); } @@ -660,7 +660,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 1) + if (arguments is not null && arguments.Count == 1) { using (IEnumerator en = arguments.GetEnumerator()) { @@ -679,10 +679,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression instance, IReadOnlyList? args) { - Debug.Assert(instance != null); - Debug.Assert(args == null || args.Count == 1); + Debug.Assert(instance is not null); + Debug.Assert(args is null || args.Count == 1); - if (args != null) + if (args is not null) { return Expression.Call(instance, Method, args[0]); } @@ -716,7 +716,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 2) + if (arguments is not null && arguments.Count == 2) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -744,10 +744,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression instance, IReadOnlyList? args) { - Debug.Assert(instance != null); - Debug.Assert(args == null || args.Count == 2); + Debug.Assert(instance is not null); + Debug.Assert(args is null || args.Count == 2); - if (args != null) + if (args is not null) { return Expression.Call(instance, Method, args[0], args[1]); } @@ -783,7 +783,7 @@ public override Expression GetArgument(int index) internal override bool SameArguments(ICollection? arguments) { - if (arguments != null && arguments.Count == 3) + if (arguments is not null && arguments.Count == 3) { if (_arg0 is ReadOnlyCollection alreadyCollection) { @@ -815,10 +815,10 @@ internal override ReadOnlyCollection GetOrMakeArguments() internal override MethodCallExpression Rewrite(Expression instance, IReadOnlyList? args) { - Debug.Assert(instance != null); - Debug.Assert(args == null || args.Count == 3); + Debug.Assert(instance is not null); + Debug.Assert(args is null || args.Count == 3); - if (args != null) + if (args is not null) { return Expression.Call(instance, Method, args[0], args[1], args[2]); } @@ -1017,7 +1017,7 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method) ValidateArgumentCount(method, ExpressionType.Call, 0, pis); - if (instance != null) + if (instance is not null) { return new InstanceMethodCallExpression0(method, instance); } @@ -1057,7 +1057,7 @@ internal static MethodCallExpression Call(Expression? instance, MethodInfo metho arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0], nameof(method), nameof(arg0)); - if (instance != null) + if (instance is not null) { return new InstanceMethodCallExpression1(method, instance, arg0); } @@ -1086,7 +1086,7 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0], nameof(method), nameof(arg0)); arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1], nameof(method), nameof(arg1)); - if (instance != null) + if (instance is not null) { return new InstanceMethodCallExpression2(method, instance, arg0, arg1); } @@ -1118,7 +1118,7 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1], nameof(method), nameof(arg1)); arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2], nameof(method), nameof(arg2)); - if (instance != null) + if (instance is not null) { return new InstanceMethodCallExpression3(method, instance, arg0, arg1, arg2); } @@ -1141,7 +1141,7 @@ public static MethodCallExpression Call(Expression instance, string methodName, { ContractUtils.RequiresNotNull(instance, nameof(instance)); ContractUtils.RequiresNotNull(methodName, nameof(methodName)); - if (arguments == null) + if (arguments is null) { arguments = Array.Empty(); } @@ -1167,7 +1167,7 @@ public static MethodCallExpression Call(Type type, string methodName, Type[]? ty ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(methodName, nameof(methodName)); - if (arguments == null) arguments = Array.Empty(); + if (arguments is null) arguments = Array.Empty(); BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, flags)!, arguments); } @@ -1199,7 +1199,7 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, return Call(instance, method, argumentList[0], argumentList[1], argumentList[2]); } - if (instance == null) + if (instance is null) { switch (argCount) { @@ -1221,7 +1221,7 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, ValidateStaticOrInstanceMethod(instance, method); ValidateArgumentTypes(method, ExpressionType.Call, ref argList, nameof(method)); - if (instance == null) + if (instance is null) { return new MethodCallExpressionN(method, argList); } @@ -1243,11 +1243,11 @@ private static void ValidateStaticOrInstanceMethod(Expression? instance, MethodI { if (method.IsStatic) { - if (instance != null) throw Error.OnlyStaticMethodsHaveNullInstance(); + if (instance is not null) throw Error.OnlyStaticMethodsHaveNullInstance(); } else { - if (instance == null) throw Error.OnlyStaticMethodsHaveNullInstance(); + if (instance is null) throw Error.OnlyStaticMethodsHaveNullInstance(); ExpressionUtils.RequiresCanRead(instance, nameof(instance)); ValidateCallInstanceType(instance.Type, method); } @@ -1297,10 +1297,10 @@ private static bool TryQuote(Type parameterType, ref Expression argument) if (mi.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase)) { MethodInfo? moo = ApplyTypeArgs(mi, typeArgs); - if (moo != null && IsCompatible(moo, args)) + if (moo is not null && IsCompatible(moo, args)) { // favor public over non-public methods - if (method == null || (!method.IsPublic && moo.IsPublic)) + if (method is null || (!method.IsPublic && moo.IsPublic)) { method = moo; count = 1; @@ -1316,7 +1316,7 @@ private static bool TryQuote(Type parameterType, ref Expression argument) if (count == 0) { - if (typeArgs != null && typeArgs.Length > 0) + if (typeArgs is not null && typeArgs.Length > 0) { throw Error.GenericMethodWithArgsDoesNotExistOnType(methodName, type); } @@ -1358,7 +1358,7 @@ private static bool IsCompatible(MethodBase m, Expression[] arguments) private static MethodInfo? ApplyTypeArgs(MethodInfo m, Type[]? typeArgs) { - if (typeArgs == null || typeArgs.Length == 0) + if (typeArgs is null || typeArgs.Length == 0) { if (!m.IsGenericMethodDefinition) return m; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs index e3e3b882d1308e..50b200cc422e6f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs @@ -150,7 +150,7 @@ public static NewArrayExpression NewArrayInit(Type type, IEnumerable { throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type); } - if (newList == null) + if (newList is null) { newList = new Expression[initializerList.Count]; for (int j = 0; j < i; j++) @@ -159,12 +159,12 @@ public static NewArrayExpression NewArrayInit(Type type, IEnumerable } } } - if (newList != null) + if (newList is not null) { newList[i] = expr; } } - if (newList != null) + if (newList is not null) { initializerList = new TrueReadOnlyCollection(newList); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs index 5587834c0b2beb..7ead3277681818 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs @@ -86,7 +86,7 @@ public NewExpression Update(IEnumerable? arguments) return this; } - return Members != null ? New(Constructor!, arguments, Members) : New(Constructor!, arguments); + return Members is not null ? New(Constructor!, arguments, Members) : New(Constructor!, arguments); } } @@ -190,7 +190,7 @@ public static NewExpression New(Type type) if (!type.IsValueType) { ConstructorInfo? ci = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SingleOrDefault(c => c.GetParametersCached().Length == 0); - if (ci == null) + if (ci is null) { throw Error.TypeMissingDefaultConstructor(type, nameof(type)); } @@ -246,7 +246,7 @@ private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCol throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType, nameof(arguments), i); } } - if (newArguments == null && arg != arguments[i]) + if (newArguments is null && arg != arguments[i]) { newArguments = new Expression[arguments.Count]; for (int j = 0; j < i; j++) @@ -254,12 +254,12 @@ private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCol newArguments[j] = arguments[j]; } } - if (newArguments != null) + if (newArguments is not null) { newArguments[i] = arg; } - if (newMembers == null && member != members[i]) + if (newMembers is null && member != members[i]) { newMembers = new MemberInfo[members.Count]; for (int j = 0; j < i; j++) @@ -267,25 +267,25 @@ private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCol newMembers[j] = members[j]; } } - if (newMembers != null) + if (newMembers is not null) { newMembers[i] = member; } } - if (newArguments != null) + if (newArguments is not null) { arguments = new TrueReadOnlyCollection(newArguments); } - if (newMembers != null) + if (newMembers is not null) { members = new TrueReadOnlyCollection(newMembers); } } - else if (arguments != null && arguments.Count > 0) + else if (arguments is not null && arguments.Count > 0) { throw Error.IncorrectNumberOfConstructorArguments(); } - else if (members != null && members.Count > 0) + else if (members is not null && members.Count > 0) { throw Error.IncorrectNumberOfMembersForGivenConstructor(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/RuntimeVariablesExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/RuntimeVariablesExpression.cs index a80fa88d8308ab..fd17b2d85a1df6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/RuntimeVariablesExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/RuntimeVariablesExpression.cs @@ -57,7 +57,7 @@ protected internal override Expression Accept(ExpressionVisitor visitor) /// This expression if no children changed, or an expression with the updated children. public RuntimeVariablesExpression Update(IEnumerable variables) { - if (variables != null) + if (variables is not null) { if (ExpressionUtils.SameElements(ref variables!, Variables)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchCase.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchCase.cs index 3871b4de1bcc6c..bc6933c41c46fe 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchCase.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchCase.cs @@ -49,7 +49,7 @@ public override string ToString() /// This expression if no children changed, or an expression with the updated children. public SwitchCase Update(IEnumerable testValues, Expression body) { - if (body == Body & testValues != null) + if (body == Body & testValues is not null) { if (ExpressionUtils.SameElements(ref testValues!, TestValues)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs index f46c49fb8bf4e6..37f960f8d133b7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs @@ -71,7 +71,7 @@ internal bool IsLifted { if (SwitchValue.Type.IsNullableType()) { - return (Comparison == null) || + return (Comparison is null) || !TypeUtils.AreEquivalent(SwitchValue.Type, Comparison.GetParametersCached()[0].ParameterType.GetNonRefType()); } return false; @@ -89,7 +89,7 @@ internal bool IsLifted /// This expression if no children changed, or an expression with the updated children. public SwitchExpression Update(Expression switchValue, IEnumerable? cases, Expression? defaultBody) { - if (switchValue == SwitchValue && defaultBody == DefaultBody && cases != null) + if (switchValue == SwitchValue && defaultBody == DefaultBody && cases is not null) { if (ExpressionUtils.SameElements(ref cases, Cases)) { @@ -184,17 +184,17 @@ public static SwitchExpression Switch(Type? type, Expression switchValue, Expres // Type of the result. Either provided, or it is type of the branches. Type resultType; - if (type != null) + if (type is not null) resultType = type; else if (caseList.Count != 0) resultType = caseList[0].Body.Type; - else if (defaultBody != null) + else if (defaultBody is not null) resultType = defaultBody.Type; else resultType = typeof(void); - bool customType = type != null; + bool customType = type is not null; - if (comparison != null) + if (comparison is not null) { ValidateMethodInfo(comparison, nameof(comparison)); ParameterInfo[] pms = comparison.GetParametersCached(); @@ -274,7 +274,7 @@ public static SwitchExpression Switch(Type? type, Expression switchValue, Expres comparison = equal.Method; } - if (defaultBody == null) + if (defaultBody is null) { if (resultType != typeof(void)) throw Error.DefaultBodyMustBeSupplied(nameof(defaultBody)); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TryExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TryExpression.cs index 6908ff02d1471e..b01d8037db905f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TryExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TryExpression.cs @@ -158,15 +158,15 @@ public static TryExpression MakeTry(Type? type, Expression body, Expression? @fi ContractUtils.RequiresNotNullItems(@catch, nameof(handlers)); ValidateTryAndCatchHaveSameType(type, body, @catch); - if (fault != null) + if (fault is not null) { - if (@finally != null || @catch.Count > 0) + if (@finally is not null || @catch.Count > 0) { throw Error.FaultCannotHaveCatchOrFinally(nameof(fault)); } ExpressionUtils.RequiresCanRead(fault, nameof(fault)); } - else if (@finally != null) + else if (@finally is not null) { ExpressionUtils.RequiresCanRead(@finally, nameof(@finally)); } @@ -181,9 +181,9 @@ public static TryExpression MakeTry(Type? type, Expression body, Expression? @fi //Validate that the body of the try expression must have the same type as the body of every try block. private static void ValidateTryAndCatchHaveSameType(Type? type, Expression tryBody, ReadOnlyCollection handlers) { - Debug.Assert(tryBody != null); + Debug.Assert(tryBody is not null); // Type unification ... all parts must be reference assignable to "type" - if (type != null) + if (type is not null) { if (type != typeof(void)) { @@ -205,7 +205,7 @@ private static void ValidateTryAndCatchHaveSameType(Type? type, Expression tryBo //The body of every try block must be null or have void type. foreach (CatchBlock cb in handlers) { - Debug.Assert(cb.Body != null); + Debug.Assert(cb.Body is not null); if (cb.Body.Type != typeof(void)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); @@ -218,7 +218,7 @@ private static void ValidateTryAndCatchHaveSameType(Type? type, Expression tryBo type = tryBody.Type; foreach (CatchBlock cb in handlers) { - Debug.Assert(cb.Body != null); + Debug.Assert(cb.Body is not null); if (!TypeUtils.AreEquivalent(cb.Body.Type, type)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs index 2a4ce5e2f763e3..305536a9708740 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs @@ -84,7 +84,7 @@ internal Expression ReduceTypeEqual() // expression is a ByVal parameter. Can safely reevaluate. var parameter = Expression as ParameterExpression; - if (parameter != null && !parameter.IsByRef) + if (parameter is not null && !parameter.IsByRef) { return ByValParameterTypeEqual(parameter); } @@ -139,7 +139,7 @@ private Expression ReduceConstantTypeEqual() { ConstantExpression? ce = Expression as ConstantExpression; //TypeEqual(null, T) always returns false. - if (ce!.Value == null) + if (ce!.Value is null) { return Utils.Constant(value: false); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs index 8c9507bce0d28a..26176c80e92b2b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs @@ -60,7 +60,7 @@ public bool IsLifted } bool operandIsNullable = Operand.Type.IsNullableType(); bool resultIsNullable = this.Type.IsNullableType(); - if (Method != null) + if (Method is not null) { return (operandIsNullable && !TypeUtils.AreEquivalent(Method.GetParametersCached()[0].ParameterType, Operand.Type)) || (resultIsNullable && !TypeUtils.AreEquivalent(Method.ReturnType, this.Type)); @@ -175,7 +175,7 @@ private Expression ReduceVariable() private Expression ReduceMember() { var member = (MemberExpression)Operand; - if (member.Expression == null) + if (member.Expression is null) { //static member, reduce the same as variable return ReduceVariable(); @@ -343,7 +343,7 @@ public static UnaryExpression MakeUnary(ExpressionType unaryType, Expression ope private static UnaryExpression GetUserDefinedUnaryOperatorOrThrow(ExpressionType unaryType, string name, Expression operand) { UnaryExpression? u = GetUserDefinedUnaryOperator(unaryType, name, operand); - if (u != null) + if (u is not null) { ValidateParamswithOperandsOrThrow(u.Method!.GetParametersCached()[0].ParameterType, operand.Type, unaryType, name); return u; @@ -357,7 +357,7 @@ private static UnaryExpression GetUserDefinedUnaryOperatorOrThrow(ExpressionType Type[] types = new Type[] { operandType }; Type nnOperandType = operandType.GetNonNullableType(); MethodInfo? method = nnOperandType.GetAnyStaticMethodValidated(name, types); - if (method != null) + if (method is not null) { return new UnaryExpression(unaryType, operand, method.ReturnType, method); } @@ -366,7 +366,7 @@ private static UnaryExpression GetUserDefinedUnaryOperatorOrThrow(ExpressionType { types[0] = nnOperandType; method = nnOperandType.GetAnyStaticMethodValidated(name, types); - if (method != null && method.ReturnType.IsValueType && !method.ReturnType.IsNullableType()) + if (method is not null && method.ReturnType.IsValueType && !method.ReturnType.IsNullableType()) { return new UnaryExpression(unaryType, operand, method.ReturnType.GetNullableType(), method); } @@ -376,7 +376,7 @@ private static UnaryExpression GetUserDefinedUnaryOperatorOrThrow(ExpressionType private static UnaryExpression GetMethodBasedUnaryOperator(ExpressionType unaryType, Expression operand, MethodInfo method) { - Debug.Assert(method != null); + Debug.Assert(method is not null); ValidateOperator(method); ParameterInfo[] pms = method.GetParametersCached(); if (pms.Length != 1) @@ -400,7 +400,7 @@ private static UnaryExpression GetMethodBasedUnaryOperator(ExpressionType unaryT private static UnaryExpression GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType) { UnaryExpression? u = GetUserDefinedCoercion(coercionType, expression, convertToType); - if (u != null) + if (u is not null) { return u; } @@ -410,7 +410,7 @@ private static UnaryExpression GetUserDefinedCoercionOrThrow(ExpressionType coer private static UnaryExpression? GetUserDefinedCoercion(ExpressionType coercionType, Expression expression, Type convertToType) { MethodInfo? method = TypeUtils.GetUserDefinedCoercionMethod(expression.Type, convertToType); - if (method != null) + if (method is not null) { return new UnaryExpression(coercionType, expression, convertToType, method); } @@ -422,7 +422,7 @@ private static UnaryExpression GetUserDefinedCoercionOrThrow(ExpressionType coer private static UnaryExpression GetMethodBasedCoercionOperator(ExpressionType unaryType, Expression operand, Type convertToType, MethodInfo method) { - Debug.Assert(method != null); + Debug.Assert(method is not null); ValidateOperator(method); ParameterInfo[] pms = method.GetParametersCached(); if (pms.Length != 1) @@ -468,7 +468,7 @@ public static UnaryExpression Negate(Expression expression) public static UnaryExpression Negate(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsArithmetic() && !expression.Type.IsUnsignedInt()) { @@ -503,7 +503,7 @@ public static UnaryExpression UnaryPlus(Expression expression) public static UnaryExpression UnaryPlus(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsArithmetic()) { @@ -537,7 +537,7 @@ public static UnaryExpression NegateChecked(Expression expression) public static UnaryExpression NegateChecked(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsArithmetic() && !expression.Type.IsUnsignedInt()) { @@ -572,14 +572,14 @@ public static UnaryExpression Not(Expression expression) public static UnaryExpression Not(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsIntegerOrBool()) { return new UnaryExpression(ExpressionType.Not, expression, expression.Type, null); } UnaryExpression? u = GetUserDefinedUnaryOperator(ExpressionType.Not, "op_LogicalNot", expression); - if (u != null) + if (u is not null) { return u; } @@ -607,7 +607,7 @@ public static UnaryExpression IsFalse(Expression expression) public static UnaryExpression IsFalse(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsBool()) { @@ -637,7 +637,7 @@ public static UnaryExpression IsTrue(Expression expression) public static UnaryExpression IsTrue(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsBool()) { @@ -667,7 +667,7 @@ public static UnaryExpression OnesComplement(Expression expression) public static UnaryExpression OnesComplement(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsInteger()) { @@ -744,7 +744,7 @@ public static UnaryExpression Convert(Expression expression, Type type, MethodIn ExpressionUtils.RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); TypeUtils.ValidateType(type, nameof(type)); - if (method == null) + if (method is null) { if (expression.Type.HasIdentityPrimitiveOrNullableConversionTo(type) || expression.Type.HasReferenceConversionTo(type)) @@ -784,7 +784,7 @@ public static UnaryExpression ConvertChecked(Expression expression, Type type, M ExpressionUtils.RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); TypeUtils.ValidateType(type, nameof(type)); - if (method == null) + if (method is null) { if (expression.Type.HasIdentityPrimitiveOrNullableConversionTo(type)) { @@ -831,7 +831,7 @@ public static UnaryExpression Quote(Expression expression) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); LambdaExpression? lambda = expression as LambdaExpression; - if (lambda == null) + if (lambda is null) { throw Error.QuotedExpressionMustBeLambda(nameof(expression)); } @@ -878,7 +878,7 @@ public static UnaryExpression Throw(Expression? value, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); TypeUtils.ValidateType(type, nameof(type)); - if (value != null) + if (value is not null) { ExpressionUtils.RequiresCanRead(value, nameof(value)); if (value.Type.IsValueType) throw Error.ArgumentMustNotHaveValueType(nameof(value)); @@ -905,7 +905,7 @@ public static UnaryExpression Increment(Expression expression) public static UnaryExpression Increment(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsArithmetic()) { @@ -935,7 +935,7 @@ public static UnaryExpression Decrement(Expression expression) public static UnaryExpression Decrement(Expression expression, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - if (method == null) + if (method is null) { if (expression.Type.IsArithmetic()) { @@ -1044,7 +1044,7 @@ private static UnaryExpression MakeOpAssignUnary(ExpressionType kind, Expression RequiresCanWrite(expression, nameof(expression)); UnaryExpression result; - if (method == null) + if (method is null) { if (expression.Type.IsArithmetic()) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs index a7c57130bd5a7e..95498a3a6cb803 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs @@ -87,7 +87,7 @@ public static CallSite Create(Type delegateType, CallSiteBinder binder) if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate(); CacheDict>? ctors = s_siteCtors; - if (ctors == null) + if (ctors is null) { // It's okay to just set this, worst case we're just throwing away some data s_siteCtors = ctors = new CacheDict>(100); @@ -128,12 +128,12 @@ public T Update // if this site is set up for match making, then use NoMatch as an Update if (_match) { - Debug.Assert(s_cachedNoMatch != null, "all normal sites should have Update cached once there is an instance."); + Debug.Assert(s_cachedNoMatch is not null, "all normal sites should have Update cached once there is an instance."); return s_cachedNoMatch; } else { - Debug.Assert(s_cachedUpdate != null, "all normal sites should have Update cached once there is an instance."); + Debug.Assert(s_cachedUpdate is not null, "all normal sites should have Update cached once there is an instance."); return s_cachedUpdate; } } @@ -180,7 +180,7 @@ internal CallSite GetMatchmaker() { // check if we have a cached matchmaker and attempt to atomically grab it. var matchmaker = _cachedMatchmaker; - if (matchmaker != null) + if (matchmaker is not null) { matchmaker = Interlocked.Exchange(ref _cachedMatchmaker, null); Debug.Assert(matchmaker?._match != false, "cached site should be set up for matchmaking"); @@ -194,7 +194,7 @@ internal void ReleaseMatchmaker(CallSite matchMaker) // If "Rules" has not been created, this is the first (and likely the only) Update of the site. // 90% sites stay monomorphic and will never need a matchmaker again. // Otherwise store the matchmaker for the future use. - if (Rules != null) + if (Rules is not null) { _cachedMatchmaker = matchMaker; } @@ -223,7 +223,7 @@ private T GetUpdateDelegate() private T GetUpdateDelegate(ref T? addr) { - if (addr == null) + if (addr is null) { // reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes // us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely @@ -239,7 +239,7 @@ private T GetUpdateDelegate(ref T? addr) internal void AddRule(T newRule) { T[]? rules = Rules; - if (rules == null) + if (rules is null) { Rules = new[] { newRule }; return; @@ -316,7 +316,7 @@ internal T MakeUpdateDelegate() noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static); } } - if (method != null) + if (method is not null) { s_cachedNoMatch = (T)(object)noMatchMethod!.MakeGenericMethod(args).CreateDelegate(target); return (T)(object)method.MakeGenericMethod(args).CreateDelegate(target); diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs index 110b6bbef4795b..7aee056adce736 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs @@ -45,7 +45,7 @@ internal static LambdaSignature Instance { get { - if (s_instance == null) + if (s_instance is null) { s_instance = new LambdaSignature(); } @@ -116,7 +116,7 @@ internal T BindCore(CallSite site, object[] args) where T : class // Try to find a precompiled delegate, and return it if found. // T? result = BindDelegate(site, args); - if (result != null) + if (result is not null) { return result; } @@ -130,7 +130,7 @@ internal T BindCore(CallSite site, object[] args) where T : class // // Check the produced rule // - if (binding == null) + if (binding is null) { throw System.Linq.Expressions.Error.NoOrInvalidRuleProduced(); } @@ -210,7 +210,7 @@ private static Expression Stitch(Expression binding, LambdaSignature si internal RuleCache GetRuleCache() where T : class { // make sure we have cache. - if (Cache == null) + if (Cache is null) { Interlocked.CompareExchange(ref Cache, new Dictionary(), null); } @@ -226,7 +226,7 @@ internal RuleCache GetRuleCache() where T : class } RuleCache? result = ruleCache as RuleCache; - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs index db23e46dc13263..5d3624a1da978d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs @@ -44,7 +44,7 @@ public DynamicAttribute() /// public DynamicAttribute(bool[] transformFlags) { - if (transformFlags == null) + if (transformFlags is null) { throw new ArgumentNullException(nameof(transformFlags)); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs index a5192b47f72066..732d3683996843 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs @@ -48,7 +48,7 @@ public ReadOnlyCollectionBuilder(int capacity) /// The collection whose elements to copy to the builder. public ReadOnlyCollectionBuilder(IEnumerable collection) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); if (collection is ICollection c) @@ -223,11 +223,11 @@ public void Clear() /// true if item is found in the ; otherwise, false. public bool Contains(T item) { - if ((object?)item == null) + if ((object?)item is null) { for (int i = 0; i < _size; i++) { - if ((object?)_items[i] == null) + if ((object?)_items[i] is null) { return true; } @@ -384,7 +384,7 @@ void IList.Remove(object? value) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(nameof(array)); @@ -477,12 +477,12 @@ private void EnsureCapacity(int min) private static bool IsCompatibleObject(object? value) { - return ((value is T) || (value == null && default(T) == null)); + return ((value is T) || (value is null && default(T) is null)); } private static void ValidateNullValue(object? value, string argument) { - if (value == null && default(T) != null) + if (value is null && default(T) is not null) { throw Error.InvalidNullValue(typeof(T), argument); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.ExpressionQuoter.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.ExpressionQuoter.cs index 15d904bac4b33d..d651d4af03b2d8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.ExpressionQuoter.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.ExpressionQuoter.cs @@ -25,7 +25,7 @@ public partial class RuntimeOps [return: NotNullIfNotNull("expression")] public static Expression? Quote(Expression? expression, object hoistedLocals, object[] locals) { - Debug.Assert(hoistedLocals != null && locals != null); + Debug.Assert(hoistedLocals is not null && locals is not null); var quoter = new ExpressionQuoter((HoistedLocals)hoistedLocals, locals); return quoter.Visit(expression); } @@ -101,7 +101,7 @@ protected internal override Expression VisitBlock(BlockExpression node) { _shadowedVars.Pop(); } - if (b == null) + if (b is null) { return node; } @@ -110,13 +110,13 @@ protected internal override Expression VisitBlock(BlockExpression node) protected override CatchBlock VisitCatchBlock(CatchBlock node) { - if (node.Variable != null) + if (node.Variable is not null) { _shadowedVars.Push(new HashSet { node.Variable }); } Expression b = Visit(node.Body); Expression? f = Visit(node.Filter); - if (node.Variable != null) + if (node.Variable is not null) { _shadowedVars.Pop(); } @@ -136,7 +136,7 @@ protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExp for (int i = 0; i < indexes.Length; i++) { IStrongBox? box = GetBox(node.Variables[i]); - if (box == null) + if (box is null) { indexes[i] = vars.Count; vars.Add(node.Variables[i]); @@ -173,7 +173,7 @@ protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExp protected internal override Expression VisitParameter(ParameterExpression node) { IStrongBox? box = GetBox(node); - if (box == null) + if (box is null) { return node; } @@ -201,7 +201,7 @@ protected internal override Expression VisitParameter(ParameterExpression node) return (IStrongBox)locals[hoistIndex]; } scope = scope.Parent; - if (scope == null) + if (scope is null) { break; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.RuntimeVariableList.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.RuntimeVariableList.cs index 919ae9e05d7ec1..de033aa5340afc 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.RuntimeVariableList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/RuntimeOps.RuntimeVariableList.cs @@ -73,8 +73,8 @@ private sealed class RuntimeVariableList : IRuntimeVariables internal RuntimeVariableList(object[] data, long[] indexes) { - Debug.Assert(data != null); - Debug.Assert(indexes != null); + Debug.Assert(data is not null); + Debug.Assert(indexes is not null); _data = data; _indexes = indexes; diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs index 350ae38f1f30a0..661878844aecd8 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs @@ -55,17 +55,17 @@ public EnumerableQuery(Expression expression) IQueryable IQueryProvider.CreateQuery(Expression expression) { - if (expression == null) + if (expression is null) throw Error.ArgumentNull(nameof(expression)); Type? iqType = TypeHelper.FindGenericType(typeof(IQueryable<>), expression.Type); - if (iqType == null) + if (iqType is null) throw Error.ArgumentNotValid(nameof(expression)); return Create(iqType.GetGenericArguments()[0], expression); } IQueryable IQueryProvider.CreateQuery(Expression expression) { - if (expression == null) + if (expression is null) throw Error.ArgumentNull(nameof(expression)); if (!typeof(IQueryable).IsAssignableFrom(expression.Type)) { @@ -76,14 +76,14 @@ IQueryable IQueryProvider.CreateQuery(Expression expression) object? IQueryProvider.Execute(Expression expression) { - if (expression == null) + if (expression is null) throw Error.ArgumentNull(nameof(expression)); return EnumerableExecutor.Create(expression).ExecuteBoxed(); } TElement IQueryProvider.Execute(Expression expression) { - if (expression == null) + if (expression is null) throw Error.ArgumentNull(nameof(expression)); if (!typeof(TElement).IsAssignableFrom(expression.Type)) throw Error.ArgumentNotValid(nameof(expression)); @@ -96,7 +96,7 @@ TElement IQueryProvider.Execute(Expression expression) private IEnumerator GetEnumerator() { - if (_enumerable == null) + if (_enumerable is null) { EnumerableRewriter rewriter = new EnumerableRewriter(); Expression body = rewriter.Visit(_expression); @@ -113,7 +113,7 @@ private IEnumerator GetEnumerator() { if (_expression is ConstantExpression c && c.Value == this) { - if (_enumerable != null) + if (_enumerable is not null) return _enumerable.ToString(); return "null"; } diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs index c7cd1e29ce0f37..80ab1f57eb80e8 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs @@ -65,7 +65,7 @@ private ReadOnlyCollection FixupQuotedArgs(MethodInfo mi, ReadOnlyCo Expression arg = argList[i]; ParameterInfo pi = pis[i]; arg = FixupQuotedExpression(pi.ParameterType, arg); - if (newArgs == null && arg != argList[i]) + if (newArgs is null && arg != argList[i]) { newArgs = new List(argList.Count); for (int j = 0; j < i; j++) @@ -76,7 +76,7 @@ private ReadOnlyCollection FixupQuotedArgs(MethodInfo mi, ReadOnlyCo newArgs?.Add(arg); } - if (newArgs != null) + if (newArgs is not null) argList = newArgs.AsReadOnly(); } return argList; @@ -137,7 +137,7 @@ private static Type GetPublicType(Type t) private Type GetEquivalentType(Type type) { Type? equiv; - if (_equivalentTypeCache == null) + if (_equivalentTypeCache is null) { // Pre-loading with the non-generic IQueryable and IEnumerable not only covers this case // without any reflection-based introspection, but also means the slightly different @@ -163,7 +163,7 @@ private Type GetEquivalentType(Type type) else if (genericType == typeof(IQueryable<>)) equiv = typeof(IEnumerable<>).MakeGenericType(pubType.GenericTypeArguments[0]); } - if (equiv == null) + if (equiv is null) { var interfacesWithInfo = pubType.GetInterfaces().Select(IntrospectionExtensions.GetTypeInfo).ToArray(); var singleTypeGenInterfacesWithGetType = interfacesWithInfo @@ -175,7 +175,7 @@ private Type GetEquivalentType(Type type) .Select(i => i.Info.GenericTypeArguments[0]) .Distinct() .SingleOrDefault(); - if (typeArg != null) + if (typeArg is not null) equiv = typeof(IOrderedEnumerable<>).MakeGenericType(typeArg); else { @@ -196,7 +196,7 @@ protected override Expression VisitConstant(ConstantExpression c) { if (c.Value is EnumerableQuery sq) { - if (sq.Enumerable != null) + if (sq.Enumerable is not null) { Type t = GetPublicType(sq.Enumerable.GetType()); return Expression.Constant(sq.Enumerable, t); @@ -213,13 +213,13 @@ protected override Expression VisitConstant(ConstantExpression c) private static ILookup? s_seqMethods; private static MethodInfo FindEnumerableMethod(string name, ReadOnlyCollection args, params Type[]? typeArgs) { - if (s_seqMethods == null) + if (s_seqMethods is null) { s_seqMethods = typeof(Enumerable).GetStaticMethods().ToLookup(m => m.Name); } MethodInfo? mi = s_seqMethods[name].FirstOrDefault(m => ArgsMatch(m, args, typeArgs)); - Debug.Assert(mi != null, "All static methods with arguments on Queryable have equivalents on Enumerable."); - if (typeArgs != null) + Debug.Assert(mi is not null, "All static methods with arguments on Queryable have equivalents on Enumerable."); + if (typeArgs is not null) return mi.MakeGenericMethod(typeArgs); return mi; } @@ -234,7 +234,7 @@ private static MethodInfo FindMethod(Type type, string name, ReadOnlyCollection< { MethodInfo mi = en.Current; if (ArgsMatch(mi, args, typeArgs)) - return (typeArgs != null) ? mi.MakeGenericMethod(typeArgs) : mi; + return (typeArgs is not null) ? mi.MakeGenericMethod(typeArgs) : mi; } while (en.MoveNext()); } throw Error.NoMethodOnTypeMatchingArguments(name, type); @@ -245,7 +245,7 @@ private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection args, ParameterInfo[] mParams = m.GetParameters(); if (mParams.Length != args.Count) return false; - if (!m.IsGenericMethod && typeArgs != null && typeArgs.Length > 0) + if (!m.IsGenericMethod && typeArgs is not null && typeArgs.Length > 0) { return false; } @@ -255,7 +255,7 @@ private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection args, } if (m.IsGenericMethodDefinition) { - if (typeArgs == null || typeArgs.Length == 0) + if (typeArgs is null || typeArgs.Length == 0) return false; if (m.GetGenericArguments().Length != typeArgs.Length) return false; @@ -265,7 +265,7 @@ private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection args, for (int i = 0, n = args.Count; i < n; i++) { Type parameterType = mParams[i].ParameterType; - if (parameterType == null) + if (parameterType is null) return false; if (parameterType.IsByRef) parameterType = parameterType.GetElementType()!; @@ -291,7 +291,7 @@ private static Type StripExpression(Type type) bool isArray = type.IsArray; Type tmp = isArray ? type.GetElementType()! : type; Type? eType = TypeHelper.FindGenericType(typeof(Expression<>), tmp); - if (eType != null) + if (eType is not null) tmp = eType.GetGenericArguments()[0]; if (isArray) { @@ -343,7 +343,7 @@ protected override Expression VisitGoto(GotoExpression node) protected override LabelTarget VisitLabelTarget(LabelTarget? node) { LabelTarget? newTarget; - if (_targetCache == null) + if (_targetCache is null) _targetCache = new Dictionary(); else if (_targetCache.TryGetValue(node!, out newTarget)) return newTarget; diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs index dab995cba60f09..0be74b8f180ab8 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs @@ -12,18 +12,18 @@ public static class Queryable { public static IQueryable AsQueryable(this IEnumerable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source as IQueryable ?? new EnumerableQuery(source); } public static IQueryable AsQueryable(this IEnumerable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); if (source is IQueryable queryable) return queryable; Type? enumType = TypeHelper.FindGenericType(typeof(IEnumerable<>), source.GetType()); - if (enumType == null) + if (enumType is null) throw Error.ArgumentNotIEnumerableGeneric(nameof(source)); return EnumerableQuery.Create(enumType.GenericTypeArguments[0], source); } @@ -31,9 +31,9 @@ public static IQueryable AsQueryable(this IEnumerable source) [DynamicDependency("Where`1", typeof(Enumerable))] public static IQueryable Where(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.CreateQuery( Expression.Call( @@ -46,9 +46,9 @@ public static IQueryable Where(this IQueryable source [DynamicDependency("Where`1", typeof(Enumerable))] public static IQueryable Where(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.CreateQuery( Expression.Call( @@ -61,7 +61,7 @@ public static IQueryable Where(this IQueryable source [DynamicDependency("OfType`1", typeof(Enumerable))] public static IQueryable OfType(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -72,7 +72,7 @@ public static IQueryable OfType(this IQueryable source) [DynamicDependency("Cast`1", typeof(Enumerable))] public static IQueryable Cast(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -83,9 +83,9 @@ public static IQueryable Cast(this IQueryable source) [DynamicDependency("Select`2", typeof(Enumerable))] public static IQueryable Select(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.CreateQuery( Expression.Call( @@ -98,9 +98,9 @@ public static IQueryable Select(this IQueryable Select(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.CreateQuery( Expression.Call( @@ -113,9 +113,9 @@ public static IQueryable Select(this IQueryable SelectMany(this IQueryable source, Expression>> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.CreateQuery( Expression.Call( @@ -128,9 +128,9 @@ public static IQueryable SelectMany(this IQueryable SelectMany(this IQueryable source, Expression>> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.CreateQuery( Expression.Call( @@ -143,11 +143,11 @@ public static IQueryable SelectMany(this IQueryable SelectMany(this IQueryable source, Expression>> collectionSelector, Expression> resultSelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (collectionSelector == null) + if (collectionSelector is null) throw Error.ArgumentNull(nameof(collectionSelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source.Provider.CreateQuery( Expression.Call( @@ -160,11 +160,11 @@ public static IQueryable SelectMany(this [DynamicDependency("SelectMany`3", typeof(Enumerable))] public static IQueryable SelectMany(this IQueryable source, Expression>> collectionSelector, Expression> resultSelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (collectionSelector == null) + if (collectionSelector is null) throw Error.ArgumentNull(nameof(collectionSelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source.Provider.CreateQuery( Expression.Call( @@ -177,21 +177,21 @@ public static IQueryable SelectMany(this private static Expression GetSourceExpression(IEnumerable source) { IQueryable? q = source as IQueryable; - return q != null ? q.Expression : Expression.Constant(source, typeof(IEnumerable)); + return q is not null ? q.Expression : Expression.Constant(source, typeof(IEnumerable)); } [DynamicDependency("Join`4", typeof(Enumerable))] public static IQueryable Join(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector) { - if (outer == null) + if (outer is null) throw Error.ArgumentNull(nameof(outer)); - if (inner == null) + if (inner is null) throw Error.ArgumentNull(nameof(inner)); - if (outerKeySelector == null) + if (outerKeySelector is null) throw Error.ArgumentNull(nameof(outerKeySelector)); - if (innerKeySelector == null) + if (innerKeySelector is null) throw Error.ArgumentNull(nameof(innerKeySelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return outer.Provider.CreateQuery( Expression.Call( @@ -202,15 +202,15 @@ public static IQueryable Join(this IQuer [DynamicDependency("Join`4", typeof(Enumerable))] public static IQueryable Join(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector, IEqualityComparer? comparer) { - if (outer == null) + if (outer is null) throw Error.ArgumentNull(nameof(outer)); - if (inner == null) + if (inner is null) throw Error.ArgumentNull(nameof(inner)); - if (outerKeySelector == null) + if (outerKeySelector is null) throw Error.ArgumentNull(nameof(outerKeySelector)); - if (innerKeySelector == null) + if (innerKeySelector is null) throw Error.ArgumentNull(nameof(innerKeySelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return outer.Provider.CreateQuery( Expression.Call( @@ -221,15 +221,15 @@ public static IQueryable Join(this IQuer [DynamicDependency("GroupJoin`4", typeof(Enumerable))] public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector) { - if (outer == null) + if (outer is null) throw Error.ArgumentNull(nameof(outer)); - if (inner == null) + if (inner is null) throw Error.ArgumentNull(nameof(inner)); - if (outerKeySelector == null) + if (outerKeySelector is null) throw Error.ArgumentNull(nameof(outerKeySelector)); - if (innerKeySelector == null) + if (innerKeySelector is null) throw Error.ArgumentNull(nameof(innerKeySelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return outer.Provider.CreateQuery( Expression.Call( @@ -240,15 +240,15 @@ public static IQueryable GroupJoin(this [DynamicDependency("GroupJoin`4", typeof(Enumerable))] public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector, IEqualityComparer? comparer) { - if (outer == null) + if (outer is null) throw Error.ArgumentNull(nameof(outer)); - if (inner == null) + if (inner is null) throw Error.ArgumentNull(nameof(inner)); - if (outerKeySelector == null) + if (outerKeySelector is null) throw Error.ArgumentNull(nameof(outerKeySelector)); - if (innerKeySelector == null) + if (innerKeySelector is null) throw Error.ArgumentNull(nameof(innerKeySelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return outer.Provider.CreateQuery( Expression.Call( @@ -259,9 +259,9 @@ public static IQueryable GroupJoin(this [DynamicDependency("OrderBy`2", typeof(Enumerable))] public static IOrderedQueryable OrderBy(this IQueryable source, Expression> keySelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -274,9 +274,9 @@ public static IOrderedQueryable OrderBy(this IQueryable< [DynamicDependency("OrderBy`2", typeof(Enumerable))] public static IOrderedQueryable OrderBy(this IQueryable source, Expression> keySelector, IComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -289,9 +289,9 @@ public static IOrderedQueryable OrderBy(this IQueryable< [DynamicDependency("OrderByDescending`2", typeof(Enumerable))] public static IOrderedQueryable OrderByDescending(this IQueryable source, Expression> keySelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -304,9 +304,9 @@ public static IOrderedQueryable OrderByDescending(this I [DynamicDependency("OrderByDescending`2", typeof(Enumerable))] public static IOrderedQueryable OrderByDescending(this IQueryable source, Expression> keySelector, IComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -319,9 +319,9 @@ public static IOrderedQueryable OrderByDescending(this I [DynamicDependency("ThenBy`2", typeof(Enumerable))] public static IOrderedQueryable ThenBy(this IOrderedQueryable source, Expression> keySelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -334,9 +334,9 @@ public static IOrderedQueryable ThenBy(this IOrderedQuer [DynamicDependency("ThenBy`2", typeof(Enumerable))] public static IOrderedQueryable ThenBy(this IOrderedQueryable source, Expression> keySelector, IComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -349,9 +349,9 @@ public static IOrderedQueryable ThenBy(this IOrderedQuer [DynamicDependency("ThenByDescending`2", typeof(Enumerable))] public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, Expression> keySelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -364,9 +364,9 @@ public static IOrderedQueryable ThenByDescending(this IO [DynamicDependency("ThenByDescending`2", typeof(Enumerable))] public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, Expression> keySelector, IComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( @@ -379,7 +379,7 @@ public static IOrderedQueryable ThenByDescending(this IO [DynamicDependency("Take`1", typeof(Enumerable))] public static IQueryable Take(this IQueryable source, int count) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -392,9 +392,9 @@ public static IQueryable Take(this IQueryable source, [DynamicDependency("TakeWhile`1", typeof(Enumerable))] public static IQueryable TakeWhile(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.CreateQuery( Expression.Call( @@ -407,9 +407,9 @@ public static IQueryable TakeWhile(this IQueryable so [DynamicDependency("TakeWhile`1", typeof(Enumerable))] public static IQueryable TakeWhile(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.CreateQuery( Expression.Call( @@ -422,7 +422,7 @@ public static IQueryable TakeWhile(this IQueryable so [DynamicDependency("Skip`1", typeof(Enumerable))] public static IQueryable Skip(this IQueryable source, int count) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -435,9 +435,9 @@ public static IQueryable Skip(this IQueryable source, [DynamicDependency("SkipWhile`1", typeof(Enumerable))] public static IQueryable SkipWhile(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.CreateQuery( Expression.Call( @@ -450,9 +450,9 @@ public static IQueryable SkipWhile(this IQueryable so [DynamicDependency("SkipWhile`1", typeof(Enumerable))] public static IQueryable SkipWhile(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.CreateQuery( Expression.Call( @@ -465,9 +465,9 @@ public static IQueryable SkipWhile(this IQueryable so [DynamicDependency("GroupBy`2", typeof(Enumerable))] public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return source.Provider.CreateQuery>( Expression.Call( @@ -480,11 +480,11 @@ public static IQueryable> GroupBy(this I [DynamicDependency("GroupBy`3", typeof(Enumerable))] public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); - if (elementSelector == null) + if (elementSelector is null) throw Error.ArgumentNull(nameof(elementSelector)); return source.Provider.CreateQuery>( Expression.Call( @@ -497,9 +497,9 @@ public static IQueryable> GroupBy> GroupBy(this IQueryable source, Expression> keySelector, IEqualityComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); return source.Provider.CreateQuery>( Expression.Call( @@ -512,11 +512,11 @@ public static IQueryable> GroupBy(this I [DynamicDependency("GroupBy`3", typeof(Enumerable))] public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector, IEqualityComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); - if (elementSelector == null) + if (elementSelector is null) throw Error.ArgumentNull(nameof(elementSelector)); return source.Provider.CreateQuery>( Expression.Call( @@ -527,13 +527,13 @@ public static IQueryable> GroupBy GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector, Expression, TResult>> resultSelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); - if (elementSelector == null) + if (elementSelector is null) throw Error.ArgumentNull(nameof(elementSelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source.Provider.CreateQuery( Expression.Call( @@ -544,11 +544,11 @@ public static IQueryable GroupBy(this [DynamicDependency("GroupBy`3", typeof(Enumerable))] public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression, TResult>> resultSelector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source.Provider.CreateQuery( Expression.Call( @@ -561,11 +561,11 @@ public static IQueryable GroupBy(this IQueryabl [DynamicDependency("GroupBy`3", typeof(Enumerable))] public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression, TResult>> resultSelector, IEqualityComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source.Provider.CreateQuery( Expression.Call( @@ -576,13 +576,13 @@ public static IQueryable GroupBy(this IQueryabl [DynamicDependency("GroupBy`4", typeof(Enumerable))] public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector, Expression, TResult>> resultSelector, IEqualityComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (keySelector == null) + if (keySelector is null) throw Error.ArgumentNull(nameof(keySelector)); - if (elementSelector == null) + if (elementSelector is null) throw Error.ArgumentNull(nameof(elementSelector)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source.Provider.CreateQuery( Expression.Call( @@ -593,7 +593,7 @@ public static IQueryable GroupBy(this [DynamicDependency("Distinct`1", typeof(Enumerable))] public static IQueryable Distinct(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -604,7 +604,7 @@ public static IQueryable Distinct(this IQueryable sou [DynamicDependency("Distinct`1", typeof(Enumerable))] public static IQueryable Distinct(this IQueryable source, IEqualityComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -617,9 +617,9 @@ public static IQueryable Distinct(this IQueryable sou [DynamicDependency("Concat`1", typeof(Enumerable))] public static IQueryable Concat(this IQueryable source1, IEnumerable source2) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -632,12 +632,12 @@ public static IQueryable Concat(this IQueryable sourc [DynamicDependency("Zip`2", typeof(Enumerable))] public static IQueryable<(TFirst First, TSecond Second)> Zip(this IQueryable source1, IEnumerable source2) { - if (source1 == null) + if (source1 is null) { throw Error.ArgumentNull(nameof(source1)); } - if (source2 == null) + if (source2 is null) { throw Error.ArgumentNull(nameof(source2)); } @@ -652,11 +652,11 @@ public static IQueryable Concat(this IQueryable sourc [DynamicDependency("Zip`3", typeof(Enumerable))] public static IQueryable Zip(this IQueryable source1, IEnumerable source2, Expression> resultSelector) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); - if (resultSelector == null) + if (resultSelector is null) throw Error.ArgumentNull(nameof(resultSelector)); return source1.Provider.CreateQuery( Expression.Call( @@ -669,9 +669,9 @@ public static IQueryable Zip(this IQueryable< [DynamicDependency("Union`1", typeof(Enumerable))] public static IQueryable Union(this IQueryable source1, IEnumerable source2) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -684,9 +684,9 @@ public static IQueryable Union(this IQueryable source [DynamicDependency("Union`1", typeof(Enumerable))] public static IQueryable Union(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -701,9 +701,9 @@ public static IQueryable Union(this IQueryable source [DynamicDependency("Intersect`1", typeof(Enumerable))] public static IQueryable Intersect(this IQueryable source1, IEnumerable source2) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -716,9 +716,9 @@ public static IQueryable Intersect(this IQueryable so [DynamicDependency("Intersect`1", typeof(Enumerable))] public static IQueryable Intersect(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -733,9 +733,9 @@ public static IQueryable Intersect(this IQueryable so [DynamicDependency("Except`1", typeof(Enumerable))] public static IQueryable Except(this IQueryable source1, IEnumerable source2) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -748,9 +748,9 @@ public static IQueryable Except(this IQueryable sourc [DynamicDependency("Except`1", typeof(Enumerable))] public static IQueryable Except(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.CreateQuery( Expression.Call( @@ -765,7 +765,7 @@ public static IQueryable Except(this IQueryable sourc [DynamicDependency("First`1", typeof(Enumerable))] public static TSource First(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -776,9 +776,9 @@ public static TSource First(this IQueryable source) [DynamicDependency("First`1", typeof(Enumerable))] public static TSource First(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -791,7 +791,7 @@ public static TSource First(this IQueryable source, Expression [DynamicDependency("FirstOrDefault`1", typeof(Enumerable))] public static TSource? FirstOrDefault(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -802,9 +802,9 @@ public static TSource First(this IQueryable source, Expression [DynamicDependency("FirstOrDefault`1", typeof(Enumerable))] public static TSource? FirstOrDefault(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -817,7 +817,7 @@ public static TSource First(this IQueryable source, Expression [DynamicDependency("Last`1", typeof(Enumerable))] public static TSource Last(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -828,9 +828,9 @@ public static TSource Last(this IQueryable source) [DynamicDependency("Last`1", typeof(Enumerable))] public static TSource Last(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -843,7 +843,7 @@ public static TSource Last(this IQueryable source, Expression< [DynamicDependency("LastOrDefault`1", typeof(Enumerable))] public static TSource? LastOrDefault(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -854,9 +854,9 @@ public static TSource Last(this IQueryable source, Expression< [DynamicDependency("LastOrDefault`1", typeof(Enumerable))] public static TSource? LastOrDefault(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -869,7 +869,7 @@ public static TSource Last(this IQueryable source, Expression< [DynamicDependency("Single`1", typeof(Enumerable))] public static TSource Single(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -880,9 +880,9 @@ public static TSource Single(this IQueryable source) [DynamicDependency("Single`1", typeof(Enumerable))] public static TSource Single(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -895,7 +895,7 @@ public static TSource Single(this IQueryable source, Expressio [DynamicDependency("SingleOrDefault`1", typeof(Enumerable))] public static TSource? SingleOrDefault(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -906,9 +906,9 @@ public static TSource Single(this IQueryable source, Expressio [DynamicDependency("SingleOrDefault`1", typeof(Enumerable))] public static TSource? SingleOrDefault(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -921,7 +921,7 @@ public static TSource Single(this IQueryable source, Expressio [DynamicDependency("ElementAt`1", typeof(Enumerable))] public static TSource ElementAt(this IQueryable source, int index) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); if (index < 0) throw Error.ArgumentOutOfRange(nameof(index)); @@ -936,7 +936,7 @@ public static TSource ElementAt(this IQueryable source, int in [DynamicDependency("ElementAtOrDefault`1", typeof(Enumerable))] public static TSource? ElementAtOrDefault(this IQueryable source, int index) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -949,7 +949,7 @@ public static TSource ElementAt(this IQueryable source, int in [DynamicDependency("DefaultIfEmpty`1", typeof(Enumerable))] public static IQueryable DefaultIfEmpty(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -960,7 +960,7 @@ public static IQueryable DefaultIfEmpty(this IQueryable DefaultIfEmpty(this IQueryable source, TSource defaultValue) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -973,7 +973,7 @@ public static IQueryable DefaultIfEmpty(this IQueryable(this IQueryable source, TSource item) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -986,7 +986,7 @@ public static bool Contains(this IQueryable source, TSource it [DynamicDependency("Contains`1", typeof(Enumerable))] public static bool Contains(this IQueryable source, TSource item, IEqualityComparer? comparer) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -999,7 +999,7 @@ public static bool Contains(this IQueryable source, TSource it [DynamicDependency("Reverse`1", typeof(Enumerable))] public static IQueryable Reverse(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -1010,9 +1010,9 @@ public static IQueryable Reverse(this IQueryable sour [DynamicDependency("SequenceEqual`1", typeof(Enumerable))] public static bool SequenceEqual(this IQueryable source1, IEnumerable source2) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.Execute( Expression.Call( @@ -1025,9 +1025,9 @@ public static bool SequenceEqual(this IQueryable source1, IEnu [DynamicDependency("SequenceEqual`1", typeof(Enumerable))] public static bool SequenceEqual(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) { - if (source1 == null) + if (source1 is null) throw Error.ArgumentNull(nameof(source1)); - if (source2 == null) + if (source2 is null) throw Error.ArgumentNull(nameof(source2)); return source1.Provider.Execute( Expression.Call( @@ -1042,7 +1042,7 @@ public static bool SequenceEqual(this IQueryable source1, IEnu [DynamicDependency("Any`1", typeof(Enumerable))] public static bool Any(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1053,9 +1053,9 @@ public static bool Any(this IQueryable source) [DynamicDependency("Any`1", typeof(Enumerable))] public static bool Any(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -1068,9 +1068,9 @@ public static bool Any(this IQueryable source, Expression(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -1083,7 +1083,7 @@ public static bool All(this IQueryable source, Expression(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1094,9 +1094,9 @@ public static int Count(this IQueryable source) [DynamicDependency("Count`1", typeof(Enumerable))] public static int Count(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -1109,7 +1109,7 @@ public static int Count(this IQueryable source, Expression(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1120,9 +1120,9 @@ public static long LongCount(this IQueryable source) [DynamicDependency("LongCount`1", typeof(Enumerable))] public static long LongCount(this IQueryable source, Expression> predicate) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (predicate == null) + if (predicate is null) throw Error.ArgumentNull(nameof(predicate)); return source.Provider.Execute( Expression.Call( @@ -1135,7 +1135,7 @@ public static long LongCount(this IQueryable source, Expressio [DynamicDependency("Min`1", typeof(Enumerable))] public static TSource? Min(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1146,9 +1146,9 @@ public static long LongCount(this IQueryable source, Expressio [DynamicDependency("Min`2", typeof(Enumerable))] public static TResult? Min(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1161,7 +1161,7 @@ public static long LongCount(this IQueryable source, Expressio [DynamicDependency("Max`1", typeof(Enumerable))] public static TSource? Max(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1172,9 +1172,9 @@ public static long LongCount(this IQueryable source, Expressio [DynamicDependency("Max`2", typeof(Enumerable))] public static TResult? Max(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1187,7 +1187,7 @@ public static long LongCount(this IQueryable source, Expressio [DynamicDependency("Sum", typeof(Enumerable))] public static int Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1198,7 +1198,7 @@ public static int Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static int? Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1209,7 +1209,7 @@ public static int Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static long Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1220,7 +1220,7 @@ public static long Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static long? Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1231,7 +1231,7 @@ public static long Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static float Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1242,7 +1242,7 @@ public static float Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static float? Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1253,7 +1253,7 @@ public static float Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static double Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1264,7 +1264,7 @@ public static double Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static double? Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1275,7 +1275,7 @@ public static double Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static decimal Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1286,7 +1286,7 @@ public static decimal Sum(this IQueryable source) [DynamicDependency("Sum", typeof(Enumerable))] public static decimal? Sum(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1297,9 +1297,9 @@ public static decimal Sum(this IQueryable source) [DynamicDependency("Sum`1", typeof(Enumerable))] public static int Sum(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1312,9 +1312,9 @@ public static int Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1327,9 +1327,9 @@ public static int Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1342,9 +1342,9 @@ public static long Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1357,9 +1357,9 @@ public static long Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1372,9 +1372,9 @@ public static float Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1387,9 +1387,9 @@ public static float Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1402,9 +1402,9 @@ public static double Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1417,9 +1417,9 @@ public static double Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1432,9 +1432,9 @@ public static decimal Sum(this IQueryable source, Expression(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1447,7 +1447,7 @@ public static decimal Sum(this IQueryable source, Expression source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1458,7 +1458,7 @@ public static double Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static double? Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1469,7 +1469,7 @@ public static double Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static double Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1480,7 +1480,7 @@ public static double Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static double? Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1491,7 +1491,7 @@ public static double Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static float Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1502,7 +1502,7 @@ public static float Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static float? Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1513,7 +1513,7 @@ public static float Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static double Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1524,7 +1524,7 @@ public static double Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static double? Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1535,7 +1535,7 @@ public static double Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static decimal Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1546,7 +1546,7 @@ public static decimal Average(this IQueryable source) [DynamicDependency("Average", typeof(Enumerable))] public static decimal? Average(this IQueryable source) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.Execute( Expression.Call( @@ -1557,9 +1557,9 @@ public static decimal Average(this IQueryable source) [DynamicDependency("Average`1", typeof(Enumerable))] public static double Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1572,9 +1572,9 @@ public static double Average(this IQueryable source, Expressio [DynamicDependency("Average`1", typeof(Enumerable))] public static double? Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1587,9 +1587,9 @@ public static double Average(this IQueryable source, Expressio [DynamicDependency("Average`1", typeof(Enumerable))] public static float Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1602,9 +1602,9 @@ public static float Average(this IQueryable source, Expression [DynamicDependency("Average`1", typeof(Enumerable))] public static float? Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1617,9 +1617,9 @@ public static float Average(this IQueryable source, Expression [DynamicDependency("Average`1", typeof(Enumerable))] public static double Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1632,9 +1632,9 @@ public static double Average(this IQueryable source, Expressio [DynamicDependency("Average`1", typeof(Enumerable))] public static double? Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1647,9 +1647,9 @@ public static double Average(this IQueryable source, Expressio [DynamicDependency("Average`1", typeof(Enumerable))] public static double Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1662,9 +1662,9 @@ public static double Average(this IQueryable source, Expressio [DynamicDependency("Average`1", typeof(Enumerable))] public static double? Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1677,9 +1677,9 @@ public static double Average(this IQueryable source, Expressio [DynamicDependency("Average`1", typeof(Enumerable))] public static decimal Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1692,9 +1692,9 @@ public static decimal Average(this IQueryable source, Expressi [DynamicDependency("Average`1", typeof(Enumerable))] public static decimal? Average(this IQueryable source, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1707,9 +1707,9 @@ public static decimal Average(this IQueryable source, Expressi [DynamicDependency("Aggregate`1", typeof(Enumerable))] public static TSource Aggregate(this IQueryable source, Expression> func) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (func == null) + if (func is null) throw Error.ArgumentNull(nameof(func)); return source.Provider.Execute( Expression.Call( @@ -1722,9 +1722,9 @@ public static TSource Aggregate(this IQueryable source, Expres [DynamicDependency("Aggregate`2", typeof(Enumerable))] public static TAccumulate Aggregate(this IQueryable source, TAccumulate seed, Expression> func) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (func == null) + if (func is null) throw Error.ArgumentNull(nameof(func)); return source.Provider.Execute( Expression.Call( @@ -1737,11 +1737,11 @@ public static TAccumulate Aggregate(this IQueryable(this IQueryable source, TAccumulate seed, Expression> func, Expression> selector) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); - if (func == null) + if (func is null) throw Error.ArgumentNull(nameof(func)); - if (selector == null) + if (selector is null) throw Error.ArgumentNull(nameof(selector)); return source.Provider.Execute( Expression.Call( @@ -1752,7 +1752,7 @@ public static TResult Aggregate(this IQueryable SkipLast(this IQueryable source, int count) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -1765,7 +1765,7 @@ public static IQueryable SkipLast(this IQueryable sou [DynamicDependency("TakeLast`1", typeof(Enumerable))] public static IQueryable TakeLast(this IQueryable source, int count) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -1778,7 +1778,7 @@ public static IQueryable TakeLast(this IQueryable sou [DynamicDependency("Append`1", typeof(Enumerable))] public static IQueryable Append(this IQueryable source, TSource element) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( @@ -1791,7 +1791,7 @@ public static IQueryable Append(this IQueryable sourc [DynamicDependency("Prepend`1", typeof(Enumerable))] public static IQueryable Prepend(this IQueryable source, TSource element) { - if (source == null) + if (source is null) throw Error.ArgumentNull(nameof(source)); return source.Provider.CreateQuery( Expression.Call( diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/TypeHelper.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/TypeHelper.cs index 7f2e0b50a6a07c..6acdbec378d461 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/TypeHelper.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/TypeHelper.cs @@ -12,7 +12,7 @@ internal static class TypeHelper internal static Type? FindGenericType(Type definition, Type type) { bool? definitionIsInterface = null; - while (type != null && type != typeof(object)) + while (type is not null && type != typeof(object)) { if (type.IsGenericType && type.GetGenericTypeDefinition() == definition) return type; @@ -23,7 +23,7 @@ internal static class TypeHelper foreach (Type itype in type.GetInterfaces()) { Type? found = FindGenericType(definition, itype); - if (found != null) + if (found is not null) return found; } } diff --git a/src/libraries/System.Management/src/System/Management/InteropClasses/WMIInterop.cs b/src/libraries/System.Management/src/System/Management/InteropClasses/WMIInterop.cs index b2de37af52c1a2..980bac04aa7d8a 100644 --- a/src/libraries/System.Management/src/System/Management/InteropClasses/WMIInterop.cs +++ b/src/libraries/System.Management/src/System/Management/InteropClasses/WMIInterop.cs @@ -39,7 +39,7 @@ public IWbemClassObjectFreeThreaded(IntPtr pWbemClassObject) public static implicit operator IntPtr(IWbemClassObjectFreeThreaded wbemClassObject) { - if (null == wbemClassObject) + if (wbemClassObject is null) return IntPtr.Zero; return wbemClassObject.pWbemClassObject; } @@ -1444,7 +1444,7 @@ public static object CreateInMTA(Type type) // release the lock so that worker thread can work on the request myReq.evtDone.WaitOne(); - if (myReq.exception != null) + if (myReq.exception is not null) { throw myReq.exception; } @@ -1761,7 +1761,7 @@ public void Start() { this.exception = null; DispatchThread(); - if (this.Exception != null) + if (this.Exception is not null) { throw this.Exception; } diff --git a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs index 16345b474973ce..651c17fb0daedc 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs @@ -200,7 +200,7 @@ internal IWbemClassObjectFreeThreaded wbemObject { get { - if (_wbemObject == null) + if (_wbemObject is null) { Initialize(true); } @@ -230,7 +230,7 @@ protected ManagementBaseObject(SerializationInfo info, StreamingContext context) public new void Dispose() { - if (_wbemObject != null) + if (_wbemObject is not null) { _wbemObject.Dispose(); _wbemObject = null; @@ -253,7 +253,7 @@ protected ManagementBaseObject(SerializationInfo info, StreamingContext context) /// public static explicit operator IntPtr(ManagementBaseObject managementObject) { - if (null == managementObject) + if (managementObject is null) return IntPtr.Zero; return (IntPtr)managementObject.wbemObject; @@ -343,7 +343,7 @@ public virtual PropertyDataCollection Properties { Initialize(true); - if (properties == null) + if (properties is null) properties = new PropertyDataCollection(this, false); return properties; @@ -365,7 +365,7 @@ public virtual PropertyDataCollection SystemProperties { Initialize(false); - if (systemProperties == null) + if (systemProperties is null) systemProperties = new PropertyDataCollection(this, true); return systemProperties; @@ -388,7 +388,7 @@ public virtual QualifierDataCollection Qualifiers { Initialize(true); - if (qualifiers == null) + if (qualifiers is null) qualifiers = new QualifierDataCollection(this); return qualifiers; @@ -502,7 +502,7 @@ public object this[string propertyName] /// public object GetPropertyValue(string propertyName) { - if (null == propertyName) + if (propertyName is null) throw new ArgumentNullException(nameof(propertyName)); // Check for system properties @@ -618,7 +618,7 @@ public string GetText(TextFormat format) ctx.SetValue_("IncludeQualifiers", 0, ref v); ctx.SetValue_("IncludeClassOrigin", 0, ref v); - if (wbemTextSrc != null) + if (wbemTextSrc is not null) { status = wbemTextSrc.GetText_(0, (IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(wbemObject)), @@ -739,12 +739,12 @@ public override int GetHashCode() /// public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings) { - if (null == otherObject) + if (otherObject is null) throw new ArgumentNullException(nameof(otherObject)); bool result = false; - if (null != wbemObject) + if (wbemObject is not null) { int status = (int)ManagementStatus.NoError; @@ -823,7 +823,7 @@ public void SetPropertyValue( string propertyName, object propertyValue) { - if (null == propertyName) + if (propertyName is null) throw new ArgumentNullException(nameof(propertyName)); // Check for system properties diff --git a/src/libraries/System.Management/src/System/Management/ManagementClass.cs b/src/libraries/System.Management/src/System/Management/ManagementClass.cs index e5c5f2c1d9258e..cd11cbed853e26 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementClass.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementClass.cs @@ -67,13 +67,13 @@ internal static ManagementClass GetManagementClass( ManagementClass newClass = new ManagementClass(); newClass.wbemObject = wbemObject; - if (null != mgObj) + if (mgObj is not null) { newClass.scope = ManagementScope._Clone(mgObj.scope); ManagementPath objPath = mgObj.Path; - if (null != objPath) + if (objPath is not null) newClass.path = ManagementPath._Clone(objPath); // Ensure we have our class name in the path @@ -94,7 +94,7 @@ internal static ManagementClass GetManagementClass( newClass.path.internalClassName = (string)className; ObjectGetOptions options = mgObj.Options; - if (null != options) + if (options is not null) newClass.options = ObjectGetOptions._Clone(options); // Finally we ensure that this object is marked as bound. @@ -117,7 +117,7 @@ internal static ManagementClass GetManagementClass( ManagementClass newClass = new ManagementClass(); newClass.path = new ManagementPath(ManagementPath.GetManagementPath(wbemObject)); - if (null != scope) + if (scope is not null) newClass.scope = ManagementScope._Clone(scope); newClass.wbemObject = wbemObject; @@ -302,7 +302,7 @@ public override ManagementPath Path set { // This must be a class path or empty (don't allow instance paths) - if ((null == value) || value.IsClass || value.IsEmpty) + if ((value is null) || value.IsClass || value.IsEmpty) base.Path = value; else throw new ArgumentOutOfRangeException(nameof(value)); @@ -351,7 +351,7 @@ public StringCollection Derivation Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } - if (null != val) + if (val is not null) result.AddRange((string[])val); return result; @@ -383,7 +383,7 @@ public MethodDataCollection Methods { Initialize(true); - if (methods == null) + if (methods is null) methods = new MethodDataCollection(this); return methods; @@ -454,13 +454,13 @@ public ManagementObjectCollection GetInstances() /// public ManagementObjectCollection GetInstances(EnumerationOptions options) { - if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) + if ((Path is null) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; - EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); + EnumerationOptions o = (options is null) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; @@ -476,7 +476,7 @@ public ManagementObjectCollection GetInstances(EnumerationOptions options) } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } @@ -575,15 +575,15 @@ public void GetInstances(ManagementOperationObserver watcher) /// The specified additional options for getting the instances. public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions options) { - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); - if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) + if ((Path is null) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); - EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); + EnumerationOptions o = (options is null) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. @@ -607,7 +607,7 @@ public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions ClassName, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -672,13 +672,13 @@ public ManagementObjectCollection GetSubclasses() /// public ManagementObjectCollection GetSubclasses(EnumerationOptions options) { - if (null == Path) + if (Path is null) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; - EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); + EnumerationOptions o = (options is null) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; @@ -694,7 +694,7 @@ public ManagementObjectCollection GetSubclasses(EnumerationOptions options) } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } @@ -728,15 +728,15 @@ public void GetSubclasses(ManagementOperationObserver watcher) public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options) { - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); - if (null == Path) + if (Path is null) throw new InvalidOperationException(); Initialize(false); - EnumerationOptions o = (null == options) ? new EnumerationOptions() : + EnumerationOptions o = (options is null) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. @@ -761,7 +761,7 @@ public void GetSubclasses(ManagementOperationObserver watcher, ClassName, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -805,7 +805,7 @@ public ManagementClass Derive(string newClassName) { ManagementClass newClass = null; - if (null == newClassName) + if (newClassName is null) throw new ArgumentNullException(nameof(newClassName)); else { @@ -1018,14 +1018,14 @@ public ManagementObjectCollection GetRelatedClasses( string thisRole, EnumerationOptions options) { - if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) + if ((Path is null) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; - EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); + EnumerationOptions o = (options is not null) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag bit is turned off as it's invalid for queries o.EnumerateDeep = true; @@ -1052,7 +1052,7 @@ public ManagementObjectCollection GetRelatedClasses( } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } @@ -1116,16 +1116,16 @@ public void GetRelatedClasses( string thisRole, EnumerationOptions options) { - if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) + if ((Path is null) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(true); - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { - EnumerationOptions o = (null != options) + EnumerationOptions o = (options is not null) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag bit is turned off as it's invalid for queries @@ -1156,7 +1156,7 @@ public void GetRelatedClasses( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -1223,14 +1223,14 @@ public ManagementObjectCollection GetRelationshipClasses( string thisRole, EnumerationOptions options) { - if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) + if ((Path is null) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; - EnumerationOptions o = (null != options) ? options : new EnumerationOptions(); + EnumerationOptions o = (options is not null) ? options : new EnumerationOptions(); //Ensure EnumerateDeep flag is turned off as it's invalid for queries o.EnumerateDeep = true; @@ -1251,7 +1251,7 @@ public ManagementObjectCollection GetRelationshipClasses( } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } @@ -1309,16 +1309,16 @@ public void GetRelationshipClasses( string thisRole, EnumerationOptions options) { - if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) + if ((Path is null) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { Initialize(true); EnumerationOptions o = - (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); + (options is not null) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag is turned off as it's invalid for queries o.EnumerateDeep = true; @@ -1344,7 +1344,7 @@ public void GetRelationshipClasses( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) diff --git a/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs b/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs index 7cd305b2749d61..b4d9db9066baa9 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs @@ -120,7 +120,7 @@ public static DateTime ToDateTime(string dmtfDate) // If the string passed is empty or null then throw // an exception - if (dmtf == null) + if (dmtf is null) { throw new ArgumentOutOfRangeException(nameof(dmtfDate)); } @@ -318,7 +318,7 @@ public static TimeSpan ToTimeSpan(string dmtfTimespan) string dmtfts = dmtfTimespan; TimeSpan timespan = TimeSpan.MinValue; - if (dmtfts == null) + if (dmtfts is null) { throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan)); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementEventArgs.cs b/src/libraries/System.Management/src/System/Management/ManagementEventArgs.cs index 39a822221713f8..c464d4e5e9aaed 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementEventArgs.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementEventArgs.cs @@ -251,7 +251,7 @@ public string Message { get { - return (null != message) ? message : string.Empty; + return (message is not null) ? message : string.Empty; } } } diff --git a/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs b/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs index b7e994e5642c55..4b4adb7ccc21e9 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs @@ -214,18 +214,18 @@ public ManagementEventWatcher( EventQuery query, EventWatcherOptions options) { - if (null != scope) + if (scope is not null) this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange)); else this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); - if (null != query) + if (query is not null) this.query = (EventQuery)query.Clone(); else this.query = new EventQuery(); this.query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); - if (null != options) + if (options is not null) this.options = (EventWatcherOptions)options.Clone(); else this.options = new EventWatcherOptions(); @@ -246,13 +246,13 @@ public ManagementEventWatcher( // Ensure any outstanding calls are cleared Stop(); - if (null != scope) + if (scope is not null) scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); - if (null != options) + if (options is not null) options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); - if (null != query) + if (query is not null) query.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); } @@ -288,13 +288,13 @@ public ManagementScope Scope } set { - if (null != value) + if (value is not null) { ManagementScope oldScope = scope; scope = (ManagementScope)value.Clone(); // Unregister ourselves from the previous scope object - if (null != oldScope) + if (oldScope is not null) oldScope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object @@ -321,13 +321,13 @@ public EventQuery Query } set { - if (null != value) + if (value is not null) { ManagementQuery oldQuery = query; query = (EventQuery)value.Clone(); // Unregister ourselves from the previous query object - if (null != oldQuery) + if (oldQuery is not null) oldQuery.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object @@ -354,13 +354,13 @@ public EventWatcherOptions Options } set { - if (null != value) + if (value is not null) { EventWatcherOptions oldOptions = options; options = (EventWatcherOptions)value.Clone(); // Unregister ourselves from the previous scope object - if (null != oldOptions) + if (oldOptions is not null) oldOptions.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize]; @@ -401,7 +401,7 @@ public ManagementBaseObject WaitForNextEvent() try { - if (null == enumWbem) //don't have an enumerator yet - get it + if (enumWbem is null) //don't have an enumerator yet - get it { //Execute the query status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecNotificationQuery_( @@ -504,7 +504,7 @@ public void Start() if (status < 0) { - if (sink != null) + if (sink is not null) { sink.ReleaseStub(); sink = null; @@ -532,7 +532,7 @@ public void Start() public void Stop() { //For semi-synchronous, release the WMI enumerator to cancel the subscription - if (null != enumWbem) + if (enumWbem is not null) { Marshal.ReleaseComObject(enumWbem); enumWbem = null; @@ -541,7 +541,7 @@ public void Stop() // In async mode cancel the call to the sink - this will // unwind the operation and cause a Stopped message - if (null != sink) + if (sink is not null) { sink.Cancel(); sink = null; @@ -551,19 +551,19 @@ public void Stop() private void Initialize() { //If the query is not set yet we can't do it - if (null == query) + if (query is null) throw new InvalidOperationException(); - if (null == options) + if (options is null) Options = new EventWatcherOptions(); //If we're not connected yet, this is the time to do it... lock (this) { - if (null == scope) + if (scope is null) Scope = new ManagementScope(); - if (null == cachedObjects) + if (cachedObjects is null) cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize]; } @@ -714,11 +714,11 @@ private void Cancel2(object o) internal void Cancel() { - if (null != stub) + if (stub is not null) { lock (this) { - if (null != stub) + if (stub is not null) { int status = services.CancelAsyncCall_(stub); @@ -740,7 +740,7 @@ internal void Cancel() internal void ReleaseStub() { - if (null != stub) + if (stub is not null) { lock (this) { @@ -749,7 +749,7 @@ internal void ReleaseStub() * unsecapp.exe to die as soon as possible. * however if it is local, unsecap won't be started */ - if (null != stub) + if (stub is not null) { try { diff --git a/src/libraries/System.Management/src/System/Management/ManagementException.cs b/src/libraries/System.Management/src/System/Management/ManagementException.cs index 31b123d841f1f0..4b17bb7b0d852c 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementException.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementException.cs @@ -598,12 +598,12 @@ internal static void ThrowWithExtendedInfo(ManagementStatus errorCode) //Try to get extended error info first, and save in errorObject member IWbemClassObjectFreeThreaded obj = WbemErrorInfo.GetErrorInfo(); - if (obj != null) + if (obj is not null) errObj = new ManagementBaseObject(obj); //If the error code is not a WMI one and there's an extended error object available, stick the message //from the extended error object in. - if (((msg = GetMessage(errorCode)) == null) && (errObj != null)) + if (((msg = GetMessage(errorCode)) is null) && (errObj is not null)) try { msg = (string)errObj["Description"]; @@ -621,12 +621,12 @@ internal static void ThrowWithExtendedInfo(Exception e) //Try to get extended error info first, and save in errorObject member IWbemClassObjectFreeThreaded obj = WbemErrorInfo.GetErrorInfo(); - if (obj != null) + if (obj is not null) errObj = new ManagementBaseObject(obj); //If the error code is not a WMI one and there's an extended error object available, stick the message //from the extended error object in. - if (((msg = GetMessage(e)) == null) && (errObj != null)) + if (((msg = GetMessage(e)) is null) && (errObj is not null)) try { msg = (string)errObj["Description"]; @@ -653,7 +653,7 @@ internal ManagementException(Exception e, string msg, ManagementBaseObject errOb // May/may not have extended error info. // - if (errorObject != null) + if (errorObject is not null) errorObject = (ManagementBaseObject)((ManagementException)e).errorObject.Clone(); else errorObject = null; @@ -735,7 +735,7 @@ private static string GetMessage(Exception e) msg = GetMessage ((ManagementStatus)((COMException)e).ErrorCode); } - if (null == msg) + if (msg is null) msg = e.Message; return msg; @@ -748,7 +748,7 @@ private static string GetMessage(ManagementStatus errorCode) int hr; statusCode = (IWbemStatusCodeText) new WbemStatusCodeText(); - if (statusCode != null) + if (statusCode is not null) { try { hr = statusCode.GetErrorCodeText_((int)errorCode, 0, 1, out msg); diff --git a/src/libraries/System.Management/src/System/Management/ManagementNamedValueCollection.cs b/src/libraries/System.Management/src/System/Management/ManagementNamedValueCollection.cs index 7da647095b362a..2279176e129d6b 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementNamedValueCollection.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementNamedValueCollection.cs @@ -21,7 +21,7 @@ public class ManagementNamedValueCollection : NameObjectCollectionBase //Fires IdentifierChanged event private void FireIdentifierChanged() { - if (IdentifierChanged != null) + if (IdentifierChanged is not null) IdentifierChanged(this, null); } @@ -141,7 +141,7 @@ public ManagementNamedValueCollection Clone() // If we can clone the value, do so. Otherwise throw. object val = base.BaseGet(name); - if (null != val) + if (val is not null) { Type valueType = val.GetType(); diff --git a/src/libraries/System.Management/src/System/Management/ManagementObject.cs b/src/libraries/System.Management/src/System/Management/ManagementObject.cs index bd551dcee66c96..c1326f5487e4b9 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObject.cs @@ -101,7 +101,7 @@ protected override void GetObjectData(SerializationInfo info, StreamingContext c public new void Dispose() { - if (wmiClass != null) + if (wmiClass is not null) { wmiClass.Dispose(); wmiClass = null; @@ -114,7 +114,7 @@ protected override void GetObjectData(SerializationInfo info, StreamingContext c internal void FireIdentifierChanged() { - if (IdentifierChanged != null) + if (IdentifierChanged is not null) IdentifierChanged(this, null); } @@ -142,7 +142,7 @@ private void HandleIdentifierChange(object sender, internal bool IsBound { get - { return _wbemObject != null; } + { return _wbemObject is not null; } } //internal constructor @@ -153,14 +153,14 @@ internal static ManagementObject GetManagementObject( ManagementObject newObject = new ManagementObject(); newObject.wbemObject = wbemObject; - if (null != mgObj) + if (mgObj is not null) { newObject.scope = ManagementScope._Clone(mgObj.scope); - if (null != mgObj.path) + if (mgObj.path is not null) newObject.path = ManagementPath._Clone(mgObj.path); - if (null != mgObj.options) + if (mgObj.options is not null) newObject.options = ObjectGetOptions._Clone(mgObj.options); // We set isBound last since assigning to Scope, Path @@ -380,7 +380,7 @@ private void ManagementObjectCTOR(ManagementScope scope, ManagementPath path, Ob // We may use this to set the scope path string nsPath = string.Empty; - if ((null != path) && !path.IsEmpty) + if ((path is not null) && !path.IsEmpty) { //If this is a ManagementObject then the path has to be an instance, // and if this is a ManagementClass the path has to be a class. @@ -393,7 +393,7 @@ private void ManagementObjectCTOR(ManagementScope scope, ManagementPath path, Ob // we don't have a scope nsPath = path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); - if ((null != scope) && (scope.Path.NamespacePath.Length > 0)) + if ((scope is not null) && (scope.Path.NamespacePath.Length > 0)) { // If the scope has a path too, the namespace portion of // scope.path takes precedence over what is specified in path @@ -410,10 +410,10 @@ private void ManagementObjectCTOR(ManagementScope scope, ManagementPath path, Ob this.path = ManagementPath._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); } - if (null != options) + if (options is not null) this.options = ObjectGetOptions._Clone(options, new IdentifierChangedEventHandler(HandleIdentifierChange)); - if (null != scope) + if (scope is not null) this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange)); else { @@ -503,16 +503,16 @@ public ManagementScope Scope { get { - if (scope == null) + if (scope is null) return scope = ManagementScope._Clone(null); else return scope; } set { - if (null != value) + if (value is not null) { - if (null != scope) + if (scope is not null) scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); scope = ManagementScope._Clone((ManagementScope)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -558,19 +558,19 @@ public virtual ManagementPath Path { get { - if (path == null) + if (path is null) return path = ManagementPath._Clone(null); else return path; } set { - ManagementPath newPath = (null != value) ? value : new ManagementPath(); + ManagementPath newPath = (value is not null) ? value : new ManagementPath(); //If the new path contains a namespace path and the scope is currently defaulted, //we want to set the scope to the new namespace path provided string nsPath = newPath.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); - if ((nsPath.Length > 0) && (scope != null) && (scope.IsDefaulted)) + if ((nsPath.Length > 0) && (scope is not null) && (scope.IsDefaulted)) Scope = new ManagementScope(nsPath); // This must be a class for a ManagementClass object or an instance for a ManagementObject, or empty @@ -578,7 +578,7 @@ public virtual ManagementPath Path (GetType() == typeof(ManagementClass) && newPath.IsClass) || newPath.IsEmpty) { - if (null != path) + if (path is not null) path.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); path = ManagementPath._Clone((ManagementPath)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -625,16 +625,16 @@ public ObjectGetOptions Options { get { - if (options == null) + if (options is null) return options = ObjectGetOptions._Clone(null); else return options; } set { - if (null != value) + if (value is not null) { - if (null != options) + if (options is not null) options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); options = ObjectGetOptions._Clone((ObjectGetOptions)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -774,12 +774,12 @@ public void Get() Initialize(false); // this may throw - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); else { ObjectGetOptions gOptions = - (null == options) ? new ObjectGetOptions() : options; + (options is null) ? new ObjectGetOptions() : options; SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; @@ -806,7 +806,7 @@ public void Get() } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } } @@ -896,9 +896,9 @@ public void Get(ManagementOperationObserver watcher) { Initialize(false); - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - else if (null == watcher) + else if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { @@ -926,7 +926,7 @@ public void Get(ManagementOperationObserver watcher) sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -1032,13 +1032,13 @@ public ManagementObjectCollection GetRelated( bool classDefinitionsOnly, EnumerationOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; - EnumerationOptions o = (null != options) ? options : new EnumerationOptions(); + EnumerationOptions o = (options is not null) ? options : new EnumerationOptions(); RelatedObjectQuery q = new RelatedObjectQuery( path.Path, relatedClass, @@ -1077,7 +1077,7 @@ public ManagementObjectCollection GetRelated( } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } @@ -1149,17 +1149,17 @@ public void GetRelated( bool classDefinitionsOnly, EnumerationOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); Initialize(true); - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { // Ensure we switch off ReturnImmediately as this is invalid for async calls - EnumerationOptions o = (null != options) + EnumerationOptions o = (options is not null) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); o.ReturnImmediately = false; @@ -1270,14 +1270,14 @@ public ManagementObjectCollection GetRelationships( bool classDefinitionsOnly, EnumerationOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = - (null != options) ? options : new EnumerationOptions(); + (options is not null) ? options : new EnumerationOptions(); RelationshipQuery q = new RelationshipQuery(path.Path, relationshipClass, relationshipQualifier, thisRole, classDefinitionsOnly); @@ -1311,7 +1311,7 @@ public ManagementObjectCollection GetRelationships( } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } @@ -1378,9 +1378,9 @@ public void GetRelationships( bool classDefinitionsOnly, EnumerationOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { @@ -1388,7 +1388,7 @@ public void GetRelationships( // Ensure we switch off ReturnImmediately as this is invalid for async calls EnumerationOptions o = - (null != options) ? (EnumerationOptions)options.Clone() : + (options is not null) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); o.ReturnImmediately = false; @@ -1418,7 +1418,7 @@ public void GetRelationships( sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -1465,7 +1465,7 @@ public ManagementPath Put(PutOptions options) { ManagementPath newPath = null; Initialize(true); - PutOptions o = (null != options) ? options : new PutOptions(); + PutOptions o = (options is not null) ? options : new PutOptions(); IWbemServices wbemServices = scope.GetIWbemServices(); @@ -1526,7 +1526,7 @@ public ManagementPath Put(PutOptions options) } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (ppwbemCallResult != IntPtr.Zero) // Cleanup from allocations above. @@ -1535,7 +1535,7 @@ public ManagementPath Put(PutOptions options) if (pwbemCallResult != IntPtr.Zero) Marshal.Release(pwbemCallResult); - if (wbemCallResult != null) + if (wbemCallResult is not null) Marshal.ReleaseComObject(wbemCallResult); } @@ -1581,13 +1581,13 @@ private ManagementPath GetPath(IWbemCallResult callResult) object pathValue = GetPropertyValue("__PATH"); // No path? Try Relpath? - if (pathValue != null) + if (pathValue is not null) newPath = new ManagementPath((string)pathValue); else { pathValue = GetPropertyValue("__RELPATH"); - if (pathValue != null) + if (pathValue is not null) { newPath = new ManagementPath(scope.Path.Path); newPath.RelativePath = (string)pathValue; @@ -1600,7 +1600,7 @@ private ManagementPath GetPath(IWbemCallResult callResult) { } - if (newPath == null) + if (newPath is null) newPath = new ManagementPath(); return newPath; @@ -1623,13 +1623,13 @@ public void Put(ManagementOperationObserver watcher) /// A used to specify additional options for the commit operation. public void Put(ManagementOperationObserver watcher, PutOptions options) { - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { Initialize(false); - PutOptions o = (null == options) ? + PutOptions o = (options is null) ? new PutOptions() : (PutOptions)options.Clone(); // If someone has registered for progress, make sure we flag it @@ -1669,7 +1669,7 @@ public void Put(ManagementOperationObserver watcher, PutOptions options) } - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -1761,7 +1761,7 @@ public ManagementPath CopyTo(ManagementPath path, PutOptions options) destinationScope = new ManagementScope(path, scope); destinationScope.Initialize(); - PutOptions o = (null != options) ? options : new PutOptions(); + PutOptions o = (options is not null) ? options : new PutOptions(); IWbemServices wbemServices = destinationScope.GetIWbemServices(); ManagementPath newPath = null; @@ -1829,7 +1829,7 @@ public ManagementPath CopyTo(ManagementPath path, PutOptions options) } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (ppwbemCallResult != IntPtr.Zero) // Cleanup from allocations above. @@ -1838,7 +1838,7 @@ public ManagementPath CopyTo(ManagementPath path, PutOptions options) if (pwbemCallResult != IntPtr.Zero) Marshal.Release(pwbemCallResult); - if (wbemCallResult != null) + if (wbemCallResult is not null) Marshal.ReleaseComObject(wbemCallResult); } @@ -1884,7 +1884,7 @@ public void CopyTo(ManagementOperationObserver watcher, string path, PutOptions /// The options for how the object should be put. public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, PutOptions options) { - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { @@ -1894,7 +1894,7 @@ public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, Put destinationScope = new ManagementScope(path, scope); destinationScope.Initialize(); - PutOptions o = (null != options) ? (PutOptions)options.Clone() : new PutOptions(); + PutOptions o = (options is not null) ? (PutOptions)options.Clone() : new PutOptions(); // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) @@ -1928,7 +1928,7 @@ public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, Put } - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -1962,11 +1962,11 @@ public void Delete() /// The options for how to delete the object. public void Delete(DeleteOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); Initialize(false); - DeleteOptions o = (null != options) ? options : new DeleteOptions(); + DeleteOptions o = (options is not null) ? options : new DeleteOptions(); IWbemServices wbemServices = scope.GetIWbemServices(); SecurityHandler securityHandler = null; @@ -2004,7 +2004,7 @@ public void Delete(DeleteOptions options) } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } } @@ -2026,14 +2026,14 @@ public void Delete(ManagementOperationObserver watcher) /// The options for how to delete the object. public void Delete(ManagementOperationObserver watcher, DeleteOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - else if (null == watcher) + else if (watcher is null) throw new ArgumentNullException(nameof(watcher)); else { Initialize(false); - DeleteOptions o = (null != options) ? (DeleteOptions)options.Clone() : new DeleteOptions(); + DeleteOptions o = (options is not null) ? (DeleteOptions)options.Clone() : new DeleteOptions(); // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) @@ -2063,7 +2063,7 @@ public void Delete(ManagementOperationObserver watcher, DeleteOptions options) } - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -2150,9 +2150,9 @@ public object InvokeMethod(string methodName, object[] args) { object result = null; - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - else if (null == methodName) + else if (methodName is null) throw new ArgumentNullException(nameof(methodName)); else { @@ -2195,11 +2195,11 @@ public void InvokeMethod( string methodName, object[] args) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - else if (null == watcher) + else if (watcher is null) throw new ArgumentNullException(nameof(watcher)); - else if (null == methodName) + else if (methodName is null) throw new ArgumentNullException(nameof(methodName)); else { @@ -2296,14 +2296,14 @@ public ManagementBaseObject InvokeMethod( { ManagementBaseObject outParameters = null; - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - else if (null == methodName) + else if (methodName is null) throw new ArgumentNullException(nameof(methodName)); else { Initialize(false); - InvokeMethodOptions o = (null != options) ? options : new InvokeMethodOptions(); + InvokeMethodOptions o = (options is not null) ? options : new InvokeMethodOptions(); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; @@ -2311,7 +2311,7 @@ public ManagementBaseObject InvokeMethod( { securityHandler = scope.GetSecurityHandler(); - IWbemClassObjectFreeThreaded inParams = (null == inParameters) ? null : inParameters.wbemObject; + IWbemClassObjectFreeThreaded inParams = (inParameters is null) ? null : inParameters.wbemObject; IWbemClassObjectFreeThreaded outParams = null; status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecMethod_( @@ -2332,12 +2332,12 @@ public ManagementBaseObject InvokeMethod( Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } - if (outParams != null) + if (outParams is not null) outParameters = new ManagementBaseObject(outParams); } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } } @@ -2362,16 +2362,16 @@ public void InvokeMethod( ManagementBaseObject inParameters, InvokeMethodOptions options) { - if ((null == path) || (path.Path.Length == 0)) + if ((path is null) || (path.Path.Length == 0)) throw new InvalidOperationException(); - else if (null == watcher) + else if (watcher is null) throw new ArgumentNullException(nameof(watcher)); - else if (null == methodName) + else if (methodName is null) throw new ArgumentNullException(nameof(methodName)); else { Initialize(false); - InvokeMethodOptions o = (null != options) ? + InvokeMethodOptions o = (options is not null) ? (InvokeMethodOptions)options.Clone() : new InvokeMethodOptions(); // If someone has registered for progress, make sure we flag it @@ -2387,7 +2387,7 @@ public void InvokeMethod( IWbemClassObjectFreeThreaded inParams = null; - if (null != inParameters) + if (inParameters is not null) inParams = inParameters.wbemObject; status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecMethodAsync_( @@ -2398,7 +2398,7 @@ public void InvokeMethod( inParams, sink.Stub); - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); if (status < 0) @@ -2448,18 +2448,18 @@ private void GetMethodParameters( inParametersClass = null; outParametersClass = null; - if (null == methodName) + if (methodName is null) throw new ArgumentNullException(nameof(methodName)); else { Initialize(false); // Do we have the class? - if (null == wmiClass) + if (wmiClass is null) { ManagementPath classPath = ClassPath; - if ((null == classPath) || !(classPath.IsClass)) + if ((classPath is null) || !(classPath.IsClass)) throw new InvalidOperationException(); else { @@ -2483,7 +2483,7 @@ private void GetMethodParameters( if (status >= 0) { // Hand out instances - if (inParametersClass != null) + if (inParametersClass is not null) { IWbemClassObjectFreeThreaded inParamsInstance = null; status = inParametersClass.SpawnInstance_(0, out inParamsInstance); @@ -2547,7 +2547,7 @@ public override object Clone() /// public override string ToString() { - if (null != path) + if (path is not null) return path.Path; else return ""; @@ -2569,7 +2569,7 @@ internal override void Initialize(bool getObject) // Make sure we have some kind of path if we get here. Note that // we don't use a set to the Path property since that would trigger // an IdentifierChanged event - if (null == path) + if (path is null) { path = new ManagementPath(); path.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); @@ -2579,7 +2579,7 @@ internal override void Initialize(bool getObject) if (!IsBound && (getObject == true)) needToGetObject = true; - if (null == scope) + if (scope is null) { // If our object has a valid namespace path, use that string nsPath = path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); @@ -2598,7 +2598,7 @@ internal override void Initialize(bool getObject) // Hook ourselves up to this scope for future change notifications scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); } - else if ((null == scope.Path) || scope.Path.IsEmpty) + else if ((scope.Path is null) || scope.Path.IsEmpty) { // We have a scope but an empty path - use the object's path or the default string nsPath = path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); @@ -2628,7 +2628,7 @@ internal override void Initialize(bool getObject) // Again we don't use the set to the Options property // since that would trigger an IdentifierChangedEvent and // force isBound=false. - if (null == options) + if (options is null) { options = new ObjectGetOptions(); options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); @@ -2685,7 +2685,7 @@ internal override void Initialize(bool getObject) } finally { - if (securityHandler != null) + if (securityHandler is not null) securityHandler.Reset(); } } @@ -2701,9 +2701,9 @@ private static void MapInParameters( { int status = (int)ManagementStatus.NoError; - if (null != inParamsClass) + if (inParamsClass is not null) { - if ((null != args) && (0 < args.Length)) + if ((args is not null) && (0 < args.Length)) { int maxIndex = args.GetUpperBound(0); int minIndex = args.GetLowerBound(0); @@ -2732,7 +2732,7 @@ private static void MapInParameters( if (status >= 0) { - if (null == propertyName) + if (propertyName is null) break; status = inParamsClass.GetPropertyQualifierSet_(propertyName, out qualifierSet); @@ -2785,9 +2785,9 @@ private static object MapOutParameters( int status = (int)ManagementStatus.NoError; - if (null != outParamsClass) + if (outParamsClass is not null) { - if ((null != args) && (0 < args.Length)) + if ((args is not null) && (0 < args.Length)) { maxIndex = args.GetUpperBound(0); minIndex = args.GetLowerBound(0); @@ -2816,7 +2816,7 @@ private static object MapOutParameters( if (status >= 0) { - if (null == propertyName) + if (propertyName is null) break; // Handle the result parameter separately diff --git a/src/libraries/System.Management/src/System/Management/ManagementObjectCollection.cs b/src/libraries/System.Management/src/System/Management/ManagementObjectCollection.cs index f99e91fd9f1c98..4cd28d027c638e 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObjectCollection.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObjectCollection.cs @@ -71,12 +71,12 @@ internal ManagementObjectCollection( EnumerationOptions options, IEnumWbemClassObject enumWbem) { - if (null != options) + if (options is not null) this.options = (EnumerationOptions)options.Clone(); else this.options = new EnumerationOptions(); - if (null != scope) + if (scope is not null) this.scope = (ManagementScope)scope.Clone(); else this.scope = ManagementScope._Clone(null); @@ -201,7 +201,7 @@ public void CopyTo(Array array, int index) if (isDisposed) throw new ObjectDisposedException(name); - if (null == array) + if (array is null) throw new ArgumentNullException(nameof(array)); if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) @@ -440,7 +440,7 @@ public void Dispose() { if (!isDisposed) { - if (null != enumWbem) + if (enumWbem is not null) { Marshal.ReleaseComObject(enumWbem); enumWbem = null; diff --git a/src/libraries/System.Management/src/System/Management/ManagementObjectSearcher.cs b/src/libraries/System.Management/src/System/Management/ManagementObjectSearcher.cs index d7b3a44ad27757..cba65f28e15065 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObjectSearcher.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObjectSearcher.cs @@ -206,12 +206,12 @@ public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query, Enumer { this.scope = ManagementScope._Clone(scope); - if (null != query) + if (query is not null) this.query = (ObjectQuery)query.Clone(); else this.query = new ObjectQuery(); - if (null != options) + if (options is not null) this.options = (EnumerationOptions)options.Clone(); else this.options = new EnumerationOptions(); @@ -250,7 +250,7 @@ public ManagementScope Scope } set { - if (null != value) + if (value is not null) scope = (ManagementScope)value.Clone(); else throw new ArgumentNullException(nameof(value)); @@ -276,7 +276,7 @@ public ObjectQuery Query } set { - if (null != value) + if (value is not null) query = (ObjectQuery)value.Clone(); else throw new ArgumentNullException(nameof(value)); @@ -297,7 +297,7 @@ public EnumerationOptions Options } set { - if (null != value) + if (value is not null) options = (EnumerationOptions)value.Clone(); else throw new ArgumentNullException(nameof(value)); @@ -333,8 +333,8 @@ public ManagementObjectCollection Get() //to find out whether this is a class enumeration or instance enumeration and call CreateInstanceEnum/ //CreateClassEnum appropriately, because with ExecQuery we can't do a deep enumeration. if ((query.GetType() == typeof(SelectQuery)) && - (((SelectQuery)query).Condition == null) && - (((SelectQuery)query).SelectedProperties == null) && + (((SelectQuery)query).Condition is null) && + (((SelectQuery)query).SelectedProperties is null) && (options.EnumerateDeep == true)) { //Need to make sure that we're not passing invalid flags to enumeration APIs. @@ -402,7 +402,7 @@ public ManagementObjectCollection Get() /// The watcher that raises events triggered by the operation. public void Get(ManagementOperationObserver watcher) { - if (null == watcher) + if (watcher is null) throw new ArgumentNullException(nameof(watcher)); Initialize(); @@ -426,8 +426,8 @@ public void Get(ManagementOperationObserver watcher) //to find out whether this is a class enumeration or instance enumeration and call CreateInstanceEnum/ //CreateClassEnum appropriately, because with ExecQuery we can't do a deep enumeration. if ((query.GetType() == typeof(SelectQuery)) && - (((SelectQuery)query).Condition == null) && - (((SelectQuery)query).SelectedProperties == null) && + (((SelectQuery)query).Condition is null) && + (((SelectQuery)query).SelectedProperties is null) && (options.EnumerateDeep == true)) { //Need to make sure that we're not passing invalid flags to enumeration APIs. @@ -486,7 +486,7 @@ public void Get(ManagementOperationObserver watcher) private void Initialize() { //If the query is not set yet we can't do it - if (null == query) + if (query is null) throw new InvalidOperationException(); //If we're not connected yet, this is the time to do it... @@ -494,7 +494,7 @@ private void Initialize() lock (this) #pragma warning restore CA2002 { - if (null == scope) + if (scope is null) scope = ManagementScope._Clone(null); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementOperationWatcher.cs b/src/libraries/System.Management/src/System/Management/ManagementOperationWatcher.cs index 94fd1f7fefd797..1a6b8742feb710 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementOperationWatcher.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementOperationWatcher.cs @@ -240,7 +240,7 @@ internal bool HaveListenersForProgress try { - if (Progress != null) + if (Progress is not null) result = ((Progress.GetInvocationList()).Length > 0); } catch @@ -422,7 +422,7 @@ internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs arg { try { - if (null != md) + if (md is not null) { foreach (Delegate d in md.GetInvocationList()) { diff --git a/src/libraries/System.Management/src/System/Management/ManagementOptions.cs b/src/libraries/System.Management/src/System/Management/ManagementOptions.cs index 42278c4f9b1719..4c5033c3740aa5 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementOptions.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementOptions.cs @@ -135,7 +135,7 @@ public abstract class ManagementOptions : ICloneable //Fires IdentifierChanged event internal void FireIdentifierChanged() { - if (IdentifierChanged != null) + if (IdentifierChanged is not null) IdentifierChanged(this, null); } @@ -167,7 +167,7 @@ public ManagementNamedValueCollection Context { get { - if (context == null) + if (context is null) return context = new ManagementNamedValueCollection(); else return context; @@ -176,12 +176,12 @@ public ManagementNamedValueCollection Context { ManagementNamedValueCollection oldContext = context; - if (null != value) + if (value is not null) context = (ManagementNamedValueCollection)value.Clone(); else context = new ManagementNamedValueCollection(); - if (null != oldContext) + if (oldContext is not null) oldContext.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object @@ -226,7 +226,7 @@ internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan time internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) { this.flags = flags; - if (context != null) + if (context is not null) this.Context = context; else this.context = null; @@ -236,7 +236,7 @@ internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan time internal IWbemContext GetContext() { - if (context != null) + if (context is not null) return context.GetContext(); else return null; @@ -566,7 +566,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new EnumerationOptions(newContext, Timeout, blockSize, Rewindable, @@ -718,7 +718,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new EventWatcherOptions(newContext, Timeout, blockSize); @@ -788,16 +788,16 @@ internal static ObjectGetOptions _Clone(ObjectGetOptions options, IdentifierChan { ObjectGetOptions optionsTmp; - if (options != null) + if (options is not null) optionsTmp = new ObjectGetOptions(options.context, options.timeout, options.UseAmendedQualifiers); else optionsTmp = new ObjectGetOptions(); // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. - if (handler != null) + if (handler is not null) optionsTmp.IdentifierChanged += handler; - else if (options != null) + else if (options is not null) optionsTmp.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); return optionsTmp; @@ -862,7 +862,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new ObjectGetOptions(newContext, Timeout, UseAmendedQualifiers); @@ -1022,7 +1022,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new PutOptions(newContext, Timeout, UseAmendedQualifiers, Type); @@ -1109,7 +1109,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new DeleteOptions(newContext, Timeout); @@ -1196,7 +1196,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new InvokeMethodOptions(newContext, Timeout); @@ -1296,7 +1296,7 @@ public class ConnectionOptions : ManagementOptions /// public string Locale { - get { return (null != locale) ? locale : string.Empty; } + get { return (locale is not null) ? locale : string.Empty; } set { if (locale != value) @@ -1348,9 +1348,9 @@ public string Password { set { - if (value != null) + if (value is not null) { - if (securePassword == null) + if (securePassword is null) { securePassword = new SecureString(); for (int i = 0; i < value.Length; i++) @@ -1373,7 +1373,7 @@ public string Password } else { - if (securePassword != null) + if (securePassword is not null) { securePassword.Dispose(); securePassword = null; @@ -1397,9 +1397,9 @@ public SecureString SecurePassword { set { - if (value != null) + if (value is not null) { - if (securePassword == null) + if (securePassword is null) { securePassword = value.Copy(); } @@ -1412,7 +1412,7 @@ public SecureString SecurePassword } else { - if (securePassword != null) + if (securePassword is not null) { securePassword.Dispose(); securePassword = null; @@ -1444,7 +1444,7 @@ public SecureString SecurePassword /// public string Authority { - get { return (null != authority) ? authority : string.Empty; } + get { return (authority is not null) ? authority : string.Empty; } set { if (authority != value) @@ -1581,13 +1581,13 @@ public ConnectionOptions(string locale, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { - if (locale != null) + if (locale is not null) this.locale = locale; this.username = username; this.enablePrivileges = enablePrivileges; - if (password != null) + if (password is not null) { this.securePassword = new SecureString(); for (int i = 0; i < password.Length; i++) @@ -1596,7 +1596,7 @@ public ConnectionOptions(string locale, } } - if (authority != null) + if (authority is not null) this.authority = authority; if (impersonation != 0) @@ -1625,18 +1625,18 @@ public ConnectionOptions(string locale, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { - if (locale != null) + if (locale is not null) this.locale = locale; this.username = username; this.enablePrivileges = enablePrivileges; - if (password != null) + if (password is not null) { this.securePassword = password.Copy(); } - if (authority != null) + if (authority is not null) this.authority = authority; if (impersonation != 0) @@ -1656,7 +1656,7 @@ public override object Clone() { ManagementNamedValueCollection newContext = null; - if (null != Context) + if (Context is not null) newContext = (ManagementNamedValueCollection)Context.Clone(); return new ConnectionOptions(locale, username, GetSecurePassword(), authority, impersonation, authentication, enablePrivileges, newContext, Timeout); @@ -1668,7 +1668,7 @@ public override object Clone() internal IntPtr GetPassword() { - if (securePassword != null) + if (securePassword is not null) { try { @@ -1684,7 +1684,7 @@ internal IntPtr GetPassword() } internal SecureString GetSecurePassword() { - if (securePassword != null) + if (securePassword is not null) return securePassword.Copy(); else return null; @@ -1703,7 +1703,7 @@ internal static ConnectionOptions _Clone(ConnectionOptions options, IdentifierCh { ConnectionOptions optionsTmp; - if (options != null) + if (options is not null) { optionsTmp = new ConnectionOptions(options.Context, options.Timeout, options.Flags); @@ -1712,14 +1712,14 @@ internal static ConnectionOptions _Clone(ConnectionOptions options, IdentifierCh optionsTmp.username = options.username; optionsTmp.enablePrivileges = options.enablePrivileges; - if (options.securePassword != null) + if (options.securePassword is not null) { optionsTmp.securePassword = options.securePassword.Copy(); } else optionsTmp.securePassword = null; - if (options.authority != null) + if (options.authority is not null) optionsTmp.authority = options.authority; if (options.impersonation != 0) @@ -1733,9 +1733,9 @@ internal static ConnectionOptions _Clone(ConnectionOptions options, IdentifierCh // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. - if (handler != null) + if (handler is not null) optionsTmp.IdentifierChanged += handler; - else if (options != null) + else if (options is not null) optionsTmp.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); return optionsTmp; diff --git a/src/libraries/System.Management/src/System/Management/ManagementPath.cs b/src/libraries/System.Management/src/System/Management/ManagementPath.cs index 8bcf9b545a23e5..f2d8ec2a84d1f8 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementPath.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementPath.cs @@ -83,7 +83,7 @@ public class ManagementPath : ICloneable //Fires IdentifierChanged event private void FireIdentifierChanged() { - if (IdentifierChanged != null) + if (IdentifierChanged is not null) IdentifierChanged(this, null); } @@ -100,7 +100,7 @@ internal static string GetManagementPath( string path = null; int status = (int)ManagementStatus.Failed; - if (null != wbemObject) + if (wbemObject is not null) { int dummy1 = 0, dummy2 = 0; object val = null; @@ -159,14 +159,14 @@ internal static ManagementPath _Clone(ManagementPath path, IdentifierChangedEven // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. - if (handler != null) + if (handler is not null) pathTmp.IdentifierChanged = handler; // Assign ManagementPath IWbemPath to this.wmiPath. // Optimization for performance : As long as the path is only read, we share this interface. // On the first write, a private copy will be needed; // isWbemPathShared signals ManagementPath to create such a copy at write-time. - if (path != null && path.wmiPath != null) + if (path is not null && path.wmiPath is not null) { pathTmp.wmiPath = path.wmiPath; pathTmp.isWbemPathShared = path.isWbemPathShared = true; @@ -190,7 +190,7 @@ public ManagementPath() : this((string)null) { } /// The object path. public ManagementPath(string path) { - if ((null != path) && (0 < path.Length)) + if ((path is not null) && (0 < path.Length)) wmiPath = CreateWbemPath(path); } @@ -256,7 +256,7 @@ private IWbemPath CreateWbemPath(string path) private void SetWbemPath(string path) { // Test/utilize isWbemPathShared *only* on public + internal members! - if (wmiPath == null) + if (wmiPath is null) wmiPath = CreateWbemPath(path); else SetWbemPath(wmiPath, path); @@ -264,7 +264,7 @@ private void SetWbemPath(string path) private static void SetWbemPath(IWbemPath wbemPath, string path) { - if (null != wbemPath) + if (wbemPath is not null) { uint flags = (uint)tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_CREATE_ACCEPT_ALL; @@ -295,7 +295,7 @@ private static string GetWbemPath(IWbemPath wbemPath) { string pathStr = string.Empty; - if (null != wbemPath) + if (wbemPath is not null) { // Requesting the path from a parser which has // been only given a relative path results in an incorrect @@ -351,12 +351,12 @@ private void ClearKeys(bool setAsSingleton) try { - if (null != wmiPath) + if (wmiPath is not null) { IWbemPathKeyList keyList = null; status = wmiPath.GetKeyList_(out keyList); - if (null != keyList) + if (keyList is not null) { status = keyList.RemoveAllKeys_(0); if ((status & 0x80000000) == 0) @@ -498,7 +498,7 @@ public string RelativePath { string pathStr = string.Empty; - if (null != wmiPath) + if (wmiPath is not null) { // Get the space we need to reserve uint bufLen = 0; @@ -562,7 +562,7 @@ internal void SetRelativePath(string relPath) //Used to update the relative path when the user changes any key properties internal void UpdateRelativePath(string relPath) { - if (relPath == null) + if (relPath is null) return; //Get the server & namespace part from the existing path, and concatenate the given relPath. @@ -601,7 +601,7 @@ public string Server { string pathStr = string.Empty; - if (null != wmiPath) + if (wmiPath is not null) { uint uLen = 0; @@ -636,7 +636,7 @@ public string Server // Only set if changed if (0 != string.Compare(oldValue, value, StringComparison.OrdinalIgnoreCase)) { - if (null == wmiPath) + if (wmiPath is null) wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath (); else if (isWbemPathShared) { @@ -669,14 +669,14 @@ internal string SetNamespacePath(string nsPath, out bool bChange) IWbemPath wmiPathTmp = null; bChange = false; - Debug.Assert(nsPath != null); + Debug.Assert(nsPath is not null); //Do some validation on the path to make sure it is a valid namespace path (at least syntactically) if (!IsValidNamespaceSyntax(nsPath)) ManagementException.ThrowWithExtendedInfo((ManagementStatus)tag_WBEMSTATUS.WBEM_E_INVALID_NAMESPACE); wmiPathTmp = CreateWbemPath(nsPath); - if (wmiPath == null) + if (wmiPath is null) wmiPath = this.CreateWbemPath(""); else if (isWbemPathShared) { @@ -793,7 +793,7 @@ internal static string GetNamespacePath(IWbemPath wbemPath, int flags) { string pathStr = string.Empty; - if (null != wbemPath) + if (wbemPath is not null) { // Requesting the namespace path from a parser which has // been only given a relative path results in an incorrect @@ -904,7 +904,7 @@ internal string internalClassName string pathStr = string.Empty; int status = (int)ManagementStatus.NoError; - if (null != wmiPath) + if (wmiPath is not null) { uint bufLen = 0; status = wmiPath.GetClassName_(ref bufLen, null); @@ -926,7 +926,7 @@ internal string internalClassName { int status = (int)ManagementStatus.NoError; - if (wmiPath == null) + if (wmiPath is null) wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath(); else if (isWbemPathShared) { @@ -966,7 +966,7 @@ public bool IsClass { get { - if (null == wmiPath) + if (wmiPath is null) return false; ulong uInfo = 0; @@ -995,7 +995,7 @@ public bool IsInstance { get { - if (null == wmiPath) + if (wmiPath is null) return false; ulong uInfo = 0; @@ -1024,7 +1024,7 @@ public bool IsSingleton { get { - if (null == wmiPath) + if (wmiPath is null) return false; ulong uInfo = 0; @@ -1098,7 +1098,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -1107,7 +1107,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { ManagementPath obj = ((ManagementPath)(value)); ConstructorInfo ctor = typeof(ManagementPath).GetConstructor(new Type[] { typeof(string) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { obj.Path }); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index 509b1cfd61df20..6e8548c7998163 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -31,7 +31,7 @@ public abstract class ManagementQuery : ICloneable //Fires IdentifierChanged event internal void FireIdentifierChanged() { - if (IdentifierChanged != null) + if (IdentifierChanged is not null) IdentifierChanged(this, null); } @@ -74,7 +74,7 @@ protected internal virtual void ParseQuery(string query) { } /// public virtual string QueryString { - get { return (null != queryString) ? queryString : string.Empty; } + get { return (queryString is not null) ? queryString : string.Empty; } set { if (queryString != value) @@ -96,7 +96,7 @@ public virtual string QueryString /// public virtual string QueryLanguage { - get { return (null != queryLanguage) ? queryLanguage : string.Empty; } + get { return (queryLanguage is not null) ? queryLanguage : string.Empty; } set { if (queryLanguage != value) @@ -125,7 +125,7 @@ internal static void ParseToken(ref string q, string token, string op, ref bool q = q.Remove(0, token.Length).TrimStart(null); // Next character should be the operator if any - if (op != null) + if (op is not null) { if (0 != q.IndexOf(op, StringComparison.Ordinal)) throw new ArgumentException(SR.InvalidQuery); // Invalid query @@ -656,7 +656,7 @@ public SelectQuery(string queryOrClassName) { selectedProperties = new StringCollection(); - if (null != queryOrClassName) + if (queryOrClassName is not null) { // Minimally determine if the string is a query or class name. // @@ -726,7 +726,7 @@ public SelectQuery(string className, string condition, string[] selectedProperti this.condition = condition; this.selectedProperties = new StringCollection(); - if (null != selectedProperties) + if (selectedProperties is not null) this.selectedProperties.AddRange(selectedProperties); BuildQuery(); @@ -844,7 +844,7 @@ public bool IsSchemaQuery /// public string ClassName { - get { return (null != className) ? className : string.Empty; } + get { return (className is not null) ? className : string.Empty; } set { className = value; BuildQuery(); FireIdentifierChanged(); } } @@ -863,7 +863,7 @@ public string ClassName /// public string Condition { - get { return (null != condition) ? condition : string.Empty; } + get { return (condition is not null) ? condition : string.Empty; } set { condition = value; BuildQuery(); FireIdentifierChanged(); } } @@ -885,7 +885,7 @@ public StringCollection SelectedProperties get { return selectedProperties; } set { - if (null != value) + if (value is not null) { // A tad painful since StringCollection doesn't support ICloneable StringCollection src = (StringCollection)value; @@ -915,17 +915,17 @@ protected internal void BuildQuery() { //If the class name is not set we can't build a query //Shouldn't throw here because the user may be in the process of filling in the properties... - if (className == null) + if (className is null) SetQueryString(string.Empty); - if ((className == null) || (className.Length == 0)) + if ((className is null) || (className.Length == 0)) return; //Select clause s = TokenSelect; //If properties are specified list them - if ((null != selectedProperties) && (0 < selectedProperties.Count)) + if ((selectedProperties is not null) && (0 < selectedProperties.Count)) { int count = selectedProperties.Count; @@ -946,7 +946,7 @@ protected internal void BuildQuery() } //Where clause - if ((Condition != null) && (Condition.Length != 0)) + if ((Condition is not null) && (Condition.Length != 0)) s = s + " where " + condition; //Set the queryString member to the built query (NB: note we set @@ -965,7 +965,7 @@ protected internal override void ParseQuery(string query) //Clear out previous property values className = null; condition = null; - if (selectedProperties != null) + if (selectedProperties is not null) selectedProperties.Clear(); //Trim whitespaces @@ -981,7 +981,7 @@ protected internal override void ParseQuery(string query) ParseToken(ref q, keyword, ref bFound); if (q[0] != '*') //we have properties { - if (null != selectedProperties) + if (selectedProperties is not null) selectedProperties.Clear(); else selectedProperties = new StringCollection(); @@ -1106,7 +1106,7 @@ public override object Clone() { string[] strArray = null; - if (null != selectedProperties) + if (selectedProperties is not null) { int count = selectedProperties.Count; @@ -1253,7 +1253,7 @@ public RelatedObjectQuery() : this(null) { } /// public RelatedObjectQuery(string queryOrSourceObject) { - if (null != queryOrSourceObject) + if (queryOrSourceObject is not null) { // Minimally determine if the string is a query or instance name. // @@ -1404,7 +1404,7 @@ public bool IsSchemaQuery /// public string SourceObject { - get { return (null != sourceObject) ? sourceObject : string.Empty; } + get { return (sourceObject is not null) ? sourceObject : string.Empty; } set { sourceObject = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1432,7 +1432,7 @@ public string SourceObject /// public string RelatedClass { - get { return (null != relatedClass) ? relatedClass : string.Empty; } + get { return (relatedClass is not null) ? relatedClass : string.Empty; } set { relatedClass = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1460,7 +1460,7 @@ public string RelatedClass /// public string RelationshipClass { - get { return (null != relationshipClass) ? relationshipClass : string.Empty; } + get { return (relationshipClass is not null) ? relationshipClass : string.Empty; } set { relationshipClass = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1478,7 +1478,7 @@ public string RelationshipClass /// public string RelatedQualifier { - get { return (null != relatedQualifier) ? relatedQualifier : string.Empty; } + get { return (relatedQualifier is not null) ? relatedQualifier : string.Empty; } set { relatedQualifier = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1496,7 +1496,7 @@ public string RelatedQualifier /// public string RelationshipQualifier { - get { return (null != relationshipQualifier) ? relationshipQualifier : string.Empty; } + get { return (relationshipQualifier is not null) ? relationshipQualifier : string.Empty; } set { relationshipQualifier = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1514,7 +1514,7 @@ public string RelationshipQualifier /// public string RelatedRole { - get { return (null != relatedRole) ? relatedRole : string.Empty; } + get { return (relatedRole is not null) ? relatedRole : string.Empty; } set { relatedRole = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1531,7 +1531,7 @@ public string RelatedRole /// public string ThisRole { - get { return (null != thisRole) ? thisRole : string.Empty; } + get { return (thisRole is not null) ? thisRole : string.Empty; } set { thisRole = value; BuildQuery(); FireIdentifierChanged(); } } @@ -1563,10 +1563,10 @@ protected internal void BuildQuery() { //If the source object is not set we can't build a query //Shouldn't throw here because the user may be in the process of filling in the properties... - if (sourceObject == null) + if (sourceObject is null) SetQueryString(string.Empty); - if ((sourceObject == null) || (sourceObject.Length == 0)) + if ((sourceObject is null) || (sourceObject.Length == 0)) return; //"associators" clause @@ -1881,7 +1881,7 @@ public RelationshipQuery() : this(null) { } /// public RelationshipQuery(string queryOrSourceObject) { - if (null != queryOrSourceObject) + if (queryOrSourceObject is not null) { // Minimally determine if the string is a query or instance name. // @@ -2014,7 +2014,7 @@ public bool IsSchemaQuery /// public string SourceObject { - get { return (null != sourceObject) ? sourceObject : string.Empty; } + get { return (sourceObject is not null) ? sourceObject : string.Empty; } set { sourceObject = value; BuildQuery(); FireIdentifierChanged(); } } @@ -2032,7 +2032,7 @@ public string SourceObject /// public string RelationshipClass { - get { return (null != relationshipClass) ? relationshipClass : string.Empty; } + get { return (relationshipClass is not null) ? relationshipClass : string.Empty; } set { relationshipClass = value; BuildQuery(); FireIdentifierChanged(); } } @@ -2050,7 +2050,7 @@ public string RelationshipClass /// public string RelationshipQualifier { - get { return (null != relationshipQualifier) ? relationshipQualifier : string.Empty; } + get { return (relationshipQualifier is not null) ? relationshipQualifier : string.Empty; } set { relationshipQualifier = value; BuildQuery(); FireIdentifierChanged(); } } @@ -2068,7 +2068,7 @@ public string RelationshipQualifier /// public string ThisRole { - get { return (null != thisRole) ? thisRole : string.Empty; } + get { return (thisRole is not null) ? thisRole : string.Empty; } set { thisRole = value; BuildQuery(); FireIdentifierChanged(); } } @@ -2098,10 +2098,10 @@ protected internal void BuildQuery() { //If the source object is not set we can't build a query //Shouldn't throw here because the user may be in the process of filling in the properties... - if (sourceObject == null) + if (sourceObject is null) SetQueryString(string.Empty); - if ((sourceObject == null) || (sourceObject.Length == 0)) + if ((sourceObject is null) || (sourceObject.Length == 0)) return; //"references" clause @@ -2474,7 +2474,7 @@ public WqlEventQuery(string queryOrEventClassName) { groupByPropertyList = new StringCollection(); - if (null != queryOrEventClassName) + if (queryOrEventClassName is not null) { // Minimally determine if the string is a query or event class name. // @@ -2694,7 +2694,7 @@ public WqlEventQuery(string eventClassName, TimeSpan withinInterval, string cond this.groupWithinInterval = groupWithinInterval; this.groupByPropertyList = new StringCollection(); - if (null != groupByPropertyList) + if (groupByPropertyList is not null) this.groupByPropertyList.AddRange(groupByPropertyList); this.havingCondition = havingCondition; @@ -2762,7 +2762,7 @@ public override string QueryString /// public string EventClassName { - get { return (null != eventClassName) ? eventClassName : string.Empty; } + get { return (eventClassName is not null) ? eventClassName : string.Empty; } set { eventClassName = value; BuildQuery(); } } @@ -2796,7 +2796,7 @@ public string EventClassName /// public string Condition { - get { return (null != condition) ? condition : string.Empty; } + get { return (condition is not null) ? condition : string.Empty; } set { condition = value; BuildQuery(); } } @@ -2953,7 +2953,7 @@ public StringCollection GroupByPropertyList /// public string HavingCondition { - get { return (null != havingCondition) ? havingCondition : string.Empty; } + get { return (havingCondition is not null) ? havingCondition : string.Empty; } set { havingCondition = value; BuildQuery(); } } @@ -2965,7 +2965,7 @@ protected internal void BuildQuery() { //If the event class name is not set we can't build a query //This shouldn't throw because the user may be in the process of setting properties... - if ((eventClassName == null) || (eventClassName.Length == 0)) + if ((eventClassName is null) || (eventClassName.Length == 0)) { SetQueryString(string.Empty); return; @@ -2991,7 +2991,7 @@ protected internal void BuildQuery() s = s + " group within " + groupWithinInterval.TotalSeconds.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(double))); //Group By clause - if ((null != groupByPropertyList) && (0 < groupByPropertyList.Count)) + if ((groupByPropertyList is not null) && (0 < groupByPropertyList.Count)) { int count = groupByPropertyList.Count; s = s + " by "; @@ -3025,7 +3025,7 @@ protected internal override void ParseQuery(string query) withinInterval = TimeSpan.Zero; condition = null; groupWithinInterval = TimeSpan.Zero; - if (groupByPropertyList != null) + if (groupByPropertyList is not null) groupByPropertyList.Clear(); havingCondition = null; @@ -3077,7 +3077,7 @@ protected internal override void ParseQuery(string query) if ((q.Length >= keyword.Length) && (0 == string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) { q = q.Remove(0, keyword.Length); - if (null != groupByPropertyList) + if (groupByPropertyList is not null) groupByPropertyList.Clear(); else groupByPropertyList = new StringCollection(); @@ -3148,7 +3148,7 @@ public override object Clone() { string[] strArray = null; - if (null != groupByPropertyList) + if (groupByPropertyList is not null) { int count = groupByPropertyList.Count; @@ -3221,7 +3221,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -3230,7 +3230,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { EventQuery obj = ((EventQuery)(value)); ConstructorInfo ctor = typeof(EventQuery).GetConstructor(new Type[] { typeof(string) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { obj.QueryString }); } @@ -3240,7 +3240,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { ObjectQuery obj = ((ObjectQuery)(value)); ConstructorInfo ctor = typeof(ObjectQuery).GetConstructor(new Type[] { typeof(string) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { obj.QueryString }); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementScope.cs b/src/libraries/System.Management/src/System/Management/ManagementScope.cs index 110abe48273b6e..d5a8c2d7d96e3c 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementScope.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementScope.cs @@ -48,7 +48,7 @@ private static bool GetSwitchValueFromRegistry() { s_switchesRegKey = Registry.LocalMachine.OpenSubKey(RegKeyLocation); - if (s_switchesRegKey == null) + if (s_switchesRegKey is null) { return false; } @@ -68,7 +68,7 @@ e is System.Threading.ThreadAbortException || finally { // dispose of the key - if (s_switchesRegKey != null) + if (s_switchesRegKey is not null) { s_switchesRegKey.Dispose(); } @@ -295,7 +295,7 @@ static WmiNetUtilsHelper() RegistryKey netFrameworkSubKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework\"); string netFrameworkInstallRoot = (string)netFrameworkSubKey?.GetValue("InstallRoot"); - if (netFrameworkInstallRoot == null) + if (netFrameworkInstallRoot is null) { // In some Windows versions, like Nano Server, the .NET Framework is not installed by default. // It is possible that general failure to access the registry get to this code branch but it is @@ -381,7 +381,7 @@ private static bool LoadDelegate(ref TDelegate delegate_f, IntPtr hMo { IntPtr procAddr = Interop.Kernel32.GetProcAddress(hModule, procName); return procAddr != IntPtr.Zero && - (delegate_f = Marshal.GetDelegateForFunctionPointer(procAddr)) != null; + (delegate_f = Marshal.GetDelegateForFunctionPointer(procAddr)) is not null; } private static void LoadPlatformNotSupportedDelegates(string exceptionMessage) @@ -494,7 +494,7 @@ public class ManagementScope : ICloneable //Fires IdentifierChanged event private void FireIdentifierChanged() { - if (IdentifierChanged != null) + if (IdentifierChanged is not null) IdentifierChanged(this, null); } @@ -524,7 +524,7 @@ private ManagementPath prvpath } set { - if (value != null) + if (value is not null) { string pathValue = value.Path; if (!ManagementPath.IsValidNamespaceSyntax(pathValue)) @@ -596,7 +596,7 @@ public bool IsConnected { get { - return (null != wbemServices); + return (wbemServices is not null); } } @@ -604,10 +604,10 @@ public bool IsConnected internal ManagementScope(ManagementPath path, IWbemServices wbemServices, ConnectionOptions options) { - if (null != path) + if (path is not null) this.Path = path; - if (null != options) + if (options is not null) { this.Options = options; } @@ -618,7 +618,7 @@ internal ManagementScope(ManagementPath path, IWbemServices wbemServices, } internal ManagementScope(ManagementPath path, ManagementScope scope) - : this(path, (null != scope) ? scope.options : null) { } + : this(path, (scope is not null) ? scope.options : null) { } internal static ManagementScope _Clone(ManagementScope scope) { @@ -631,13 +631,13 @@ internal static ManagementScope _Clone(ManagementScope scope, IdentifierChangedE // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the scope argument. - if (handler != null) + if (handler is not null) scopeTmp.IdentifierChanged = handler; - else if (scope != null) + else if (scope is not null) scopeTmp.IdentifierChanged = new IdentifierChangedEventHandler(scope.HandleIdentifierChange); // Set scope path. - if (scope == null) + if (scope is null) { // No path specified. Default. scopeTmp.prvpath = ManagementPath._Clone(ManagementPath.DefaultPath, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); @@ -648,7 +648,7 @@ internal static ManagementScope _Clone(ManagementScope scope, IdentifierChangedE } else { - if (scope.prvpath == null) + if (scope.prvpath is null) { // No path specified. Default. scopeTmp.prvpath = ManagementPath._Clone(ManagementPath.DefaultPath, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); @@ -662,7 +662,7 @@ internal static ManagementScope _Clone(ManagementScope scope, IdentifierChangedE } scopeTmp.wbemServices = scope.wbemServices; - if (scope.options != null) + if (scope.options is not null) scopeTmp.options = ConnectionOptions._Clone(scope.options, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); } @@ -767,12 +767,12 @@ public ManagementScope(string path, ConnectionOptions options) : this(new Manage /// public ManagementScope(ManagementPath path, ConnectionOptions options) { - if (null != path) + if (path is not null) this.prvpath = ManagementPath._Clone(path, new IdentifierChangedEventHandler(HandleIdentifierChange)); else this.prvpath = ManagementPath._Clone(null); - if (null != options) + if (options is not null) { this.options = ConnectionOptions._Clone(options, new IdentifierChangedEventHandler(HandleIdentifierChange)); } @@ -809,16 +809,16 @@ public ConnectionOptions Options { get { - if (options == null) + if (options is null) return options = ConnectionOptions._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); else return options; } set { - if (null != value) + if (value is not null) { - if (null != options) + if (options is not null) options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); options = ConnectionOptions._Clone((ConnectionOptions)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -850,16 +850,16 @@ public ManagementPath Path { get { - if (prvpath == null) + if (prvpath is null) return prvpath = ManagementPath._Clone(null); else return prvpath; } set { - if (null != value) + if (value is not null) { - if (null != prvpath) + if (prvpath is not null) prvpath.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); IsDefaulted = false; //someone is specifically setting the scope path so it's not defaulted any more @@ -932,7 +932,7 @@ public void Connect() internal void Initialize() { //If the path is not set yet we can't do it - if (null == prvpath) + if (prvpath is null) throw new InvalidOperationException(); @@ -970,7 +970,7 @@ private void InitializeGuts(object o) { ManagementScope threadParam = (ManagementScope)o; - if (null == threadParam.options) + if (threadParam.options is null) { threadParam.Options = new ConnectionOptions(); } @@ -978,7 +978,7 @@ private void InitializeGuts(object o) string nsPath = threadParam.prvpath.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); // If no namespace specified, fill in the default one - if ((null == nsPath) || (0 == nsPath.Length)) + if ((nsPath is null) || (0 == nsPath.Length)) { // NB: we use a special method to set the namespace // path here as we do NOT want to trigger an @@ -1068,7 +1068,7 @@ internal int NextAsync_(uint uCount, IWbemObjectSink pSink) internal int Clone_(ref IEnumWbemClassObject ppEnum) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.CloneEnumWbemClassObject_f( @@ -1103,7 +1103,7 @@ internal SecuredConnectHandler(ManagementScope theScope) internal int ConnectNSecureIWbemServices(string path, ref IWbemServices pServices) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { bool needToReset = false; IntPtr handle = IntPtr.Zero; @@ -1186,7 +1186,7 @@ internal int GetObjectAsync_(string strObjectPath, int lFlags, IWbemContext pCtx internal int PutClass_(IWbemClassObjectFreeThreaded pObject, int lFlags, IWbemContext pCtx, IntPtr ppCallResult) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.PutClassWmi_f(pObject, @@ -1224,7 +1224,7 @@ internal int DeleteClassAsync_(string strClass, int lFlags, IWbemContext pCtx, I internal int CreateClassEnum_(string strSuperClass, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.CreateClassEnumWmi_f(strSuperClass, @@ -1250,7 +1250,7 @@ internal int CreateClassEnumAsync_(string strSuperClass, int lFlags, IWbemContex internal int PutInstance_(IWbemClassObjectFreeThreaded pInst, int lFlags, IWbemContext pCtx, IntPtr ppCallResult) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.PutInstanceWmi_f(pInst, @@ -1289,7 +1289,7 @@ internal int DeleteInstanceAsync_(string strObjectPath, int lFlags, IWbemContext internal int CreateInstanceEnum_(string strFilter, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.CreateInstanceEnumWmi_f(strFilter, @@ -1315,7 +1315,7 @@ internal int CreateInstanceEnumAsync_(string strFilter, int lFlags, IWbemContext internal int ExecQuery_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.ExecQueryWmi_f(strQueryLanguage, @@ -1342,7 +1342,7 @@ internal int ExecQueryAsync_(string strQueryLanguage, string strQuery, int lFlag internal int ExecNotificationQuery_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) { int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); status = WmiNetUtilsHelper.ExecNotificationQueryWmi_f(strQueryLanguage, @@ -1390,7 +1390,7 @@ internal class SecurityHandler internal SecurityHandler(ManagementScope theScope) { this.scope = theScope; - if (null != scope) + if (scope is not null) { if (scope.Options.EnablePrivileges) { @@ -1405,7 +1405,7 @@ internal void Reset() { needToReset = false; - if (null != scope) + if (scope is not null) { WmiNetUtilsHelper.ResetSecurity_f(handle); } @@ -1416,7 +1416,7 @@ internal void Reset() internal void Secure(IWbemServices services) { - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); int status = WmiNetUtilsHelper.BlessIWbemServices_f @@ -1442,7 +1442,7 @@ internal void SecureIUnknown(object unknown) // In VNext, we should really change the implementation of WMINet_Utils.dll so that it has // a method which explicitly takes an IUnknown. We rely on the fact that the implementation // of BlessIWbemServices actually casts the first parameter to IUnknown before blessing - if (null != scope) + if (scope is not null) { IntPtr password = scope.Options.GetPassword(); int status = WmiNetUtilsHelper.BlessIWbemServicesObject_f @@ -1521,7 +1521,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) + if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } @@ -1530,7 +1530,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { ManagementScope obj = ((ManagementScope)(value)); ConstructorInfo ctor = typeof(ManagementScope).GetConstructor(new Type[] { typeof(string) }); - if (ctor != null) + if (ctor is not null) { return new InstanceDescriptor(ctor, new object[] { obj.Path.Path }); } diff --git a/src/libraries/System.Management/src/System/Management/Method.cs b/src/libraries/System.Management/src/System/Management/Method.cs index fd000d104d5e7f..cf31a509ddd36d 100644 --- a/src/libraries/System.Management/src/System/Management/Method.cs +++ b/src/libraries/System.Management/src/System/Management/Method.cs @@ -144,7 +144,7 @@ private void RefreshMethodInfo() /// public string Name { - get { return methodName != null ? methodName : ""; } + get { return methodName is not null ? methodName : ""; } } /// @@ -169,7 +169,7 @@ public ManagementBaseObject InParameters get { RefreshMethodInfo(); - return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams); + return (wmiInParams is null) ? null : new ManagementBaseObject(wmiInParams); } } @@ -196,7 +196,7 @@ public ManagementBaseObject OutParameters get { RefreshMethodInfo(); - return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams); + return (wmiOutParams is null) ? null : new ManagementBaseObject(wmiOutParams); } } @@ -244,7 +244,7 @@ public QualifierDataCollection Qualifiers { get { - if (qualifiers == null) + if (qualifiers is null) qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier); return qualifiers; } diff --git a/src/libraries/System.Management/src/System/Management/MethodSet.cs b/src/libraries/System.Management/src/System/Management/MethodSet.cs index 1219df1d895f2d..d3df5bbfedb6fd 100644 --- a/src/libraries/System.Management/src/System/Management/MethodSet.cs +++ b/src/libraries/System.Management/src/System/Management/MethodSet.cs @@ -86,7 +86,7 @@ public int Count if (status >= 0) { methodName = ""; // Condition primer to branch into the while loop. - while (methodName != null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) + while (methodName is not null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) { methodName = null; inParameters = null; outParameters = null; status = parent.wbemObject.NextMethod_(0, out methodName, out inParameters, out outParameters); @@ -264,7 +264,7 @@ internal MethodDataEnumerator(ManagementObject parent) if (status >= 0) { tempMethodName = ""; // Condition primer to branch into the while loop. - while (tempMethodName != null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) + while (tempMethodName is not null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) { tempMethodName = null; status = parent.wbemObject.NextMethod_(0, out tempMethodName, out inP, out outP); @@ -340,7 +340,7 @@ public virtual MethodData this[string methodName] { get { - if (null == methodName) + if (methodName is null) throw new ArgumentNullException(nameof(methodName)); return new MethodData(parent, methodName); @@ -425,9 +425,9 @@ public virtual void Add(string methodName, ManagementBaseObject inParameters, Ma if (parent.GetType() == typeof(ManagementObject)) //can't add methods to instance throw new InvalidOperationException(); - if (inParameters != null) + if (inParameters is not null) wbemIn = inParameters.wbemObject; - if (outParameters != null) + if (outParameters is not null) wbemOut = outParameters.wbemObject; int status = (int)ManagementStatus.Failed; diff --git a/src/libraries/System.Management/src/System/Management/Property.cs b/src/libraries/System.Management/src/System/Management/Property.cs index bac0155b51996b..4795ca8238b8e7 100644 --- a/src/libraries/System.Management/src/System/Management/Property.cs +++ b/src/libraries/System.Management/src/System/Management/Property.cs @@ -20,7 +20,7 @@ internal class ValueTypeSafety { public static object GetSafeObject(object theValue) { - if (null == theValue) + if (theValue is null) return null; else if (theValue.GetType().IsPrimitive) return ((IConvertible)theValue).ToType(typeof(object), null); @@ -121,7 +121,7 @@ private void RefreshPropertyInfo() /// public string Name { //doesn't change for this object so we don't need to refresh - get { return propertyName != null ? propertyName : ""; } + get { return propertyName is not null ? propertyName : ""; } } /// @@ -254,7 +254,7 @@ public QualifierDataCollection Qualifiers { get { - if (qualifiers == null) + if (qualifiers is null) qualifiers = new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier); return qualifiers; @@ -284,7 +284,7 @@ internal static object MapWmiValueToValue(object wmiValue, CimType type, bool is { object val = null; - if ((System.DBNull.Value != wmiValue) && (null != wmiValue)) + if ((System.DBNull.Value != wmiValue) && (wmiValue is not null)) { if (isArray) { @@ -376,7 +376,7 @@ internal static object MapValueToWmiValue(object val, CimType type, bool isArray { object wmiValue = System.DBNull.Value; CultureInfo culInfo = CultureInfo.InvariantCulture; - if (null != val) + if (val is not null) { if (isArray) { @@ -600,7 +600,7 @@ internal static object MapValueToWmiValue(object val, out bool isArray, out CimT isArray = false; type = 0; - if (null != val) + if (val is not null) { isArray = val.GetType().IsArray; Type valueType = val.GetType(); diff --git a/src/libraries/System.Management/src/System/Management/PropertySet.cs b/src/libraries/System.Management/src/System/Management/PropertySet.cs index 8e748bfcf913ad..24b1b686c9baac 100644 --- a/src/libraries/System.Management/src/System/Management/PropertySet.cs +++ b/src/libraries/System.Management/src/System/Management/PropertySet.cs @@ -128,7 +128,7 @@ public object SyncRoot /// The index from which to start copying. public void CopyTo(Array array, int index) { - if (null == array) + if (array is null) throw new ArgumentNullException(nameof(array)); if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) @@ -347,7 +347,7 @@ public virtual PropertyData this[string propertyName] { get { - if (null == propertyName) + if (propertyName is null) throw new ArgumentNullException(nameof(propertyName)); return new PropertyData(parent, propertyName); @@ -410,7 +410,7 @@ public virtual void Remove(string propertyName) /// public virtual void Add(string propertyName, object propertyValue) { - if (null == propertyValue) + if (propertyValue is null) throw new ArgumentNullException(nameof(propertyValue)); if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance @@ -449,7 +449,7 @@ public virtual void Add(string propertyName, object propertyValue) /// public void Add(string propertyName, object propertyValue, CimType propertyType) { - if (null == propertyName) + if (propertyName is null) throw new ArgumentNullException(nameof(propertyName)); if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance @@ -458,7 +458,7 @@ public void Add(string propertyName, object propertyValue, CimType propertyType) int wmiCimType = (int)propertyType; bool isArray = false; - if ((null != propertyValue) && propertyValue.GetType().IsArray) + if ((propertyValue is not null) && propertyValue.GetType().IsArray) { isArray = true; wmiCimType = (wmiCimType | (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY); @@ -491,7 +491,7 @@ public void Add(string propertyName, object propertyValue, CimType propertyType) /// public void Add(string propertyName, CimType propertyType, bool isArray) { - if (null == propertyName) + if (propertyName is null) throw new ArgumentNullException(propertyName); if (parent.GetType() == typeof(ManagementObject)) //can't add properties to instance diff --git a/src/libraries/System.Management/src/System/Management/Qualifier.cs b/src/libraries/System.Management/src/System/Management/Qualifier.cs index 5784fca1efe039..a01959c219697b 100644 --- a/src/libraries/System.Management/src/System/Management/Qualifier.cs +++ b/src/libraries/System.Management/src/System/Management/Qualifier.cs @@ -77,7 +77,7 @@ private void RefreshQualifierInfo() if ((status & 0x80000000) == 0) //success { qualifierValue = null; //Make sure it's null so that we don't leak ! - if (qualifierSet != null) + if (qualifierSet is not null) status = qualifierSet.Get_(qualifierName, 0, ref qualifierValue, ref qualifierFlavor); } @@ -92,7 +92,7 @@ private static object MapQualValueToWmiValue(object qualVal) { object wmiValue = System.DBNull.Value; - if (null != qualVal) + if (qualVal is not null) { if (qualVal is Array) { @@ -148,7 +148,7 @@ private static object MapQualValueToWmiValue(object qualVal) /// public string Name { - get { return qualifierName != null ? qualifierName : ""; } + get { return qualifierName is not null ? qualifierName : ""; } } /// diff --git a/src/libraries/System.Management/src/System/Management/QualifierSet.cs b/src/libraries/System.Management/src/System/Management/QualifierSet.cs index 528f244a8c1a92..a3aef81746724f 100644 --- a/src/libraries/System.Management/src/System/Management/QualifierSet.cs +++ b/src/libraries/System.Management/src/System/Management/QualifierSet.cs @@ -177,7 +177,7 @@ public object SyncRoot /// The index from which to start copying. public void CopyTo(Array array, int index) { - if (null == array) + if (array is null) throw new ArgumentNullException(nameof(array)); if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) @@ -410,7 +410,7 @@ public virtual QualifierData this[string qualifierName] { get { - if (null == qualifierName) + if (qualifierName is null) throw new ArgumentNullException(nameof(qualifierName)); return new QualifierData(parent, propertyOrMethodName, qualifierName, qualifierSetType); diff --git a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs index 56a515ca09cb90..c6432a68724e1d 100644 --- a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs +++ b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs @@ -166,7 +166,7 @@ public CodeTypeDeclaration GenerateCode(bool includeSystemProperties, bool syste public bool GenerateCode(CodeLanguage lang, string filePath, string netNamespace) { // check for proper arguments - if (filePath == null) + if (filePath is null) { throw new ArgumentOutOfRangeException(SR.NullFilePathException); } @@ -193,14 +193,14 @@ public bool GenerateCode(CodeLanguage lang, string filePath, string netNamespace /// private void CheckIfClassIsProperlyInitialized() { - if (classobj == null) + if (classobj is null) { - if (OriginalNamespace == null || (OriginalNamespace != null && OriginalNamespace.Length == 0)) + if (OriginalNamespace is null || (OriginalNamespace is not null && OriginalNamespace.Length == 0)) { throw new ArgumentOutOfRangeException(SR.NamespaceNotInitializedException); } - if (OriginalClassName == null || (OriginalClassName != null && OriginalClassName.Length == 0)) + if (OriginalClassName is null || (OriginalClassName is not null && OriginalClassName.Length == 0)) { throw new ArgumentOutOfRangeException(SR.ClassNameNotInitializedException); } @@ -260,10 +260,10 @@ private CodeTypeDeclaration GetCodeTypeDeclarationForClass(bool bIncludeSystemCl public string ManagementClassName { get { string strRet = CreatedClassName; - if (((PrivateLateBoundObject != null) - && (PrivateLateBoundObject.Path != null))) { + if (((PrivateLateBoundObject is not null) + && (PrivateLateBoundObject.Path is not null))) { strRet = ((string)(PrivateLateBoundObject["__CLASS"])); - if (((strRet == null) + if (((strRet is null) || (strRet.Length == 0))) { strRet = CreatedClassName; } @@ -519,7 +519,7 @@ private void InitializeClassObject() // If it fails then no point in continuing // If object is not initialized by the constructor - if (classobj == null) + if (classobj is null) { ManagementPath thePath; if (OriginalPath.Length != 0) @@ -681,7 +681,7 @@ private void InitilializePublicPrivateMembers() /// private void ProcessNamingCollisions() { - if (classobj.Properties != null) + if (classobj.Properties is not null) { foreach (PropertyData prop in classobj.Properties) { @@ -689,7 +689,7 @@ private void ProcessNamingCollisions() } } - if (classobj.Methods != null) + if (classobj.Methods is not null) { foreach (MethodData meth in classobj.Methods) { @@ -879,11 +879,11 @@ private void ProcessNamespaceAndClassName() // Try to get a type from any of the namespace which are used in the generated code and see if // it collides with any of the standard classes. - if (Type.GetType("System." + strClass) != null || - Type.GetType("System.ComponentModel." + strClass) != null || - Type.GetType("System.Management." + strClass) != null || - Type.GetType("System.Collections." + strClass) != null || - Type.GetType("System.Globalization." + strClass) != null) + if (Type.GetType("System." + strClass) is not null || + Type.GetType("System.ComponentModel." + strClass) is not null || + Type.GetType("System.Management." + strClass) is not null || + Type.GetType("System.Collections." + strClass) is not null || + Type.GetType("System.Globalization." + strClass) is not null) { PublicNamesUsed.Add(strClass, strClass); strClass = ResolveCollision(strClass, true); @@ -957,7 +957,7 @@ private void GeneratePublicReadOnlyProperty(string propName, string propType, ob cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(propValue))); } cc.Members.Add(cmp); - if (Comment != null && Comment.Length != 0) + if (Comment is not null && Comment.Length != 0) { 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 (Comment is not null && Comment.Length != 0) { cmp.Comments.Add(new CodeCommentStatement(Comment)); } @@ -1284,7 +1284,7 @@ private void GenerateProperties() [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IsNull { get { - if ((PrivateLateBoundObject[] == null)) { + if ((PrivateLateBoundObject[] is null)) { return true; } else { @@ -1329,7 +1329,7 @@ private void GenerateProperties() } else { - //if ((curObj[""] == null)) + //if ((curObj[""] is null)) //{ // return (()(System.Convert.ToInt32(0))); //} @@ -1343,7 +1343,7 @@ private void GenerateProperties() } else { - // if ((curObj[""] == null)) + // if ((curObj[""] is null)) //{ // return System.Convert.(0); //} @@ -1641,7 +1641,7 @@ private string ProcessPropertyQualifiers(PropertyData prop, ref bool bRead, ref //Now check whether the type of the property is int if (isTypeInt(prop.Type) == true) { - if (q.Value != null) + if (q.Value is not null) { string[] strArray = (string[])q.Value; for (int i = 0; i < strArray.Length; i++) @@ -1676,7 +1676,7 @@ private string ProcessPropertyQualifiers(PropertyData prop, ref bool bRead, ref Values.Clear(); if (isTypeInt(prop.Type) == true) { - if (q.Value != null) + if (q.Value is not null) { ArrayList arTemp = new ArrayList(5); string[] strArray = (string[])q.Value; @@ -1709,7 +1709,7 @@ private string ProcessPropertyQualifiers(PropertyData prop, ref bool bRead, ref BitMap.Clear(); if (isTypeInt(prop.Type) == true) { - if (q.Value != null) + if (q.Value is not null) { string[] strArray = (string[])q.Value; for (int i = 0; i < strArray.Length; i++) @@ -1738,7 +1738,7 @@ private string ProcessPropertyQualifiers(PropertyData prop, ref bool bRead, ref BitValues.Clear(); if (isTypeInt(prop.Type) == true) { - if (q.Value != null) + if (q.Value is not null) { ArrayList arTemp = new ArrayList(5); string[] strArray = (string[])q.Value; @@ -2794,9 +2794,9 @@ private void GenerateMethods() bStatic = false; MethodData meth = classobj.Methods[PublicMethods.GetKey(k).ToString()]; string strTemp = PrivateNamesUsed["LateBoundObject"].ToString(); - if (meth.OutParameters != null) + if (meth.OutParameters is not null) { - if (meth.OutParameters.Properties != null) + if (meth.OutParameters.Properties is not null) { //First Populate the out Params name so that we can find in/out parameters foreach (PropertyData prop in meth.OutParameters.Properties) @@ -2893,10 +2893,10 @@ private void GenerateMethods() } //Do these things only when there is a valid InParameters - if (meth.InParameters != null) + if (meth.InParameters is not null) { //Now put the in parameters - if (meth.InParameters.Properties != null) + if (meth.InParameters.Properties is not null) { foreach (PropertyData prop in meth.InParameters.Properties) { @@ -2992,9 +2992,9 @@ private void GenerateMethods() CodeMethodInvokeExpression cmie2 = null; //Do these only when the outParams is Valid - if (meth.OutParameters != null) + if (meth.OutParameters is not null) { - if (meth.OutParameters.Properties != null) + if (meth.OutParameters.Properties is not null) { foreach (PropertyData prop in meth.OutParameters.Properties) { @@ -3394,7 +3394,7 @@ private void GenerateGetInstancesWithWhereProperties() /// This is a static method. The output is like this /// public static (ObjectCollection)GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) /// { - /// if ((mgmtScope == null)) + /// if ((mgmtScope is null)) /// { /// mgmtScope = new System.Management.ManagementScope(); /// mgmtScope.Path.NamespacePath = "root\\CimV2"; @@ -3403,7 +3403,7 @@ private void GenerateGetInstancesWithWhereProperties() /// pathObj.ClassName = "CIM_LogicalDisk"; /// pathObj.NamespacePath = "root\\CimV2"; /// System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - /// if ((enumOptions == null)) + /// if ((enumOptions is null)) /// { /// enumOptions = new System.Management.EnumerationOptions(); /// enumOptions.EnsureLocatable = true; @@ -3580,7 +3580,7 @@ private void GenerateGetInstancesWithScopeProperties() /// /// This function generates the code like /// public static ServiceCollection GetInstances(ManagementScope scope,String Condition, String[] selectedProperties) { - /// if (scope == null) + /// if (scope is null) /// { /// scope = new ManagementScope(); /// scope.Path.NamespacePath = WMINamespace; @@ -3704,13 +3704,13 @@ private void GeneratePrivateMember(string memberName, string MemberType, CodeExp cf.Attributes = cf.Attributes | MemberAttributes.Static; } cf.Type = new CodeTypeReference(MemberType); - if (initExpression != null && isStatic == true) + if (initExpression is not null && isStatic == true) { cf.InitExpression = initExpression; } cc.Members.Add(cf); - if (Comment != null && Comment.Length != 0) + if (Comment is not null && Comment.Length != 0) { cf.Comments.Add(new CodeCommentStatement(Comment)); } @@ -4012,7 +4012,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co if ( baseType.BaseType == typeof(System.Enum) ) { if (value.GetType() == destinationType) return value; - if ((value == null) && (context != null) + if ((value is null) && (context is not null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) { return "NULL_ENUM_VALUE"; @@ -4022,7 +4022,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co if ( (baseType == typeof(System.Boolean)) && (baseType.BaseType == typeof(System.ValueType)) ) { - if ((value == null) && (context != null) + if ((value is null) && (context is not null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) { return ""; @@ -4030,7 +4030,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co return baseConverter.ConvertTo(context, culture, value, destinationType); } - if ((context != null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) + if ((context is not null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) { return ""; } @@ -4077,7 +4077,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co // true statements: /* if (value.GetType() == destinationType) return value; - if ((value == null) && (context != null) + if ((value is null) && (context is not null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) { return "NULL_ENUM_VALUE"; @@ -4151,7 +4151,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co /* true statements - if ((value == null) && (context != null) + if ((value is null) && (context is not null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) { return ""; @@ -4192,7 +4192,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co // add the condition statement to the method and work on the next condition section cmm.Statements.Add(cis); /* - if ((context != null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) + if ((context is not null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false)) { return ""; } @@ -4856,10 +4856,10 @@ private bool InitializeCodeGenerator(CodeLanguage lang) assemblyName.Version = curAssemblyName.Version; asm = Assembly.Load(assemblyName); //asm = Assembly.LoadWithPartialName("VJSharpCodeProvider"); - if (asm != null) + if (asm is not null) { codeProvType = asm.GetType("Microsoft.VJSharp.VJSharpCodeProvider"); - if (codeProvType != null) + if (codeProvType is not null) { cp = (System.CodeDom.Compiler.CodeDomProvider)Activator.CreateInstance(codeProvType); bSucceeded = true; @@ -4878,10 +4878,10 @@ private bool InitializeCodeGenerator(CodeLanguage lang) assemblyName.Version = new Version(VSVERSION); asm = Assembly.Load(assemblyName); - if (asm != null) + if (asm is not null) { codeProvType = asm.GetType("Microsoft.VisualC.CppCodeProvider"); - if (codeProvType != null) + if (codeProvType is not null) { cp = (System.CodeDom.Compiler.CodeDomProvider)Activator.CreateInstance(codeProvType); bSucceeded = true; @@ -5609,7 +5609,7 @@ private void GenerateCodeForRefAndDateTimeTypes(CodeIndexerExpression prop, bool cmie = new CodeMethodInvokeExpression(); cmie.Method = cmre; - if (varToAssign == null) + if (varToAssign is null) { cis1.TrueStatements.Add(new CodeMethodReturnStatement(CreateObjectForProperty(strType, cmie))); statColl.Add(cis1); @@ -5637,7 +5637,7 @@ private void GenerateCodeForRefAndDateTimeTypes(CodeIndexerExpression prop, bool ce = new CodeCastExpression(new CodeTypeReference("System.String"), prop); } - if (varToAssign == null) + if (varToAssign is null) { cis1.TrueStatements.Add(new CodeMethodReturnStatement(CreateObjectForProperty(strType, ce))); cis1.FalseStatements.Add(new CodeMethodReturnStatement(CreateObjectForProperty(strType, null))); @@ -5752,7 +5752,7 @@ private void GenerateCodeForRefAndDateTimeTypes(CodeIndexerExpression prop, bool new CodeVariableReferenceExpression(strnCtr)), CreateObjectForProperty(strType, cmie2))); cis1.TrueStatements.Add(cfls); - if (varToAssign == null) + if (varToAssign is null) { cis1.TrueStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(strArray))); statColl.Add(cis1); @@ -5775,7 +5775,7 @@ private void GenerateCodeForRefAndDateTimeTypes(CodeIndexerExpression prop, bool /// private void AddPropertySet(CodeIndexerExpression prop, bool bArray, CodeStatementCollection statColl, string strType, CodeVariableReferenceExpression varValue) { - if (varValue == null) + if (varValue is null) { varValue = new CodeVariableReferenceExpression("value"); } @@ -5879,7 +5879,7 @@ private CodeExpression CreateObjectForProperty(string strType, CodeExpression pa switch (strType) { case "System.DateTime": - if (param == null) + if (param is null) { return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"), "MinValue"); } @@ -5892,7 +5892,7 @@ private CodeExpression CreateObjectForProperty(string strType, CodeExpression pa } case "System.TimeSpan": - if (param == null) + if (param is null) { coce = new CodeObjectCreateExpression(); coce.CreateType = new CodeTypeReference("System.TimeSpan"); @@ -7372,7 +7372,7 @@ private void AddToTimeSpanFunction() cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int64"), ticks, new CodePrimitiveExpression(0))); /* - if (dmtfTimespan == null) + if (dmtfTimespan is null) { throw new System.ArgumentOutOfRangeException(); } diff --git a/src/libraries/System.Management/src/System/Management/WmiEventSink.cs b/src/libraries/System.Management/src/System/Management/WmiEventSink.cs index d70cc2c39a1e69..e61be57c82a5ed 100644 --- a/src/libraries/System.Management/src/System/Management/WmiEventSink.cs +++ b/src/libraries/System.Management/src/System/Management/WmiEventSink.cs @@ -72,7 +72,7 @@ protected WmiEventSink(ManagementOperationObserver watcher, this.className = className; this.isLocal = false; - if (null != path) + if (path is not null) { this.path = new ManagementPath(path); if ((0 == string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase)) || @@ -82,10 +82,10 @@ protected WmiEventSink(ManagementOperationObserver watcher, } } - if (null != scope) + if (scope is not null) { this.scope = (ManagementScope)scope.Clone(); - if (null == path) // use scope to see if sink is local + if (path is null) // use scope to see if sink is local { if ((0 == string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) || (0 == string.Compare(this.scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase))) @@ -112,7 +112,7 @@ public IWbemObjectSink Stub { try { - return (null != stub) ? (IWbemObjectSink)stub : null; + return (stub is not null) ? (IWbemObjectSink)stub : null; } catch { @@ -152,15 +152,15 @@ public void SetStatus( if (flags == (int)tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE) { // Is this a Put? If so fire the ObjectPut event - if (null != path) + if (path is not null) { - if (null == className) + if (className is null) path.RelativePath = message; else path.RelativePath = className; // Fire the internal event (if anyone is interested) - if (null != InternalObjectPut) + if (InternalObjectPut is not null) { try { @@ -176,7 +176,7 @@ public void SetStatus( // Fire Completed event CompletedEventArgs args2 = null; - if (errObj != null) + if (errObj is not null) { args2 = new CompletedEventArgs(context, hResult, new ManagementBaseObject(errObj) @@ -222,7 +222,7 @@ internal void ReleaseStub() * We force a release of the stub here so as to allow * unsecapp.exe to die as soon as possible. */ - if (null != stub) + if (stub is not null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(stub); stub = null; @@ -288,7 +288,7 @@ public override void Indicate(IntPtr pIWbemClassObject) { Marshal.AddRef(pIWbemClassObject); IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject); - if (null != managementObject) + if (managementObject is not null) { try { diff --git a/src/libraries/System.Memory/src/System/Buffers/ArrayMemoryPool.ArrayMemoryPoolBuffer.cs b/src/libraries/System.Memory/src/System/Buffers/ArrayMemoryPool.ArrayMemoryPoolBuffer.cs index 0d6769b100bf45..3d8de5b5c33490 100644 --- a/src/libraries/System.Memory/src/System/Buffers/ArrayMemoryPool.ArrayMemoryPoolBuffer.cs +++ b/src/libraries/System.Memory/src/System/Buffers/ArrayMemoryPool.ArrayMemoryPoolBuffer.cs @@ -19,7 +19,7 @@ public Memory Memory get { T[]? array = _array; - if (array == null) + if (array is null) { ThrowHelper.ThrowObjectDisposedException_ArrayMemoryPoolBuffer(); } @@ -31,7 +31,7 @@ public Memory Memory public void Dispose() { T[]? array = _array; - if (array != null) + if (array is not null) { _array = null; ArrayPool.Shared.Return(array); diff --git a/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs b/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs index 05c89507316afb..a040f3e08cb6d1 100644 --- a/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs +++ b/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs @@ -43,7 +43,7 @@ public static class BuffersExtensions { return source.GetPosition(index, result); } - else if (position.GetObject() == null) + else if (position.GetObject() is null) { break; } @@ -85,7 +85,7 @@ private static void CopyToMultiSegment(in ReadOnlySequence sequence, Span< { ReadOnlySpan span = memory.Span; span.CopyTo(destination); - if (position.GetObject() != null) + if (position.GetObject() is not null) { destination = destination.Slice(span.Length); } diff --git a/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.Helpers.cs b/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.Helpers.cs index 4bd3eadb22fa7b..fde5a0c43eaddb 100644 --- a/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.Helpers.cs +++ b/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.Helpers.cs @@ -17,7 +17,7 @@ internal bool TryGetBuffer(in SequencePosition position, out ReadOnlyMemory m object? positionObject = position.GetObject(); next = default; - if (positionObject == null) + if (positionObject is null) { memory = default; return false; @@ -38,7 +38,7 @@ internal bool TryGetBuffer(in SequencePosition position, out ReadOnlyMemory m { ReadOnlySequenceSegment? nextSegment = startSegment.Next; - if (nextSegment == null) + if (nextSegment is null) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); next = new SequencePosition(nextSegment, 0); @@ -83,7 +83,7 @@ private ReadOnlyMemory GetFirstBuffer() { object? startObject = _startObject; - if (startObject == null) + if (startObject is null) return default; int startIndex = _startInteger; @@ -159,7 +159,7 @@ private ReadOnlySpan GetFirstSpan() { object? startObject = _startObject; - if (startObject == null) + if (startObject is null) return default; int startIndex = _startInteger; @@ -242,7 +242,7 @@ internal SequencePosition Seek(long offset, ExceptionArgument exceptionArgument if (startObject != endObject) { - Debug.Assert(startObject != null); + Debug.Assert(startObject is not null); var startSegment = (ReadOnlySequenceSegment)startObject; int currentLength = startSegment.Memory.Length - startIndex; @@ -278,7 +278,7 @@ private SequencePosition Seek(in SequencePosition start, long offset) if (startObject != endObject) { - Debug.Assert(startObject != null); + Debug.Assert(startObject is not null); var startSegment = (ReadOnlySequenceSegment)startObject; int currentLength = startSegment.Memory.Length - startIndex; @@ -307,10 +307,10 @@ private SequencePosition Seek(in SequencePosition start, long offset) [MethodImpl(MethodImplOptions.NoInlining)] private static SequencePosition SeekMultiSegment(ReadOnlySequenceSegment? currentSegment, object endObject, int endIndex, long offset, ExceptionArgument argument) { - Debug.Assert(currentSegment != null); // currentSegment parameter is marked as nullable as the parameter is reused/reassigned in the body + Debug.Assert(currentSegment is not null); // currentSegment parameter is marked as nullable as the parameter is reused/reassigned in the body Debug.Assert(offset >= 0); - while (currentSegment != null && currentSegment != endObject) + while (currentSegment is not null && currentSegment != endObject) { int memoryLength = currentSegment.Memory.Length; @@ -324,7 +324,7 @@ private static SequencePosition SeekMultiSegment(ReadOnlySequenceSegment? cur } // Hit the end of the segments but didn't reach the count - if (currentSegment == null || endIndex < offset) + if (currentSegment is null || endIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(argument); FoundSegment: @@ -357,7 +357,7 @@ private void BoundsCheck(in SequencePosition position, bool positionIsNotNull) long runningIndex = 0; if (positionIsNotNull) { - Debug.Assert(position.GetObject() != null); + Debug.Assert(position.GetObject() is not null); runningIndex = ((ReadOnlySequenceSegment)position.GetObject()!).RunningIndex; } @@ -400,12 +400,12 @@ private void BoundsCheck(uint sliceStartIndex, object? sliceStartObject, uint sl ulong sliceStartRange = sliceStartIndex; ulong sliceEndRange = sliceEndIndex; - if (sliceStartObject != null) + if (sliceStartObject is not null) { sliceStartRange += (ulong)((ReadOnlySequenceSegment)sliceStartObject).RunningIndex; } - if (sliceEndObject != null) + if (sliceEndObject is not null) { sliceEndRange += (ulong)((ReadOnlySequenceSegment)sliceEndObject).RunningIndex; } @@ -522,7 +522,7 @@ internal bool TryGetReadOnlySequenceSegment([NotNullWhen(true)] out ReadOnlySequ object? startObject = _startObject; // Default or not MultiSegment - if (startObject == null || GetSequenceType() != SequenceType.MultiSegment) + if (startObject is null || GetSequenceType() != SequenceType.MultiSegment) { startSegment = null; startIndex = 0; @@ -531,7 +531,7 @@ internal bool TryGetReadOnlySequenceSegment([NotNullWhen(true)] out ReadOnlySequ return false; } - Debug.Assert(_endObject != null); + Debug.Assert(_endObject is not null); startSegment = (ReadOnlySequenceSegment)startObject; startIndex = GetIndex(_startInteger); @@ -548,7 +548,7 @@ internal bool TryGetArray(out ArraySegment segment) return false; } - Debug.Assert(_startObject != null); + Debug.Assert(_startObject is not null); int startIndex = GetIndex(_startInteger); segment = new ArraySegment((T[])_startObject, startIndex, GetIndex(_endInteger) - startIndex); @@ -565,7 +565,7 @@ internal bool TryGetString([NotNullWhen(true)] out string? text, out int start, return false; } - Debug.Assert(_startObject != null); + Debug.Assert(_startObject is not null); start = GetIndex(_startInteger); length = GetIndex(_endInteger) - start; @@ -638,7 +638,7 @@ internal void GetFirstSpan(out ReadOnlySpan first, out SequencePosition next) object? startObject = _startObject; int startIndex = _startInteger; - if (startObject != null) + if (startObject is not null) { bool hasMultipleSegments = startObject != _endObject; int endIndex = _endInteger; diff --git a/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.cs b/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.cs index 1953fb08c14967..335ec3211b1ca8 100644 --- a/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.cs +++ b/src/libraries/System.Memory/src/System/Buffers/ReadOnlySequence.cs @@ -80,8 +80,8 @@ private ReadOnlySequence(object? startSegment, int startIndexAndFlags, object? e // Used by SliceImpl to create new ReadOnlySequence // startSegment and endSegment can be null for default ReadOnlySequence only - Debug.Assert((startSegment != null && endSegment != null) || - (startSegment == null && endSegment == null && startIndexAndFlags == 0 && endIndexAndFlags == 0)); + Debug.Assert((startSegment is not null && endSegment is not null) || + (startSegment is null && endSegment is null && startIndexAndFlags == 0 && endIndexAndFlags == 0)); _startObject = startSegment; _endObject = endSegment; @@ -95,8 +95,8 @@ private ReadOnlySequence(object? startSegment, int startIndexAndFlags, object? e /// public ReadOnlySequence(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment, int endIndex) { - if (startSegment == null || - endSegment == null || + if (startSegment is null || + endSegment is null || (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) || (uint)startSegment.Memory.Length < (uint)startIndex || (uint)endSegment.Memory.Length < (uint)endIndex || @@ -114,7 +114,7 @@ public ReadOnlySequence(ReadOnlySequenceSegment startSegment, int startIndex, /// public ReadOnlySequence(T[] array) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _startObject = array; @@ -128,7 +128,7 @@ public ReadOnlySequence(T[] array) /// public ReadOnlySequence(T[] array, int start, int length) { - if (array == null || + if (array is null || (uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentValidationException(array, start); @@ -204,7 +204,7 @@ public ReadOnlySequence Slice(long start, long length) if (startObject != endObject) { - Debug.Assert(startObject != null); + Debug.Assert(startObject is not null); var startSegment = (ReadOnlySequenceSegment)startObject; int currentLength = startSegment.Memory.Length - startIndex; @@ -229,7 +229,7 @@ public ReadOnlySequence Slice(long start, long length) if (beginObject != endObject) { - Debug.Assert(beginObject != null); + Debug.Assert(beginObject is not null); end = GetEndPosition((ReadOnlySequenceSegment)beginObject, beginObject, beginIndex, endObject!, endIndex, length); } else @@ -278,7 +278,7 @@ public ReadOnlySequence Slice(long start, SequencePosition end) uint sliceEndIndex = (uint)GetIndex(end); object? sliceEndObject = end.GetObject(); - if (sliceEndObject == null) + if (sliceEndObject is null) { sliceEndObject = _startObject; sliceEndIndex = startIndex; @@ -355,7 +355,7 @@ public ReadOnlySequence Slice(SequencePosition start, long length) uint sliceStartIndex = (uint)GetIndex(start); object? sliceStartObject = start.GetObject(); - if (sliceStartObject == null) + if (sliceStartObject is null) { sliceStartIndex = startIndex; sliceStartObject = _startObject; @@ -465,7 +465,7 @@ public ReadOnlySequence Slice(SequencePosition start, SequencePosition end) [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySequence Slice(SequencePosition start) { - bool positionIsNotNull = start.GetObject() != null; + bool positionIsNotNull = start.GetObject() is not null; BoundsCheck(start, positionIsNotNull); return SliceImpl(positionIsNotNull ? start : Start); } @@ -534,7 +534,7 @@ public SequencePosition GetPosition(long offset) public long GetOffset(SequencePosition position) { object? positionSequenceObject = position.GetObject(); - bool positionIsNull = positionSequenceObject == null; + bool positionIsNull = positionSequenceObject is null; BoundsCheck(position, !positionIsNull); object? startObject = _startObject; @@ -559,14 +559,14 @@ public long GetOffset(SequencePosition position) // Verify position validity, this is not covered by BoundsCheck for Multi-Segment Sequence // BoundsCheck for Multi-Segment Sequence check only validity inside current sequence but not for SequencePosition validity. // For single segment position bound check is implicit. - Debug.Assert(positionSequenceObject != null); + Debug.Assert(positionSequenceObject is not null); if (((ReadOnlySequenceSegment)positionSequenceObject).Memory.Length - positionIndex < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); // Multi-Segment Sequence ReadOnlySequenceSegment? currentSegment = (ReadOnlySequenceSegment?)startObject; - while (currentSegment != null && currentSegment != positionSequenceObject) + while (currentSegment is not null && currentSegment != positionSequenceObject) { currentSegment = currentSegment.Next!; } @@ -639,7 +639,7 @@ public Enumerator(in ReadOnlySequence sequence) /// public bool MoveNext() { - if (_next.GetObject() == null) + if (_next.GetObject() is null) { return false; } diff --git a/src/libraries/System.Memory/src/System/ThrowHelper.cs b/src/libraries/System.Memory/src/System/ThrowHelper.cs index 23a1ced8b478d3..625443ef7541af 100644 --- a/src/libraries/System.Memory/src/System/ThrowHelper.cs +++ b/src/libraries/System.Memory/src/System/ThrowHelper.cs @@ -68,9 +68,9 @@ public static void ThrowArgumentValidationException(ReadOnlySequenceSegment(ReadOnlySequenceSegment? startSegment, int startIndex, ReadOnlySequenceSegment? endSegment) { - if (startSegment == null) + if (startSegment is null) return CreateArgumentNullException(ExceptionArgument.startSegment); - else if (endSegment == null) + else if (endSegment is null) return CreateArgumentNullException(ExceptionArgument.endSegment); else if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) return CreateArgumentOutOfRangeException(ExceptionArgument.endSegment); @@ -86,7 +86,7 @@ public static void ThrowArgumentValidationException(Array? array, int start) private static Exception CreateArgumentValidationException(Array? array, int start) { - if (array == null) + if (array is null) return CreateArgumentNullException(ExceptionArgument.array); else if ((uint)start > (uint)array.Length) return CreateArgumentOutOfRangeException(ExceptionArgument.start); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs index 908b5bc1566786..dad8692a4051e3 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs @@ -14,7 +14,7 @@ public static partial class HttpClientJsonExtensions { public static Task GetFromJsonAsync(this HttpClient client, string? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } @@ -25,7 +25,7 @@ public static partial class HttpClientJsonExtensions public static Task GetFromJsonAsync(this HttpClient client, Uri? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } @@ -36,7 +36,7 @@ public static partial class HttpClientJsonExtensions public static Task GetFromJsonAsync(this HttpClient client, string? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } @@ -47,7 +47,7 @@ public static partial class HttpClientJsonExtensions public static Task GetFromJsonAsync(this HttpClient client, Uri? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs index 86d91add941cb0..26d9f2cd71ba7b 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs @@ -11,7 +11,7 @@ public static partial class HttpClientJsonExtensions { public static Task PostAsJsonAsync(this HttpClient client, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } @@ -22,7 +22,7 @@ public static Task PostAsJsonAsync(this HttpClient public static Task PostAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs index 0550254318a233..9df7a364edfcaf 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs @@ -11,7 +11,7 @@ public static partial class HttpClientJsonExtensions { public static Task PutAsJsonAsync(this HttpClient client, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } @@ -22,7 +22,7 @@ public static Task PutAsJsonAsync(this HttpClient c public static Task PutAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs index 5457a1b65a7b87..e76095243b0dd5 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs @@ -13,7 +13,7 @@ public static partial class HttpContentJsonExtensions { public static Task ReadFromJsonAsync(this HttpContent content, Type type, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -25,7 +25,7 @@ public static partial class HttpContentJsonExtensions public static Task ReadFromJsonAsync(this HttpContent content, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -40,7 +40,7 @@ public static partial class HttpContentJsonExtensions Stream contentStream = await ReadHttpContentStreamAsync(content, cancellationToken).ConfigureAwait(false); // Wrap content stream into a transcoding stream that buffers the data transcoded from the sourceEncoding to utf-8. - if (sourceEncoding != null && sourceEncoding != Encoding.UTF8) + if (sourceEncoding is not null && sourceEncoding != Encoding.UTF8) { contentStream = GetTranscodingStream(contentStream, sourceEncoding); } @@ -56,7 +56,7 @@ public static partial class HttpContentJsonExtensions Stream contentStream = await ReadHttpContentStreamAsync(content, cancellationToken).ConfigureAwait(false); // Wrap content stream into a transcoding stream that buffers the data transcoded from the sourceEncoding to utf-8. - if (sourceEncoding != null && sourceEncoding != Encoding.UTF8) + if (sourceEncoding is not null && sourceEncoding != Encoding.UTF8) { contentStream = GetTranscodingStream(contentStream, sourceEncoding); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs index cdd1472cd4e42d..8320443321d829 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs @@ -27,12 +27,12 @@ private static MediaTypeHeaderValue DefaultMediaType private JsonContent(object? inputValue, Type inputType, MediaTypeHeaderValue? mediaType, JsonSerializerOptions? options) { - if (inputType == null) + if (inputType is null) { throw new ArgumentNullException(nameof(inputType)); } - if (inputValue != null && !inputType.IsAssignableFrom(inputValue.GetType())) + if (inputValue is not null && !inputType.IsAssignableFrom(inputValue.GetType())) { throw new ArgumentException(SR.Format(SR.SerializeWrongType, inputType, inputValue.GetType())); } @@ -63,7 +63,7 @@ private async Task SerializeToStreamAsyncCore(Stream targetStream, bool async, C Encoding? targetEncoding = GetEncoding(Headers.ContentType?.CharSet); // Wrap provided stream into a transcoding stream that buffers the data transcoded from utf-8 to the targetEncoding. - if (targetEncoding != null && targetEncoding != Encoding.UTF8) + if (targetEncoding is not null && targetEncoding != Encoding.UTF8) { #if NETCOREAPP Stream transcodingStream = Encoding.CreateTranscodingStream(targetStream, targetEncoding, Encoding.UTF8, leaveOpen: true); @@ -131,7 +131,7 @@ private async Task SerializeToStreamAsyncCore(Stream targetStream, bool async, C { Encoding? encoding = null; - if (charset != null) + if (charset is not null) { try { @@ -150,7 +150,7 @@ private async Task SerializeToStreamAsyncCore(Stream targetStream, bool async, C throw new InvalidOperationException(SR.CharSetInvalid, e); } - Debug.Assert(encoding != null); + Debug.Assert(encoding is not null); } return encoding; diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs index 894ea8c7860cd6..64c81fa94bdab1 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs @@ -69,7 +69,7 @@ public override int Read(byte[] buffer, int offset, int count) public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -151,7 +151,7 @@ private async Task ReadAsyncCore(ArraySegment readBuffer, Cancellatio Debug.Assert(readBuffer.Count < overflowBytes); _overflowBuffer.Array.AsSpan(0, readBuffer.Count).CopyTo(readBuffer); - Debug.Assert(_overflowBuffer.Array != null); + Debug.Assert(_overflowBuffer.Array is not null); _overflowBuffer = new ArraySegment(_overflowBuffer.Array, readBuffer.Count, overflowBytes - readBuffer.Count); @@ -164,7 +164,7 @@ private async Task ReadInputChars(CancellationToken cancellationToken) { // If we had left-over bytes from a previous read, move it to the start of the buffer and read content into // the segment that follows. - Debug.Assert(_byteBuffer.Array != null); + Debug.Assert(_byteBuffer.Array is not null); Buffer.BlockCopy(_byteBuffer.Array, _byteBuffer.Offset, _byteBuffer.Array, 0, _byteBuffer.Count); int offset = _byteBuffer.Count; @@ -174,8 +174,8 @@ private async Task ReadInputChars(CancellationToken cancellationToken) _byteBuffer = new ArraySegment(_byteBuffer.Array, 0, offset + bytesRead); - Debug.Assert(_byteBuffer.Array != null); - Debug.Assert(_charBuffer.Array != null); + Debug.Assert(_byteBuffer.Array is not null); + Debug.Assert(_charBuffer.Array is not null); Debug.Assert(_charBuffer.Count == 0, "We should only expect to read more input chars once all buffered content is read"); _decoder.Convert(_byteBuffer.Array, _byteBuffer.Offset, _byteBuffer.Count, _charBuffer.Array, charIndex: 0, _charBuffer.Array.Length, @@ -208,15 +208,15 @@ protected override void Dispose(bool disposing) { _disposed = true; - Debug.Assert(_charBuffer.Array != null); + Debug.Assert(_charBuffer.Array is not null); ArrayPool.Shared.Return(_charBuffer.Array); _charBuffer = default; - Debug.Assert(_byteBuffer.Array != null); + Debug.Assert(_byteBuffer.Array is not null); ArrayPool.Shared.Return(_byteBuffer.Array); _byteBuffer = default; - Debug.Assert(_overflowBuffer.Array != null); + Debug.Assert(_overflowBuffer.Array is not null); ArrayPool.Shared.Return(_overflowBuffer.Array); _overflowBuffer = default; diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs index 51c73d00634c39..f0dc2176eae558 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs @@ -68,7 +68,7 @@ public override void Write(byte[] buffer, int offset, int count) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs index eb11b2f14aa8bb..7a55ed71930e8d 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs @@ -17,7 +17,7 @@ internal sealed class NoWriteNoSeekStreamContent : HttpContent internal NoWriteNoSeekStreamContent(Stream content) { - Debug.Assert(content != null); + Debug.Assert(content is not null); Debug.Assert(content.CanRead); Debug.Assert(!content.CanWrite); Debug.Assert(!content.CanSeek); @@ -35,7 +35,7 @@ protected override #endif Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); if (_contentConsumed) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs index 5407ccdf9b476f..ccdc55749a5d86 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs @@ -66,7 +66,7 @@ public void CheckResponseForAuthentication( switch (statusCode) { case HttpStatusCode.Unauthorized: - if (state.ServerCredentials == null || state.LastStatusCode == HttpStatusCode.Unauthorized) + if (state.ServerCredentials is null || state.LastStatusCode == HttpStatusCode.Unauthorized) { // Either we don't have server credentials or we already tried // to set the credentials and it failed before. @@ -121,10 +121,10 @@ public void CheckResponseForAuthentication( state.LastStatusCode = statusCode; // If we don't have any proxy credentials to try, then we end up with 407. - ICredentials proxyCreds = state.Proxy == null ? + ICredentials proxyCreds = state.Proxy is null ? state.DefaultProxyCredentials : state.Proxy.Credentials; - if (proxyCreds == null) + if (proxyCreds is null) { break; } @@ -179,7 +179,7 @@ public void PreAuthenticateRequest(WinHttpRequestState state, uint proxyAuthSche { ICredentials proxyCredentials; Uri proxyUri; - if (state.Proxy != null) + if (state.Proxy is not null) { proxyCredentials = state.Proxy.Credentials; proxyUri = state.Proxy.GetProxy(state.RequestMessage.RequestUri); @@ -238,7 +238,7 @@ public bool GetServerCredentialsFromCache( foreach (uint authScheme in s_authSchemePriorityOrder) { cred = _credentialCache.GetCredential(uri, s_authSchemeStringMapping[authScheme]); - if (cred != null) + if (cred is not null) { serverAuthScheme = authScheme; serverCredentials = cred; @@ -257,7 +257,7 @@ public void SaveServerCredentialsToCache(Uri uri, uint authScheme, ICredentials Debug.Assert(!string.IsNullOrEmpty(authType)); NetworkCredential cred = serverCredentials.GetCredential(uri, authType); - if (cred != null) + if (cred is not null) { lock (_credentialCacheLock) { @@ -306,14 +306,14 @@ private bool SetWinHttpCredential( string userName; string password; - Debug.Assert(credentials != null); + Debug.Assert(credentials is not null); Debug.Assert(authScheme != 0); Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY || authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER); NetworkCredential networkCredential = credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]); - if (networkCredential == null) + if (networkCredential is null) { return false; } @@ -369,12 +369,12 @@ private bool SetWinHttpCredential( private static uint ChooseAuthScheme(uint supportedSchemes, Uri uri, ICredentials credentials) { - if (credentials == null) + if (credentials is null) { return 0; } - if (uri == null && !(credentials is NetworkCredential)) + if (uri is null && !(credentials is NetworkCredential)) { // https://github.com/dotnet/runtime/issues/16737. // If the credentials are a NetworkCredential, the uri isn't used when calling .GetCredential() since @@ -385,7 +385,7 @@ private static uint ChooseAuthScheme(uint supportedSchemes, Uri uri, ICredential foreach (uint authScheme in s_authSchemePriorityOrder) { - if ((supportedSchemes & authScheme) != 0 && credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]) != null) + if ((supportedSchemes & authScheme) != 0 && credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]) is not null) { return authScheme; } diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs index 67b2f99fcadaf4..3d0e2cecdccc34 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs @@ -57,7 +57,7 @@ public override int Size public override string ToString() { - if (_cachedToString == null && !IsInvalid) + if (_cachedToString is null && !IsInvalid) { var bytes = new byte[_size]; Marshal.Copy(this.handle, bytes, 0, _size); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCookieContainerAdapter.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCookieContainerAdapter.cs index ff0ac8798aeed4..e864d34b7fbdaf 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCookieContainerAdapter.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCookieContainerAdapter.cs @@ -20,7 +20,7 @@ public static void AddResponseCookiesToContainer(WinHttpRequestState state) CookieContainer cookieContainer = state.Handler.CookieContainer; Debug.Assert(state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer); - Debug.Assert(cookieContainer != null); + Debug.Assert(cookieContainer is not null); // Get 'Set-Cookie' headers from response. char[] buffer = null; @@ -82,7 +82,7 @@ public static string GetCookieHeader(Uri uri, CookieContainer cookies) { string cookieHeader = null; - Debug.Assert(cookies != null); + Debug.Assert(cookies is not null); string cookieValues = cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookieValues)) diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs index b8d859e615b84f..32d5866b9245cf 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs @@ -251,7 +251,7 @@ public X509Certificate2Collection ClientCertificates throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual")); } - if (_clientCertificates == null) + if (_clientCertificates is null) { _clientCertificates = new X509Certificate2Collection(); } @@ -478,7 +478,7 @@ public IDictionary Properties { get { - if (_properties == null) + if (_properties is null) { _properties = new Dictionary(); } @@ -494,7 +494,7 @@ protected override void Dispose(bool disposing) { _disposed = true; - if (disposing && _sessionHandle != null) + if (disposing && _sessionHandle is not null) { SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle); } @@ -507,24 +507,24 @@ protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } // Check for invalid combinations of properties. - if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) + if (_proxy is not null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) { throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy); } - if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null) + if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy is null) { throw new InvalidOperationException(SR.net_http_invalid_proxy); } if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer && - _cookieContainer == null) + _cookieContainer is null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } @@ -568,7 +568,7 @@ private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage) requestMessage.Headers.TransferEncodingChunked.Value; HttpContent requestContent = requestMessage.Content; - if (requestContent != null) + if (requestContent is not null) { if (requestContent.Headers.ContentLength.HasValue) { @@ -612,7 +612,7 @@ private static void AddRequestHeaders( // Get a StringBuilder to use for creating the request headers. // We cache one in TLS to avoid creating a new one for each request. StringBuilder requestHeadersBuffer = t_requestHeadersBuilder; - if (requestHeadersBuffer != null) + if (requestHeadersBuffer is not null) { requestHeadersBuffer.Clear(); } @@ -642,7 +642,7 @@ private static void AddRequestHeaders( } // Manually add cookies. - if (cookies != null && cookies.Count > 0) + if (cookies is not null && cookies.Count > 0) { string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies); if (!string.IsNullOrEmpty(cookieHeader)) @@ -655,7 +655,7 @@ private static void AddRequestHeaders( requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString()); // Serialize entity-body (content) headers. - if (requestMessage.Content != null) + if (requestMessage.Content is not null) { // TODO https://github.com/dotnet/runtime/issues/16162: // Content-Length header isn't getting correctly placed using ToString() @@ -683,11 +683,11 @@ private static void AddRequestHeaders( private void EnsureSessionHandleExists(WinHttpRequestState state) { - if (_sessionHandle == null) + if (_sessionHandle is null) { lock (_lockObject) { - if (_sessionHandle == null) + if (_sessionHandle is null) { SafeWinHttpHandle sessionHandle; uint accessType; @@ -697,7 +697,7 @@ private void EnsureSessionHandleExists(WinHttpRequestState state) // since that object is only a sentinel. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { - Debug.Assert(state.Proxy != null); + Debug.Assert(state.Proxy is not null); try { state.Proxy.GetProxy(state.RequestMessage.RequestUri); @@ -875,7 +875,7 @@ private async Task StartRequestAsync(WinHttpRequestState state) await InternalSendRequestAsync(state); - if (state.RequestMessage.Content != null) + if (state.RequestMessage.Content is not null) { await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false); } @@ -1032,7 +1032,7 @@ private void SetRequestHandleProxyOptions(WinHttpRequestState state) try { - if (state.Proxy != null) + if (state.Proxy is not null) { Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy); updateProxySettings = true; @@ -1048,7 +1048,7 @@ private void SetRequestHandleProxyOptions(WinHttpRequestState state) proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString); } } - else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed) + else if (_proxyHelper is not null && _proxyHelper.AutoSettingsUsed) { if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo)) { @@ -1152,7 +1152,7 @@ private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle) // we need to have WinHTTP ignore some errors so that the callback method // will have a chance to be called. uint optionData; - if (_serverCertificateValidationCallback != null) + if (_serverCertificateValidationCallback is not null) { optionData = Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA | @@ -1186,7 +1186,7 @@ private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestH clientCertificate = CertificateHelper.GetEligibleClientCertificate(); } - if (clientCertificate != null) + if (clientCertificate is not null) { SetWinHttpOption( requestHandle, @@ -1274,7 +1274,7 @@ private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle) private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion) { - Debug.Assert(requestHandle != null); + Debug.Assert(requestHandle is not null); uint optionData = (requestVersion == HttpVersion20) ? Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2 : 0; if (Interop.WinHttp.WinHttpSetOption( requestHandle, @@ -1291,7 +1291,7 @@ private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Versi private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData) { - Debug.Assert(handle != null); + Debug.Assert(handle is not null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, @@ -1307,7 +1307,7 @@ private static void SetWinHttpOption( IntPtr optionData, uint optionSize) { - Debug.Assert(handle != null); + Debug.Assert(handle is not null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs index 3b2212ec42aa7a..5c532dc94c1255 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs @@ -41,7 +41,7 @@ public static void WinHttpCallback( } WinHttpRequestState state = WinHttpRequestState.FromIntPtr(context); - Debug.Assert(state != null, "WinHttpCallback must have a non-null state object"); + Debug.Assert(state is not null, "WinHttpCallback must have a non-null state object"); RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength); } @@ -110,7 +110,7 @@ private static void RequestCallback( catch (Exception ex) { state.SavedException = ex; - if (state.RequestHandle != null) + if (state.RequestHandle is not null) { // Since we got a fatal error processing the request callback, // we need to close the WinHttp request handle in order to @@ -127,7 +127,7 @@ private static void RequestCallback( private static void OnRequestHandleClosing(WinHttpRequestState state) { - Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null"); + Debug.Assert(state is not null, "OnRequestSendRequestComplete: state is null"); // This is the last notification callback that WinHTTP will send. Therefore, we can // now explicitly dispose the state object which will free its corresponding GCHandle. @@ -137,22 +137,22 @@ private static void OnRequestHandleClosing(WinHttpRequestState state) private static void OnRequestSendRequestComplete(WinHttpRequestState state) { - Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null"); - Debug.Assert(state.LifecycleAwaitable != null, "OnRequestSendRequestComplete: LifecycleAwaitable is null"); + Debug.Assert(state is not null, "OnRequestSendRequestComplete: state is null"); + Debug.Assert(state.LifecycleAwaitable is not null, "OnRequestSendRequestComplete: LifecycleAwaitable is null"); state.LifecycleAwaitable.SetResult(1); } private static void OnRequestDataAvailable(WinHttpRequestState state, int bytesAvailable) { - Debug.Assert(state != null, "OnRequestDataAvailable: state is null"); + Debug.Assert(state is not null, "OnRequestDataAvailable: state is null"); state.LifecycleAwaitable.SetResult(bytesAvailable); } private static void OnRequestReadComplete(WinHttpRequestState state, uint bytesRead) { - Debug.Assert(state != null, "OnRequestReadComplete: state is null"); + Debug.Assert(state is not null, "OnRequestReadComplete: state is null"); // If we read to the end of the stream and we're using 'Content-Length' semantics on the response body, // then verify we read at least the number of bytes required. @@ -174,8 +174,8 @@ private static void OnRequestReadComplete(WinHttpRequestState state, uint bytesR private static void OnRequestWriteComplete(WinHttpRequestState state) { - Debug.Assert(state != null, "OnRequestWriteComplete: state is null"); - Debug.Assert(state.TcsInternalWriteDataToRequestStream != null, "TcsInternalWriteDataToRequestStream is null"); + Debug.Assert(state is not null, "OnRequestWriteComplete: state is null"); + Debug.Assert(state.TcsInternalWriteDataToRequestStream is not null, "TcsInternalWriteDataToRequestStream is null"); Debug.Assert(!state.TcsInternalWriteDataToRequestStream.Task.IsCompleted, "TcsInternalWriteDataToRequestStream.Task is completed"); state.TcsInternalWriteDataToRequestStream.TrySetResult(true); @@ -183,16 +183,16 @@ private static void OnRequestWriteComplete(WinHttpRequestState state) private static void OnRequestReceiveResponseHeadersComplete(WinHttpRequestState state) { - Debug.Assert(state != null, "OnRequestReceiveResponseHeadersComplete: state is null"); - Debug.Assert(state.LifecycleAwaitable != null, "LifecycleAwaitable is null"); + Debug.Assert(state is not null, "OnRequestReceiveResponseHeadersComplete: state is null"); + Debug.Assert(state.LifecycleAwaitable is not null, "LifecycleAwaitable is null"); state.LifecycleAwaitable.SetResult(1); } private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri) { - Debug.Assert(state != null, "OnRequestRedirect: state is null"); - Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null"); + Debug.Assert(state is not null, "OnRequestRedirect: state is null"); + Debug.Assert(redirectUri is not null, "OnRequestRedirect: redirectUri is null"); // If we're manually handling cookies, we need to reset them based on the new URI. if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) @@ -232,8 +232,8 @@ private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri private static void OnRequestSendingRequest(WinHttpRequestState state) { - Debug.Assert(state != null, "OnRequestSendingRequest: state is null"); - Debug.Assert(state.RequestHandle != null, "OnRequestSendingRequest: state.RequestHandle is null"); + Debug.Assert(state is not null, "OnRequestSendingRequest: state is null"); + Debug.Assert(state.RequestHandle is not null, "OnRequestSendingRequest: state.RequestHandle is null"); if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https) { @@ -245,7 +245,7 @@ private static void OnRequestSendingRequest(WinHttpRequestState state) // the TransportContext object. state.TransportContext.SetChannelBinding(state.RequestHandle); - if (state.ServerCertificateValidationCallback != null) + if (state.ServerCertificateValidationCallback is not null) { IntPtr certHandle = IntPtr.Zero; uint certHandleSize = (uint)IntPtr.Size; @@ -307,7 +307,7 @@ private static void OnRequestSendingRequest(WinHttpRequestState state) } finally { - if (chain != null) + if (chain is not null) { chain.Dispose(); } @@ -325,7 +325,7 @@ private static void OnRequestSendingRequest(WinHttpRequestState state) private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { - Debug.Assert(state != null, "OnRequestError: state is null"); + Debug.Assert(state is not null, "OnRequestError: state is null"); if (NetEventSource.Log.IsEnabled()) WinHttpTraceHelper.TraceAsyncError(state, asyncResult); @@ -350,7 +350,7 @@ private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WI // (which means we have no certs to send). For security reasons, we don't // allow the certificate to be re-applied. But we need to tell WinHttp // explicitly that we don't have any certificate to send. - Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null"); + Debug.Assert(state.RequestHandle is not null, "OnRequestError: state.RequestHandle is null"); WinHttpHandler.SetNoClientCertificate(state.RequestHandle); state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs index 93595b1d12af63..92bc191dc9307e 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs @@ -85,7 +85,7 @@ public void ClearSendRequestState() ServerCredentials = null; DefaultProxyCredentials = null; - if (RequestHandle != null) + if (RequestHandle is not null) { RequestHandle.Dispose(); RequestHandle = null; @@ -111,7 +111,7 @@ public SafeWinHttpHandle RequestHandle set { #if DEBUG - if (value != null) + if (value is not null) { s_dbg_requestHandle = value.DangerousGetHandle(); } diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs index 5db9aa5a1a862e..22da33d7448ceb 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs @@ -91,7 +91,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -120,7 +120,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati CheckDisposed(); - if (_state.TcsInternalWriteDataToRequestStream != null && + if (_state.TcsInternalWriteDataToRequestStream is not null && !_state.TcsInternalWriteDataToRequestStream.Task.IsCompleted) { throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs index 02ce3184f8fe49..acdf6488126229 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs @@ -90,7 +90,7 @@ public bool ReadLine() /// true if the next line was read successfully, or false if all characters have been read. private bool ReadLine(out int startIndex, out int length) { - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); int i = _position; diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseParser.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseParser.cs index 1f9c88a019a91a..5c7072ee0483ed 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseParser.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseParser.cs @@ -139,12 +139,12 @@ public static unsafe bool GetResponseHeader( { const int StackLimit = 128; - Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit)); + Debug.Assert(buffer is null || (buffer is not null && buffer.Length > StackLimit)); int bufferLength; uint originalIndex = index; - if (buffer == null) + if (buffer is null) { bufferLength = StackLimit; char* pBuffer = stackalloc char[bufferLength]; @@ -194,7 +194,7 @@ public static unsafe bool GetResponseHeader( /// private static unsafe int GetResponseHeader(SafeWinHttpHandle requestHandle, uint infoLevel, char[] buffer) { - Debug.Assert(buffer != null, "buffer must not be null."); + Debug.Assert(buffer is not null, "buffer must not be null."); Debug.Assert(buffer.Length > 0, "buffer must not be empty."); int bufferLength = buffer.Length; @@ -281,7 +281,7 @@ private static string GetReasonPhrase(HttpStatusCode statusCode, char[] buffer, string knownReasonPhrase = HttpStatusDescription.Get(statusCode); - return (knownReasonPhrase != null && knownReasonPhrase.AsSpan().SequenceEqual(buffer.AsSpan(0, bufferLength))) ? + return (knownReasonPhrase is not null && knownReasonPhrase.AsSpan().SequenceEqual(buffer.AsSpan(0, bufferLength))) ? knownReasonPhrase : new string(buffer, 0, bufferLength); } diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs index 812a56e7232cff..19a2288dc16ae1 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs @@ -163,7 +163,7 @@ private async Task CopyToAsyncCore(Stream destination, byte[] buffer, Cancellati public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken token) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -280,7 +280,7 @@ protected override void Dispose(bool disposing) if (disposing) { - if (_requestHandle != null) + if (_requestHandle is not null) { _requestHandle.Dispose(); _requestHandle = null; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs index f4aa20af26b0e9..f86795d5e47a15 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs @@ -175,7 +175,7 @@ protected internal override async Task SendAsync(HttpReques } // We need to check for body content - if (request.Content != null) + if (request.Content is not null) { if (request.Content is StringContent) { @@ -202,7 +202,7 @@ protected internal override async Task SendAsync(HttpReques jsHeaders.Invoke("append", header.Key, value); } } - if (request.Content != null) + if (request.Content is not null) { foreach (KeyValuePair> header in request.Content.Headers) { @@ -236,7 +236,7 @@ protected internal override async Task SendAsync(HttpReques })); var args = new System.Runtime.InteropServices.JavaScript.Array(); - if (request.RequestUri != null) + if (request.RequestUri is not null) { args.Push(request.RequestUri.ToString()); args.Push(requestObject); @@ -246,7 +246,7 @@ protected internal override async Task SendAsync(HttpReques var response = s_fetch?.Invoke("apply", s_window, args) as Task; args.Dispose(); - if (response == null) + if (response is null) throw new Exception("Internal error marshalling the response Promise from `fetch`."); JSObject t = (JSObject)await response.ConfigureAwait(continueOnCapturedContext: true); @@ -287,7 +287,7 @@ protected internal override async Task SendAsync(HttpReques // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation using (JSObject respHeaders = status.Headers) { - if (respHeaders != null) + if (respHeaders is not null) { using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) { @@ -392,7 +392,7 @@ public BrowserHttpContent(WasmFetchResponse status) private async Task GetResponseData() { - if (_data != null) + if (_data is not null) { return _data; } @@ -424,7 +424,7 @@ protected override async Task SerializeToStreamAsync(Stream stream, TransportCon } protected internal override bool TryComputeLength(out long length) { - if (_data != null) + if (_data is not null) { length = _data.Length; return true; @@ -466,7 +466,7 @@ public override long Position public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -479,10 +479,10 @@ public override async Task ReadAsync(byte[] buffer, int offset, int count, throw new ArgumentOutOfRangeException(nameof(count)); } - if (_reader == null) + if (_reader is null) { // If we've read everything, then _reader and _status will be null - if (_status == null) + if (_status is null) { return 0; } @@ -501,7 +501,7 @@ public override async Task ReadAsync(byte[] buffer, int offset, int count, } } - if (_bufferedBytes != null && _position < _bufferedBytes.Length) + if (_bufferedBytes is not null && _position < _bufferedBytes.Length) { return ReadBuffered(); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs index fd9e91ad4f4cba..8422a383073082 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs @@ -16,7 +16,7 @@ public class ByteArrayContent : HttpContent public ByteArrayContent(byte[] content) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -27,7 +27,7 @@ public ByteArrayContent(byte[] content) public ByteArrayContent(byte[] content, int offset, int count) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayHelpers.cs b/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayHelpers.cs index d6299477cf8d71..808530ce489368 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayHelpers.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayHelpers.cs @@ -12,7 +12,7 @@ internal static class ByteArrayHelpers internal static bool EqualsOrdinalAsciiIgnoreCase(string left, ReadOnlySpan right) { - Debug.Assert(left != null, "Expected non-null string"); + Debug.Assert(left is not null, "Expected non-null string"); if (left.Length != right.Length) { @@ -41,7 +41,7 @@ internal static bool EqualsOrdinalAsciiIgnoreCase(string left, ReadOnlySpan right) { - Debug.Assert(left != null, "Expected non-null string"); + Debug.Assert(left is not null, "Expected non-null string"); if (left.Length != right.Length) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs index ebc61f3922392c..4a3ffd314a16a8 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs @@ -25,7 +25,7 @@ public HttpMessageHandler? InnerHandler } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -47,7 +47,7 @@ protected DelegatingHandler(HttpMessageHandler innerHandler) protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } @@ -57,7 +57,7 @@ protected internal override HttpResponseMessage Send(HttpRequestMessage request, protected internal override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } @@ -70,7 +70,7 @@ protected override void Dispose(bool disposing) if (disposing && !_disposed) { _disposed = true; - if (_innerHandler != null) + if (_innerHandler is not null) { _innerHandler.Dispose(); } @@ -99,7 +99,7 @@ private void CheckDisposedOrStarted() private void SetOperationStarted() { CheckDisposed(); - if (_innerHandler == null) + if (_innerHandler is null) { throw new InvalidOperationException(SR.net_http_handler_not_assigned); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs index 47f260eec04b03..de126e69adc98a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs @@ -27,7 +27,7 @@ internal static bool IsEnabled() { // check if there is a parent Activity (and propagation is not suppressed) // or if someone listens to HttpHandlerDiagnosticListener - return IsGloballyEnabled() && (Activity.Current != null || Settings.s_diagnosticListener.IsEnabled()); + return IsGloballyEnabled() && (Activity.Current is not null || Settings.s_diagnosticListener.IsEnabled()); } internal static bool IsGloballyEnabled() @@ -57,7 +57,7 @@ private async ValueTask SendAsyncCore(HttpRequestMessage re // So some requests happening right after subscription starts might not be instrumented. Similarly, // when consumer unsubscribes, extra requests might be instrumented - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } @@ -113,7 +113,7 @@ await base.SendAsync(request, cancellationToken).ConfigureAwait(false) : // If we are on at all, we propagate current activity information Activity? currentActivity = Activity.Current; - if (currentActivity != null) + if (currentActivity is not null) { InjectHeaders(currentActivity, request); } @@ -150,7 +150,7 @@ await base.SendAsync(request, cancellationToken).ConfigureAwait(false) : finally { // always stop activity if it was started - if (activity != null) + if (activity is not null) { diagnosticListener.StopActivity(activity, new ActivityStopData( response, @@ -269,7 +269,7 @@ private static bool GetEnableActivityPropagationValue() // AppContext switch wasn't used. Check the environment variable to determine which handler should be used. string? envVar = Environment.GetEnvironmentVariable(EnableActivityPropagationEnvironmentVariableSettingName); - if (envVar != null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0"))) + if (envVar is not null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0"))) { // Suppress Activity propagation. return false; @@ -290,7 +290,7 @@ private static void InjectHeaders(Activity currentActivity, HttpRequestMessage r if (!request.Headers.Contains(DiagnosticsHandlerLoggingStrings.TraceParentHeaderName)) { request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.TraceParentHeaderName, currentActivity.Id); - if (currentActivity.TraceStateString != null) + if (currentActivity.TraceStateString is not null) { request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.TraceStateHeaderName, currentActivity.TraceStateString); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs index fe723de2c33300..ba1b59529c48e2 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs @@ -20,7 +20,7 @@ public FormUrlEncodedContent(IEnumerable> nameVal private static byte[] GetContentByteArray(IEnumerable> nameValueCollection) { - if (nameValueCollection == null) + if (nameValueCollection is null) { throw new ArgumentNullException(nameof(nameValueCollection)); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderParser.cs index 35c98f80b66e32..df09b6788b849b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderParser.cs @@ -135,7 +135,7 @@ protected override int GetParsedValueLength(string value, int startIndex, object return 0; } - if (maxAge == null) + if (maxAge is null) { maxAge = maxAgeTmp; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs index ce534b0e1d5425..236fa583948cb0 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs @@ -54,7 +54,7 @@ public override string ToString() sb.Append(AlpnProtocolName); sb.Append("=\""); - if (Host != null) sb.Append(Host); + if (Host is not null) sb.Append(Host); sb.Append(':'); sb.Append(Port.ToString(CultureInfo.InvariantCulture)); sb.Append('"'); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs index 0a4be0f75d0055..e91df6a0d22012 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs @@ -44,7 +44,7 @@ public AuthenticationHeaderValue(string scheme, string? parameter) private AuthenticationHeaderValue(AuthenticationHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _scheme = source._scheme; _parameter = source._parameter; @@ -67,7 +67,7 @@ public override bool Equals(object? obj) { AuthenticationHeaderValue? other = obj as AuthenticationHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -145,7 +145,7 @@ internal static int GetAuthenticationLength(string? input, int startIndex, out o case 4: targetScheme = "NTLM"; break; case 9: targetScheme = "Negotiate"; break; } - result._scheme = targetScheme != null && string.CompareOrdinal(input, startIndex, targetScheme, 0, schemeLength) == 0 ? + result._scheme = targetScheme is not null && string.CompareOrdinal(input, startIndex, targetScheme, 0, schemeLength) == 0 ? targetScheme : input.Substring(startIndex, schemeLength); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderParser.cs index 53480344bcddcb..369dfcbf1868d9 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderParser.cs @@ -23,7 +23,7 @@ protected override int GetParsedValueLength(string value, int startIndex, object out object? parsedValue) { CacheControlHeaderValue? temp = storeValue as CacheControlHeaderValue; - Debug.Assert(storeValue == null || temp != null, "'storeValue' is not of type CacheControlHeaderValue"); + Debug.Assert(storeValue is null || temp is not null, "'storeValue' is not of type CacheControlHeaderValue"); int resultLength = CacheControlHeaderValue.GetCacheControlLength(value, startIndex, temp, out temp); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs index e51a5c56d2f4ce..258efa5d6417fc 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs @@ -135,7 +135,7 @@ public CacheControlHeaderValue() private CacheControlHeaderValue(CacheControlHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _noCache = source._noCache; _noStore = source._noStore; @@ -151,7 +151,7 @@ private CacheControlHeaderValue(CacheControlHeaderValue source) _mustRevalidate = source._mustRevalidate; _proxyRevalidate = source._proxyRevalidate; - if (source._noCacheHeaders != null) + if (source._noCacheHeaders is not null) { foreach (var noCacheHeader in source._noCacheHeaders) { @@ -159,7 +159,7 @@ private CacheControlHeaderValue(CacheControlHeaderValue source) } } - if (source._privateHeaders != null) + if (source._privateHeaders is not null) { foreach (var privateHeader in source._privateHeaders) { @@ -167,7 +167,7 @@ private CacheControlHeaderValue(CacheControlHeaderValue source) } } - if (source._extensions != null) + if (source._extensions is not null) { foreach (var extension in source._extensions) { @@ -190,7 +190,7 @@ public override string ToString() if (_noCache) { AppendValueWithSeparatorIfRequired(sb, noCacheString); - if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0)) + if ((_noCacheHeaders is not null) && (_noCacheHeaders.Count > 0)) { sb.Append("=\""); AppendValues(sb, _noCacheHeaders); @@ -272,7 +272,7 @@ public override string ToString() if (_privateField) { AppendValueWithSeparatorIfRequired(sb, privateString); - if ((_privateHeaders != null) && (_privateHeaders.Count > 0)) + if ((_privateHeaders is not null) && (_privateHeaders.Count > 0)) { sb.Append("=\""); AppendValues(sb, _privateHeaders); @@ -289,7 +289,7 @@ public override bool Equals(object? obj) { CacheControlHeaderValue? other = obj as CacheControlHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -341,7 +341,7 @@ public override int GetHashCode() (_maxStaleLimit.HasValue ? _maxStaleLimit.Value.GetHashCode() ^ 4 : 0) ^ (_minFresh.HasValue ? _minFresh.Value.GetHashCode() ^ 8 : 0); - if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0)) + if ((_noCacheHeaders is not null) && (_noCacheHeaders.Count > 0)) { foreach (var noCacheHeader in _noCacheHeaders) { @@ -349,7 +349,7 @@ public override int GetHashCode() } } - if ((_privateHeaders != null) && (_privateHeaders.Count > 0)) + if ((_privateHeaders is not null) && (_privateHeaders.Count > 0)) { foreach (var privateHeader in _privateHeaders) { @@ -357,7 +357,7 @@ public override int GetHashCode() } } - if ((_extensions != null) && (_extensions.Count > 0)) + if ((_extensions is not null) && (_extensions.Count > 0)) { foreach (var extension in _extensions) { @@ -421,7 +421,7 @@ internal static int GetCacheControlLength(string? input, int startIndex, CacheCo // CacheControlHeaderValue. So if we already have an instance of CacheControlHeaderValue, add the values // from this string to the existing instances. CacheControlHeaderValue? result = storeValue; - if (result == null) + if (result is null) { result = new CacheControlHeaderValue(); } @@ -434,7 +434,7 @@ internal static int GetCacheControlLength(string? input, int startIndex, CacheCo // If we had an existing store value and we just updated that instance, return 'null' to indicate that // we don't have a new instance of CacheControlHeaderValue, but just updated an existing one. This is the // case if we have multiple 'Cache-Control' headers set in a request/response message. - if (storeValue == null) + if (storeValue is null) { parsedValue = result; } @@ -466,7 +466,7 @@ private static bool TrySetCacheControlValues(CacheControlHeaderValue cc, break; case maxStaleString: - success = ((nameValue.Value == null) || TrySetTimeSpan(nameValue, ref cc._maxStaleLimit)); + success = ((nameValue.Value is null) || TrySetTimeSpan(nameValue, ref cc._maxStaleLimit)); if (success) { cc._maxStale = true; @@ -521,7 +521,7 @@ private static bool TrySetCacheControlValues(CacheControlHeaderValue cc, private static bool TrySetTokenOnlyValue(NameValueHeaderValue nameValue, ref bool boolField) { - if (nameValue.Value != null) + if (nameValue.Value is not null) { return false; } @@ -533,9 +533,9 @@ private static bool TrySetTokenOnlyValue(NameValueHeaderValue nameValue, ref boo private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref bool boolField, ref ObjectCollection? destination) { - Debug.Assert(nameValue != null); + Debug.Assert(nameValue is not null); - if (nameValue.Value == null) + if (nameValue.Value is null) { boolField = true; return true; @@ -553,7 +553,7 @@ private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref int current = 1; // skip the initial '"' character. int maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'. bool separatorFound = false; - int originalValueCount = destination == null ? 0 : destination.Count; + int originalValueCount = destination is null ? 0 : destination.Count; while (current < maxLength) { current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true, @@ -580,7 +580,7 @@ private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref } // After parsing a valid token list, we expect to have at least one value - if ((destination != null) && (destination.Count > originalValueCount)) + if ((destination is not null) && (destination.Count > originalValueCount)) { boolField = true; return true; @@ -591,9 +591,9 @@ private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref private static bool TrySetTimeSpan(NameValueHeaderValue nameValue, ref TimeSpan? timeSpan) { - Debug.Assert(nameValue != null); + Debug.Assert(nameValue is not null); - if (nameValue.Value == null) + if (nameValue.Value is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs index d58feb4a2e2624..c6de06c5cafe16 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs @@ -83,7 +83,7 @@ public long? Size { NameValueHeaderValue? sizeParameter = NameValueHeaderValue.Find(_parameters, size); ulong value; - if (sizeParameter != null) + if (sizeParameter is not null) { string? sizeString = sizeParameter.Value; if (ulong.TryParse(sizeString, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) @@ -96,10 +96,10 @@ public long? Size set { NameValueHeaderValue? sizeParameter = NameValueHeaderValue.Find(_parameters, size); - if (value == null) + if (value is null) { // Remove parameter. - if (sizeParameter != null) + if (sizeParameter is not null) { _parameters!.Remove(sizeParameter); } @@ -108,7 +108,7 @@ public long? Size { throw new ArgumentOutOfRangeException(nameof(value)); } - else if (sizeParameter != null) + else if (sizeParameter is not null) { sizeParameter.Value = value.Value.ToString(CultureInfo.InvariantCulture); } @@ -131,11 +131,11 @@ internal ContentDispositionHeaderValue() protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _dispositionType = source._dispositionType; - if (source._parameters != null) + if (source._parameters is not null) { foreach (var parameter in source._parameters) { @@ -166,7 +166,7 @@ public override bool Equals(object? obj) { ContentDispositionHeaderValue? other = obj as ContentDispositionHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -259,7 +259,7 @@ internal static int GetDispositionTypeLength(string? input, int startIndex, out private static int GetDispositionTypeExpressionLength(string input, int startIndex, out string? dispositionType) { - Debug.Assert((input != null) && (input.Length > 0) && (startIndex < input.Length)); + Debug.Assert((input is not null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the disposition type string, it does not parse parameters. dispositionType = null; @@ -303,7 +303,7 @@ private static void CheckDispositionTypeFormat(string dispositionType, string pa { NameValueHeaderValue? dateParameter = NameValueHeaderValue.Find(_parameters, parameter); DateTimeOffset date; - if (dateParameter != null) + if (dateParameter is not null) { ReadOnlySpan dateString = dateParameter.Value; // Should have quotes, remove them. @@ -323,10 +323,10 @@ private static void CheckDispositionTypeFormat(string dispositionType, string pa private void SetDate(string parameter, DateTimeOffset? date) { NameValueHeaderValue? dateParameter = NameValueHeaderValue.Find(_parameters, parameter); - if (date == null) + if (date is null) { // Remove parameter. - if (dateParameter != null) + if (dateParameter is not null) { _parameters!.Remove(dateParameter); } @@ -335,7 +335,7 @@ private void SetDate(string parameter, DateTimeOffset? date) { // Must always be quoted. string dateString = "\"" + HttpDateParser.DateToString(date.Value) + "\""; - if (dateParameter != null) + if (dateParameter is not null) { dateParameter.Value = dateString; } @@ -351,13 +351,13 @@ private void SetDate(string parameter, DateTimeOffset? date) private string? GetName(string parameter) { NameValueHeaderValue? nameParameter = NameValueHeaderValue.Find(_parameters, parameter); - if (nameParameter != null) + if (nameParameter is not null) { string? result; // filename*=utf-8'lang'%7FMyString if (parameter.EndsWith('*')) { - Debug.Assert(nameParameter.Value != null); + Debug.Assert(nameParameter.Value is not null); if (TryDecode5987(nameParameter.Value, out result)) { return result; @@ -384,7 +384,7 @@ private void SetName(string parameter, string? value) if (string.IsNullOrEmpty(value)) { // Remove parameter. - if (nameParameter != null) + if (nameParameter is not null) { _parameters!.Remove(nameParameter); } @@ -401,7 +401,7 @@ private void SetName(string parameter, string? value) processedValue = EncodeAndQuoteMime(value); } - if (nameParameter != null) + if (nameParameter is not null) { nameParameter.Value = processedValue; } @@ -467,7 +467,7 @@ private static string EncodeMime(string input) // Attempt to decode MIME encoded strings. private static bool TryDecodeMime(string? input, [NotNullWhen(true)] out string? output) { - Debug.Assert(input != null); + Debug.Assert(input is not null); output = null; string? processedInput = input; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs index ef5c13729ac247..9ef1d870e0152a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs @@ -43,12 +43,12 @@ public long? Length public bool HasLength // e.g. "Content-Range: bytes 12-34/*" { - get { return _length != null; } + get { return _length is not null; } } public bool HasRange // e.g. "Content-Range: bytes */1234" { - get { return _from != null; } + get { return _from is not null; } } public ContentRangeHeaderValue(long from, long to, long length) @@ -111,7 +111,7 @@ private ContentRangeHeaderValue() private ContentRangeHeaderValue(ContentRangeHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _from = source._from; _to = source._to; @@ -123,7 +123,7 @@ public override bool Equals(object? obj) { ContentRangeHeaderValue? other = obj as ContentRangeHeaderValue; - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs index 80830224ff260c..e629ae65557650 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs @@ -27,7 +27,7 @@ public static EntityTagHeaderValue Any { get { - if (s_any == null) + if (s_any is null) { s_any = new EntityTagHeaderValue(); s_any._tag = "*"; @@ -63,7 +63,7 @@ public EntityTagHeaderValue(string tag, bool isWeak) private EntityTagHeaderValue(EntityTagHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _tag = source._tag; _isWeak = source._isWeak; @@ -86,7 +86,7 @@ public override bool Equals(object? obj) { EntityTagHeaderValue? other = obj as EntityTagHeaderValue; - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs index d0297d7db91942..57f962307683d9 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs @@ -56,7 +56,7 @@ private GenericHeaderParser(bool supportsMultipleValues, GetParsedValueLengthDel IEqualityComparer? comparer) : base(supportsMultipleValues) { - Debug.Assert(getParsedValueLength != null); + Debug.Assert(getParsedValueLength is not null); _getParsedValueLength = getParsedValueLength; _comparer = comparer; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderDescriptor.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderDescriptor.cs index 229490b5432dd9..a9b58b54eddf59 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderDescriptor.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderDescriptor.cs @@ -33,11 +33,11 @@ internal HeaderDescriptor(string headerName) public string Name => _headerName; public HttpHeaderParser? Parser => _knownHeader?.Parser; - public HttpHeaderType HeaderType => _knownHeader == null ? HttpHeaderType.Custom : _knownHeader.HeaderType; + public HttpHeaderType HeaderType => _knownHeader is null ? HttpHeaderType.Custom : _knownHeader.HeaderType; public KnownHeader? KnownHeader => _knownHeader; public bool Equals(HeaderDescriptor other) => - _knownHeader == null ? + _knownHeader is null ? string.Equals(_headerName, other._headerName, StringComparison.OrdinalIgnoreCase) : _knownHeader == other._knownHeader; public override int GetHashCode() => _knownHeader?.GetHashCode() ?? StringComparer.OrdinalIgnoreCase.GetHashCode(_headerName); @@ -49,7 +49,7 @@ public static bool TryGet(string headerName, out HeaderDescriptor descriptor) Debug.Assert(!string.IsNullOrEmpty(headerName)); KnownHeader? knownHeader = KnownHeaders.TryGetKnownHeader(headerName); - if (knownHeader != null) + if (knownHeader is not null) { descriptor = new HeaderDescriptor(knownHeader); return true; @@ -71,7 +71,7 @@ public static bool TryGet(ReadOnlySpan headerName, out HeaderDescriptor de Debug.Assert(headerName.Length > 0); KnownHeader? knownHeader = KnownHeaders.TryGetKnownHeader(headerName); - if (knownHeader != null) + if (knownHeader is not null) { descriptor = new HeaderDescriptor(knownHeader); return true; @@ -112,7 +112,7 @@ internal static bool TryGetStaticQPackHeader(int index, out HeaderDescriptor des public HeaderDescriptor AsCustomHeader() { - Debug.Assert(_knownHeader != null); + Debug.Assert(_knownHeader is not null); Debug.Assert(_knownHeader.HeaderType != HttpHeaderType.Custom); return new HeaderDescriptor(_knownHeader.Name); } @@ -125,10 +125,10 @@ public string GetHeaderValue(ReadOnlySpan headerValue, Encoding? valueEnco } // If it's a known header value, use the known value instead of allocating a new string. - if (_knownHeader != null) + if (_knownHeader is not null) { string[]? knownValues = _knownHeader.KnownValues; - if (knownValues != null) + if (knownValues is not null) { for (int i = 0; i < knownValues.Length; i++) { @@ -142,7 +142,7 @@ public string GetHeaderValue(ReadOnlySpan headerValue, Encoding? valueEnco if (_knownHeader == KnownHeaders.ContentType) { string? contentType = GetKnownContentType(headerValue); - if (contentType != null) + if (contentType is not null) { return contentType; } @@ -239,7 +239,7 @@ public string GetHeaderValue(ReadOnlySpan headerValue, Encoding? valueEnco Debug.Assert(candidate is null || candidate.Length == contentTypeValue.Length); - return candidate != null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate, contentTypeValue) ? + return candidate is not null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate, contentTypeValue) ? candidate : null; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs index 8834b0bca994b0..6ed35519764076 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs @@ -28,7 +28,7 @@ internal static class HeaderUtilities internal static void SetQuality(ObjectCollection parameters, double? value) { - Debug.Assert(parameters != null); + Debug.Assert(parameters is not null); NameValueHeaderValue? qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (value.HasValue) @@ -44,7 +44,7 @@ internal static void SetQuality(ObjectCollection parameter } string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo); - if (qualityParameter != null) + if (qualityParameter is not null) { qualityParameter.Value = qualityString; } @@ -56,7 +56,7 @@ internal static void SetQuality(ObjectCollection parameter else { // Remove quality parameter - if (qualityParameter != null) + if (qualityParameter is not null) { parameters.Remove(qualityParameter); } @@ -65,7 +65,7 @@ internal static void SetQuality(ObjectCollection parameter internal static bool ContainsNonAscii(string input) { - Debug.Assert(input != null); + Debug.Assert(input is not null); foreach (char c in input) { @@ -119,7 +119,7 @@ internal static string Encode5987(string input) /// Transforms an ASCII character into its hexadecimal representation, adding the characters to a StringBuilder. private static void AddHexEscaped(byte c, StringBuilder destination) { - Debug.Assert(destination != null); + Debug.Assert(destination is not null); destination.Append('%'); destination.Append(HexConverter.ToCharUpper(c >> 4)); @@ -128,10 +128,10 @@ private static void AddHexEscaped(byte c, StringBuilder destination) internal static double? GetQuality(ObjectCollection parameters) { - Debug.Assert(parameters != null); + Debug.Assert(parameters is not null); NameValueHeaderValue? qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); - if (qualityParameter != null) + if (qualityParameter is not null) { // Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal // separator is considered invalid (even if the current culture would allow it). @@ -197,12 +197,12 @@ internal static bool AreEqualCollections(ObjectCollection? x, ObjectCollec internal static bool AreEqualCollections(ObjectCollection? x, ObjectCollection? y, IEqualityComparer? comparer) where T : class { - if (x == null) + if (x is null) { - return (y == null) || (y.Count == 0); + return (y is null) || (y.Count == 0); } - if (y == null) + if (y is null) { return (x.Count == 0); } @@ -223,7 +223,7 @@ internal static bool AreEqualCollections(ObjectCollection? x, ObjectCollec int i = 0; foreach (var xItem in x) { - Debug.Assert(xItem != null); + Debug.Assert(xItem is not null); i = 0; bool found = false; @@ -231,8 +231,8 @@ internal static bool AreEqualCollections(ObjectCollection? x, ObjectCollec { if (!alreadyFound[i]) { - if (((comparer == null) && xItem.Equals(yItem)) || - ((comparer != null) && comparer.Equals(xItem, yItem))) + if (((comparer is null) && xItem.Equals(yItem)) || + ((comparer is not null) && comparer.Equals(xItem, yItem))) { alreadyFound[i] = true; found = true; @@ -259,7 +259,7 @@ internal static bool AreEqualCollections(ObjectCollection? x, ObjectCollec internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues, out bool separatorFound) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(startIndex <= input.Length); // it's OK if index == value.Length. separatorFound = false; @@ -290,14 +290,14 @@ internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startInde internal static DateTimeOffset? GetDateTimeOffsetValue(HeaderDescriptor descriptor, HttpHeaders store, DateTimeOffset? defaultValue = null) { - Debug.Assert(store != null); + Debug.Assert(store is not null); object? storedValue = store.GetParsedValues(descriptor); - if (storedValue != null) + if (storedValue is not null) { return (DateTimeOffset)storedValue; } - else if (defaultValue != null && store.Contains(descriptor)) + else if (defaultValue is not null && store.Contains(descriptor)) { return defaultValue; } @@ -307,10 +307,10 @@ internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startInde internal static TimeSpan? GetTimeSpanValue(HeaderDescriptor descriptor, HttpHeaders store) { - Debug.Assert(store != null); + Debug.Assert(store is not null); object? storedValue = store.GetParsedValues(descriptor); - if (storedValue != null) + if (storedValue is not null) { return (TimeSpan)storedValue; } @@ -355,7 +355,7 @@ internal static void DumpHeaders(StringBuilder sb, params HttpHeaders?[] headers for (int i = 0; i < headers.Length; i++) { - if (headers[i] != null) + if (headers[i] is not null) { foreach (var header in headers[i]!) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpContentHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpContentHeaders.cs index 92a88c22a3edfd..ae79185f7ad6de 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpContentHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpContentHeaders.cs @@ -20,7 +20,7 @@ public ICollection Allow { get { - if (_allow == null) + if (_allow is null) { _allow = new HttpHeaderValueCollection(KnownHeaders.Allow.Descriptor, this, HeaderUtilities.TokenValidator); @@ -41,7 +41,7 @@ public ICollection ContentEncoding { get { - if (_contentEncoding == null) + if (_contentEncoding is null) { _contentEncoding = new HttpHeaderValueCollection(KnownHeaders.ContentEncoding.Descriptor, this, HeaderUtilities.TokenValidator); @@ -54,7 +54,7 @@ public ICollection ContentLanguage { get { - if (_contentLanguage == null) + if (_contentLanguage is null) { _contentLanguage = new HttpHeaderValueCollection(KnownHeaders.ContentLanguage.Descriptor, this, HeaderUtilities.TokenValidator); @@ -71,14 +71,14 @@ public long? ContentLength object? storedValue = GetParsedValues(KnownHeaders.ContentLength.Descriptor); // Only try to calculate the length if the user didn't set the value explicitly using the setter. - if (!_contentLengthSet && (storedValue == null)) + if (!_contentLengthSet && (storedValue is null)) { // If we don't have a value for Content-Length in the store, try to let the content calculate // it's length. If the content object is able to calculate the length, we'll store it in the // store. long? calculatedLength = _parent.GetComputedOrBufferLength(); - if (calculatedLength != null) + if (calculatedLength is not null) { SetParsedValue(KnownHeaders.ContentLength.Descriptor, (object)calculatedLength.Value); } @@ -86,7 +86,7 @@ public long? ContentLength return calculatedLength; } - if (storedValue == null) + if (storedValue is null) { return null; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs index 0acffa6098ac80..3f48836349ce1f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs @@ -50,7 +50,7 @@ public bool? ConnectionClose } else { - _connectionCloseSet = value != null; + _connectionCloseSet = value is not null; ConnectionCore.RemoveSpecialValue(); } } @@ -62,7 +62,7 @@ public bool? ConnectionClose // and it contains the special value, or if we haven't and the headers contain // the parsed special value, return true. We don't just access ConnectionCore, // as doing so will unnecessarily initialize the collection even if it's not needed. - if (headers?._connection != null) + if (headers?._connection is not null) { if (headers._connection.IsSpecialValueSet) { @@ -73,7 +73,7 @@ public bool? ConnectionClose { return true; } - if (headers != null && headers._connectionCloseSet) + if (headers is not null && headers._connectionCloseSet) { return false; } @@ -90,7 +90,7 @@ public HttpHeaderValueCollection Pragma { get { - if (_pragma == null) + if (_pragma is null) { _pragma = new HttpHeaderValueCollection(KnownHeaders.Pragma.Descriptor, _parent); } @@ -102,7 +102,7 @@ public HttpHeaderValueCollection Trailer { get { - if (_trailer == null) + if (_trailer is null) { _trailer = new HttpHeaderValueCollection(KnownHeaders.Trailer.Descriptor, _parent, HeaderUtilities.TokenValidator); @@ -122,7 +122,7 @@ public HttpHeaderValueCollection TransferEncoding // and it contains the special value, or if we haven't and the headers contain // the parsed special value, return true. We don't just access TransferEncodingCore, // as doing so will unnecessarily initialize the collection even if it's not needed. - if (headers?._transferEncoding != null) + if (headers?._transferEncoding is not null) { if (headers._transferEncoding.IsSpecialValueSet) { @@ -133,7 +133,7 @@ public HttpHeaderValueCollection TransferEncoding { return true; } - if (headers != null && headers._transferEncodingChunkedSet) + if (headers is not null && headers._transferEncodingChunkedSet) { return false; } @@ -158,7 +158,7 @@ public bool? TransferEncodingChunked } else { - _transferEncodingChunkedSet = value != null; + _transferEncodingChunkedSet = value is not null; TransferEncodingCore.RemoveSpecialValue(); } } @@ -168,7 +168,7 @@ public HttpHeaderValueCollection Upgrade { get { - if (_upgrade == null) + if (_upgrade is null) { _upgrade = new HttpHeaderValueCollection(KnownHeaders.Upgrade.Descriptor, _parent); } @@ -180,7 +180,7 @@ public HttpHeaderValueCollection Via { get { - if (_via == null) + if (_via is null) { _via = new HttpHeaderValueCollection(KnownHeaders.Via.Descriptor, _parent); } @@ -192,7 +192,7 @@ public HttpHeaderValueCollection Warning { get { - if (_warning == null) + if (_warning is null) { _warning = new HttpHeaderValueCollection(KnownHeaders.Warning.Descriptor, _parent); } @@ -204,7 +204,7 @@ private HttpHeaderValueCollection ConnectionCore { get { - if (_connection == null) + if (_connection is null) { _connection = new HttpHeaderValueCollection(KnownHeaders.Connection.Descriptor, _parent, HeaderUtilities.ConnectionClose, HeaderUtilities.TokenValidator); @@ -217,7 +217,7 @@ private HttpHeaderValueCollection TransferEncodingCor { get { - if (_transferEncoding == null) + if (_transferEncoding is null) { _transferEncoding = new HttpHeaderValueCollection( KnownHeaders.TransferEncoding.Descriptor, _parent, HeaderUtilities.TransferEncodingChunked); @@ -228,7 +228,7 @@ private HttpHeaderValueCollection TransferEncodingCor internal HttpGeneralHeaders(HttpHeaders parent) { - Debug.Assert(parent != null); + Debug.Assert(parent is not null); _parent = parent; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderParser.cs index 2fa79f1f41812e..a01b1917d408a6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderParser.cs @@ -63,14 +63,14 @@ public object ParseValue(string? value, object? storeValue, ref int index) { // Index may be value.Length (e.g. both 0). This may be allowed for some headers (e.g. Accept but not // allowed by others (e.g. Content-Length). The parser has to decide if this is valid or not. - Debug.Assert((value == null) || ((index >= 0) && (index <= value.Length))); + Debug.Assert((value is null) || ((index >= 0) && (index <= value.Length))); // If a parser returns 'null', it means there was no value, but that's valid (e.g. "Accept: "). The caller // can ignore the value. if (!TryParseValue(value, storeValue, ref index, out object? result)) { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, - value == null ? "" : value.Substring(index))); + value is null ? "" : value.Substring(index))); } return result; } @@ -81,7 +81,7 @@ public object ParseValue(string? value, object? storeValue, ref int index) // values (e.g. byte[] to Base64 encoded string). public virtual string? ToString(object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); return value.ToString(); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs index 17c775921e2004..a889c76e74c1c5 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs @@ -53,7 +53,7 @@ internal bool IsSpecialValueSet get { // If this collection instance has a "special value", then check whether that value was already set. - if (_specialValue == null) + if (_specialValue is null) { return false; } @@ -80,8 +80,8 @@ internal HttpHeaderValueCollection(HeaderDescriptor descriptor, HttpHeaders stor internal HttpHeaderValueCollection(HeaderDescriptor descriptor, HttpHeaders store, T? specialValue, Action, T>? validator) { - Debug.Assert(descriptor.Name != null); - Debug.Assert(store != null); + Debug.Assert(descriptor.Name is not null); + Debug.Assert(store is not null); _store = store; _descriptor = descriptor; @@ -118,7 +118,7 @@ public bool Contains(T item) public void CopyTo(T[] array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -130,14 +130,14 @@ public void CopyTo(T[] array, int arrayIndex) object? storeValue = _store.GetParsedValues(_descriptor); - if (storeValue == null) + if (storeValue is null) { return; } List? storeValues = storeValue as List; - if (storeValues == null) + if (storeValues is null) { // We only have 1 value: If it is the "special value" just return, otherwise add the value to the // array and return. @@ -166,14 +166,14 @@ public IEnumerator GetEnumerator() { object? storeValue = _store.GetParsedValues(_descriptor); - if (storeValue == null) + if (storeValue is null) { yield break; } List? storeValues = storeValue as List; - if (storeValues == null) + if (storeValues is null) { Debug.Assert(storeValue is T); yield return (T)storeValue; @@ -207,7 +207,7 @@ public override string ToString() internal void SetSpecialValue() { - Debug.Assert(_specialValue != null, + Debug.Assert(_specialValue is not null, "This method can only be used if the collection has a 'special value' set."); if (!_store.ContainsParsedValue(_descriptor, _specialValue)) @@ -218,7 +218,7 @@ internal void SetSpecialValue() internal void RemoveSpecialValue() { - Debug.Assert(_specialValue != null, + Debug.Assert(_specialValue is not null, "This method can only be used if the collection has a 'special value' set."); // We're not interested in the return value. It's OK if the "special value" wasn't in the store @@ -228,13 +228,13 @@ internal void RemoveSpecialValue() private void CheckValue(T item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } // If this instance has a custom validator for validating arguments, call it now. - if (_validator != null) + if (_validator is not null) { _validator(this, item); } @@ -246,14 +246,14 @@ private int GetCount() object? storeValue = _store.GetParsedValues(_descriptor); - if (storeValue == null) + if (storeValue is null) { return 0; } List? storeValues = storeValue as List; - if (storeValues == null) + if (storeValues is null) { return 1; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs index edb3077d6a0143..323b2735c0c3b7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs @@ -87,7 +87,7 @@ internal void Add(HeaderDescriptor descriptor, string? value) // If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add // it to the store if we added at least one value. - if (addToStore && (info.ParsedValue != null)) + if (addToStore && (info.ParsedValue is not null)) { AddHeaderToStore(descriptor, info); } @@ -97,7 +97,7 @@ internal void Add(HeaderDescriptor descriptor, string? value) internal void Add(HeaderDescriptor descriptor, IEnumerable values) { - if (values == null) + if (values is null) { throw new ArgumentNullException(nameof(values)); } @@ -120,7 +120,7 @@ internal void Add(HeaderDescriptor descriptor, IEnumerable values) // get added. Same here: If multiple values get added to a _new_ header, make sure the header gets added // with the valid values. // However, if all values for a _new_ header were invalid, then don't add the header. - if (addToStore && (info.ParsedValue != null)) + if (addToStore && (info.ParsedValue is not null)) { AddHeaderToStore(descriptor, info); } @@ -172,7 +172,7 @@ public bool TryAddWithoutValidation(string name, IEnumerable values) => internal bool TryAddWithoutValidation(HeaderDescriptor descriptor, IEnumerable values) { - if (values == null) + if (values is null) { throw new ArgumentNullException(nameof(values)); } @@ -224,7 +224,7 @@ public bool TryGetValues(string name, [NotNullWhen(true)] out IEnumerable? values) { - if (_headerStore != null && TryGetAndParseHeaderInfo(descriptor, out HeaderStoreItemInfo? info)) + if (_headerStore is not null && TryGetAndParseHeaderInfo(descriptor, out HeaderStoreItemInfo? info)) { values = GetValuesAsStrings(descriptor, info); return true; @@ -241,12 +241,12 @@ internal bool Contains(HeaderDescriptor descriptor) // We can't just call headerStore.ContainsKey() since after parsing the value the header may not exist // anymore (if the value contains invalid newline chars, we remove the header). So try to parse the // header value. - return _headerStore != null && TryGetAndParseHeaderInfo(descriptor, out _); + return _headerStore is not null && TryGetAndParseHeaderInfo(descriptor, out _); } public override string ToString() { - if (_headerStore == null || _headerStore.Count == 0) + if (_headerStore is null || _headerStore.Count == 0) { return string.Empty; } @@ -266,7 +266,7 @@ public override string ToString() internal IEnumerable> GetHeaderStrings() { - if (_headerStore == null) + if (_headerStore is null) { yield break; } @@ -296,7 +296,7 @@ private string GetHeaderString(HeaderDescriptor descriptor, object info, object? // Note that if we get multiple values for a header that doesn't support multiple values, we'll // just separate the values using a comma (default separator). string? separator = HttpHeaderParser.DefaultSeparator; - if ((descriptor.Parser != null) && (descriptor.Parser.SupportsMultipleValues)) + if ((descriptor.Parser is not null) && (descriptor.Parser.SupportsMultipleValues)) { separator = descriptor.Parser.Separator; } @@ -305,7 +305,7 @@ private string GetHeaderString(HeaderDescriptor descriptor, object info, object? #region IEnumerable>> Members - public IEnumerator>> GetEnumerator() => _headerStore != null && _headerStore.Count > 0 ? + public IEnumerator>> GetEnumerator() => _headerStore is not null && _headerStore.Count > 0 ? GetEnumeratorCore() : ((IEnumerable>>)Array.Empty>>()).GetEnumerator(); @@ -358,8 +358,8 @@ private IEnumerator>> GetEnumeratorCore internal void AddParsedValue(HeaderDescriptor descriptor, object value) { - Debug.Assert(value != null); - Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); + Debug.Assert(value is not null); + Debug.Assert(descriptor.Parser is not null, "Can't add parsed value if there is no parser available."); HeaderStoreItemInfo info = GetOrCreateHeaderInfo(descriptor, parseRawValues: true); @@ -372,8 +372,8 @@ internal void AddParsedValue(HeaderDescriptor descriptor, object value) internal void SetParsedValue(HeaderDescriptor descriptor, object value) { - Debug.Assert(value != null); - Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); + Debug.Assert(value is not null); + Debug.Assert(descriptor.Parser is not null, "Can't add parsed value if there is no parser available."); // This method will first clear all values. This is used e.g. when setting the 'Date' or 'Host' header. // i.e. headers not supporting collections. @@ -388,7 +388,7 @@ internal void SetParsedValue(HeaderDescriptor descriptor, object value) internal void SetOrRemoveParsedValue(HeaderDescriptor descriptor, object? value) { - if (value == null) + if (value is null) { Remove(descriptor); } @@ -400,13 +400,13 @@ internal void SetOrRemoveParsedValue(HeaderDescriptor descriptor, object? value) public bool Remove(string name) => Remove(GetHeaderDescriptor(name)); - internal bool Remove(HeaderDescriptor descriptor) => _headerStore != null && _headerStore.Remove(descriptor); + internal bool Remove(HeaderDescriptor descriptor) => _headerStore is not null && _headerStore.Remove(descriptor); internal bool RemoveParsedValue(HeaderDescriptor descriptor, object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); - if (_headerStore == null) + if (_headerStore is null) { return false; } @@ -415,12 +415,12 @@ internal bool RemoveParsedValue(HeaderDescriptor descriptor, object value) // value with 'item'. If we have a list of values, then remove 'item' from the list. if (TryGetAndParseHeaderInfo(descriptor, out HeaderStoreItemInfo? info)) { - Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); + Debug.Assert(descriptor.Parser is not null, "Can't add parsed value if there is no parser available."); Debug.Assert(descriptor.Parser.SupportsMultipleValues, "This method should not be used for single-value headers. Use Remove(string) instead."); // If there is no entry, just return. - if (info.ParsedValue == null) + if (info.ParsedValue is null) { return false; } @@ -429,7 +429,7 @@ internal bool RemoveParsedValue(HeaderDescriptor descriptor, object value) IEqualityComparer? comparer = descriptor.Parser.Comparer; List? parsedValues = info.ParsedValue as List; - if (parsedValues == null) + if (parsedValues is null) { Debug.Assert(info.ParsedValue.GetType() == value.GetType(), "Stored value does not have the same type as 'value'."); @@ -479,9 +479,9 @@ internal bool RemoveParsedValue(HeaderDescriptor descriptor, object value) internal bool ContainsParsedValue(HeaderDescriptor descriptor, object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); - if (_headerStore == null) + if (_headerStore is null) { return false; } @@ -490,12 +490,12 @@ internal bool ContainsParsedValue(HeaderDescriptor descriptor, object value) // value with 'item'. If we have a list of values, then compare each item in the list with 'item'. if (TryGetAndParseHeaderInfo(descriptor, out HeaderStoreItemInfo? info)) { - Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); + Debug.Assert(descriptor.Parser is not null, "Can't add parsed value if there is no parser available."); Debug.Assert(descriptor.Parser.SupportsMultipleValues, "This method should not be used for single-value headers. Use equality comparer instead."); // If there is no entry, just return. - if (info.ParsedValue == null) + if (info.ParsedValue is null) { return false; } @@ -504,7 +504,7 @@ internal bool ContainsParsedValue(HeaderDescriptor descriptor, object value) IEqualityComparer? comparer = descriptor.Parser.Comparer; - if (parsedValues == null) + if (parsedValues is null) { Debug.Assert(info.ParsedValue.GetType() == value.GetType(), "Stored value does not have the same type as 'value'."); @@ -533,7 +533,7 @@ internal bool ContainsParsedValue(HeaderDescriptor descriptor, object value) internal virtual void AddHeaders(HttpHeaders sourceHeaders) { - Debug.Assert(sourceHeaders != null); + Debug.Assert(sourceHeaders is not null); Debug.Assert(GetType() == sourceHeaders.GetType(), "Can only copy headers from an instance of the same type."); Dictionary? sourceHeadersStore = sourceHeaders._headerStore; @@ -581,9 +581,9 @@ private void AddHeaderInfo(HeaderDescriptor descriptor, HeaderStoreItemInfo sour HeaderStoreItemInfo destinationInfo = CreateAndAddHeaderToStore(descriptor); // We have custom header values. The parsed values are strings. - if (descriptor.Parser == null) + if (descriptor.Parser is null) { - Debug.Assert((sourceInfo.RawValue == null) && (sourceInfo.InvalidValue == null), + Debug.Assert((sourceInfo.RawValue is null) && (sourceInfo.InvalidValue is null), "No raw or invalid values expected for custom headers."); // Custom header values are always stored as string or list of strings. @@ -598,10 +598,10 @@ private void AddHeaderInfo(HeaderDescriptor descriptor, HeaderStoreItemInfo sour destinationInfo.InvalidValue = CloneStringHeaderInfoValues(sourceInfo.InvalidValue); // Now clone and add parsed values (if any). - if (sourceInfo.ParsedValue != null) + if (sourceInfo.ParsedValue is not null) { List? sourceValues = sourceInfo.ParsedValue as List; - if (sourceValues == null) + if (sourceValues is null) { CloneAndAddValue(destinationInfo, sourceInfo.ParsedValue); } @@ -633,13 +633,13 @@ private static void CloneAndAddValue(HeaderStoreItemInfo destinationInfo, object [return: NotNullIfNotNull("source")] private static object? CloneStringHeaderInfoValues(object? source) { - if (source == null) + if (source is null) { return null; } List? sourceValues = source as List; - if (sourceValues == null) + if (sourceValues is null) { // If we just have one value, return the reference to the string (strings are immutable so it's OK // to use the reference). @@ -682,7 +682,7 @@ private HeaderStoreItemInfo GetOrCreateHeaderInfo(HeaderDescriptor descriptor, b result = CreateAndAddHeaderToStore(descriptor); } - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } @@ -707,7 +707,7 @@ private void AddHeaderToStore(HeaderDescriptor descriptor, object value) private bool TryGetHeaderValue(HeaderDescriptor descriptor, [NotNullWhen(true)] out object? value) { - if (_headerStore == null) + if (_headerStore is null) { value = null; return false; @@ -745,11 +745,11 @@ private bool ParseRawHeaderValues(HeaderDescriptor descriptor, HeaderStoreItemIn { // Unlike TryGetHeaderInfo() this method tries to parse all non-validated header values (if any) // before returning to the caller. - if (info.RawValue != null) + if (info.RawValue is not null) { List? rawValues = info.RawValue as List; - if (rawValues == null) + if (rawValues is null) { ParseSingleRawHeaderValue(descriptor, info); } @@ -765,13 +765,13 @@ private bool ParseRawHeaderValues(HeaderDescriptor descriptor, HeaderStoreItemIn // During parsing, we removed the value since it contains invalid newline chars. Return false to indicate that // this is an empty header. If the caller specified to remove empty headers, we'll remove the header before // returning. - if ((info.InvalidValue == null) && (info.ParsedValue == null)) + if ((info.InvalidValue is null) && (info.ParsedValue is null)) { if (removeEmptyHeader) { // After parsing the raw value, no value is left because all values contain invalid newline // chars. - Debug.Assert(_headerStore != null); + Debug.Assert(_headerStore is not null); _headerStore.Remove(descriptor); } return false; @@ -784,7 +784,7 @@ private bool ParseRawHeaderValues(HeaderDescriptor descriptor, HeaderStoreItemIn private static void ParseMultipleRawHeaderValues(HeaderDescriptor descriptor, HeaderStoreItemInfo info, List rawValues) { - if (descriptor.Parser == null) + if (descriptor.Parser is null) { foreach (string rawValue in rawValues) { @@ -809,9 +809,9 @@ private static void ParseMultipleRawHeaderValues(HeaderDescriptor descriptor, He private static void ParseSingleRawHeaderValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info) { string? rawValue = info.RawValue as string; - Debug.Assert(rawValue != null, "RawValue must either be List or string."); + Debug.Assert(rawValue is not null, "RawValue must either be List or string."); - if (descriptor.Parser == null) + if (descriptor.Parser is null) { if (!ContainsInvalidNewLine(rawValue, descriptor.Name)) { @@ -839,7 +839,7 @@ internal bool TryParseAndAddValue(HeaderDescriptor descriptor, string? value) bool result = TryParseAndAddRawHeaderValue(descriptor, info, value, false); - if (result && addToStore && (info.ParsedValue != null)) + if (result && addToStore && (info.ParsedValue is not null)) { // If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add // it to the store if we added at least one value. @@ -852,8 +852,8 @@ internal bool TryParseAndAddValue(HeaderDescriptor descriptor, string? value) // See ParseAndAddValue private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, string? value, bool addWhenInvalid) { - Debug.Assert(info != null); - Debug.Assert(descriptor.Parser != null); + Debug.Assert(info is not null); + Debug.Assert(descriptor.Parser is not null); // Values are added as 'invalid' if we either can't parse the value OR if we already have a value // and the current header doesn't support multiple values: e.g. trying to add a date/time value @@ -873,9 +873,9 @@ private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, He if (descriptor.Parser.TryParseValue(value, info.ParsedValue, ref index, out object? parsedValue)) { // The raw string only represented one value (which was successfully parsed). Add the value and return. - if ((value == null) || (index == value.Length)) + if ((value is null) || (index == value.Length)) { - if (parsedValue != null) + if (parsedValue is not null) { AddValue(info, parsedValue, StoreLocation.Parsed); } @@ -886,7 +886,7 @@ private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, He // If we successfully parsed a value, but there are more left to read, store the results in a temp // list. Only when all values are parsed successfully write the list to the store. List parsedValues = new List(); - if (parsedValue != null) + if (parsedValue is not null) { parsedValues.Add(parsedValue); } @@ -895,7 +895,7 @@ private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, He { if (descriptor.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue)) { - if (parsedValue != null) + if (parsedValue is not null) { parsedValues.Add(parsedValue); } @@ -918,7 +918,7 @@ private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, He return true; } - Debug.Assert(value != null); + Debug.Assert(value is not null); if (!ContainsInvalidNewLine(value, descriptor.Name) && addWhenInvalid) { AddValue(info, value ?? string.Empty, StoreLocation.Invalid); @@ -951,7 +951,7 @@ private static void AddValue(HeaderStoreItemInfo info, object? value, StoreLocat break; case StoreLocation.Parsed: - Debug.Assert((value == null) || (!(value is List)), + Debug.Assert((value is null) || (!(value is List)), "Header value types must not derive from List since this type is used internally to store " + "lists of values. So we would not be able to distinguish between a single value and a list of values."); currentStoreValue = info.ParsedValue; @@ -970,7 +970,7 @@ private static void AddValueToStoreValue(object? value, ref object? currentSt // If there is no value set yet, then add current item as value (we don't create a list // if not required). If 'info.Value' is already assigned then make sure 'info.Value' is a // List and append 'item' to the list. - if (currentStoreValue == null) + if (currentStoreValue is null) { currentStoreValue = value; } @@ -978,7 +978,7 @@ private static void AddValueToStoreValue(object? value, ref object? currentSt { List? storeValues = currentStoreValue as List; - if (storeValues == null) + if (storeValues is null) { storeValues = new List(2); Debug.Assert(currentStoreValue is T); @@ -1022,9 +1022,9 @@ private void PrepareHeaderInfoForAdd(HeaderDescriptor descriptor, out HeaderStor private void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, string? value) { - Debug.Assert(info != null); + Debug.Assert(info is not null); - if (descriptor.Parser == null) + if (descriptor.Parser is null) { // If we don't have a parser for the header, we consider the value valid if it doesn't contains // invalid newline characters. We add the values as "parsed value". Note that we allow empty values. @@ -1046,11 +1046,11 @@ private void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo i // The raw string only represented one value (which was successfully parsed). Add the value and return. // If value is null we still have to first call ParseValue() to allow the parser to decide whether null is // a valid value. If it is (i.e. no exception thrown), we set the parsed value (if any) and return. - if ((value == null) || (index == value.Length)) + if ((value is null) || (index == value.Length)) { // If the returned value is null, then it means the header accepts empty values. i.e. we don't throw // but we don't add 'null' to the store either. - if (parsedValue != null) + if (parsedValue is not null) { AddValue(info, parsedValue, StoreLocation.Parsed); } @@ -1061,7 +1061,7 @@ private void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo i // If we successfully parsed a value, but there are more left to read, store the results in a temp // list. Only when all values are parsed successfully write the list to the store. List parsedValues = new List(); - if (parsedValue != null) + if (parsedValue is not null) { parsedValues.Add(parsedValue); } @@ -1069,7 +1069,7 @@ private void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo i while (index < value.Length) { parsedValue = descriptor.Parser.ParseValue(value, info.ParsedValue, ref index); - if (parsedValue != null) + if (parsedValue is not null) { parsedValues.Add(parsedValue); } @@ -1133,7 +1133,7 @@ private bool TryGetHeaderDescriptor(string name, out HeaderDescriptor descriptor private static void CheckInvalidNewLine(string? value) { - if (value == null) + if (value is null) { return; } @@ -1189,7 +1189,7 @@ private static string[] GetValuesAsStrings(HeaderDescriptor descriptor, object v values = Array.Empty(); } - Debug.Assert(values != null); + Debug.Assert(values is not null); return values; } @@ -1232,7 +1232,7 @@ internal static int GetValuesAsStrings(HeaderDescriptor descriptor, object sourc private static int GetValueCount(HeaderStoreItemInfo info) { - Debug.Assert(info != null); + Debug.Assert(info is not null); int valueCount = Count(info.RawValue); valueCount += Count(info.InvalidValue); @@ -1248,17 +1248,17 @@ static int Count(object? valueStore) => private static void ReadStoreValues(string?[] values, object? storeValue, HttpHeaderParser? parser, T exclude, ref int currentIndex) { - Debug.Assert(values != null); + Debug.Assert(values is not null); - if (storeValue != null) + if (storeValue is not null) { List? storeValues = storeValue as List; - if (storeValues == null) + if (storeValues is null) { if (ShouldAdd(storeValue, parser, exclude)) { - values[currentIndex] = parser == null ? storeValue.ToString() : parser.ToString(storeValue); + values[currentIndex] = parser is null ? storeValue.ToString() : parser.ToString(storeValue); currentIndex++; } } @@ -1268,8 +1268,8 @@ private static void ReadStoreValues(string?[] values, object? storeValue, Htt { if (ShouldAdd(item, parser, exclude)) { - Debug.Assert(item != null); - values[currentIndex] = parser == null ? item.ToString() : parser.ToString(item); + Debug.Assert(item is not null); + values[currentIndex] = parser is null ? item.ToString() : parser.ToString(item); currentIndex++; } } @@ -1280,9 +1280,9 @@ private static void ReadStoreValues(string?[] values, object? storeValue, Htt private static bool ShouldAdd(object? storeValue, HttpHeaderParser? parser, T exclude) { bool add = true; - if (parser != null && exclude != null) + if (parser is not null && exclude is not null) { - if (parser.Comparer != null) + if (parser.Comparer is not null) { add = !parser.Comparer.Equals(exclude, storeValue); } @@ -1296,9 +1296,9 @@ private static bool ShouldAdd(object? storeValue, HttpHeaderParser? parser, T private bool AreEqual(object value, object? storeValue, IEqualityComparer? comparer) { - Debug.Assert(value != null); + Debug.Assert(value is not null); - if (comparer != null) + if (comparer is not null) { return comparer.Equals(value, storeValue); } @@ -1319,7 +1319,7 @@ internal HeaderStoreItemInfo() { } internal bool CanAddValue(HttpHeaderParser parser) { - Debug.Assert(parser != null, "There should be no reason to call CanAddValue if there is no parser for the current header."); + Debug.Assert(parser is not null, "There should be no reason to call CanAddValue if there is no parser for the current header."); // If the header only supports one value, and we have already a value set, then we can't add // another value. E.g. the 'Date' header only supports one value. We can't add multiple timestamps @@ -1330,10 +1330,10 @@ internal bool CanAddValue(HttpHeaderParser parser) // supporting 1 value. When the first value gets parsed, CanAddValue returns true and we add the // parsed value to ParsedValue. When the second value is parsed, CanAddValue returns false, because // we have already a parsed value. - return parser.SupportsMultipleValues || ((InvalidValue == null) && (ParsedValue == null)); + return parser.SupportsMultipleValues || ((InvalidValue is null) && (ParsedValue is null)); } - internal bool IsEmpty => (RawValue == null) && (InvalidValue == null) && (ParsedValue == null); + internal bool IsEmpty => (RawValue is null) && (InvalidValue is null) && (ParsedValue is null); } #endregion } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs index b2eacbfd619f00..531875a325246e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs @@ -85,7 +85,7 @@ public bool? ExpectContinue } else { - _expectContinueSet = value != null; + _expectContinueSet = value is not null; ExpectCore.RemoveSpecialValue(); } } @@ -102,7 +102,7 @@ public string? From value = null; } - if ((value != null) && !HeaderUtilities.IsValidEmailAddress(value)) + if ((value is not null) && !HeaderUtilities.IsValidEmailAddress(value)) { throw new FormatException(SR.net_http_headers_invalid_from_header); } @@ -121,7 +121,7 @@ public string? Host value = null; } - if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false, out string? _) != value.Length)) + if ((value is not null) && (HttpRuleParser.GetHostLength(value, 0, false, out string? _) != value.Length)) { throw new FormatException(SR.net_http_headers_invalid_host_header); } @@ -158,7 +158,7 @@ public int? MaxForwards get { object? storedValue = GetParsedValues(KnownHeaders.MaxForwards.Descriptor); - if (storedValue != null) + if (storedValue is not null) { return (int)storedValue; } @@ -274,10 +274,10 @@ internal override void AddHeaders(HttpHeaders sourceHeaders) { base.AddHeaders(sourceHeaders); HttpRequestHeaders? sourceRequestHeaders = sourceHeaders as HttpRequestHeaders; - Debug.Assert(sourceRequestHeaders != null); + Debug.Assert(sourceRequestHeaders is not null); // Copy special values but do not overwrite. - if (sourceRequestHeaders._generalHeaders != null) + if (sourceRequestHeaders._generalHeaders is not null) { GeneralHeaders.AddSpecialsFrom(sourceRequestHeaders._generalHeaders); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs index 2c03f00acf7972..b21dd7c4562094 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs @@ -27,7 +27,7 @@ private T GetSpecializedCollection(int slot, Func cre // allocated. Then we only pay for the 45 bytes for those fields when any is actually accessed. object[] collections = _specialCollectionsSlots ?? (_specialCollectionsSlots = new object[NumCollectionsSlots]); object result = collections[slot]; - if (result == null) + if (result is null) { collections[slot] = result = creationFunc(this)!; } @@ -151,10 +151,10 @@ internal override void AddHeaders(HttpHeaders sourceHeaders) { base.AddHeaders(sourceHeaders); HttpResponseHeaders? sourceResponseHeaders = sourceHeaders as HttpResponseHeaders; - Debug.Assert(sourceResponseHeaders != null); + Debug.Assert(sourceResponseHeaders is not null); // Copy special values, but do not overwrite - if (sourceResponseHeaders._generalHeaders != null) + if (sourceResponseHeaders._generalHeaders is not null) { GeneralHeaders.AddSpecialsFrom(sourceResponseHeaders._generalHeaders); } @@ -166,7 +166,7 @@ internal override bool IsAllowedHeaderName(HeaderDescriptor descriptor) return true; KnownHeader? knownHeader = KnownHeaders.TryGetKnownHeader(descriptor.Name); - if (knownHeader == null) + if (knownHeader is null) return true; return (knownHeader.HeaderType & HttpHeaderType.NonTrailing) == 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/KnownHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/KnownHeaders.cs index ccccd5e6e6cf61..eab3045bcbc578 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/KnownHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/KnownHeaders.cs @@ -408,7 +408,7 @@ public BytePtrAccessor(byte* p, int length) internal static KnownHeader? TryGetKnownHeader(string name) { KnownHeader? candidate = GetCandidate(new StringAccessor(name)); - if (candidate != null && StringComparer.OrdinalIgnoreCase.Equals(name, candidate.Name)) + if (candidate is not null && StringComparer.OrdinalIgnoreCase.Equals(name, candidate.Name)) { return candidate; } @@ -421,7 +421,7 @@ public BytePtrAccessor(byte* p, int length) fixed (byte* p = &MemoryMarshal.GetReference(name)) { KnownHeader? candidate = GetCandidate(new BytePtrAccessor(p, name.Length)); - if (candidate != null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate.Name, name)) + if (candidate is not null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate.Name, name)) { return candidate; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderParser.cs index 42e4cf3f043fc5..2b8b0da06feeb1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderParser.cs @@ -17,7 +17,7 @@ internal class MediaTypeHeaderParser : BaseHeaderParser private MediaTypeHeaderParser(bool supportsMultipleValues, Func mediaTypeCreator) : base(supportsMultipleValues) { - Debug.Assert(mediaTypeCreator != null); + Debug.Assert(mediaTypeCreator is not null); _supportsMultipleValues = supportsMultipleValues; _mediaTypeCreator = mediaTypeCreator; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderValue.cs index 430b9dbeee59b4..19e1f67b05d83c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/MediaTypeHeaderValue.cs @@ -21,7 +21,7 @@ public string? CharSet get { NameValueHeaderValue? charSetParameter = NameValueHeaderValue.Find(_parameters, charSet); - if (charSetParameter != null) + if (charSetParameter is not null) { return charSetParameter.Value; } @@ -35,14 +35,14 @@ public string? CharSet if (string.IsNullOrEmpty(value)) { // Remove charset parameter - if (charSetParameter != null) + if (charSetParameter is not null) { _parameters!.Remove(charSetParameter); } } else { - if (charSetParameter != null) + if (charSetParameter is not null) { charSetParameter.Value = value; } @@ -74,11 +74,11 @@ internal MediaTypeHeaderValue() protected MediaTypeHeaderValue(MediaTypeHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _mediaType = source._mediaType; - if (source._parameters != null) + if (source._parameters is not null) { foreach (var parameter in source._parameters) { @@ -105,7 +105,7 @@ public override bool Equals(object? obj) { MediaTypeHeaderValue? other = obj as MediaTypeHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -142,7 +142,7 @@ public static bool TryParse([NotNullWhen(true)] string? input, [NotNullWhen(true internal static int GetMediaTypeLength(string? input, int startIndex, Func mediaTypeCreator, out MediaTypeHeaderValue? parsedValue) { - Debug.Assert(mediaTypeCreator != null); + Debug.Assert(mediaTypeCreator is not null); Debug.Assert(startIndex >= 0); parsedValue = null; @@ -192,7 +192,7 @@ internal static int GetMediaTypeLength(string? input, int startIndex, private static int GetMediaTypeExpressionLength(string input, int startIndex, out string? mediaType) { - Debug.Assert((input != null) && (input.Length > 0) && (startIndex < input.Length)); + Debug.Assert((input is not null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the "type/subtype" string, it does not parse parameters. mediaType = null; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueHeaderValue.cs index ccda2cb76f3bce..3c97fccaa18ef4 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueHeaderValue.cs @@ -53,7 +53,7 @@ public NameValueHeaderValue(string name, string? value) protected NameValueHeaderValue(NameValueHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _name = source._name; _value = source._value; @@ -61,7 +61,7 @@ protected NameValueHeaderValue(NameValueHeaderValue source) public override int GetHashCode() { - Debug.Assert(_name != null); + Debug.Assert(_name is not null); int nameHashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(_name); @@ -84,7 +84,7 @@ public override bool Equals(object? obj) { NameValueHeaderValue? other = obj as NameValueHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -167,9 +167,9 @@ private void AddToStringBuilder(StringBuilder sb) internal static void ToString(ObjectCollection? values, char separator, bool leadingSeparator, StringBuilder destination) { - Debug.Assert(destination != null); + Debug.Assert(destination is not null); - if ((values == null) || (values.Count == 0)) + if ((values is null) || (values.Count == 0)) { return; } @@ -187,7 +187,7 @@ internal static void ToString(ObjectCollection? values, ch internal static int GetHashCode(ObjectCollection? values) { - if ((values == null) || (values.Count == 0)) + if ((values is null) || (values.Count == 0)) { return 0; } @@ -208,9 +208,9 @@ internal static int GetNameValueLength(string input, int startIndex, out NameVal internal static int GetNameValueLength(string input, int startIndex, Func nameValueCreator, out NameValueHeaderValue? parsedValue) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(startIndex >= 0); - Debug.Assert(nameValueCreator != null); + Debug.Assert(nameValueCreator is not null); parsedValue = null; @@ -267,7 +267,7 @@ internal static int GetNameValueLength(string input, int startIndex, internal static int GetNameValueListLength(string? input, int startIndex, char delimiter, ObjectCollection nameValueCollection) { - Debug.Assert(nameValueCollection != null); + Debug.Assert(nameValueCollection is not null); Debug.Assert(startIndex >= 0); if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length)) @@ -305,9 +305,9 @@ internal static int GetNameValueListLength(string? input, int startIndex, char d internal static NameValueHeaderValue? Find(ObjectCollection? values, string name) { - Debug.Assert((name != null) && (name.Length > 0)); + Debug.Assert((name is not null) && (name.Length > 0)); - if ((values == null) || (values.Count == 0)) + if ((values is null) || (values.Count == 0)) { return null; } @@ -324,7 +324,7 @@ internal static int GetNameValueListLength(string? input, int startIndex, char d internal static int GetValueLength(string input, int startIndex) { - Debug.Assert(input != null); + Debug.Assert(input is not null); if (startIndex >= input.Length) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueWithParametersHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueWithParametersHeaderValue.cs index e5fefd53fe807c..10ba2d80416e23 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueWithParametersHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/NameValueWithParametersHeaderValue.cs @@ -36,7 +36,7 @@ internal NameValueWithParametersHeaderValue() protected NameValueWithParametersHeaderValue(NameValueWithParametersHeaderValue source) : base(source) { - if (source._parameters != null) + if (source._parameters is not null) { foreach (var parameter in source._parameters) { @@ -53,7 +53,7 @@ public override bool Equals(object? obj) { NameValueWithParametersHeaderValue? other = obj as NameValueWithParametersHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -100,7 +100,7 @@ public static bool TryParse([NotNullWhen(true)] string? input, [NotNullWhen(true internal static int GetNameValueWithParametersLength(string? input, int startIndex, out object? parsedValue) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(startIndex >= 0); parsedValue = null; @@ -122,7 +122,7 @@ internal static int GetNameValueWithParametersLength(string? input, int startInd current = current + HttpRuleParser.GetWhitespaceLength(input, current); NameValueWithParametersHeaderValue? nameValueWithParameters = nameValue as NameValueWithParametersHeaderValue; - Debug.Assert(nameValueWithParameters != null); + Debug.Assert(nameValueWithParameters is not null); // So far we have a valid name/value pair. Check if we have also parameters for the name/value pair. If // yes, parse parameters. E.g. something like "name=value; param1=value1; param2=value2". diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs index e7b3c4e9522389..283256d4c034c4 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs @@ -43,7 +43,7 @@ public void Add(T item) else { _validator.Invoke(item); - Debug.Assert(item != null); + Debug.Assert(item is not null); } if (_items is null) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductHeaderValue.cs index 1d307b8398fefa..cbd4d923ccaf05 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductHeaderValue.cs @@ -42,7 +42,7 @@ public ProductHeaderValue(string name, string? version) private ProductHeaderValue(ProductHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _name = source._name; _version = source._version; @@ -65,7 +65,7 @@ public override bool Equals(object? obj) { ProductHeaderValue? other = obj as ProductHeaderValue; - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs index 504976bbaba32c..74f53c55637357 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs @@ -28,7 +28,7 @@ public ProductInfoHeaderValue(string productName, string? productVersion) public ProductInfoHeaderValue(ProductHeaderValue product) { - if (product == null) + if (product is null) { throw new ArgumentNullException(nameof(product)); } @@ -44,7 +44,7 @@ public ProductInfoHeaderValue(string comment) private ProductInfoHeaderValue(ProductInfoHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _product = source._product; _comment = source._comment; @@ -56,9 +56,9 @@ private ProductInfoHeaderValue() public override string ToString() { - if (_product == null) + if (_product is null) { - Debug.Assert(_comment != null); + Debug.Assert(_comment is not null); return _comment; } return _product.ToString(); @@ -68,12 +68,12 @@ public override bool Equals(object? obj) { ProductInfoHeaderValue? other = obj as ProductInfoHeaderValue; - if (other == null) + if (other is null) { return false; } - if (_product == null) + if (_product is null) { // We compare comments using case-sensitive comparison. return string.Equals(_comment, other._comment, StringComparison.Ordinal); @@ -84,9 +84,9 @@ public override bool Equals(object? obj) public override int GetHashCode() { - if (_product == null) + if (_product is null) { - Debug.Assert(_comment != null); + Debug.Assert(_comment is not null); return _comment.GetHashCode(); } return _product.GetHashCode(); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs index ac2a3462958bef..85bd72745b5a16 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs @@ -28,7 +28,7 @@ public RangeConditionHeaderValue(DateTimeOffset date) public RangeConditionHeaderValue(EntityTagHeaderValue entityTag) { - if (entityTag == null) + if (entityTag is null) { throw new ArgumentNullException(nameof(entityTag)); } @@ -43,7 +43,7 @@ public RangeConditionHeaderValue(string entityTag) private RangeConditionHeaderValue(RangeConditionHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _entityTag = source._entityTag; _date = source._date; @@ -55,9 +55,9 @@ private RangeConditionHeaderValue() public override string ToString() { - if (_entityTag == null) + if (_entityTag is null) { - Debug.Assert(_date != null); + Debug.Assert(_date is not null); return HttpDateParser.DateToString(_date.Value); } return _entityTag.ToString(); @@ -67,15 +67,15 @@ public override bool Equals(object? obj) { RangeConditionHeaderValue? other = obj as RangeConditionHeaderValue; - if (other == null) + if (other is null) { return false; } - if (_entityTag == null) + if (_entityTag is null) { - Debug.Assert(_date != null); - return (other._date != null) && (_date.Value == other._date.Value); + Debug.Assert(_date is not null); + return (other._date is not null) && (_date.Value == other._date.Value); } return _entityTag.Equals(other._entityTag); @@ -83,9 +83,9 @@ public override bool Equals(object? obj) public override int GetHashCode() { - if (_entityTag == null) + if (_entityTag is null) { - Debug.Assert(_date != null); + Debug.Assert(_date is not null); return _date.Value.GetHashCode(); } @@ -166,7 +166,7 @@ internal static int GetRangeConditionLength(string? input, int startIndex, out o } RangeConditionHeaderValue result = new RangeConditionHeaderValue(); - if (entityTag == null) + if (entityTag is null) { result._date = date; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeHeaderValue.cs index a1ba30e4c693a9..4ee3d13f0cba94 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeHeaderValue.cs @@ -40,10 +40,10 @@ public RangeHeaderValue(long? from, long? to) private RangeHeaderValue(RangeHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _unit = source._unit; - if (source._ranges != null) + if (source._ranges is not null) { foreach (RangeItemHeaderValue range in source._ranges) { @@ -58,7 +58,7 @@ public override string ToString() sb.Append(_unit); sb.Append('='); - if (_ranges != null) + if (_ranges is not null) { bool first = true; foreach (RangeItemHeaderValue range in _ranges) @@ -85,7 +85,7 @@ public override bool Equals(object? obj) { RangeHeaderValue? other = obj as RangeHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -98,7 +98,7 @@ public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_unit); - if (_ranges != null) + if (_ranges is not null) { foreach (RangeItemHeaderValue range in _ranges) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs index 5cc5f5c44c7252..d7684fcee82e1a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs @@ -47,7 +47,7 @@ public RangeItemHeaderValue(long? from, long? to) private RangeItemHeaderValue(RangeItemHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _from = source._from; _to = source._to; @@ -57,7 +57,7 @@ public override string ToString() { if (!_from.HasValue) { - Debug.Assert(_to != null); + Debug.Assert(_to is not null); return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo); } else if (!_to.HasValue) @@ -72,7 +72,7 @@ public override bool Equals(object? obj) { RangeItemHeaderValue? other = obj as RangeItemHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -97,7 +97,7 @@ public override int GetHashCode() internal static int GetRangeItemListLength(string? input, int startIndex, ICollection rangeCollection) { - Debug.Assert(rangeCollection != null); + Debug.Assert(rangeCollection is not null); Debug.Assert(startIndex >= 0); if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length)) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs index db8f308dc82734..fb4be8f55f24a3 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs @@ -40,7 +40,7 @@ public RetryConditionHeaderValue(TimeSpan delta) private RetryConditionHeaderValue(RetryConditionHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _delta = source._delta; _date = source._date; @@ -56,7 +56,7 @@ public override string ToString() { return ((int)_delta.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo); } - Debug.Assert(_date != null); + Debug.Assert(_date is not null); return HttpDateParser.DateToString(_date.Value); } @@ -64,25 +64,25 @@ public override bool Equals(object? obj) { RetryConditionHeaderValue? other = obj as RetryConditionHeaderValue; - if (other == null) + if (other is null) { return false; } if (_delta.HasValue) { - return (other._delta != null) && (_delta.Value == other._delta.Value); + return (other._delta is not null) && (_delta.Value == other._delta.Value); } - Debug.Assert(_date != null); - return (other._date != null) && (_date.Value == other._date.Value); + Debug.Assert(_date is not null); + return (other._date is not null) && (_date.Value == other._date.Value); } public override int GetHashCode() { - if (_delta == null) + if (_delta is null) { - Debug.Assert(_date != null); + Debug.Assert(_date is not null); return _date.Value.GetHashCode(); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs index e004b2ac3e9d3e..994f9ca0578397 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs @@ -44,7 +44,7 @@ public StringWithQualityHeaderValue(string value, double quality) private StringWithQualityHeaderValue(StringWithQualityHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _value = source._value; _quality = source._quality; @@ -68,7 +68,7 @@ public override bool Equals(object? obj) { StringWithQualityHeaderValue? other = obj as StringWithQualityHeaderValue; - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderParser.cs index 1faee74b7a8995..b2277257520257 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderParser.cs @@ -22,7 +22,7 @@ private TransferCodingHeaderParser(bool supportsMultipleValues, Func transferCodingCreator) : base(supportsMultipleValues) { - Debug.Assert(transferCodingCreator != null); + Debug.Assert(transferCodingCreator is not null); _transferCodingCreator = transferCodingCreator; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderValue.cs index 7e767d877d0cdc..9ddcb2c88f3ff1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderValue.cs @@ -28,11 +28,11 @@ internal TransferCodingHeaderValue() protected TransferCodingHeaderValue(TransferCodingHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _value = source._value; - if (source._parameters != null) + if (source._parameters is not null) { foreach (var parameter in source._parameters) { @@ -70,7 +70,7 @@ public static bool TryParse([NotNullWhen(true)] string? input, [NotNullWhen(true internal static int GetTransferCodingLength(string input, int startIndex, Func transferCodingCreator, out TransferCodingHeaderValue? parsedValue) { - Debug.Assert(transferCodingCreator != null); + Debug.Assert(transferCodingCreator is not null); Debug.Assert(startIndex >= 0); parsedValue = null; @@ -131,7 +131,7 @@ public override bool Equals(object? obj) { TransferCodingHeaderValue? other = obj as TransferCodingHeaderValue; - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs index 6d89a4c2393c2c..41a82dad72d2ea 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs @@ -72,7 +72,7 @@ private ViaHeaderValue() private ViaHeaderValue(ViaHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _protocolName = source._protocolName; _protocolVersion = source._protocolVersion; @@ -107,7 +107,7 @@ public override bool Equals(object? obj) { ViaHeaderValue? other = obj as ViaHeaderValue; - if (other == null) + if (other is null) { return false; } @@ -177,7 +177,7 @@ internal static int GetViaLength(string? input, int startIndex, out object? pars { return 0; } - Debug.Assert(protocolVersion != null); + Debug.Assert(protocolVersion is not null); // Read in '[/] []' int receivedByLength = HttpRuleParser.GetHostLength(input, current, true, out string? receivedBy); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs index ab6cd609d17ce0..4bffd00ae0c308 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs @@ -65,7 +65,7 @@ private WarningHeaderValue() private WarningHeaderValue(WarningHeaderValue source) { - Debug.Assert(source != null); + Debug.Assert(source is not null); _code = source._code; _agent = source._agent; @@ -99,7 +99,7 @@ public override bool Equals(object? obj) { WarningHeaderValue? other = obj as WarningHeaderValue; - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpBaseStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpBaseStream.cs index 168dab895ca843..684009f6ee5023 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpBaseStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpBaseStream.cs @@ -38,7 +38,7 @@ public sealed override long Position protected static void ValidateBufferArgs(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -60,7 +60,7 @@ protected static void ValidateBufferArgs(byte[] buffer, int offset, int count) /// protected static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize) { - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs index cb68aaaf61ce53..49765137574aeb 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs @@ -484,7 +484,7 @@ public Task SendAsync(HttpRequestMessage request, HttpCompl private void CheckRequestBeforeSend(HttpRequestMessage request) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } @@ -577,7 +577,7 @@ private void HandleFailure(Exception e, bool telemetryStarted, HttpResponseMessa if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e); - if (toThrow != null) + if (toThrow is not null) { throw toThrow; } @@ -585,7 +585,7 @@ private void HandleFailure(Exception e, bool telemetryStarted, HttpResponseMessa private static bool StartSend(HttpRequestMessage request) { - if (HttpTelemetry.Log.IsEnabled() && request.RequestUri != null) + if (HttpTelemetry.Log.IsEnabled() && request.RequestUri is not null) { HttpTelemetry.Log.RequestStart(request); return true; @@ -708,11 +708,11 @@ private static void CheckRequestMessage(HttpRequestMessage request) private void PrepareRequestMessage(HttpRequestMessage request) { Uri? requestUri = null; - if ((request.RequestUri == null) && (_baseAddress == null)) + if ((request.RequestUri is null) && (_baseAddress is null)) { throw new InvalidOperationException(SR.net_http_client_invalid_requesturi); } - if (request.RequestUri == null) + if (request.RequestUri is null) { requestUri = _baseAddress; } @@ -721,7 +721,7 @@ private void PrepareRequestMessage(HttpRequestMessage request) // If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri. if (!request.RequestUri.IsAbsoluteUri) { - if (_baseAddress == null) + if (_baseAddress is null) { throw new InvalidOperationException(SR.net_http_client_invalid_requesturi); } @@ -733,13 +733,13 @@ private void PrepareRequestMessage(HttpRequestMessage request) } // We modified the original request Uri. Assign the new Uri to the request message. - if (requestUri != null) + if (requestUri is not null) { request.RequestUri = requestUri; } // Add default headers - if (_defaultRequestHeaders != null) + if (_defaultRequestHeaders is not null) { request.Headers.AddHeaders(_defaultRequestHeaders); } @@ -771,7 +771,7 @@ private void PrepareRequestMessage(HttpRequestMessage request) private static void CheckBaseAddress(Uri? baseAddress, string parameterName) { - if (baseAddress == null) + if (baseAddress is null) { return; // It's OK to not have a base address specified. } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs index 81de5ba140afe2..73e836072b52e7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs @@ -63,7 +63,7 @@ public CookieContainer CookieContainer get => _underlyingHandler.CookieContainer; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -256,7 +256,7 @@ public X509CertificateCollection ClientCertificates set { ThrowForModifiedManagedSslOptionsIfStarted(); - _underlyingHandler.SslOptions.RemoteCertificateValidationCallback = value != null ? + _underlyingHandler.SslOptions.RemoteCertificateValidationCallback = value is not null ? new ConnectHelper.CertificateCallbackMapper(value).ForSocketsHttpHandler : null; } @@ -291,7 +291,7 @@ public SslProtocols SslProtocols protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { - return DiagnosticsHandler.IsEnabled() && _diagnosticsHandler != null ? + return DiagnosticsHandler.IsEnabled() && _diagnosticsHandler is not null ? _diagnosticsHandler.Send(request, cancellationToken) : _underlyingHandler.Send(request, cancellationToken); } @@ -299,7 +299,7 @@ protected internal override HttpResponseMessage Send(HttpRequestMessage request, protected internal override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - return DiagnosticsHandler.IsEnabled() && _diagnosticsHandler != null ? + return DiagnosticsHandler.IsEnabled() && _diagnosticsHandler is not null ? _diagnosticsHandler.SendAsync(request, cancellationToken) : _underlyingHandler.SendAsync(request, cancellationToken); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs index 7ceae4eeacccea..fad57e9b414d50 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs @@ -76,8 +76,8 @@ static HttpContent() private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { - Debug.Assert(encoding != null); - Debug.Assert(preamble != null); + Debug.Assert(encoding is not null); + Debug.Assert(preamble is not null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, @@ -117,7 +117,7 @@ public HttpContentHeaders Headers { get { - if (_headers == null) + if (_headers is null) { _headers = new HttpContentHeaders(this); } @@ -127,12 +127,12 @@ public HttpContentHeaders Headers private bool IsBuffered { - get { return _bufferedContent != null; } + get { return _bufferedContent is not null; } } internal bool TryGetBuffer(out ArraySegment buffer) { - if (_bufferedContent != null) + if (_bufferedContent is not null) { return _bufferedContent.TryGetBuffer(out buffer); } @@ -190,7 +190,7 @@ internal static string ReadBufferAsString(ArraySegment buffer, HttpContent // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. - if (charset != null) + if (charset is not null) { try { @@ -217,7 +217,7 @@ internal static string ReadBufferAsString(ArraySegment buffer, HttpContent // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. - if (encoding == null) + if (encoding is null) { if (!TryDetectEncoding(buffer, out encoding, out bomLength)) { @@ -245,7 +245,7 @@ public Task ReadAsByteArrayAsync(CancellationToken cancellationToken) internal byte[] ReadBufferedContentAsByteArray() { - Debug.Assert(_bufferedContent != null); + Debug.Assert(_bufferedContent is not null); // The returned array is exposed out of the library, so use ToArray rather // than TryGetBuffer in order to make a copy. return _bufferedContent.ToArray(); @@ -262,7 +262,7 @@ public Stream ReadAsStream(CancellationToken cancellationToken) // initialized in TryReadAsStream/ReadAsStream), or a Task (it was previously initialized // in ReadAsStreamAsync). - if (_contentReadStream == null) // don't yet have a Stream + if (_contentReadStream is null) // don't yet have a Stream { Stream s = TryGetBuffer(out ArraySegment buffer) ? new MemoryStream(buffer.Array!, buffer.Offset, buffer.Count, writable: false) : @@ -292,7 +292,7 @@ public Task ReadAsStreamAsync(CancellationToken cancellationToken) // initialized in TryReadAsStream/ReadAsStream), or a Task (it was previously initialized here // in ReadAsStreamAsync). - if (_contentReadStream == null) // don't yet have a Stream + if (_contentReadStream is null) // don't yet have a Stream { Task t = TryGetBuffer(out ArraySegment buffer) ? Task.FromResult(new MemoryStream(buffer.Array!, buffer.Offset, buffer.Count, writable: false)) : @@ -321,7 +321,7 @@ public Task ReadAsStreamAsync(CancellationToken cancellationToken) // initialized in TryReadAsStream/ReadAsStream), or a Task (it was previously initialized here // in ReadAsStreamAsync). - if (_contentReadStream == null) // don't yet have a Stream + if (_contentReadStream is null) // don't yet have a Stream { Stream? s = TryGetBuffer(out ArraySegment buffer) ? new MemoryStream(buffer.Array!, buffer.Offset, buffer.Count, writable: false) : @@ -365,7 +365,7 @@ protected virtual Task SerializeToStreamAsync(Stream stream, TransportContext? c public void CopyTo(Stream stream, TransportContext? context, CancellationToken cancellationToken) { CheckDisposed(); - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -399,7 +399,7 @@ public Task CopyToAsync(Stream stream, TransportContext? context) => public Task CopyToAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { CheckDisposed(); - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -448,7 +448,7 @@ internal void LoadIntoBuffer(long maxBufferSize, CancellationToken cancellationT return; } - if (tempBuffer == null) + if (tempBuffer is null) { throw error!; } @@ -510,7 +510,7 @@ internal Task LoadIntoBufferAsync(long maxBufferSize, CancellationToken cancella return Task.CompletedTask; } - if (tempBuffer == null) + if (tempBuffer is null) { // We don't throw in LoadIntoBufferAsync(): return a faulted task. return Task.FromException(error!); @@ -643,7 +643,7 @@ private bool CreateTemporaryBuffer(long maxBufferSize, out MemoryStream? tempBuf // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; - if (contentLength != null) + if (contentLength is not null) { Debug.Assert(contentLength >= 0); @@ -669,7 +669,7 @@ protected virtual void Dispose(bool disposing) { _disposed = true; - if (_contentReadStream != null) + if (_contentReadStream is not null) { Stream? s = _contentReadStream as Stream ?? (_contentReadStream is Task t && t.Status == TaskStatus.RanToCompletion ? t.Result : null); @@ -704,7 +704,7 @@ private void CheckDisposed() private void CheckTaskNotNull(Task task) { - if (task == null) + if (task is null) { var e = new InvalidOperationException(SR.net_http_content_no_task_returned); if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e); @@ -742,8 +742,8 @@ private static int GetPreambleLength(ArraySegment buffer, Encoding encodin int offset = buffer.Offset; int dataLength = buffer.Count; - Debug.Assert(data != null); - Debug.Assert(encoding != null); + Debug.Assert(data is not null); + Debug.Assert(encoding is not null); switch (encoding.CodePage) { @@ -780,7 +780,7 @@ private static bool TryDetectEncoding(ArraySegment buffer, [NotNullWhen(tr int offset = buffer.Offset; int dataLength = buffer.Count; - Debug.Assert(data != null); + Debug.Assert(data is not null); if (dataLength >= 2) { @@ -826,7 +826,7 @@ private static bool TryDetectEncoding(ArraySegment buffer, [NotNullWhen(tr private static bool BufferHasPrefix(ArraySegment buffer, byte[] prefix) { byte[]? byteArray = buffer.Array; - if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0) + if (prefix is null || byteArray is null || prefix.Length > buffer.Count || prefix.Length == 0) return false; for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++) @@ -960,7 +960,7 @@ public LimitArrayPoolWriteStream(int maxBufferSize, long capacity) protected override void Dispose(bool disposing) { - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); ArrayPool.Shared.Return(_buffer); _buffer = null!; @@ -1017,7 +1017,7 @@ private void Grow(int value) public override void Write(byte[] buffer, int offset, int count) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs index 4988469f1ec03c..87ff4a96acbbd1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs @@ -22,7 +22,7 @@ public HttpMessageInvoker(HttpMessageHandler handler) public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler) { - if (handler == null) + if (handler is null) { throw new ArgumentNullException(nameof(handler)); } @@ -37,13 +37,13 @@ public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler) public virtual HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } CheckDisposed(); - if (HttpTelemetry.Log.IsEnabled() && !request.WasSentByHttpClient() && request.RequestUri != null) + if (HttpTelemetry.Log.IsEnabled() && !request.WasSentByHttpClient() && request.RequestUri is not null) { HttpTelemetry.Log.RequestStart(request); @@ -70,13 +70,13 @@ public virtual HttpResponseMessage Send(HttpRequestMessage request, public virtual Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } CheckDisposed(); - if (HttpTelemetry.Log.IsEnabled() && !request.WasSentByHttpClient() && request.RequestUri != null) + if (HttpTelemetry.Log.IsEnabled() && !request.WasSentByHttpClient() && request.RequestUri is not null) { return SendAsyncWithTelemetry(_handler, request, cancellationToken); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs index ccbae0f866706f..dcb31a2da44ecc 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs @@ -111,7 +111,7 @@ public HttpMethod(string method) private HttpMethod(string method, int? http3StaticTableIndex) : this(method) { - _http3EncodedBytes = http3StaticTableIndex != null ? + _http3EncodedBytes = http3StaticTableIndex is not null ? QPackEncoder.EncodeStaticIndexedHeaderFieldToArray(http3StaticTableIndex.GetValueOrDefault()) : QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.MethodGet, method); } @@ -178,7 +178,7 @@ internal static HttpMethod Normalize(HttpMethod method) // _http3EncodedBytes is only set for the singleton instances, so if it's not null, // we can avoid the dictionary lookup. Otherwise, look up the method instance in the // dictionary and return the normalized instance if it's found. - Debug.Assert(method != null); + Debug.Assert(method is not null); return method._http3EncodedBytes is null && s_knownMethods.TryGetValue(method, out HttpMethod? normalized) ? normalized : method; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestException.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestException.cs index a2b68319a21d4b..8b88cd90d83f33 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestException.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestException.cs @@ -21,7 +21,7 @@ public HttpRequestException(string? message) public HttpRequestException(string? message, Exception? inner) : base(message, inner) { - if (inner != null) + if (inner is not null) { HResult = inner.HResult; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs index eaa59cd022a886..93da01bbee3096 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs @@ -33,7 +33,7 @@ public Version Version get { return _version; } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -66,7 +66,7 @@ public HttpContent? Content if (NetEventSource.Log.IsEnabled()) { - if (value == null) + if (value is null) { NetEventSource.ContentNull(this); } @@ -86,7 +86,7 @@ public HttpMethod Method get { return _method; } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -101,7 +101,7 @@ public Uri? RequestUri get { return _requestUri; } set { - if ((value != null) && (value.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(value))) + if ((value is not null) && (value.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(value))) { throw new ArgumentException(HttpUtilities.InvalidUriMessage, nameof(value)); } @@ -117,7 +117,7 @@ public HttpRequestHeaders Headers { get { - if (_headers == null) + if (_headers is null) { _headers = new HttpRequestHeaders(); } @@ -125,7 +125,7 @@ public HttpRequestHeaders Headers } } - internal bool HasHeaders => _headers != null; + internal bool HasHeaders => _headers is not null; [Obsolete("Use Options instead.")] public IDictionary Properties => Options; @@ -165,13 +165,13 @@ public override string ToString() sb.Append(_method); sb.Append(", RequestUri: '"); - sb.Append(_requestUri == null ? "" : _requestUri.ToString()); + sb.Append(_requestUri is null ? "" : _requestUri.ToString()); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); - sb.Append(_content == null ? "" : _content.GetType().ToString()); + sb.Append(_content is null ? "" : _content.GetType().ToString()); sb.AppendLine(", Headers:"); HeaderUtilities.DumpHeaders(sb, _headers, _content?.Headers); @@ -187,7 +187,7 @@ private void InitializeValues(HttpMethod method, Uri? requestUri) { throw new ArgumentNullException(nameof(method)); } - if ((requestUri != null) && (requestUri.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(requestUri))) + if ((requestUri is not null) && (requestUri.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(requestUri))) { throw new ArgumentException(HttpUtilities.InvalidUriMessage, nameof(requestUri)); } @@ -214,7 +214,7 @@ protected virtual void Dispose(bool disposing) if (disposing && !_disposed) { _disposed = true; - if (_content != null) + if (_content is not null) { _content.Dispose(); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestOptions.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestOptions.cs index 195eb0d10fe621..befcf3301b11ce 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestOptions.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestOptions.cs @@ -53,4 +53,4 @@ public void Set(HttpRequestOptionsKey key, TValue value) Options[key.Key] = value; } } -} \ No newline at end of file +} diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs index dafe058a360696..80bc76931bbbf2 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs @@ -27,7 +27,7 @@ public Version Version set { #if !PHONE - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -50,7 +50,7 @@ public HttpContent Content if (NetEventSource.Log.IsEnabled()) { - if (value == null) + if (value is null) { NetEventSource.ContentNull(this); } @@ -85,7 +85,7 @@ public string? ReasonPhrase { get { - if (_reasonPhrase != null) + if (_reasonPhrase is not null) { return _reasonPhrase; } @@ -94,7 +94,7 @@ public string? ReasonPhrase } set { - if ((value != null) && ContainsNewLineCharacter(value)) + if ((value is not null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } @@ -137,7 +137,7 @@ public HttpRequestMessage? RequestMessage set { CheckDisposed(); - if (value != null) NetEventSource.Associate(this, value); + if (value is not null) NetEventSource.Associate(this, value); _requestMessage = value; } } @@ -194,12 +194,12 @@ public override string ToString() sb.Append(_version); sb.Append(", Content: "); - sb.Append(_content == null ? "" : _content.GetType().ToString()); + sb.Append(_content is null ? "" : _content.GetType().ToString()); sb.AppendLine(", Headers:"); HeaderUtilities.DumpHeaders(sb, _headers, _content?.Headers); - if (_trailingHeaders != null) + if (_trailingHeaders is not null) { sb.AppendLine(", Trailing Headers:"); HeaderUtilities.DumpHeaders(sb, _trailingHeaders); @@ -229,7 +229,7 @@ protected virtual void Dispose(bool disposing) if (disposing && !_disposed) { _disposed = true; - if (_content != null) + if (_content is not null) { _content.Dispose(); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs index 72fed31d318632..80579c1fe0aa84 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs @@ -66,7 +66,7 @@ internal static bool IsTokenChar(char character) internal static int GetTokenLength(string input, int startIndex) { - Debug.Assert(input != null); + Debug.Assert(input is not null); if (startIndex >= input.Length) { @@ -121,7 +121,7 @@ internal static string GetTokenString(ReadOnlySpan input) internal static int GetWhitespaceLength(string input, int startIndex) { - Debug.Assert(input != null); + Debug.Assert(input is not null); if (startIndex >= input.Length) { @@ -202,7 +202,7 @@ internal static bool ContainsInvalidNewLine(string value, int startIndex) internal static int GetNumberLength(string input, int startIndex, bool allowDecimal) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert((startIndex >= 0) && (startIndex < input.Length)); int current = startIndex; @@ -246,7 +246,7 @@ internal static int GetNumberLength(string input, int startIndex, bool allowDeci internal static int GetHostLength(string input, int startIndex, bool allowToken, out string? host) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(startIndex >= 0); host = null; @@ -308,7 +308,7 @@ internal static HttpParseResult GetQuotedStringLength(string input, int startInd // CHAR = internal static HttpParseResult GetQuotedPairLength(string input, int startIndex, out int length) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert((startIndex >= 0) && (startIndex < input.Length)); length = 0; @@ -344,7 +344,7 @@ internal static HttpParseResult GetQuotedPairLength(string input, int startIndex private static HttpParseResult GetExpressionLength(string input, int startIndex, char openChar, char closeChar, bool supportsNesting, int nestedCount, out int length) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert((startIndex >= 0) && (startIndex < input.Length)); length = 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs index 5879581504f45e..05ebc2d2e21a11 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs @@ -46,7 +46,7 @@ private void RequestStart(string scheme, string host, int port, string pathAndQu [NonEvent] public void RequestStart(HttpRequestMessage request) { - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); RequestStart( request.RequestUri.Scheme, @@ -255,9 +255,9 @@ private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, int arg3 { if (IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg4 == null) arg4 = ""; + if (arg1 is null) arg1 = ""; + if (arg2 is null) arg2 = ""; + if (arg4 is null) arg4 = ""; fixed (char* arg1Ptr = arg1) fixed (char* arg2Ptr = arg2) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpUtilities.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpUtilities.cs index e31e93080751e8..053e397af805aa 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpUtilities.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpUtilities.cs @@ -17,7 +17,7 @@ internal static partial class HttpUtilities internal static bool IsHttpUri(Uri uri) { - Debug.Assert(uri != null); + Debug.Assert(uri is not null); return IsSupportedScheme(uri.Scheme); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs index f903186995e70c..1eb4a76bb35534 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs @@ -30,7 +30,7 @@ protected abstract HttpResponseMessage ProcessResponse(HttpResponseMessage respo protected internal sealed override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } @@ -45,7 +45,7 @@ protected internal sealed override HttpResponseMessage Send(HttpRequestMessage r protected internal sealed override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } @@ -81,7 +81,7 @@ protected internal sealed override Task SendAsync(HttpReque return; } - if (task.Result == null) + if (task.Result is null) { sendState.TrySetException(ExceptionDispatchInfo.SetCurrentStackTrace(new InvalidOperationException(SR.net_http_handler_noresponse))); return; @@ -146,7 +146,7 @@ private sealed class SendState : TaskCompletionSource public SendState(MessageProcessingHandler handler, CancellationToken token) { - Debug.Assert(handler != null); + Debug.Assert(handler is not null); _handler = handler; _token = token; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs index 7ea8eb232f0397..e4758cc661767f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs @@ -111,7 +111,7 @@ private static string GetDefaultBoundary() public virtual void Add(HttpContent content) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -174,7 +174,7 @@ Collections.IEnumerator Collections.IEnumerable.GetEnumerator() // then the stream will be closed an exception thrown. protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); try { // Write start boundary. @@ -218,7 +218,7 @@ protected override Task SerializeToStreamAsync(Stream stream, TransportContext? private protected async Task SerializeToStreamAsyncCore(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); try { // Write start boundary. @@ -438,7 +438,7 @@ private sealed class ContentReadStream : Stream internal ContentReadStream(Stream[] streams) { - Debug.Assert(streams != null); + Debug.Assert(streams is not null); _streams = streams; foreach (Stream stream in streams) { @@ -479,7 +479,7 @@ public override int Read(byte[] buffer, int offset, int count) while (true) { - if (_current != null) + if (_current is not null) { int bytesRead = _current.Read(buffer, offset, count); if (bytesRead != 0) @@ -509,7 +509,7 @@ public override int Read(Span buffer) while (true) { - if (_current != null) + if (_current is not null) { int bytesRead = _current.Read(buffer); if (bytesRead != 0) @@ -554,7 +554,7 @@ public async ValueTask ReadAsyncPrivate(Memory buffer, CancellationTo while (true) { - if (_current != null) + if (_current is not null) { int bytesRead = await _current.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) @@ -643,7 +643,7 @@ public override long Seek(long offset, SeekOrigin origin) private static void ValidateReadArgs(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -691,7 +691,7 @@ private static void WriteToStream(Stream stream, string content, Encoding encodi } finally { - if (rentedBuffer != null) + if (rentedBuffer is not null) { ArrayPool.Shared.Return(rentedBuffer); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs index 2ea780aa3a65fa..876fc97771fc53 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs @@ -25,12 +25,12 @@ public MultipartFormDataContent(string boundary) public override void Add(HttpContent content) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } - if (content.Headers.ContentDisposition == null) + if (content.Headers.ContentDisposition is null) { content.Headers.ContentDisposition = new ContentDispositionHeaderValue(formData); } @@ -40,7 +40,7 @@ public override void Add(HttpContent content) public void Add(HttpContent content, string name) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -54,7 +54,7 @@ public void Add(HttpContent content, string name) public void Add(HttpContent content, string name, string fileName) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -72,7 +72,7 @@ public void Add(HttpContent content, string name, string fileName) private void AddInternal(HttpContent content, string name, string? fileName) { - if (content.Headers.ContentDisposition == null) + if (content.Headers.ContentDisposition is null) { ContentDispositionHeaderValue header = new ContentDispositionHeaderValue(formData); header.Name = name; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs b/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs index d30e6cc90e7c2f..67721387d8e529 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs @@ -78,8 +78,8 @@ private unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3, string { if (IsEnabled()) { - if (arg4 == null) arg4 = ""; - if (arg5 == null) arg5 = ""; + if (arg4 is null) arg4 = ""; + if (arg5 is null) arg5 = ""; fixed (char* string4Bytes = arg4) fixed (char* string5Bytes = arg5) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs index 6def0c00e3b5d7..4be34edadb604b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs @@ -109,7 +109,7 @@ internal partial class AuthenticationHelper // Add nonce sb.AppendKeyValue(Nonce, nonce); - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); // Add uri sb.AppendKeyValue(Uri, request.RequestUri.PathAndQuery); @@ -151,7 +151,7 @@ internal partial class AuthenticationHelper string a2 = request.Method.Method + ":" + request.RequestUri.PathAndQuery; if (qop == AuthInt) { - string content = request.Content == null ? string.Empty : await request.Content.ReadAsStringAsync().ConfigureAwait(false); + string content = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync().ConfigureAwait(false); a2 = a2 + ":" + ComputeHash(content, algorithm); } @@ -173,10 +173,10 @@ internal partial class AuthenticationHelper } // Add response - sb.AppendKeyValue(Response, response, includeComma: opaque != null || isAlgorithmSpecified || isQopSpecified); + sb.AppendKeyValue(Response, response, includeComma: opaque is not null || isAlgorithmSpecified || isQopSpecified); // Add opaque - if (opaque != null) + if (opaque is not null) { sb.AppendKeyValue(Opaque, opaque, includeComma: isAlgorithmSpecified || isQopSpecified); } @@ -404,7 +404,7 @@ private unsafe void Parse(string challenge) string? value = GetNextValue(challenge, parsedIndex, MustValueBeQuoted(key), out parsedIndex); // Ensure value is valid. if (string.IsNullOrEmpty(value) - && (value == null || !key.Equals(Opaque, StringComparison.OrdinalIgnoreCase))) + && (value is null || !key.Equals(Opaque, StringComparison.OrdinalIgnoreCase))) break; // Add the key-value pair to Parameters. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs index 3b2e5694451057..fafe08f64dca54 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs @@ -67,7 +67,7 @@ private static async Task SendWithNtAuthAsync(HttpRequestMe #pragma warning disable CS8600 (connection, response) = await connectionPool.CreateHttp11ConnectionAsync(request, async, cancellationToken).ConfigureAwait(false); #pragma warning restore CS8600 - if (response != null) + if (response is not null) { return response; } @@ -88,7 +88,7 @@ private static async Task SendWithNtAuthAsync(HttpRequestMe // Ignore the 'Host' header if this is proxy authentication since we need to use // the host name of the proxy itself for SPN calculation. string hostName; - if (!isProxyAuth && request.HasHeaders && request.Headers.Host != null) + if (!isProxyAuth && request.HasHeaders && request.Headers.Host is not null) { // Use the host name without any normalization. hostName = request.Headers.Host; @@ -134,7 +134,7 @@ private static async Task SendWithNtAuthAsync(HttpRequestMe while (true) { string? challengeResponse = authContext.GetOutgoingBlob(challengeData); - if (challengeResponse == null) + if (challengeResponse is null) { // Response indicated denial even after login, so stop processing and return current response. break; @@ -181,7 +181,7 @@ public static Task SendWithNtProxyAuthAsync(HttpRequestMess public static Task SendWithNtConnectionAuthAsync(HttpRequestMessage request, bool async, ICredentials credentials, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken) { - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); return SendWithNtAuthAsync(request, request.RequestUri, async, credentials, isProxyAuth: false, connection, connectionPool, cancellationToken); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.cs index 44d5a48c8cf9ae..30085c007b6533 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.cs @@ -47,7 +47,7 @@ private static bool TryGetChallengeDataForScheme(string scheme, HttpHeaderValueC { if (StringComparer.OrdinalIgnoreCase.Equals(scheme, ahv.Scheme)) { - // Note, a valid challenge can have challengeData == null + // Note, a valid challenge can have challengeData is null challengeData = ahv.Parameter; return true; } @@ -88,7 +88,7 @@ private static bool TryGetValidAuthenticationChallengeForScheme(string scheme, A } NetworkCredential? credential = credentials.GetCredential(uri, scheme); - if (credential == null) + if (credential is null) { // We have no credential for this auth type, so we can't respond to the challenge. // We'll continue to look for a different auth type that we do have a credential for. @@ -218,19 +218,19 @@ private static async ValueTask SendWithAuthAsync(HttpReques bool performedBasicPreauth = false; if (preAuthenticate) { - Debug.Assert(pool.PreAuthCredentials != null); + Debug.Assert(pool.PreAuthCredentials is not null); NetworkCredential? credential; lock (pool.PreAuthCredentials) { // Just look for basic credentials. If in the future we support preauth // for other schemes, this will need to search in order of precedence. - Debug.Assert(pool.PreAuthCredentials.GetCredential(authUri, NegotiateScheme) == null); - Debug.Assert(pool.PreAuthCredentials.GetCredential(authUri, NtlmScheme) == null); - Debug.Assert(pool.PreAuthCredentials.GetCredential(authUri, DigestScheme) == null); + Debug.Assert(pool.PreAuthCredentials.GetCredential(authUri, NegotiateScheme) is null); + Debug.Assert(pool.PreAuthCredentials.GetCredential(authUri, NtlmScheme) is null); + Debug.Assert(pool.PreAuthCredentials.GetCredential(authUri, DigestScheme) is null); credential = pool.PreAuthCredentials.GetCredential(authUri, BasicScheme); } - if (credential != null) + if (credential is not null) { SetBasicAuthToken(request, credential, isProxyAuth); performedBasicPreauth = true; @@ -332,7 +332,7 @@ public static ValueTask SendWithProxyAuthAsync(HttpRequestM public static ValueTask SendWithRequestAuthAsync(HttpRequestMessage request, bool async, ICredentials credentials, bool preAuthenticate, HttpConnectionPool pool, CancellationToken cancellationToken) { - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); return SendWithAuthAsync(request, request.RequestUri, async, credentials, preAuthenticate, isProxyAuth: false, doRequestAuth: true, pool, cancellationToken); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingReadStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingReadStream.cs index b9ccbcef76d653..ec28e745455f4a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingReadStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingReadStream.cs @@ -31,13 +31,13 @@ private sealed class ChunkedEncodingReadStream : HttpContentReadStream public ChunkedEncodingReadStream(HttpConnection connection, HttpResponseMessage response) : base(connection) { - Debug.Assert(response != null, "The HttpResponseMessage cannot be null."); + Debug.Assert(response is not null, "The HttpResponseMessage cannot be null."); _response = response; } public override int Read(Span buffer) { - if (_connection == null || buffer.Length == 0) + if (_connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data. return 0; @@ -53,7 +53,7 @@ public override int Read(Span buffer) // Nothing available to consume. Fall back to I/O. while (true) { - if (_connection == null) + if (_connection is null) { // Fully consumed the response in ReadChunksFromConnectionBuffer. return 0; @@ -102,7 +102,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken return ValueTask.FromCanceled(cancellationToken); } - if (_connection == null || buffer.Length == 0) + if (_connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data. return new ValueTask(0); @@ -117,7 +117,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken // We may have just consumed the remainder of the response (with no actual data // available), so check again. - if (_connection == null) + if (_connection is null) { Debug.Assert(_state == ParsingState.Done); return new ValueTask(0); @@ -131,7 +131,7 @@ private async ValueTask ReadAsyncCore(Memory buffer, CancellationToke { // Should only be called if ReadChunksFromConnectionBuffer returned 0. - Debug.Assert(_connection != null); + Debug.Assert(_connection is not null); Debug.Assert(buffer.Length > 0); CancellationTokenRegistration ctr = _connection.RegisterCancellation(cancellationToken); @@ -139,7 +139,7 @@ private async ValueTask ReadAsyncCore(Memory buffer, CancellationToke { while (true) { - if (_connection == null) + if (_connection is null) { // Fully consumed the response in ReadChunksFromConnectionBuffer. return 0; @@ -195,7 +195,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : - _connection == null ? Task.CompletedTask : + _connection is null ? Task.CompletedTask : CopyToAsyncCore(destination, cancellationToken); } @@ -216,7 +216,7 @@ private async Task CopyToAsyncCore(Stream destination, CancellationToken cancell await destination.WriteAsync(bytesRead, cancellationToken).ConfigureAwait(false); } - if (_connection == null) + if (_connection is null) { // Fully consumed the response. return; @@ -256,7 +256,7 @@ private int ReadChunksFromConnectionBuffer(Span buffer, CancellationTokenR private ReadOnlyMemory ReadChunkFromConnectionBuffer(int maxBytesToRead, CancellationTokenRegistration cancellationRegistration) { - Debug.Assert(maxBytesToRead > 0 && _connection != null); + Debug.Assert(maxBytesToRead > 0 && _connection is not null); try { @@ -425,11 +425,11 @@ private enum ParsingState : byte Done } - public override bool NeedsDrain => (_connection != null); + public override bool NeedsDrain => (_connection is not null); public override async ValueTask DrainAsync(int maxDrainBytes) { - Debug.Assert(_connection != null); + Debug.Assert(_connection is not null); CancellationTokenSource? cts = null; CancellationTokenRegistration ctr = default; @@ -450,7 +450,7 @@ public override async ValueTask DrainAsync(int maxDrainBytes) // When ReadChunkFromConnectionBuffer reads the final chunk, it will clear out _connection // and return the connection to the pool. - if (_connection == null) + if (_connection is null) { return true; } @@ -460,7 +460,7 @@ public override async ValueTask DrainAsync(int maxDrainBytes) return false; } - if (cts == null) // only create the drain timer if we have to go async + if (cts is null) // only create the drain timer if we have to go async { TimeSpan drainTime = _connection._pool.Settings._maxResponseDrainTime; if (drainTime != Timeout.InfiniteTimeSpan) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingWriteStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingWriteStream.cs index e66dbf095cef91..08c8d48b89b8df 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingWriteStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingWriteStream.cs @@ -22,7 +22,7 @@ public override void Write(ReadOnlySpan buffer) BytesWritten += buffer.Length; HttpConnection connection = GetConnectionOrThrow(); - Debug.Assert(connection._currentRequest != null); + Debug.Assert(connection._currentRequest is not null); if (buffer.Length == 0) { @@ -44,7 +44,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo BytesWritten += buffer.Length; HttpConnection connection = GetConnectionOrThrow(); - Debug.Assert(connection._currentRequest != null); + Debug.Assert(connection._currentRequest is not null); // The token is ignored because it's coming from SendAsync and the only operations // here are those that are already covered by the token having been registered with diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs index e3079e8a836f6d..1eac2d486c72db 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs @@ -48,7 +48,7 @@ public static async ValueTask ConnectAsync(Func EstablishSslConnectionAsync(SslClientAuthenti // If there's a cert validation callback, and if it came from HttpClientHandler, // wrap the original delegate in order to change the sender to be the request message (expected by HttpClientHandler's delegate). RemoteCertificateValidationCallback? callback = sslOptions.RemoteCertificateValidationCallback; - if (callback != null && callback.Target is CertificateCallbackMapper mapper) + if (callback is not null && callback.Target is CertificateCallbackMapper mapper) { sslOptions = sslOptions.ShallowClone(); // Clone as we're about to mutate it and don't want to affect the cached copy Func localFromHttpClientHandler = mapper.FromHttpClientHandler; HttpRequestMessage localRequest = request; sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) => { - Debug.Assert(localRequest != null); + Debug.Assert(localRequest is not null); bool result = localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors); localRequest = null!; // ensure the SslOptions and this callback don't keep the first HttpRequestMessage alive indefinitely return result; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionCloseReadStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionCloseReadStream.cs index 28ef24fe4aa24a..9ad06374beb615 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionCloseReadStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionCloseReadStream.cs @@ -18,7 +18,7 @@ public ConnectionCloseReadStream(HttpConnection connection) : base(connection) public override int Read(Span buffer) { HttpConnection? connection = _connection; - if (connection == null || buffer.Length == 0) + if (connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data return 0; @@ -40,7 +40,7 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation CancellationHelper.ThrowIfCancellationRequested(cancellationToken); HttpConnection? connection = _connection; - if (connection == null || buffer.Length == 0) + if (connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data return 0; @@ -97,7 +97,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio } HttpConnection? connection = _connection; - if (connection == null) + if (connection is null) { // null if response body fully consumed return Task.CompletedTask; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthReadStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthReadStream.cs index a946a7aa1cfe8b..28d2d064a468fe 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthReadStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthReadStream.cs @@ -22,7 +22,7 @@ public ContentLengthReadStream(HttpConnection connection, ulong contentLength) : public override int Read(Span buffer) { - if (_connection == null || buffer.Length == 0) + if (_connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data. return 0; @@ -58,7 +58,7 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation { CancellationHelper.ThrowIfCancellationRequested(cancellationToken); - if (_connection == null || buffer.Length == 0) + if (_connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data return 0; @@ -125,7 +125,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio return Task.FromCanceled(cancellationToken); } - if (_connection == null) + if (_connection is null) { // null if response body fully consumed return Task.CompletedTask; @@ -143,7 +143,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio private async Task CompleteCopyToAsync(Task copyTask, CancellationToken cancellationToken) { - Debug.Assert(_connection != null); + Debug.Assert(_connection is not null); CancellationTokenRegistration ctr = _connection.RegisterCancellation(cancellationToken); try { @@ -173,7 +173,7 @@ private ReadOnlyMemory ReadFromConnectionBuffer(int maxBytesToRead) { Debug.Assert(maxBytesToRead > 0); Debug.Assert(_contentBytesRemaining > 0); - Debug.Assert(_connection != null); + Debug.Assert(_connection is not null); ReadOnlyMemory connectionBuffer = _connection.RemainingBuffer; if (connectionBuffer.Length == 0) @@ -190,11 +190,11 @@ private ReadOnlyMemory ReadFromConnectionBuffer(int maxBytesToRead) return connectionBuffer.Slice(0, bytesToConsume); } - public override bool NeedsDrain => (_connection != null); + public override bool NeedsDrain => (_connection is not null); public override async ValueTask DrainAsync(int maxDrainBytes) { - Debug.Assert(_connection != null); + Debug.Assert(_connection is not null); Debug.Assert(_contentBytesRemaining > 0); ReadFromConnectionBuffer(int.MaxValue); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthWriteStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthWriteStream.cs index e51c5e06cbe716..3e32807ed0de7f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthWriteStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthWriteStream.cs @@ -23,7 +23,7 @@ public override void Write(ReadOnlySpan buffer) // force a flush of anything already in the buffer, i.e. any remaining request headers // that are still buffered. HttpConnection connection = GetConnectionOrThrow(); - Debug.Assert(connection._currentRequest != null); + Debug.Assert(connection._currentRequest is not null); connection.Write(buffer); } @@ -35,7 +35,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo // force a flush of anything already in the buffer, i.e. any remaining request headers // that are still buffered. HttpConnection connection = GetConnectionOrThrow(); - Debug.Assert(connection._currentRequest != null); + Debug.Assert(connection._currentRequest is not null); return connection.WriteAsync(buffer, async: true); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CookieHelper.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CookieHelper.cs index 7979d23d49529d..ebfe9640a43b5f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CookieHelper.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CookieHelper.cs @@ -16,7 +16,7 @@ public static void ProcessReceivedCookies(HttpResponseMessage response, CookieCo // The header values are always a string[] var valuesArray = (string[])values; Debug.Assert(valuesArray.Length > 0, "No values for header??"); - Debug.Assert(response.RequestMessage != null && response.RequestMessage.RequestUri != null); + Debug.Assert(response.RequestMessage is not null && response.RequestMessage.RequestUri is not null); Uri requestUri = response.RequestMessage.RequestUri; for (int i = 0; i < valuesArray.Length; i++) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CreditManager.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CreditManager.cs index 1174a85996974e..937c25995cb598 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CreditManager.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CreditManager.cs @@ -19,7 +19,7 @@ internal sealed class CreditManager public CreditManager(IHttpTrace owner, string name, int initialCredit) { - Debug.Assert(owner != null); + Debug.Assert(owner is not null); Debug.Assert(!string.IsNullOrWhiteSpace(name)); if (NetEventSource.Log.IsEnabled()) owner.Trace($"{name}. {nameof(initialCredit)}={initialCredit}"); @@ -98,11 +98,11 @@ public void AdjustCredit(int amount) _current = checked(_current + amount); - while (_current > 0 && _waitersTail != null) + while (_current > 0 && _waitersTail is not null) { // Get the waiter from the head of the queue. CreditWaiter? waiter = _waitersTail.Next; - Debug.Assert(waiter != null); + Debug.Assert(waiter is not null); int granted = Math.Min(waiter.Amount, _current); // Remove the waiter from the list. @@ -140,7 +140,7 @@ public void Dispose() _disposed = true; CreditWaiter? waiter = _waitersTail; - if (waiter != null) + if (waiter is not null) { do { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/DecompressionHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/DecompressionHandler.cs index 08ecfdebaad085..3cf6b69ee09bdd 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/DecompressionHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/DecompressionHandler.cs @@ -27,7 +27,7 @@ internal sealed class DecompressionHandler : HttpMessageHandlerStage public DecompressionHandler(DecompressionMethods decompressionMethods, HttpMessageHandlerStage innerHandler) { Debug.Assert(decompressionMethods != DecompressionMethods.None); - Debug.Assert(innerHandler != null); + Debug.Assert(innerHandler is not null); _decompressionMethods = decompressionMethods; _innerHandler = innerHandler; @@ -56,7 +56,7 @@ internal override async ValueTask SendAsync(HttpRequestMess HttpResponseMessage response = await _innerHandler.SendAsync(request, async, cancellationToken).ConfigureAwait(false); - Debug.Assert(response.Content != null); + Debug.Assert(response.Content is not null); ICollection contentEncodings = response.Content.Headers.ContentEncoding; if (contentEncodings.Count > 0) { @@ -112,7 +112,7 @@ public DecompressedContent(HttpContent originalContent) string? prevEncoding = null; foreach (string encoding in originalContent.Headers.ContentEncoding) { - if (prevEncoding != null) + if (prevEncoding is not null) { Headers.ContentEncoding.Add(prevEncoding); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs index e966271b7e5860..b2e4f4e22dd579 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs @@ -428,7 +428,7 @@ private async ValueTask ProcessHeadersFrame(FrameHeader frameHeader) Http2Stream? http2Stream = GetStream(streamId); IHttpHeadersHandler headersHandler; - if (http2Stream != null) + if (http2Stream is not null) { http2Stream.OnHeadersStart(); headersHandler = http2Stream; @@ -557,7 +557,7 @@ private void ProcessDataFrame(FrameHeader frameHeader) ReadOnlySpan frameData = GetFrameData(_incomingBuffer.ActiveSpan.Slice(0, frameHeader.PayloadLength), hasPad: frameHeader.PaddedFlag, hasPriority: false); - if (http2Stream != null) + if (http2Stream is not null) { bool endStream = frameHeader.EndStreamFlag; @@ -767,7 +767,7 @@ private void ProcessWindowUpdateFrame(FrameHeader frameHeader) else { Http2Stream? http2Stream = GetStream(frameHeader.StreamId); - if (http2Stream == null) + if (http2Stream is null) { // Ignore invalid stream ID, as per RFC return; @@ -792,7 +792,7 @@ private void ProcessRstStreamFrame(FrameHeader frameHeader) } Http2Stream? http2Stream = GetStream(frameHeader.StreamId); - if (http2Stream == null) + if (http2Stream is null) { // Ignore invalid stream ID, as per RFC _incomingBuffer.Discard(frameHeader.PayloadLength); @@ -1135,7 +1135,7 @@ private void WriteHeaderCollection(HttpRequestMessage request, HttpHeaders heade Encoding? valueEncoding = encodingSelector?.Invoke(header.Key.Name, request); KnownHeader? knownHeader = header.Key.KnownHeader; - if (knownHeader != null) + if (knownHeader is not null) { // The Host header is not sent for HTTP2 because we send the ":authority" pseudo-header instead // (see pseudo-header handling below in WriteHeaders). @@ -1163,7 +1163,7 @@ private void WriteHeaderCollection(HttpRequestMessage request, HttpHeaders heade if (headerValues.Length > 1) { HttpHeaderParser? parser = header.Key.Parser; - if (parser != null && parser.SupportsMultipleValues) + if (parser is not null && parser.SupportsMultipleValues) { separator = parser.Separator; } @@ -1212,7 +1212,7 @@ private void WriteHeaders(HttpRequestMessage request, ref ArrayBuffer headerBuff WriteIndexedHeader(_stream is SslStream ? H2StaticTable.SchemeHttps : H2StaticTable.SchemeHttp, ref headerBuffer); - if (request.HasHeaders && request.Headers.Host != null) + if (request.HasHeaders && request.Headers.Host is not null) { WriteIndexedHeader(H2StaticTable.Authority, request.Headers.Host, ref headerBuffer); } @@ -1221,7 +1221,7 @@ private void WriteHeaders(HttpRequestMessage request, ref ArrayBuffer headerBuff WriteBytes(_pool._http2EncodedAuthorityHostHeader, ref headerBuffer); } - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); string pathAndQuery = request.RequestUri.PathAndQuery; if (pathAndQuery == "/") { @@ -1250,7 +1250,7 @@ private void WriteHeaders(HttpRequestMessage request, ref ArrayBuffer headerBuff } } - if (request.Content == null) + if (request.Content is null) { // Write out Content-Length: 0 header to indicate no body, // unless this is a method that never has a body. @@ -1276,7 +1276,7 @@ private void ThrowShutdownException() // actually retry the request, so we must give a useful exception here for these cases. Exception innerException; - if (_abortException != null) + if (_abortException is not null) { innerException = _abortException; } @@ -1369,7 +1369,7 @@ private async ValueTask SendHeadersAsync(HttpRequestMessage request // Start the write. This serializes access to write to the connection, and ensures that HEADERS // and CONTINUATION frames stay together, as they must do. We use the lock as well to ensure new // streams are created and started in order. - await PerformWriteAsync(totalSize, (thisRef: this, http2Stream, headerBytes, endStream: (request.Content == null), mustFlush), static (s, writeBuffer) => + await PerformWriteAsync(totalSize, (thisRef: this, http2Stream, headerBytes, endStream: (request.Content is null), mustFlush), static (s, writeBuffer) => { if (NetEventSource.Log.IsEnabled()) s.thisRef.Trace(s.http2Stream.StreamId, $"Started writing. Total header bytes={s.headerBytes.Length}"); @@ -1840,10 +1840,10 @@ public sealed override async Task SendAsync(HttpRequestMess try { // Send request headers - bool shouldExpectContinue = request.Content != null && request.HasHeaders && request.Headers.ExpectContinue == true; + bool shouldExpectContinue = request.Content is not null && request.HasHeaders && request.Headers.ExpectContinue == true; Http2Stream http2Stream = await SendHeadersAsync(request, cancellationToken, mustFlush: shouldExpectContinue).ConfigureAwait(false); - bool duplex = request.Content != null && request.Content.AllowDuplex; + bool duplex = request.Content is not null && request.Content.AllowDuplex; // If we have duplex content, then don't propagate the cancellation to the request body task. // If cancellation occurs before we receive the response headers, then we will cancel the request body anyway. @@ -1916,7 +1916,7 @@ e is Http2ProtocolException || private void RemoveStream(Http2Stream http2Stream) { if (NetEventSource.Log.IsEnabled()) Trace(http2Stream.StreamId, ""); - Debug.Assert(http2Stream != null); + Debug.Assert(http2Stream is not null); lock (SyncObject) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs index 4b2d1697c510e0..3d1440233ee9c8 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs @@ -47,7 +47,7 @@ private sealed class Http2Stream : IValueTaskSource, IHttpHeadersHandler, IHttpT // If this is not null, then we have received a reset from the server // (i.e. RST_STREAM or general IO error processing the connection) private Exception? _resetException; - private bool _canRetry; // if _resetException != null, this indicates the stream was refused and so the request is retryable + private bool _canRetry; // if _resetException is not null, this indicates the stream was refused and so the request is retryable // This flag indicates that, per section 8.1 of the RFC, the server completed the response and then sent a RST_STREAM with error = NO_ERROR. // This is a signal to stop sending the request body, but the request is still considered successful. @@ -104,7 +104,7 @@ public Http2Stream(HttpRequestMessage request, Http2Connection connection) _pendingWindowUpdate = 0; _headerBudgetRemaining = connection._pool.Settings._maxResponseHeadersLength * 1024; - if (_request.Content == null) + if (_request.Content is null) { _requestCompletionState = StreamCompletionState.Completed; } @@ -154,7 +154,7 @@ public HttpResponseMessage GetAndClearResponse() // Since the Http2Stream is rooted by the Http2Connection dictionary, doing so would prevent // the response stream from being collected and finalized if it were to be dropped without // being disposed first. - Debug.Assert(_response != null); + Debug.Assert(_response is not null); HttpResponseMessage r = _response; _response = null; return r; @@ -162,14 +162,14 @@ public HttpResponseMessage GetAndClearResponse() public async Task SendRequestBodyAsync(CancellationToken cancellationToken) { - if (_request.Content == null) + if (_request.Content is null) { Debug.Assert(_requestCompletionState == StreamCompletionState.Completed); return; } if (NetEventSource.Log.IsEnabled()) Trace($"{_request.Content}"); - Debug.Assert(_requestBodyCancellationSource != null); + Debug.Assert(_requestBodyCancellationSource is not null); // Cancel the request body sending if cancellation is requested on the supplied cancellation token. // Normally we might create a linked token, but once cancellation is requested, we can't recover anyway, @@ -184,7 +184,7 @@ public async Task SendRequestBodyAsync(CancellationToken cancellationToken) try { bool sendRequestContent = true; - if (_expect100ContinueWaiter != null) + if (_expect100ContinueWaiter is not null) { linkedRegistration = RegisterRequestBodyCancellation(cancellationToken); sendRequestContent = await WaitFor100ContinueAsync(_requestBodyCancellationSource.Token).ConfigureAwait(false); @@ -295,7 +295,7 @@ public async Task SendRequestBodyAsync(CancellationToken cancellationToken) // If we get response status >= 300, we will not send the request body. public async ValueTask WaitFor100ContinueAsync(CancellationToken cancellationToken) { - Debug.Assert(_request?.Content != null); + Debug.Assert(_request?.Content is not null); if (NetEventSource.Log.IsEnabled()) Trace($"Waiting to send request body content for 100-Continue."); // Use TCS created in constructor. It will complete when one of three things occurs: @@ -333,7 +333,7 @@ private void SendReset() if (NetEventSource.Log.IsEnabled()) Trace($"Stream reset. Request={_requestCompletionState}, Response={_responseCompletionState}."); // Don't send a RST_STREAM if we've already received one from the server. - if (_resetException == null) + if (_resetException is null) { _connection.LogExceptions(_connection.SendRstStreamAsync(StreamId, Http2ProtocolErrorCode.Cancel)); } @@ -350,7 +350,7 @@ private void Complete() _connection.RemoveStream(this); CreditWaiter? w = _creditWaiter; - if (w != null) + if (w is not null) { w.Dispose(); _creditWaiter = null; @@ -371,7 +371,7 @@ private void Cancel() if (_requestCompletionState == StreamCompletionState.InProgress) { requestBodyCancellationSource = _requestBodyCancellationSource; - Debug.Assert(requestBodyCancellationSource != null); + Debug.Assert(requestBodyCancellationSource is not null); } (signalWaiter, sendReset) = CancelResponseBody(); @@ -427,7 +427,7 @@ public void OnWindowUpdate(int amount) lock (SyncObject) { _availableCredit = checked(_availableCredit + amount); - if (_availableCredit > 0 && _creditWaiter != null) + if (_availableCredit > 0 && _creditWaiter is not null) { int granted = Math.Min(_availableCredit, _creditWaiter.Amount); if (_creditWaiter.TrySetResult(granted)) @@ -581,7 +581,7 @@ private void OnStatus(int statusCode) throw new HttpRequestException(SR.net_http_invalid_response_pseudo_header_in_trailer); } - Debug.Assert(_response != null); + Debug.Assert(_response is not null); _response.StatusCode = (HttpStatusCode)statusCode; if (statusCode < 200) @@ -589,7 +589,7 @@ private void OnStatus(int statusCode) // We do not process headers from 1xx responses. _responseProtocolState = ResponseProtocolState.ExpectingIgnoredHeaders; - if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueWaiter != null) + if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueWaiter is not null) { if (NetEventSource.Log.IsEnabled()) Trace("Received 100-Continue status."); _expect100ContinueWaiter.TrySetResult(true); @@ -600,7 +600,7 @@ private void OnStatus(int statusCode) _responseProtocolState = ResponseProtocolState.ExpectingHeaders; // If we are waiting for a 100-continue response, signal the waiter now. - if (_expect100ContinueWaiter != null) + if (_expect100ContinueWaiter is not null) { // If the final status code is >= 300, skip sending the body. bool shouldSendBody = (statusCode < 300); @@ -645,19 +645,19 @@ private void OnHeader(HeaderDescriptor descriptor, ReadOnlySpan value) // if the header can't be added, we silently drop it. if (_responseProtocolState == ResponseProtocolState.ExpectingTrailingHeaders) { - Debug.Assert(_trailers != null); + Debug.Assert(_trailers is not null); string headerValue = descriptor.GetHeaderValue(value, valueEncoding); _trailers.TryAddWithoutValidation((descriptor.HeaderType & HttpHeaderType.Request) == HttpHeaderType.Request ? descriptor.AsCustomHeader() : descriptor, headerValue); } else if ((descriptor.HeaderType & HttpHeaderType.Content) == HttpHeaderType.Content) { - Debug.Assert(_response != null && _response.Content != null); + Debug.Assert(_response is not null && _response.Content is not null); string headerValue = descriptor.GetHeaderValue(value, valueEncoding); _response.Content.Headers.TryAddWithoutValidation(descriptor, headerValue); } else { - Debug.Assert(_response != null); + Debug.Assert(_response is not null); string headerValue = _connection.GetResponseHeaderValueWithCaching(descriptor, value, valueEncoding); _response.Headers.TryAddWithoutValidation((descriptor.HeaderType & HttpHeaderType.Request) == HttpHeaderType.Request ? descriptor.AsCustomHeader() : descriptor, headerValue); } @@ -867,7 +867,7 @@ public void OnReset(Exception resetException, Http2ProtocolErrorCode? resetStrea // It's possible we could be called twice, e.g. we receive a RST_STREAM and then the whole connection dies // before we have a chance to process cancellation and tear everything down. Just ignore this. - if (_resetException != null) + if (_resetException is not null) { return; } @@ -892,7 +892,7 @@ public void OnReset(Exception resetException, Http2ProtocolErrorCode? resetStrea { _requestBodyAbandoned = true; requestBodyCancellationSource = _requestBodyCancellationSource; - Debug.Assert(requestBodyCancellationSource != null); + Debug.Assert(requestBodyCancellationSource is not null); } } else @@ -903,7 +903,7 @@ public void OnReset(Exception resetException, Http2ProtocolErrorCode? resetStrea } } - if (requestBodyCancellationSource != null) + if (requestBodyCancellationSource is not null) { Debug.Assert(_requestBodyAbandoned); Debug.Assert(!cancel); @@ -990,7 +990,7 @@ public async Task ReadResponseHeadersAsync(CancellationToken cancellationToken) throw; } - Debug.Assert(_response != null && _response.Content != null); + Debug.Assert(_response is not null && _response.Content is not null); // Start to process the response body. var responseContent = (HttpConnectionResponseContent)_response.Content; if (emptyResponse) @@ -1201,7 +1201,7 @@ public async Task CopyToAsync(HttpResponseMessage responseMessage, Stream destin private void MoveTrailersToResponseMessage(HttpResponseMessage responseMessage) { - if (_trailers != null) + if (_trailers is not null) { responseMessage.StoreReceivedTrailingHeaders(_trailers); } @@ -1209,7 +1209,7 @@ private void MoveTrailersToResponseMessage(HttpResponseMessage responseMessage) private async ValueTask SendDataAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) { - Debug.Assert(_requestBodyCancellationSource != null); + Debug.Assert(_requestBodyCancellationSource is not null); // Cancel the request body sending if cancellation is requested on the supplied cancellation token. CancellationTokenRegistration linkedRegistration = cancellationToken.CanBeCanceled && cancellationToken != _requestBodyCancellationSource.Token ? @@ -1245,7 +1245,7 @@ private async ValueTask SendDataAsync(ReadOnlyMemory buffer, CancellationT if (sendSize == -1) { // Logically this is part of the else block above, but we can't await while holding the lock. - Debug.Assert(_creditWaiter != null); + Debug.Assert(_creditWaiter is not null); sendSize = await _creditWaiter.AsValueTask().ConfigureAwait(false); } @@ -1377,8 +1377,8 @@ private sealed class Http2ReadStream : HttpBaseStream public Http2ReadStream(Http2Stream http2Stream) { - Debug.Assert(http2Stream != null); - Debug.Assert(http2Stream._response != null); + Debug.Assert(http2Stream is not null); + Debug.Assert(http2Stream._response is not null); _http2Stream = http2Stream; _responseMessage = _http2Stream._response; } @@ -1399,7 +1399,7 @@ public Http2ReadStream(Http2Stream http2Stream) protected override void Dispose(bool disposing) { Http2Stream? http2Stream = Interlocked.Exchange(ref _http2Stream, null); - if (http2Stream == null) + if (http2Stream is null) { return; } @@ -1429,7 +1429,7 @@ public override ValueTask ReadAsync(Memory destination, CancellationT { Http2Stream? http2Stream = _http2Stream; - if (http2Stream == null) + if (http2Stream is null) { return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new ObjectDisposedException(nameof(Http2ReadStream)))); } @@ -1472,14 +1472,14 @@ private sealed class Http2WriteStream : HttpBaseStream public Http2WriteStream(Http2Stream http2Stream) { - Debug.Assert(http2Stream != null); + Debug.Assert(http2Stream is not null); _http2Stream = http2Stream; } protected override void Dispose(bool disposing) { Http2Stream? http2Stream = Interlocked.Exchange(ref _http2Stream, null); - if (http2Stream == null) + if (http2Stream is null) { return; } @@ -1500,7 +1500,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo Http2Stream? http2Stream = _http2Stream; - if (http2Stream == null) + if (http2Stream is null) { return ValueTask.FromException(new ObjectDisposedException(nameof(Http2WriteStream))); } @@ -1517,7 +1517,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) Http2Stream? http2Stream = _http2Stream; - if (http2Stream == null) + if (http2Stream is null) { return Task.CompletedTask; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs index c149d9bed84940..2be0ba23f0dd53 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs @@ -119,17 +119,17 @@ private void CheckForShutdown() return; } - if (_clientControl != null) + if (_clientControl is not null) { _clientControl.Dispose(); _clientControl = null; } - if (_connection != null) + if (_connection is not null) { // Close the QuicConnection in the background. - if (_connectionClosedTask == null) + if (_connectionClosedTask is null) { _connectionClosedTask = _connection.CloseAsync((long)Http3ErrorCode.NoError).AsTask(); } @@ -177,7 +177,7 @@ public override async Task SendAsync(HttpRequestMessage req } } - if (waitForAvailableStreamTcs != null) + if (waitForAvailableStreamTcs is not null) { await waitForAvailableStreamTcs.WaitWithCancellationAsync(cancellationToken).ConfigureAwait(false); } @@ -191,7 +191,7 @@ public override async Task SendAsync(HttpRequestMessage req { lock (SyncObj) { - if (_connection != null) + if (_connection is not null) { quicStream = _connection.OpenBidirectionalStream(); requestStream = new Http3RequestStream(request, this, quicStream); @@ -199,7 +199,7 @@ public override async Task SendAsync(HttpRequestMessage req } } - if (quicStream == null) + if (quicStream is null) { throw new HttpRequestException(SR.net_http_request_aborted, null, RequestRetryType.RetryOnSameOrNextProxy); } @@ -311,7 +311,7 @@ internal Exception Abort(Exception abortException) // Only observe the first exception we get. Exception? firstException = Interlocked.CompareExchange(ref _abortException, abortException, null); - if (firstException != null) + if (firstException is not null) { if (NetEventSource.Log.IsEnabled() && !ReferenceEquals(firstException, abortException)) { @@ -337,7 +337,7 @@ internal Exception Abort(Exception abortException) } // Abort the connection. This will cause all of our streams to abort on their next I/O. - if (_connection != null && _connectionClosedTask == null) + if (_connection is not null && _connectionClosedTask is null) { _connectionClosedTask = _connection.CloseAsync((long)connectionResetErrorCode).AsTask(); } @@ -619,7 +619,7 @@ private async Task ProcessServerControlStreamAsync(QuicStream stream, ArrayBuffe (Http3FrameType? frameType, long payloadLength) = await ReadFrameEnvelopeAsync().ConfigureAwait(false); - if (frameType == null) + if (frameType is null) { // Connection closed prematurely, expected SETTINGS frame. throw new Http3ConnectionException(Http3ErrorCode.ClosedCriticalStream); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs index 6cb250922a6e2c..73a518f6da2b9f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs @@ -130,7 +130,7 @@ public async Task SendAsync(CancellationToken cancellationT _expect100ContinueCompletionSource = new TaskCompletionSource(); } - if (_expect100ContinueCompletionSource != null || _request.Content == null) + if (_expect100ContinueCompletionSource is not null || _request.Content is null) { // Ideally, headers will be sent out in a gathered write inside of SendContentAsync(). // If we don't have content, or we are doing Expect 100 Continue, then we can't rely on @@ -139,7 +139,7 @@ public async Task SendAsync(CancellationToken cancellationT await _stream.WriteAsync(_sendBuffer.ActiveMemory, requestCancellationSource.Token).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); - if (_expect100ContinueCompletionSource != null) + if (_expect100ContinueCompletionSource is not null) { // Flush to ensure we get a response. // TODO: MsQuic may not need any flushing. @@ -157,7 +157,7 @@ public async Task SendAsync(CancellationToken cancellationT // In parallel, send content and read response. // Depending on Expect 100 Continue usage, one will depend on the other making progress. - Task sendContentTask = _request.Content != null ? SendContentAsync(_request.Content, sendContentCancellationToken) : Task.CompletedTask; + Task sendContentTask = _request.Content is not null ? SendContentAsync(_request.Content, sendContentCancellationToken) : Task.CompletedTask; Task readResponseTask = ReadResponseAsync(requestCancellationSource.Token); bool sendContentObserved = false; @@ -197,7 +197,7 @@ public async Task SendAsync(CancellationToken cancellationT // Use an atomic exchange to avoid a race to Cancel()/Dispose(). Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); - Debug.Assert(_response != null && _response.Content != null); + Debug.Assert(_response is not null && _response.Content is not null); // Set our content stream. var responseContent = (HttpConnectionResponseContent)_response.Content; @@ -296,7 +296,7 @@ public async Task SendAsync(CancellationToken cancellationT /// private async Task ReadResponseAsync(CancellationToken cancellationToken) { - Debug.Assert(_response == null); + Debug.Assert(_response is null); do { _headerState = HeaderState.StatusHeader; @@ -313,7 +313,7 @@ private async Task ReadResponseAsync(CancellationToken cancellationToken) } await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); - Debug.Assert(_response != null); + Debug.Assert(_response is not null); } while ((int)_response.StatusCode < 200); @@ -324,7 +324,7 @@ private async Task SendContentAsync(HttpContent content, CancellationToken cance { // If we're using Expect 100 Continue, wait to send content // until we get a response back or until our timeout elapses. - if (_expect100ContinueCompletionSource != null) + if (_expect100ContinueCompletionSource is not null) { Timer? timer = null; @@ -344,7 +344,7 @@ private async Task SendContentAsync(HttpContent content, CancellationToken cance } finally { - if (timer != null) + if (timer is not null) { await timer.DisposeAsync().ConfigureAwait(false); } @@ -499,7 +499,7 @@ private void BufferHeaders(HttpRequestMessage request) _sendBuffer.Commit(2); HttpMethod normalizedMethod = HttpMethod.Normalize(request.Method); - if (normalizedMethod.Http3EncodedBytes != null) + if (normalizedMethod.Http3EncodedBytes is not null) { BufferBytes(normalizedMethod.Http3EncodedBytes); } @@ -510,7 +510,7 @@ private void BufferHeaders(HttpRequestMessage request) BufferIndexedHeader(H3StaticTable.SchemeHttps); - if (request.HasHeaders && request.Headers.Host != null) + if (request.HasHeaders && request.Headers.Host is not null) { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Authority, request.Headers.Host); } @@ -519,7 +519,7 @@ private void BufferHeaders(HttpRequestMessage request) BufferBytes(_connection.Pool._http3EncodedAuthorityHostHeader); } - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); string pathAndQuery = request.RequestUri.PathAndQuery; if (pathAndQuery == "/") { @@ -554,7 +554,7 @@ private void BufferHeaders(HttpRequestMessage request) } } - if (request.Content == null) + if (request.Content is null) { if (normalizedMethod.MustHaveRequestBody) { @@ -581,7 +581,7 @@ private void BufferHeaders(HttpRequestMessage request) // TODO: special-case Content-Type for static table values values? private void BufferHeaderCollection(HttpHeaders headers) { - if (headers.HeaderStore == null) + if (headers.HeaderStore is null) { return; } @@ -597,7 +597,7 @@ private void BufferHeaderCollection(HttpHeaders headers) Encoding? valueEncoding = encodingSelector?.Invoke(header.Key.Name, _request); KnownHeader? knownHeader = header.Key.KnownHeader; - if (knownHeader != null) + if (knownHeader is not null) { // The Host header is not sent for HTTP/3 because we send the ":authority" pseudo-header instead // (see pseudo-header handling below in WriteHeaders). @@ -625,7 +625,7 @@ private void BufferHeaderCollection(HttpHeaders headers) if (headerValues.Length > 1) { HttpHeaderParser? parser = header.Key.Parser; - if (parser != null && parser.SupportsMultipleValues) + if (parser is not null && parser.SupportsMultipleValues) { separator = parser.Separator; } @@ -897,7 +897,7 @@ private void OnHeader(int? staticIndex, HeaderDescriptor descriptor, string? sta // Informational responses should not contain headers -- skip them. _headerState = HeaderState.SkipExpect100Headers; - if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueCompletionSource != null) + if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueCompletionSource is not null) { _expect100ContinueCompletionSource.TrySetResult(true); } @@ -905,7 +905,7 @@ private void OnHeader(int? staticIndex, HeaderDescriptor descriptor, string? sta else { _headerState = HeaderState.ResponseHeaders; - if (_expect100ContinueCompletionSource != null) + if (_expect100ContinueCompletionSource is not null) { // If the final status code is >= 300, skip sending the body. bool shouldSendBody = (statusCode < 300); @@ -986,7 +986,7 @@ private int ReadResponseContent(HttpResponseMessage response, Span buffer) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. - Debug.Assert(_response == null); + Debug.Assert(_response is null); try { @@ -1044,7 +1044,7 @@ private async ValueTask ReadResponseContentAsync(HttpResponseMessage respon { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. - Debug.Assert(_response == null); + Debug.Assert(_response is null); try { @@ -1188,7 +1188,7 @@ public Http3ReadStream(Http3RequestStream stream) protected override void Dispose(bool disposing) { - if (_stream != null) + if (_stream is not null) { if (disposing) { @@ -1212,7 +1212,7 @@ protected override void Dispose(bool disposing) public override async ValueTask DisposeAsync() { - if (_stream != null) + if (_stream is not null) { await _stream.DisposeAsync().ConfigureAwait(false); _stream = null!; @@ -1223,23 +1223,23 @@ public override async ValueTask DisposeAsync() public override int Read(Span buffer) { - if (_stream == null) + if (_stream is null) { throw new ObjectDisposedException(nameof(Http3RequestStream)); } - Debug.Assert(_response != null); + Debug.Assert(_response is not null); return _stream.ReadResponseContent(_response, buffer); } public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) { - if (_stream == null) + if (_stream is null) { return ValueTask.FromException(new ObjectDisposedException(nameof(Http3RequestStream))); } - Debug.Assert(_response != null); + Debug.Assert(_response is not null); return _stream.ReadResponseContentAsync(_response, buffer, cancellationToken); } @@ -1281,7 +1281,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) { - if (_stream == null) + if (_stream is null) { return ValueTask.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpAuthority.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpAuthority.cs index 43a4181aa60c0f..4aa70e677032e9 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpAuthority.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpAuthority.cs @@ -16,7 +16,7 @@ internal sealed class HttpAuthority : IEquatable public HttpAuthority(string host, int port) { - Debug.Assert(host != null); + Debug.Assert(host is not null); // This is very rarely called, but could be optimized to avoid the URI-specific stuff by bringing in DomainNameHelpers from System.Private.Uri. var builder = new UriBuilder(Uri.UriSchemeHttp, host, port); @@ -31,7 +31,7 @@ public HttpAuthority(string host, int port) public bool Equals(HttpAuthority? other) { - return other != null && string.Equals(IdnHost, other.IdnHost) && Port == other.Port; + return other is not null && string.Equals(IdnHost, other.IdnHost) && Port == other.Port; } public override bool Equals(object? obj) @@ -47,7 +47,7 @@ public override int GetHashCode() // For diagnostics public override string ToString() { - return IdnHost != null ? $"{IdnHost}:{Port}" : ""; + return IdnHost is not null ? $"{IdnHost}:{Port}" : ""; } } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index ca579ec3ae4034..2834cefcc00c7b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -74,8 +74,8 @@ public HttpConnection( Stream stream, TransportContext? transportContext) { - Debug.Assert(pool != null); - Debug.Assert(stream != null); + Debug.Assert(pool is not null); + Debug.Assert(stream is not null); _pool = pool; _stream = stream; @@ -129,7 +129,7 @@ protected void Dispose(bool disposing) // Eat any exceptions from the read-ahead task. We don't need to log, as we expect // failures from this task due to closing the connection while a read is in progress. ValueTask? readAheadTask = ConsumeReadAheadTask(); - if (readAheadTask != null) + if (readAheadTask is not null) { IgnoreExceptions(readAheadTask.GetValueOrDefault()); } @@ -141,7 +141,7 @@ protected void Dispose(bool disposing) /// If we don't have direct access to the underlying socket, we instead use a read-ahead task. public bool PollRead() { - if (_socket != null) // may be null if we don't have direct access to the socket + if (_socket is not null) // may be null if we don't have direct access to the socket { try { @@ -168,8 +168,8 @@ public bool EnsureReadAheadAndPollRead() { try { - Debug.Assert(_readAheadTask == null || _socket == null, "Should only already have a read-ahead task if we don't have a socket to poll"); - if (_readAheadTask == null) + Debug.Assert(_readAheadTask is null || _socket is null, "Should only already have a read-ahead task if we don't have a socket to poll"); + if (_readAheadTask is null) { #pragma warning disable CA2012 // we're very careful to ensure the ValueTask is only consumed once, even though it's stored into a field _readAheadTask = _stream.ReadAsync(new Memory(_readBuffer)); @@ -218,13 +218,13 @@ private void ConsumeFromRemainingBuffer(int bytesToConsume) private async ValueTask WriteHeadersAsync(HttpHeaders headers, string? cookiesFromContainer, bool async) { - Debug.Assert(_currentRequest != null); + Debug.Assert(_currentRequest is not null); - if (headers.HeaderStore != null) + if (headers.HeaderStore is not null) { foreach (KeyValuePair header in headers.HeaderStore) { - if (header.Key.KnownHeader != null) + if (header.Key.KnownHeader is not null) { await WriteBytesAsync(header.Key.KnownHeader.AsciiBytesWithColonSpace, async).ConfigureAwait(false); } @@ -242,7 +242,7 @@ private async ValueTask WriteHeadersAsync(HttpHeaders headers, string? cookiesFr await WriteStringAsync(_headerValues[0], async, valueEncoding).ConfigureAwait(false); - if (cookiesFromContainer != null && header.Key.KnownHeader == KnownHeaders.Cookie) + if (cookiesFromContainer is not null && header.Key.KnownHeader == KnownHeaders.Cookie) { await WriteTwoBytesAsync((byte)';', (byte)' ', async).ConfigureAwait(false); await WriteStringAsync(cookiesFromContainer, async, valueEncoding).ConfigureAwait(false); @@ -255,7 +255,7 @@ private async ValueTask WriteHeadersAsync(HttpHeaders headers, string? cookiesFr { HttpHeaderParser? parser = header.Key.Parser; string separator = HttpHeaderParser.DefaultSeparator; - if (parser != null && parser.SupportsMultipleValues) + if (parser is not null && parser.SupportsMultipleValues) { separator = parser.Separator!; } @@ -272,7 +272,7 @@ private async ValueTask WriteHeadersAsync(HttpHeaders headers, string? cookiesFr } } - if (cookiesFromContainer != null) + if (cookiesFromContainer is not null) { await WriteAsciiStringAsync(HttpKnownHeaderNames.Cookie, async).ConfigureAwait(false); await WriteTwoBytesAsync((byte)':', (byte)' ', async).ConfigureAwait(false); @@ -288,7 +288,7 @@ private async ValueTask WriteHostHeaderAsync(Uri uri, bool async) { await WriteBytesAsync(KnownHeaders.Host.AsciiBytesWithColonSpace, async).ConfigureAwait(false); - if (_pool.HostHeaderValueBytes != null) + if (_pool.HostHeaderValueBytes is not null) { Debug.Assert(Kind != HttpConnectionKind.Proxy); await WriteBytesAsync(_pool.HostHeaderValueBytes, async).ConfigureAwait(false); @@ -351,7 +351,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, { TaskCompletionSource? allowExpect100ToContinue = null; Task? sendRequestContentTask = null; - Debug.Assert(_currentRequest == null, $"Expected null {nameof(_currentRequest)}."); + Debug.Assert(_currentRequest is null, $"Expected null {nameof(_currentRequest)}."); Debug.Assert(RemainingBuffer.Length == 0, "Unexpected data in read buffer"); _currentRequest = request; @@ -367,7 +367,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, { if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStart(); - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); // Write request line await WriteStringAsync(normalizedMethod.Method, async).ConfigureAwait(false); await WriteByteAsync((byte)' ', async).ConfigureAwait(false); @@ -376,7 +376,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, { // RFC 7231 #section-4.3.6. // Write only CONNECT foo.com:345 HTTP/1.1 - if (!request.HasHeaders || request.Headers.Host == null) + if (!request.HasHeaders || request.Headers.Host is null) { throw new HttpRequestException(SR.net_http_request_no_host); } @@ -431,18 +431,18 @@ public async Task SendAsyncCore(HttpRequestMessage request, // Write special additional headers. If a host isn't in the headers list, then a Host header // wasn't sent, so as it's required by HTTP 1.1 spec, send one based on the Request Uri. - if (!request.HasHeaders || request.Headers.Host == null) + if (!request.HasHeaders || request.Headers.Host is null) { await WriteHostHeaderAsync(request.RequestUri, async).ConfigureAwait(false); } // Write request headers - if (request.HasHeaders || cookiesFromContainer != null) + if (request.HasHeaders || cookiesFromContainer is not null) { await WriteHeadersAsync(request.Headers, cookiesFromContainer, async).ConfigureAwait(false); } - if (request.Content == null) + if (request.Content is null) { // Write out Content-Length: 0 header to indicate no body, // unless this is a method that never has a body. @@ -462,7 +462,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStop(); - if (request.Content == null) + if (request.Content is null) { // We have nothing more to send, so flush out any headers we haven't yet sent. await FlushAsync(async).ConfigureAwait(false); @@ -508,7 +508,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, // When the connection was taken out of the pool, a pre-emptive read was performed // into the read buffer. We need to consume that read prior to issuing another read. ValueTask? t = ConsumeReadAheadTask(); - if (t != null) + if (t is not null) { // Handle the pre-emptive read. For the async==false case, hopefully the read has // already completed and this will be a nop, but if it hasn't, we're forced to block @@ -551,7 +551,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, { // If other 1xx responses come before an expected 100 continue, we will wait for the 100 response before // sending request body (if any). - if (allowExpect100ToContinue != null && response.StatusCode == HttpStatusCode.Continue) + if (allowExpect100ToContinue is not null && response.StatusCode == HttpStatusCode.Continue) { allowExpect100ToContinue.TrySetResult(true); allowExpect100ToContinue = null; @@ -591,13 +591,13 @@ public async Task SendAsyncCore(HttpRequestMessage request, if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop(); - if (allowExpect100ToContinue != null) + if (allowExpect100ToContinue is not null) { // If we sent an Expect: 100-continue header, and didn't receive a 100-continue. Handle the final response accordingly. // Note that the developer may have added an Expect: 100-continue header even if there is no Content. if ((int)response.StatusCode >= 300 && - request.Content != null && - (request.Content.Headers.ContentLength == null || request.Content.Headers.ContentLength.GetValueOrDefault() > Expect100ErrorSendThreshold) && + request.Content is not null && + (request.Content.Headers.ContentLength is null || request.Content.Headers.ContentLength.GetValueOrDefault() > Expect100ErrorSendThreshold) && !AuthenticationHelper.IsSessionAuthenticationChallenge(response)) { // For error final status codes, try to avoid sending the payload if its size is unknown or if it's known to be "big". @@ -631,7 +631,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, // Now that we've received our final status line, wait for the request content to fully send. // In most common scenarios, the server won't send back a response until all of the request // content has been received, so this task should generally already be complete. - if (sendRequestContentTask != null) + if (sendRequestContentTask is not null) { Task sendTask = sendRequestContentTask; sendRequestContentTask = null; @@ -676,7 +676,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, { responseStream = new RawConnectionStream(this); } - else if (response.Content.Headers.ContentLength != null) + else if (response.Content.Headers.ContentLength is not null) { long contentLength = response.Content.Headers.ContentLength.GetValueOrDefault(); if (contentLength <= 0) @@ -726,7 +726,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, // (we're about to Dispose for the connection). In such cases, we don't want any // exception in that sending task to become unobserved and raise alarm bells, so we // hook up a continuation that will log it. - if (sendRequestContentTask != null && !sendRequestContentTask.IsCompletedSuccessfully) + if (sendRequestContentTask is not null && !sendRequestContentTask.IsCompletedSuccessfully) { // In case the connection is disposed, it's most probable that // expect100Continue timer expired and request content sending failed. @@ -951,7 +951,7 @@ private static void ParseStatusLine(ReadOnlySpan line, HttpResponseMessage { ReadOnlySpan reasonBytes = line.Slice(MinStatusLineLength + 1); string? knownReasonPhrase = HttpStatusDescription.Get(response.StatusCode); - if (knownReasonPhrase != null && EqualsOrdinal(knownReasonPhrase, reasonBytes)) + if (knownReasonPhrase is not null && EqualsOrdinal(knownReasonPhrase, reasonBytes)) { response.SetReasonPhraseWithoutValidation(knownReasonPhrase); } @@ -1000,7 +1000,7 @@ private static void ParseHeaderNameValue(HttpConnection connection, ReadOnlySpan throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(line.Slice(0, pos)))); } - if (isFromTrailer && descriptor.KnownHeader != null && (descriptor.KnownHeader.HeaderType & HttpHeaderType.NonTrailing) == HttpHeaderType.NonTrailing) + if (isFromTrailer && descriptor.KnownHeader is not null && (descriptor.KnownHeader.HeaderType & HttpHeaderType.NonTrailing) == HttpHeaderType.NonTrailing) { // Disallowed trailer fields. // A recipient MUST ignore fields that are forbidden to be sent in a trailer. @@ -1031,7 +1031,7 @@ private static void ParseHeaderNameValue(HttpConnection connection, ReadOnlySpan pos++; } - Debug.Assert(response.RequestMessage != null); + Debug.Assert(response.RequestMessage is not null); Encoding? valueEncoding = connection._pool.Settings._responseHeaderEncodingSelector?.Invoke(descriptor.Name, response.RequestMessage); // Note we ignore the return value from TryAddWithoutValidation. If the header can't be added, we silently drop it. @@ -1529,7 +1529,7 @@ private void Fill() // Throws IOException on EOF. This is only called when we expect more data. private async ValueTask FillAsync(bool async) { - Debug.Assert(_readAheadTask == null); + Debug.Assert(_readAheadTask is null); int remaining = _readLength - _readOffset; Debug.Assert(remaining >= 0); @@ -1605,7 +1605,7 @@ private int Read(Span destination) // No data in read buffer. // Do an unbuffered read directly against the underlying stream. - Debug.Assert(_readAheadTask == null, "Read ahead task should have been consumed as part of the headers."); + Debug.Assert(_readAheadTask is null, "Read ahead task should have been consumed as part of the headers."); int count = _stream.Read(destination); if (NetEventSource.Log.IsEnabled()) Trace($"Received {count} bytes."); return count; @@ -1633,7 +1633,7 @@ private async ValueTask ReadAsync(Memory destination) // No data in read buffer. // Do an unbuffered read directly against the underlying stream. - Debug.Assert(_readAheadTask == null, "Read ahead task should have been consumed as part of the headers."); + Debug.Assert(_readAheadTask is null, "Read ahead task should have been consumed as part of the headers."); int count = await _stream.ReadAsync(destination).ConfigureAwait(false); if (NetEventSource.Log.IsEnabled()) Trace($"Received {count} bytes."); return count; @@ -1664,7 +1664,7 @@ private int ReadBuffered(Span destination) _readOffset = _readLength = 0; // Do a buffered read directly against the underlying stream. - Debug.Assert(_readAheadTask == null, "Read ahead task should have been consumed as part of the headers."); + Debug.Assert(_readAheadTask is null, "Read ahead task should have been consumed as part of the headers."); int bytesRead = _stream.Read(_readBuffer, 0, _readBuffer.Length); if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); _readLength = bytesRead; @@ -1710,7 +1710,7 @@ private async ValueTask ReadBufferedAsyncCore(Memory destination) _readOffset = _readLength = 0; // Do a buffered read directly against the underlying stream. - Debug.Assert(_readAheadTask == null, "Read ahead task should have been consumed as part of the headers."); + Debug.Assert(_readAheadTask is null, "Read ahead task should have been consumed as part of the headers."); int bytesRead = await _stream.ReadAsync(_readBuffer.AsMemory()).ConfigureAwait(false); if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); _readLength = bytesRead; @@ -1740,7 +1740,7 @@ private async ValueTask CopyFromBufferAsync(Stream destination, bool async, int private Task CopyToUntilEofAsync(Stream destination, bool async, int bufferSize, CancellationToken cancellationToken) { - Debug.Assert(destination != null); + Debug.Assert(destination is not null); int remaining = _readLength - _readOffset; @@ -1779,7 +1779,7 @@ private async Task CopyToUntilEofWithExistingBufferedDataAsync(Stream destinatio // Copy *exactly* [length] bytes into destination; throws on end of stream. private async Task CopyToContentLengthAsync(Stream destination, bool async, ulong length, int bufferSize, CancellationToken cancellationToken) { - Debug.Assert(destination != null); + Debug.Assert(destination is not null); Debug.Assert(length > 0); // Copy any data left in the connection's buffer to the destination. @@ -1828,7 +1828,7 @@ private async Task CopyToContentLengthAsync(Stream destination, bool async, ulon // if we filled the read buffer while doing the last read (which is at least one indication that the // data arrival rate is fast enough to warrant a larger buffer), and if the buffer size we'd want is // larger than the one we already have, then grow the connection's read buffer to that size. - if (origReadBuffer == null) + if (origReadBuffer is null) { byte[] currentReadBuffer = _readBuffer; if (remaining == currentReadBuffer.Length) @@ -1845,7 +1845,7 @@ private async Task CopyToContentLengthAsync(Stream destination, bool async, ulon } finally { - if (origReadBuffer != null) + if (origReadBuffer is not null) { byte[] tmp = _readBuffer; _readBuffer = origReadBuffer; @@ -1865,7 +1865,7 @@ private async Task CopyToContentLengthAsync(Stream destination, bool async, ulon internal void Acquire() { - Debug.Assert(_currentRequest == null); + Debug.Assert(_currentRequest is null); Debug.Assert(!_inUse); _inUse = true; @@ -1879,7 +1879,7 @@ internal void Release() // If the last request already completed (because the response had no content), return the connection to the pool now. // Otherwise, it will be returned when the response has been consumed and CompleteResponse below is called. - if (_currentRequest == null) + if (_currentRequest is null) { ReturnConnectionToPool(); } @@ -1887,7 +1887,7 @@ internal void Release() private void CompleteResponse() { - Debug.Assert(_currentRequest != null, "Expected the connection to be associated with a request."); + Debug.Assert(_currentRequest is not null, "Expected the connection to be associated with a request."); Debug.Assert(_writeOffset == 0, "Everything in write buffer should have been flushed."); // Disassociate the connection from a request. @@ -1925,13 +1925,13 @@ public async ValueTask DrainResponseAsync(HttpResponseMessage response, Cancella throw new HttpRequestException(SR.net_http_authconnectionfailure); } - Debug.Assert(response.Content != null); + Debug.Assert(response.Content is not null); Stream stream = response.Content.ReadAsStream(cancellationToken); HttpContentReadStream? responseStream = stream as HttpContentReadStream; - Debug.Assert(responseStream != null || stream is EmptyReadStream); + Debug.Assert(responseStream is not null || stream is EmptyReadStream); - if (responseStream != null && responseStream.NeedsDrain) + if (responseStream is not null && responseStream.NeedsDrain) { Debug.Assert(response.RequestMessage == _currentRequest); @@ -1942,15 +1942,15 @@ public async ValueTask DrainResponseAsync(HttpResponseMessage response, Cancella } } - Debug.Assert(_currentRequest == null); + Debug.Assert(_currentRequest is null); response.Dispose(); } private void ReturnConnectionToPool() { - Debug.Assert(_currentRequest == null, "Connection should no longer be associated with a request."); - Debug.Assert(_readAheadTask == null, "Expected a previous initial read to already be consumed."); + Debug.Assert(_currentRequest is null, "Connection should no longer be associated with a request."); + Debug.Assert(_readAheadTask is null, "Expected a previous initial read to already be consumed."); Debug.Assert(RemainingBuffer.Length == 0, "Unexpected data in connection read buffer."); // If we decided not to reuse the connection (either because the server sent Connection: close, @@ -1975,7 +1975,7 @@ private void ReturnConnectionToPool() private static bool EqualsOrdinal(string left, ReadOnlySpan right) { - Debug.Assert(left != null, "Expected non-null string"); + Debug.Assert(left is not null, "Expected non-null string"); if (left.Length != right.Length) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs index cfd4252c3db9fe..a49543798cdf4f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs @@ -114,7 +114,7 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK _proxyUri = proxyUri; _maxConnections = maxConnections; - if (host != null) + if (host is not null) { _originAuthority = new HttpAuthority(host, port); } @@ -125,55 +125,55 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK switch (kind) { case HttpConnectionKind.Http: - Debug.Assert(host != null); + Debug.Assert(host is not null); Debug.Assert(port != 0); - Debug.Assert(sslHostName == null); - Debug.Assert(proxyUri == null); + Debug.Assert(sslHostName is null); + Debug.Assert(proxyUri is null); _http3Enabled = false; break; case HttpConnectionKind.Https: - Debug.Assert(host != null); + Debug.Assert(host is not null); Debug.Assert(port != 0); - Debug.Assert(sslHostName != null); - Debug.Assert(proxyUri == null); + Debug.Assert(sslHostName is not null); + Debug.Assert(proxyUri is null); break; case HttpConnectionKind.Proxy: - Debug.Assert(host == null); + Debug.Assert(host is null); Debug.Assert(port == 0); - Debug.Assert(sslHostName == null); - Debug.Assert(proxyUri != null); + Debug.Assert(sslHostName is null); + Debug.Assert(proxyUri is not null); _http2Enabled = false; _http3Enabled = false; break; case HttpConnectionKind.ProxyTunnel: - Debug.Assert(host != null); + Debug.Assert(host is not null); Debug.Assert(port != 0); - Debug.Assert(sslHostName == null); - Debug.Assert(proxyUri != null); + Debug.Assert(sslHostName is null); + Debug.Assert(proxyUri is not null); _http2Enabled = false; _http3Enabled = false; break; case HttpConnectionKind.SslProxyTunnel: - Debug.Assert(host != null); + Debug.Assert(host is not null); Debug.Assert(port != 0); - Debug.Assert(sslHostName != null); - Debug.Assert(proxyUri != null); + Debug.Assert(sslHostName is not null); + Debug.Assert(proxyUri is not null); _http3Enabled = false; // TODO: how do we tunnel HTTP3? break; case HttpConnectionKind.ProxyConnect: - Debug.Assert(host != null); + Debug.Assert(host is not null); Debug.Assert(port != 0); - Debug.Assert(sslHostName == null); - Debug.Assert(proxyUri != null); + Debug.Assert(sslHostName is null); + Debug.Assert(proxyUri is not null); _http2Enabled = false; _http3Enabled = false; @@ -191,26 +191,26 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK } string? hostHeader = null; - if (_originAuthority != null) + if (_originAuthority is not null) { // Precalculate ASCII bytes for Host header // Note that if _host is null, this is a (non-tunneled) proxy connection, and we can't cache the hostname. hostHeader = - (_originAuthority.Port != (sslHostName == null ? DefaultHttpPort : DefaultHttpsPort)) ? + (_originAuthority.Port != (sslHostName is null ? DefaultHttpPort : DefaultHttpsPort)) ? $"{_originAuthority.IdnHost}:{_originAuthority.Port}" : _originAuthority.IdnHost; // Note the IDN hostname should always be ASCII, since it's already been IDNA encoded. _hostHeaderValueBytes = Encoding.ASCII.GetBytes(hostHeader); Debug.Assert(Encoding.ASCII.GetString(_hostHeaderValueBytes) == hostHeader); - if (sslHostName == null) + if (sslHostName is null) { _http2EncodedAuthorityHostHeader = HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(H2StaticTable.Authority, hostHeader); _http3EncodedAuthorityHostHeader = QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.Authority, hostHeader); } } - if (sslHostName != null) + if (sslHostName is not null) { _sslOptionsHttp11 = ConstructSslOptions(poolManager, sslHostName); _sslOptionsHttp11.ApplicationProtocols = null; @@ -236,7 +236,7 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK // For now, if an HTTP/2 server erroneously issues a renegotiation, we'll // allow it. - Debug.Assert(hostHeader != null); + Debug.Assert(hostHeader is not null); _http2EncodedAuthorityHostHeader = HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(H2StaticTable.Authority, hostHeader); _http3EncodedAuthorityHostHeader = QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.Authority, hostHeader); } @@ -263,7 +263,7 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK private static SslClientAuthenticationOptions ConstructSslOptions(HttpConnectionPoolManager poolManager, string sslHostName) { - Debug.Assert(sslHostName != null); + Debug.Assert(sslHostName is not null); SslClientAuthenticationOptions sslOptions = poolManager.Settings._sslOptions?.ShallowClone() ?? new SslClientAuthenticationOptions(); @@ -291,7 +291,7 @@ private static SslClientAuthenticationOptions ConstructSslOptions(HttpConnection public HttpConnectionSettings Settings => _poolManager.Settings; public HttpConnectionKind Kind => _kind; public bool IsSecure => _kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel; - public bool AnyProxyKind => (_proxyUri != null); + public bool AnyProxyKind => (_proxyUri is not null); public Uri? ProxyUri => _proxyUri; public ICredentials? ProxyCredentials => _poolManager.ProxyCredentials; public byte[]? HostHeaderValueBytes => _hostHeaderValueBytes; @@ -307,11 +307,11 @@ public byte[] Http2AltSvcOriginUri { get { - if (_http2AltSvcOriginUri == null) + if (_http2AltSvcOriginUri is null) { var sb = new StringBuilder(); - Debug.Assert(_originAuthority != null); + Debug.Assert(_originAuthority is not null); sb .Append(_kind == HttpConnectionKind.Https ? "https://" : "http://") .Append(_originAuthority.IdnHost); @@ -362,7 +362,7 @@ public byte[] Http2AltSvcOriginUri { authority = authority ?? _originAuthority; } - if (authority != null) + if (authority is not null) { if (IsAltSvcBlocked(authority)) { @@ -523,7 +523,7 @@ public byte[] Http2AltSvcOriginUri GetHttpConnectionAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken) { HttpConnection? connection = await GetOrReserveHttp11ConnectionAsync(async, cancellationToken).ConfigureAwait(false); - if (connection != null) + if (connection is not null) { return (connection, false, null); } @@ -534,9 +534,9 @@ public byte[] Http2AltSvcOriginUri { HttpResponseMessage? failureResponse; (connection, failureResponse) = await CreateHttp11ConnectionAsync(request, async, cancellationToken).ConfigureAwait(false); - if (connection == null) + if (connection is null) { - Debug.Assert(failureResponse != null); + Debug.Assert(failureResponse is not null); DecrementConnectionCount(); } return (connection, true, failureResponse); @@ -556,7 +556,7 @@ public byte[] Http2AltSvcOriginUri // See if we have an HTTP2 connection Http2Connection? http2Connection = GetExistingHttp2Connection(); - if (http2Connection != null) + if (http2Connection is not null) { // Connection exists and it is still good to use. if (NetEventSource.Log.IsEnabled()) Trace("Using existing HTTP2 connection."); @@ -565,11 +565,11 @@ public byte[] Http2AltSvcOriginUri } // Ensure that the connection creation semaphore is created - if (_http2ConnectionCreateLock == null) + if (_http2ConnectionCreateLock is null) { lock (SyncObj) { - if (_http2ConnectionCreateLock == null) + if (_http2ConnectionCreateLock is null) { _http2ConnectionCreateLock = new SemaphoreSlim(1); } @@ -586,7 +586,7 @@ public byte[] Http2AltSvcOriginUri try { http2Connection = GetExistingHttp2Connection(); - if (http2Connection != null) + if (http2Connection is not null) { return (http2Connection, false, null); } @@ -604,12 +604,12 @@ public byte[] Http2AltSvcOriginUri (stream, transportContext, failureResponse) = await ConnectAsync(request, async, cancellationToken).ConfigureAwait(false); - if (failureResponse != null) + if (failureResponse is not null) { return (null, true, failureResponse); } - Debug.Assert(stream != null); + Debug.Assert(stream is not null); sslStream = stream as SslStream; @@ -625,7 +625,7 @@ public byte[] Http2AltSvcOriginUri return (http2Connection, true, null); } - Debug.Assert(sslStream != null); + Debug.Assert(sslStream is not null); if (sslStream.NegotiatedApplicationProtocol == SslApplicationProtocol.Http2) { @@ -653,7 +653,7 @@ public byte[] Http2AltSvcOriginUri _http2ConnectionCreateLock.Release(); } - if (sslStream != null) + if (sslStream is not null) { // We established an SSL connection, but the server denied our request for HTTP2. // Continue as an HTTP/1.1 connection. @@ -712,7 +712,7 @@ public byte[] Http2AltSvcOriginUri { Http2Connection[]? localConnections = _http2Connections; - if (localConnections == null) + if (localConnections is null) { return null; } @@ -742,11 +742,11 @@ private void AddHttp2Connection(Http2Connection newConnection) lock (SyncObj) { Http2Connection[]? localHttp2Connections = _http2Connections; - int newCollectionSize = localHttp2Connections == null ? 1 : localHttp2Connections.Length + 1; + int newCollectionSize = localHttp2Connections is null ? 1 : localHttp2Connections.Length + 1; Http2Connection[] newHttp2Connections = new Http2Connection[newCollectionSize]; newHttp2Connections[0] = newConnection; - if (localHttp2Connections != null) + if (localHttp2Connections is not null) { Array.Copy(localHttp2Connections, 0, newHttp2Connections, 1, localHttp2Connections.Length); } @@ -763,7 +763,7 @@ private void AddHttp2Connection(Http2Connection newConnection) Http3Connection? http3Connection = Volatile.Read(ref _http3Connection); - if (http3Connection != null) + if (http3Connection is not null) { TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime; if (http3Connection.LifetimeExpired(Environment.TickCount64, pooledConnectionLifetime) || http3Connection.Authority != authority) @@ -782,11 +782,11 @@ private void AddHttp2Connection(Http2Connection newConnection) } // Ensure that the connection creation semaphore is created - if (_http3ConnectionCreateLock == null) + if (_http3ConnectionCreateLock is null) { lock (SyncObj) { - if (_http3ConnectionCreateLock == null) + if (_http3ConnectionCreateLock is null) { _http3ConnectionCreateLock = new SemaphoreSlim(1); } @@ -796,7 +796,7 @@ private void AddHttp2Connection(Http2Connection newConnection) await _http3ConnectionCreateLock.WaitAsync(cancellationToken).ConfigureAwait(false); try { - if (_http3Connection != null) + if (_http3Connection is not null) { // Someone beat us to creating the connection. @@ -857,11 +857,11 @@ public async ValueTask SendWithRetryAsync(HttpRequestMessag // Loop on connection failures and retry if possible. (HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse) = await GetConnectionAsync(request, async, cancellationToken).ConfigureAwait(false); - if (failureResponse != null) + if (failureResponse is not null) { // Proxy tunnel failure; return proxy response Debug.Assert(isNewConnection); - Debug.Assert(connection == null); + Debug.Assert(connection is null); return failureResponse; } @@ -874,7 +874,7 @@ public async ValueTask SendWithRetryAsync(HttpRequestMessag ((HttpConnection)connection).Acquire(); try { - response = await (doRequestAuth && Settings._credentials != null ? + response = await (doRequestAuth && Settings._credentials is not null ? AuthenticationHelper.SendWithNtConnectionAuthAsync(request, async, Settings._credentials, (HttpConnection)connection, this, cancellationToken) : SendWithNtProxyAuthAsync((HttpConnection)connection, request, async, cancellationToken)).ConfigureAwait(false); } @@ -969,12 +969,12 @@ internal void HandleAltSvc(IEnumerable altSvcHeaderValues, TimeSpan? res if (value == AltSvcHeaderValue.Clear) { ExpireAltSvcAuthority(); - Debug.Assert(_authorityExpireTimer != null); + Debug.Assert(_authorityExpireTimer is not null); _authorityExpireTimer.Change(Timeout.Infinite, Timeout.Infinite); break; } - if (nextAuthority == null && value != null && value.AlpnProtocolName == "h3") + if (nextAuthority is null && value is not null && value.AlpnProtocolName == "h3") { var authority = new HttpAuthority(value.Host!, value.Port); @@ -986,7 +986,7 @@ internal void HandleAltSvc(IEnumerable altSvcHeaderValues, TimeSpan? res TimeSpan authorityMaxAge = value.MaxAge; - if (responseAge != null) + if (responseAge is not null) { authorityMaxAge -= responseAge.GetValueOrDefault(); } @@ -1003,7 +1003,7 @@ internal void HandleAltSvc(IEnumerable altSvcHeaderValues, TimeSpan? res // There's a race here in checking _http3Authority outside of the lock, // but there's really no bad behavior if _http3Authority changes in the mean time. - if (nextAuthority != null && !nextAuthority.Equals(_http3Authority)) + if (nextAuthority is not null && !nextAuthority.Equals(_http3Authority)) { // Clamp the max age to 30 days... this is arbitrary but prevents passing a too-large TimeSpan to the Timer. if (nextAuthorityMaxAge.Ticks > (30 * TimeSpan.TicksPerDay)) @@ -1013,7 +1013,7 @@ internal void HandleAltSvc(IEnumerable altSvcHeaderValues, TimeSpan? res lock (SyncObj) { - if (_authorityExpireTimer == null) + if (_authorityExpireTimer is null) { var thisRef = new WeakReference(this); @@ -1071,7 +1071,7 @@ private void ExpireAltSvcAuthority() /// private bool IsAltSvcBlocked(HttpAuthority authority) { - if (_altSvcBlocklist != null) + if (_altSvcBlocklist is not null) { lock (_altSvcBlocklist) { @@ -1096,16 +1096,16 @@ private bool IsAltSvcBlocked(HttpAuthority authority) /// internal void BlocklistAuthority(HttpAuthority badAuthority) { - Debug.Assert(badAuthority != null); + Debug.Assert(badAuthority is not null); HashSet? altSvcBlocklist = _altSvcBlocklist; - if (altSvcBlocklist == null) + if (altSvcBlocklist is null) { lock (SyncObj) { altSvcBlocklist = _altSvcBlocklist; - if (altSvcBlocklist == null) + if (altSvcBlocklist is null) { altSvcBlocklist = new HashSet(); _altSvcBlocklistTimerCancellation = new CancellationTokenSource(); @@ -1132,12 +1132,12 @@ internal void BlocklistAuthority(HttpAuthority badAuthority) if (_http3Authority == badAuthority) { ExpireAltSvcAuthority(); - Debug.Assert(_authorityExpireTimer != null); + Debug.Assert(_authorityExpireTimer is not null); _authorityExpireTimer.Change(Timeout.Infinite, Timeout.Infinite); } } - Debug.Assert(_altSvcBlocklistTimerCancellation != null); + Debug.Assert(_altSvcBlocklistTimerCancellation is not null); if (added) { _ = Task.Delay(AltSvcBlocklistTimeoutInMilliseconds) @@ -1164,10 +1164,10 @@ public void OnNetworkChanged() { lock (SyncObj) { - if (_http3Authority != null && _persistAuthority == false) + if (_http3Authority is not null && _persistAuthority == false) { ExpireAltSvcAuthority(); - Debug.Assert(_authorityExpireTimer != null); + Debug.Assert(_authorityExpireTimer is not null); _authorityExpireTimer.Change(Timeout.Infinite, Timeout.Infinite); } } @@ -1178,7 +1178,7 @@ public async Task SendWithNtConnectionAuthAsync(HttpConnect connection.Acquire(); try { - if (doRequestAuth && Settings._credentials != null) + if (doRequestAuth && Settings._credentials is not null) { return await AuthenticationHelper.SendWithNtConnectionAuthAsync(request, async, Settings._credentials, connection, this, cancellationToken).ConfigureAwait(false); } @@ -1193,7 +1193,7 @@ public async Task SendWithNtConnectionAuthAsync(HttpConnect public Task SendWithNtProxyAuthAsync(HttpConnection connection, HttpRequestMessage request, bool async, CancellationToken cancellationToken) { - if (AnyProxyKind && ProxyCredentials != null) + if (AnyProxyKind && ProxyCredentials is not null) { return AuthenticationHelper.SendWithNtProxyAuthAsync(request, ProxyUri!, async, ProxyCredentials, connection, this, cancellationToken); } @@ -1205,7 +1205,7 @@ public Task SendWithNtProxyAuthAsync(HttpConnection connect public ValueTask SendWithProxyAuthAsync(HttpRequestMessage request, bool async, bool doRequestAuth, CancellationToken cancellationToken) { if ((_kind == HttpConnectionKind.Proxy || _kind == HttpConnectionKind.ProxyConnect) && - _poolManager.ProxyCredentials != null) + _poolManager.ProxyCredentials is not null) { return AuthenticationHelper.SendWithProxyAuthAsync(request, _proxyUri!, async, _poolManager.ProxyCredentials, doRequestAuth, this, cancellationToken); } @@ -1215,7 +1215,7 @@ public ValueTask SendWithProxyAuthAsync(HttpRequestMessage public ValueTask SendAsync(HttpRequestMessage request, bool async, bool doRequestAuth, CancellationToken cancellationToken) { - if (doRequestAuth && Settings._credentials != null) + if (doRequestAuth && Settings._credentials is not null) { return AuthenticationHelper.SendWithRequestAuthAsync(request, async, Settings._credentials, Settings._preAuthenticate, this, cancellationToken); } @@ -1243,7 +1243,7 @@ public ValueTask SendAsync(HttpRequestMessage request, bool case HttpConnectionKind.Http: case HttpConnectionKind.Https: case HttpConnectionKind.ProxyConnect: - Debug.Assert(_originAuthority != null); + Debug.Assert(_originAuthority is not null); stream = await ConnectToTcpHostAsync(_originAuthority.IdnHost, _originAuthority.Port, request, async, cancellationToken).ConfigureAwait(false); break; @@ -1255,7 +1255,7 @@ public ValueTask SendAsync(HttpRequestMessage request, bool case HttpConnectionKind.SslProxyTunnel: HttpResponseMessage? response; (stream, response) = await EstablishProxyTunnel(async, request.HasHeaders ? request.Headers : null, cancellationToken).ConfigureAwait(false); - if (response != null) + if (response is not null) { // Return non-success response from proxy. response.RequestMessage = request; @@ -1264,7 +1264,7 @@ public ValueTask SendAsync(HttpRequestMessage request, bool break; } - Debug.Assert(stream != null); + Debug.Assert(stream is not null); TransportContext? transportContext = null; if (IsSecure) @@ -1333,7 +1333,7 @@ private ValueTask ConnectToTcpHostAsync(string host, int port, HttpReque (Stream? stream, TransportContext? transportContext, HttpResponseMessage? failureResponse) = await ConnectAsync(request, async, cancellationToken).ConfigureAwait(false); - if (failureResponse != null) + if (failureResponse is not null) { return (null, failureResponse); } @@ -1376,7 +1376,7 @@ private async ValueTask ApplyPlaintextFilter(Stream stream, Version http throw new HttpRequestException(SR.net_http_exception_during_plaintext_filter, e); } - if (newStream == null) + if (newStream is null) { stream.Dispose(); throw new HttpRequestException(SR.net_http_null_from_plaintext_filter); @@ -1407,12 +1407,12 @@ private async ValueTask ConstructHttp2Connection(Stream stream, // Returns the established stream or an HttpResponseMessage from the proxy indicating failure. private async ValueTask<(Stream?, HttpResponseMessage?)> EstablishProxyTunnel(bool async, HttpRequestHeaders? headers, CancellationToken cancellationToken) { - Debug.Assert(_originAuthority != null); + Debug.Assert(_originAuthority is not null); // Send a CONNECT request to the proxy server to establish a tunnel. HttpRequestMessage tunnelRequest = new HttpRequestMessage(HttpMethod.Connect, _proxyUri); tunnelRequest.Headers.Host = $"{_originAuthority.IdnHost}:{_originAuthority.Port}"; // This specifies destination host/port to connect to - if (headers != null && headers.TryGetValues(HttpKnownHeaderNames.UserAgent, out IEnumerable? values)) + if (headers is not null && headers.TryGetValues(HttpKnownHeaderNames.UserAgent, out IEnumerable? values)) { tunnelRequest.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.UserAgent, values); } @@ -1436,7 +1436,7 @@ private async ValueTask ConstructHttp2Connection(Stream stream, Debug.Assert(Settings._maxConnectionsPerServer != int.MaxValue); Debug.Assert(_idleConnections.Count == 0, $"With {_idleConnections.Count} idle connections, we shouldn't have a waiter."); - if (_waiters == null) + if (_waiters is null) { _waiters = new Queue>(); } @@ -1450,7 +1450,7 @@ private bool HasWaiter() { Debug.Assert(Monitor.IsEntered(SyncObj)); - return (_waiters != null && _waiters.Count > 0); + return (_waiters is not null && _waiters.Count > 0); } /// Dequeues a waiter from the waiters list. The list must not be empty. @@ -1602,7 +1602,7 @@ public void InvalidateHttp2Connection(Http2Connection connection) { Http2Connection[]? localHttp2Connections = _http2Connections; - if (localHttp2Connections == null) + if (localHttp2Connections is null) { return; } @@ -1664,7 +1664,7 @@ public void Dispose() list.ForEach(c => c._connection.Dispose()); list.Clear(); - if (_http2Connections != null) + if (_http2Connections is not null) { for (int i = 0; i < _http2Connections.Length; i++) { @@ -1673,13 +1673,13 @@ public void Dispose() _http2Connections = null; } - if (_authorityExpireTimer != null) + if (_authorityExpireTimer is not null) { _authorityExpireTimer.Dispose(); _authorityExpireTimer = null; } - if (_altSvcBlocklistTimerCancellation != null) + if (_altSvcBlocklistTimerCancellation is not null) { _altSvcBlocklistTimerCancellation.Cancel(); _altSvcBlocklistTimerCancellation.Dispose(); @@ -1717,7 +1717,7 @@ public bool CleanCacheAndDisposeIfUnused() // Copy the reference to a local variable to simplify the removal logic below. Http2Connection[]? localHttp2Connections = _http2Connections; - if (localHttp2Connections != null) + if (localHttp2Connections is not null) { Http2Connection[]? newHttp2Connections = null; int newIndex = 0; @@ -1728,7 +1728,7 @@ public bool CleanCacheAndDisposeIfUnused() { http2Connection.Dispose(); - if (newHttp2Connections == null) + if (newHttp2Connections is null) { newHttp2Connections = new Http2Connection[localHttp2Connections.Length]; if (i > 0) @@ -1739,14 +1739,14 @@ public bool CleanCacheAndDisposeIfUnused() } } } - else if (newHttp2Connections != null) + else if (newHttp2Connections is not null) { newHttp2Connections[newIndex] = localHttp2Connections[i]; newIndex++; } } - if (newHttp2Connections != null) + if (newHttp2Connections is not null) { //Some connections have been removed, so _http2Connections must be replaced. if (newIndex > 0) @@ -1807,7 +1807,7 @@ public bool CleanCacheAndDisposeIfUnused() // if a pool was used since the last time we cleaned up, give it another chance. New pools // start out saying they've recently been used, to give them a bit of breathing room and time // for the initial collection to be added to it. - if (_associatedConnectionCount == 0 && !_usedSinceLastCleanup && _http2Connections == null) + if (_associatedConnectionCount == 0 && !_usedSinceLastCleanup && _http2Connections is null) { Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0"); _disposed = true; @@ -1850,7 +1850,7 @@ private static bool GetIsWindows7Or2008R2() internal void HeartBeat() { Http2Connection[]? localHttp2Connections = _http2Connections; - if (localHttp2Connections != null) + if (localHttp2Connections is not null) { foreach (Http2Connection http2Connection in localHttp2Connections) { @@ -1863,11 +1863,11 @@ internal void HeartBeat() // For diagnostic purposes public override string ToString() => $"{nameof(HttpConnectionPool)} " + - (_proxyUri == null ? - (_sslOptionsHttp11 == null ? + (_proxyUri is null ? + (_sslOptionsHttp11 is null ? $"http://{_originAuthority}" : $"https://{_originAuthority}" + (_sslOptionsHttp11.TargetHost != _originAuthority!.IdnHost ? $", SSL TargetHost={_sslOptionsHttp11.TargetHost}" : null)) : - (_sslOptionsHttp11 == null ? + (_sslOptionsHttp11 is null ? $"Proxy {_proxyUri}" : $"https://{_originAuthority}/ tunnelled via Proxy {_proxyUri}" + (_sslOptionsHttp11.TargetHost != _originAuthority!.IdnHost ? $", SSL TargetHost={_sslOptionsHttp11.TargetHost}" : null))); @@ -1892,7 +1892,7 @@ private void Trace(string? message, [CallerMemberName] string? memberName = null /// The connection. public CachedConnection(HttpConnection connection) { - Debug.Assert(connection != null); + Debug.Assert(connection is not null); _connection = connection; _returnedTickCount = Environment.TickCount64; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs index 84ac7270df15cc..80c6ee8134c180 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs @@ -145,7 +145,7 @@ public HttpConnectionPoolManager(HttpConnectionSettings settings) if (settings._useProxy) { _proxy = settings._proxy ?? HttpClient.DefaultProxy; - if (_proxy != null) + if (_proxy is not null) { _proxyCredentials = _proxy.Credentials ?? settings._defaultProxyCredentials; } @@ -158,7 +158,7 @@ public HttpConnectionPoolManager(HttpConnectionSettings settings) /// public void StartMonitoringNetworkChanges() { - if (_networkChangeCleanup != null) + if (_networkChangeCleanup is not null) { return; } @@ -179,7 +179,7 @@ public void StartMonitoringNetworkChanges() var cleanup = new NetworkChangeCleanup(networkChangedDelegate); - if (Interlocked.CompareExchange(ref _networkChangeCleanup, cleanup, null) != null) + if (Interlocked.CompareExchange(ref _networkChangeCleanup, cleanup, null) is not null) { // We lost a race, another thread already started monitoring. GC.SuppressFinalize(cleanup); @@ -254,7 +254,7 @@ private static string ParseHostNameFromHeader(string hostHeader) private HttpConnectionKey GetConnectionKey(HttpRequestMessage request, Uri? proxyUri, bool isProxyConnect) { Uri? uri = request.RequestUri; - Debug.Assert(uri != null); + Debug.Assert(uri is not null); if (isProxyConnect) { @@ -266,7 +266,7 @@ private HttpConnectionKey GetConnectionKey(HttpRequestMessage request, Uri? prox if (HttpUtilities.IsSupportedSecureScheme(uri.Scheme)) { string? hostHeader = request.Headers.Host; - if (hostHeader != null) + if (hostHeader is not null) { sslHostName = ParseHostNameFromHeader(hostHeader); } @@ -277,12 +277,12 @@ private HttpConnectionKey GetConnectionKey(HttpRequestMessage request, Uri? prox } } - string identity = GetIdentityIfDefaultCredentialsUsed(proxyUri != null ? _settings._defaultCredentialsUsedForProxy : _settings._defaultCredentialsUsedForServer); + string identity = GetIdentityIfDefaultCredentialsUsed(proxyUri is not null ? _settings._defaultCredentialsUsedForProxy : _settings._defaultCredentialsUsedForServer); - if (proxyUri != null) + if (proxyUri is not null) { Debug.Assert(HttpUtilities.IsSupportedNonSecureScheme(proxyUri.Scheme)); - if (sslHostName == null) + if (sslHostName is null) { if (HttpUtilities.IsNonSecureWebSocketScheme(uri.Scheme)) { @@ -303,7 +303,7 @@ private HttpConnectionKey GetConnectionKey(HttpRequestMessage request, Uri? prox return new HttpConnectionKey(HttpConnectionKind.SslProxyTunnel, uri.IdnHost, uri.Port, sslHostName, proxyUri, identity); } } - else if (sslHostName != null) + else if (sslHostName is not null) { return new HttpConnectionKey(HttpConnectionKind.Https, uri.IdnHost, uri.Port, sslHostName, null, identity); } @@ -322,7 +322,7 @@ public ValueTask SendAsyncCore(HttpRequestMessage request, { pool = new HttpConnectionPool(this, key.Kind, key.Host, key.Port, key.SslHostName, key.ProxyUri, _maxConnectionsPerServer); - if (_cleaningTimer == null) + if (_cleaningTimer is null) { // There's no cleaning timer, which means we're not adding connections into pools, but we still need // the pool object for this request. We don't need or want to add the pool to the pools, though, @@ -359,7 +359,7 @@ public ValueTask SendProxyConnectAsync(HttpRequestMessage r public ValueTask SendAsync(HttpRequestMessage request, bool async, bool doRequestAuth, CancellationToken cancellationToken) { - if (_proxy == null) + if (_proxy is null) { return SendAsyncCore(request, null, async, doRequestAuth, isProxyConnect: false, cancellationToken); } @@ -368,7 +368,7 @@ public ValueTask SendAsync(HttpRequestMessage request, bool Uri? proxyUri = null; try { - Debug.Assert(request.RequestUri != null); + Debug.Assert(request.RequestUri is not null); if (!_proxy.IsBypassed(request.RequestUri)) { if (_proxy is IMultiWebProxy multiWebProxy) @@ -393,7 +393,7 @@ public ValueTask SendAsync(HttpRequestMessage request, bool if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Exception from {_proxy.GetType().Name}.GetProxy({request.RequestUri}): {ex}"); } - if (proxyUri != null && proxyUri.Scheme != UriScheme.Http) + if (proxyUri is not null && proxyUri.Scheme != UriScheme.Http) { throw new NotSupportedException(SR.net_http_invalid_proxy_scheme); } @@ -464,7 +464,7 @@ private void SetCleaningTimer(TimeSpan timeout) /// Removes unusable connections from each pool, and removes stale pools entirely. private void RemoveStalePools() { - Debug.Assert(_cleaningTimer != null); + Debug.Assert(_cleaningTimer is not null); // Iterate through each pool in the set of pools. For each, ask it to clear out // any unusable connections (e.g. those which have expired, those which have been closed, etc.) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs index 72befb088edce5..db0d6910d534da 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs @@ -15,7 +15,7 @@ internal sealed class HttpConnectionResponseContent : HttpContent public void SetStream(Stream stream) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); Debug.Assert(stream.CanRead); Debug.Assert(!_consumedStream); @@ -24,7 +24,7 @@ public void SetStream(Stream stream) private Stream ConsumeStream() { - if (_consumedStream || _stream == null) + if (_consumedStream || _stream is null) { throw new InvalidOperationException(SR.net_http_content_stream_already_read); } @@ -36,7 +36,7 @@ private Stream ConsumeStream() protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -53,7 +53,7 @@ protected sealed override Task SerializeToStreamAsync(Stream stream, TransportCo protected sealed override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -86,7 +86,7 @@ protected sealed override void Dispose(bool disposing) { if (disposing) { - if (_stream != null) + if (_stream is not null) { _stream.Dispose(); _stream = null; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs index afa5b26d1a9d0f..f3dbd0c36f5eee 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs @@ -73,7 +73,7 @@ public HttpConnectionSettings() AllowDraftHttp3 && allowHttp2 ? Http3Connection.HttpVersion30 : allowHttp2 ? HttpVersion.Version20 : HttpVersion.Version11; - _defaultCredentialsUsedForProxy = _proxy != null && (_proxy.Credentials == CredentialCache.DefaultCredentials || _defaultProxyCredentials == CredentialCache.DefaultCredentials); + _defaultCredentialsUsedForProxy = _proxy is not null && (_proxy.Credentials == CredentialCache.DefaultCredentials || _defaultProxyCredentials == CredentialCache.DefaultCredentials); _defaultCredentialsUsedForServer = _credentials == CredentialCache.DefaultCredentials; } @@ -81,7 +81,7 @@ public HttpConnectionSettings() public HttpConnectionSettings CloneAndNormalize() { // Force creation of the cookie container if needed, so the original and clone share the same instance. - if (_useCookies && _cookieContainer == null) + if (_useCookies && _cookieContainer is null) { _cookieContainer = new CookieContainer(); } @@ -138,7 +138,7 @@ private static bool AllowHttp2 // AppContext switch wasn't used. Check the environment variable. string? envVar = Environment.GetEnvironmentVariable(Http2SupportEnvironmentVariableSettingName); - if (envVar != null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0"))) + if (envVar is not null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0"))) { // Disallow HTTP/2 protocol. return false; @@ -164,7 +164,7 @@ private static bool AllowDraftHttp3 // AppContext switch wasn't used. Check the environment variable. string? envVar = Environment.GetEnvironmentVariable(Http3DraftSupportEnvironmentVariableSettingName); - if (envVar != null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0"))) + if (envVar is not null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0"))) { // Disallow HTTP/3 protocol for HTTP endpoints. return false; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentReadStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentReadStream.cs index a6b3fe009f74d7..4b57ac38dfa070 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentReadStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentReadStream.cs @@ -61,7 +61,7 @@ protected override void Dispose(bool disposing) private async Task DrainOnDisposeAsync() { HttpConnection? connection = _connection; // Will be null after drain succeeds - Debug.Assert(connection != null); + Debug.Assert(connection is not null); try { bool drained = await DrainAsync(connection._pool.Settings._maxResponseDrainSize).ConfigureAwait(false); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs index c5da3efdd53208..f96e33cb254e13 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs @@ -21,7 +21,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_connection != null) + if (_connection is not null) { _connection.Dispose(); _connection = null; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentWriteStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentWriteStream.cs index 2ae430c4a40f59..53c3ef41a9c85e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentWriteStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentWriteStream.cs @@ -15,7 +15,7 @@ private abstract class HttpContentWriteStream : HttpContentStream public long BytesWritten { get; protected set; } public HttpContentWriteStream(HttpConnection connection) : base(connection) => - Debug.Assert(connection != null); + Debug.Assert(connection is not null); public sealed override bool CanRead => false; public sealed override bool CanWrite => true; @@ -26,7 +26,7 @@ public sealed override void Flush() => public sealed override Task FlushAsync(CancellationToken ignored) { HttpConnection? connection = _connection; - return connection != null ? + return connection is not null ? connection.FlushAsync(async: true).AsTask() : default!; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs index f466dbe997c4b9..9a27eaa7833de7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs @@ -19,7 +19,7 @@ public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy) // Note that curl uses HTTPS_PROXY but not HTTP_PROXY. Uri? httpProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpProxyLC)); - if (httpProxy == null && Environment.GetEnvironmentVariable(EnvCGI) == null) + if (httpProxy is null && Environment.GetEnvironmentVariable(EnvCGI) is null) { httpProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpProxyUC)); } @@ -27,17 +27,17 @@ public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy) Uri? httpsProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpsProxyLC)) ?? GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpsProxyUC)); - if (httpProxy == null || httpsProxy == null) + if (httpProxy is null || httpsProxy is null) { Uri? allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyLC)) ?? GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC)); - if (httpProxy == null) + if (httpProxy is null) { httpProxy = allProxy; } - if (httpsProxy == null) + if (httpsProxy is null) { httpsProxy = allProxy; } @@ -45,7 +45,7 @@ public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy) // Do not instantiate if nothing is set. // Caller may pick some other proxy type. - if (httpProxy == null && httpsProxy == null) + if (httpProxy is null && httpsProxy is null) { proxy = null; return false; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs index 272235c1cdab9b..a2d621dcc66829 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs @@ -13,23 +13,23 @@ public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy) // general all_*. On Windows, environment variables are case insensitive. Uri? httpProxy = null; - if (Environment.GetEnvironmentVariable(EnvCGI) == null) + if (Environment.GetEnvironmentVariable(EnvCGI) is null) { httpProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpProxyUC)); } Uri? httpsProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpsProxyUC)); - if (httpProxy == null || httpsProxy == null) + if (httpProxy is null || httpsProxy is null) { Uri? allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC)); - if (httpProxy == null) + if (httpProxy is null) { httpProxy = allProxy; } - if (httpsProxy == null) + if (httpsProxy is null) { httpsProxy = allProxy; } @@ -37,7 +37,7 @@ public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy) // Do not instantiate if nothing is set. // Caller may pick some other proxy type. - if (httpProxy == null && httpsProxy == null) + if (httpProxy is null && httpsProxy is null) { proxy = null; return false; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.cs index e00cd368f8b6d7..1c5995d90a5286 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.cs @@ -27,7 +27,7 @@ public HttpEnvironmentProxyCredentials(Uri? httpProxy, NetworkCredential? httpCr public NetworkCredential? GetCredential(Uri? uri, string authType) { - if (uri == null) + if (uri is null) { return null; } @@ -40,15 +40,15 @@ public HttpEnvironmentProxyCredentials(Uri? httpProxy, NetworkCredential? httpCr NetworkCredential? httpCred = null; NetworkCredential? httpsCred = null; - if (httpProxy != null) + if (httpProxy is not null) { httpCred = GetCredentialsFromString(httpProxy.UserInfo); } - if (httpsProxy != null) + if (httpsProxy is not null) { httpsCred = GetCredentialsFromString(httpsProxy.UserInfo); } - if (httpCred == null && httpsCred == null) + if (httpCred is null && httpsCred is null) { return null; } @@ -189,12 +189,12 @@ private HttpEnvironmentProxy(Uri? httpProxy, Uri? httpsProxy, string? bypassList try { UriBuilder ub = new UriBuilder("http", host, port); - if (user != null) + if (user is not null) { ub.UserName = Uri.EscapeDataString(user); } - if (password != null) + if (password is not null) { ub.Password = Uri.EscapeDataString(password); } @@ -211,7 +211,7 @@ private HttpEnvironmentProxy(Uri? httpProxy, Uri? httpsProxy, string? bypassList /// private bool IsMatchInBypassList(Uri input) { - if (_bypass != null) + if (_bypass is not null) { foreach (string s in _bypass) { @@ -255,7 +255,7 @@ private bool IsMatchInBypassList(Uri input) /// public bool IsBypassed(Uri uri) { - return GetProxy(uri) == null ? true : IsMatchInBypassList(uri); + return GetProxy(uri) is null ? true : IsMatchInBypassList(uri); } public ICredentials? Credentials diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs index 176b35c7401964..bc820b4d949d49 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs @@ -132,7 +132,7 @@ private HttpWindowsProxy(WinInetProxyHelper proxyHelper, SafeWinHttpHandle? sess { idx++; } - if (tmp == null) + if (tmp is null) { continue; } @@ -167,7 +167,7 @@ public void Dispose() { _disposed = true; - if (_sessionHandle != null && !_sessionHandle.IsInvalid) + if (_sessionHandle is not null && !_sessionHandle.IsInvalid) { SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle); } @@ -279,7 +279,7 @@ public MultiProxy GetMultiProxy(Uri uri) } // Check if we have other rules for bypass. - if (_bypass != null) + if (_bypass is not null) { foreach (string entry in _bypass) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs index 61c22cc158e0dd..7a313c2221e8f0 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs @@ -97,7 +97,7 @@ private static Uri GetProxyUri(string scheme, CFProxy proxy) if (proxy.ProxyType == CFProxy.kCFProxyTypeAutoConfigurationURL || proxy.ProxyType == CFProxy.kCFProxyTypeAutoConfigurationJavaScript) { Uri? result = ExecuteProxyAutoConfiguration(cfurl, proxy); - if (result != null) + if (result is not null) return result; } else if (proxy.ProxyType == CFProxy.kCFProxyTypeHTTP || proxy.ProxyType == CFProxy.kCFProxyTypeHTTPS) @@ -113,11 +113,11 @@ private static Uri GetProxyUri(string scheme, CFProxy proxy) public bool IsBypassed(Uri targetUri) { - if (targetUri == null) + if (targetUri is null) throw new ArgumentNullException(nameof(targetUri)); Uri? proxyUri = GetProxy(targetUri); - return Equals(proxyUri, targetUri) || proxyUri == null; + return Equals(proxyUri, targetUri) || proxyUri is null; } } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MultiProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MultiProxy.cs index 087d104153b10b..c9e9d195ff9c2c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MultiProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MultiProxy.cs @@ -49,7 +49,7 @@ private MultiProxy(FailedProxyCache failedProxyCache, string proxyConfig, bool s /// If true, return proxies suitable for use with a secure connection. If false, return proxies suitable for an insecure connection. public static MultiProxy Parse(FailedProxyCache failedProxyCache, string? proxyConfig, bool secure) { - Debug.Assert(failedProxyCache != null); + Debug.Assert(failedProxyCache is not null); Uri[] uris = Array.Empty(); @@ -78,7 +78,7 @@ public static MultiProxy Parse(FailedProxyCache failedProxyCache, string? proxyC /// If true, return proxies suitable for use with a secure connection. If false, return proxies suitable for an insecure connection. public static MultiProxy CreateLazy(FailedProxyCache failedProxyCache, string proxyConfig, bool secure) { - Debug.Assert(failedProxyCache != null); + Debug.Assert(failedProxyCache is not null); return string.IsNullOrEmpty(proxyConfig) == false ? new MultiProxy(failedProxyCache, proxyConfig, secure) : @@ -94,9 +94,9 @@ public static MultiProxy CreateLazy(FailedProxyCache failedProxyCache, string pr public bool ReadNext([NotNullWhen(true)] out Uri? uri, out bool isFinalProxy) { // Enumerating indicates the previous proxy has failed; mark it as such. - if (_currentUri != null) + if (_currentUri is not null) { - Debug.Assert(_failedProxyCache != null); + Debug.Assert(_failedProxyCache is not null); _failedProxyCache.SetProxyFailed(_currentUri); } @@ -113,7 +113,7 @@ public bool ReadNext([NotNullWhen(true)] out Uri? uri, out bool isFinalProxy) do { - Debug.Assert(_failedProxyCache != null); + Debug.Assert(_failedProxyCache is not null); long renewTicks = _failedProxyCache.GetProxyRenewTicks(uri); // Proxy hasn't failed recently, return for use. @@ -132,14 +132,14 @@ public bool ReadNext([NotNullWhen(true)] out Uri? uri, out bool isFinalProxy) while (ReadNextHelper(out uri, out isFinalProxy)); // All the proxies in the config have failed; in this case, return the proxy that is closest to renewal. - if (_currentUri == null) + if (_currentUri is null) { uri = oldestFailedProxyUri; _currentUri = oldestFailedProxyUri; - if (oldestFailedProxyUri != null) + if (oldestFailedProxyUri is not null) { - Debug.Assert(uri != null); + Debug.Assert(uri is not null); _failedProxyCache.TryRenewProxy(uri, oldestFailedProxyTicks); return true; } @@ -153,9 +153,9 @@ public bool ReadNext([NotNullWhen(true)] out Uri? uri, out bool isFinalProxy) /// private bool ReadNextHelper([NotNullWhen(true)] out Uri? uri, out bool isFinalProxy) { - Debug.Assert(_uris != null || _proxyConfig != null, $"{nameof(ReadNext)} must not be called on a default-initialized {nameof(MultiProxy)}."); + Debug.Assert(_uris is not null || _proxyConfig is not null, $"{nameof(ReadNext)} must not be called on a default-initialized {nameof(MultiProxy)}."); - if (_uris != null) + if (_uris is not null) { if (_currentIndex == _uris.Length) { @@ -169,7 +169,7 @@ private bool ReadNextHelper([NotNullWhen(true)] out Uri? uri, out bool isFinalPr return true; } - Debug.Assert(_proxyConfig != null); + Debug.Assert(_proxyConfig is not null); if (_currentIndex < _proxyConfig.Length) { bool hasProxy = TryParseProxyConfigPart(_proxyConfig.AsSpan(_currentIndex), _secure, out uri!, out int charactersConsumed); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RawConnectionStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RawConnectionStream.cs index b1f8bd90c8824b..01ede74ba7d9e7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RawConnectionStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RawConnectionStream.cs @@ -23,7 +23,7 @@ public RawConnectionStream(HttpConnection connection) : base(connection) public override int Read(Span buffer) { HttpConnection? connection = _connection; - if (connection == null || buffer.Length == 0) + if (connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data return 0; @@ -45,7 +45,7 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation CancellationHelper.ThrowIfCancellationRequested(cancellationToken); HttpConnection? connection = _connection; - if (connection == null || buffer.Length == 0) + if (connection is null || buffer.Length == 0) { // Response body fully consumed or the caller didn't ask for any data return 0; @@ -97,7 +97,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio } HttpConnection? connection = _connection; - if (connection == null) + if (connection is null) { // null if response body fully consumed return Task.CompletedTask; @@ -148,7 +148,7 @@ private void Finish(HttpConnection connection) public override void Write(ReadOnlySpan buffer) { HttpConnection? connection = _connection; - if (connection == null) + if (connection is null) { throw new IOException(SR.ObjectDisposed_StreamClosed); } @@ -167,7 +167,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo } HttpConnection? connection = _connection; - if (connection == null) + if (connection is null) { return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new IOException(SR.ObjectDisposed_StreamClosed))); } @@ -193,7 +193,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) } HttpConnection? connection = _connection; - if (connection == null) + if (connection is null) { return Task.CompletedTask; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs index cf1693672b03e4..63555f1fa506ae 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs @@ -16,8 +16,8 @@ internal sealed class RedirectHandler : HttpMessageHandlerStage public RedirectHandler(int maxAutomaticRedirections, HttpMessageHandlerStage initialInnerHandler, HttpMessageHandlerStage redirectInnerHandler) { - Debug.Assert(initialInnerHandler != null); - Debug.Assert(redirectInnerHandler != null); + Debug.Assert(initialInnerHandler is not null); + Debug.Assert(redirectInnerHandler is not null); Debug.Assert(maxAutomaticRedirections > 0); _maxAutomaticRedirections = maxAutomaticRedirections; @@ -31,8 +31,8 @@ internal override async ValueTask SendAsync(HttpRequestMess uint redirectCount = 0; Uri? redirectUri; - Debug.Assert(request.RequestUri != null); - while ((redirectUri = GetUriForRedirect(request.RequestUri, response)) != null) + Debug.Assert(request.RequestUri is not null); + while ((redirectUri = GetUriForRedirect(request.RequestUri, response)) is not null) { redirectCount++; @@ -99,7 +99,7 @@ internal override async ValueTask SendAsync(HttpRequestMess } Uri? location = response.Headers.Location; - if (location == null) + if (location is null) { return null; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs index 7e2631ec1541ea..c3f7281cb3fcf4 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs @@ -33,7 +33,7 @@ private void CheckDisposed() private void CheckDisposedOrStarted() { CheckDisposed(); - if (_handler != null) + if (_handler is not null) { throw new InvalidOperationException(SR.net_http_operation_started); } @@ -460,7 +460,7 @@ private HttpMessageHandlerStage SetupHandlerChain() HttpMessageHandlerStage handler; - if (settings._credentials == null) + if (settings._credentials is null) { handler = new HttpConnectionHandler(poolManager); } @@ -475,7 +475,7 @@ private HttpMessageHandlerStage SetupHandlerChain() // if the credential is anything other than a CredentialCache. // We allow credentials in a CredentialCache since they are specifically tied to URIs. HttpMessageHandlerStage redirectHandler = - (settings._credentials == null || settings._credentials is CredentialCache) ? + (settings._credentials is null || settings._credentials is CredentialCache) ? handler : new HttpConnectionHandler(poolManager); // will not authenticate @@ -488,7 +488,7 @@ private HttpMessageHandlerStage SetupHandlerChain() } // Ensure a single handler is used for all requests. - if (Interlocked.CompareExchange(ref _handler, handler, null) != null) + if (Interlocked.CompareExchange(ref _handler, handler, null) is not null) { handler.Dispose(); } @@ -519,7 +519,7 @@ protected internal override HttpResponseMessage Send(HttpRequestMessage request, } Exception? error = ValidateAndNormalizeRequest(request); - if (error != null) + if (error is not null) { throw error; } @@ -533,7 +533,7 @@ protected internal override Task SendAsync(HttpRequestMessa HttpMessageHandler handler = _handler ?? SetupHandlerChain(); Exception? error = ValidateAndNormalizeRequest(request); - if (error != null) + if (error is not null) { return Task.FromException(error); } @@ -551,7 +551,7 @@ protected internal override Task SendAsync(HttpRequestMessa // Add headers to define content transfer, if not present if (request.HasHeaders && request.Headers.TransferEncodingChunked.GetValueOrDefault()) { - if (request.Content == null) + if (request.Content is null) { return new HttpRequestException(SR.net_http_client_execution_error, new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content)); @@ -561,7 +561,7 @@ protected internal override Task SendAsync(HttpRequestMessa // the Content-Length header if present, as sending both is invalid. request.Content.Headers.ContentLength = null; } - else if (request.Content != null && request.Content.Headers.ContentLength == null) + else if (request.Content is not null && request.Content.Headers.ContentLength is null) { // We have content, but neither Transfer-Encoding nor Content-Length is set. request.Headers.TransferEncodingChunked = true; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs index 12fab2a7807a87..e1a3fc0a15eccc 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs @@ -19,7 +19,7 @@ public class StreamContent : HttpContent public StreamContent(Stream content) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -30,7 +30,7 @@ public StreamContent(Stream content) public StreamContent(Stream content, int bufferSize) { - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -56,7 +56,7 @@ private void InitializeContent(Stream content, int bufferSize) protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); PrepareContent(); // If the stream can't be re-read, make sure that it gets disposed once it is consumed. StreamToStreamCopy.Copy(_content, stream, _bufferSize, !_content.CanSeek); @@ -73,7 +73,7 @@ protected override Task SerializeToStreamAsync(Stream stream, TransportContext? private Task SerializeToStreamAsyncCore(Stream stream, CancellationToken cancellationToken) { - Debug.Assert(stream != null); + Debug.Assert(stream is not null); PrepareContent(); return StreamToStreamCopy.CopyAsync( _content, diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs index ee0c09220b7d55..1eeab712a5ec31 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs @@ -22,8 +22,8 @@ internal static class StreamToStreamCopy /// Whether to dispose of the source stream after the copy has finished successfully. public static void Copy(Stream source, Stream destination, int bufferSize, bool disposeSource) { - Debug.Assert(source != null); - Debug.Assert(destination != null); + Debug.Assert(source is not null); + Debug.Assert(destination is not null); Debug.Assert(bufferSize >= 0); if (bufferSize == 0) @@ -49,8 +49,8 @@ public static void Copy(Stream source, Stream destination, int bufferSize, bool /// CancellationToken used to cancel the copy operation. public static Task CopyAsync(Stream source, Stream destination, int bufferSize, bool disposeSource, CancellationToken cancellationToken = default(CancellationToken)) { - Debug.Assert(source != null); - Debug.Assert(destination != null); + Debug.Assert(source is not null); + Debug.Assert(destination is not null); Debug.Assert(bufferSize >= 0); try diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs index 05ec413dbdb533..4027149b64182f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs @@ -27,8 +27,8 @@ public StringContent(string content, Encoding? encoding, string? mediaType) : base(GetContentByteArray(content, encoding)) { // Initialize the 'Content-Type' header with information provided by parameters. - MediaTypeHeaderValue headerValue = new MediaTypeHeaderValue((mediaType == null) ? DefaultMediaType : mediaType); - headerValue.CharSet = (encoding == null) ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName; + MediaTypeHeaderValue headerValue = new MediaTypeHeaderValue((mediaType is null) ? DefaultMediaType : mediaType); + headerValue.CharSet = (encoding is null) ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName; Headers.ContentType = headerValue; } @@ -40,12 +40,12 @@ private static byte[] GetContentByteArray(string content, Encoding? encoding) { // In this case we treat 'null' strings different from string.Empty in order to be consistent with our // other *Content constructors: 'null' throws, empty values are allowed. - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } - if (encoding == null) + if (encoding is null) { encoding = HttpContent.DefaultStringEncoding; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs index d40826ba07710e..4bbc7aeb5054e4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs @@ -60,7 +60,7 @@ public ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate set { CheckDisposed(); - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -86,11 +86,11 @@ public ExtendedProtectionPolicy ExtendedProtectionPolicy set { CheckDisposed(); - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } - if (value.CustomChannelBinding != null) + if (value.CustomChannelBinding is not null) { throw new ArgumentException(SR.net_listener_cannot_set_custom_cbt, nameof(value)); } @@ -115,7 +115,7 @@ internal void AddPrefix(string uriPrefix) string? registeredPrefix = null; try { - if (uriPrefix == null) + if (uriPrefix is null) { throw new ArgumentNullException(nameof(uriPrefix)); } @@ -199,7 +199,7 @@ internal bool RemovePrefix(string uriPrefix) { CheckDisposed(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"uriPrefix: {uriPrefix}"); - if (uriPrefix == null) + if (uriPrefix is null) { throw new ArgumentNullException(nameof(uriPrefix)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs index fe1a1c42f8de78..098d001e3f0767 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs @@ -24,7 +24,7 @@ public HttpListenerResponse Response { get { - if (_response == null) + if (_response is null) { _response = new HttpListenerResponse(this); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs index bcd9cc4beb547e..0672c6c6ba86c8 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs @@ -38,7 +38,7 @@ internal HttpListenerPrefixCollection(HttpListener listener) public void CopyTo(Array array, int offset) { _httpListener.CheckDisposed(); - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -60,7 +60,7 @@ public void CopyTo(Array array, int offset) public void CopyTo(string[] array, int offset) { _httpListener.CheckDisposed(); - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index a431ed61e3fc63..c86f77db31d72a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -34,7 +34,7 @@ private CookieCollection ParseCookies(Uri? uri, string setCookieHeader) while (true) { Cookie? cookie = parser.GetServer(); - if (cookie == null) + if (cookie is null) { // EOF, done. break; @@ -54,14 +54,14 @@ public CookieCollection Cookies { get { - if (_cookies == null) + if (_cookies is null) { string? cookieString = Headers[HttpKnownHeaderNames.Cookie]; if (!string.IsNullOrEmpty(cookieString)) { _cookies = ParseCookies(RequestUri, cookieString); } - if (_cookies == null) + if (_cookies is null) { _cookies = new CookieCollection(); } @@ -74,10 +74,10 @@ public Encoding ContentEncoding { get { - if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) + if (UserAgent is not null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) { string? postDataCharset = Headers["x-up-devcap-post-charset"]; - if (postDataCharset != null && postDataCharset.Length > 0) + if (postDataCharset is not null && postDataCharset.Length > 0) { try { @@ -90,10 +90,10 @@ public Encoding ContentEncoding } if (HasEntityBody) { - if (ContentType != null) + if (ContentType is not null) { string? charSet = Helpers.GetCharSetValueFromHeader(ContentType); - if (charSet != null) + if (charSet is not null) { try { @@ -218,7 +218,7 @@ public Uri? UrlReferrer get { string? referrer = Headers[HttpKnownHeaderNames.Referer]; - if (referrer == null) + if (referrer is null) { return null; } @@ -289,7 +289,7 @@ private static class Helpers { const string AttrName = "charset"; - if (headerValue == null) + if (headerValue is null) return null; int l = headerValue.Length; @@ -363,7 +363,7 @@ private static class Helpers internal static string[]? ParseMultivalueHeader(string s) { - if (s == null) + if (s is null) return null; int l = s.Length; @@ -518,7 +518,7 @@ internal void AddChar(char ch) internal void AddByte(byte b) { { - if (_byteBuffer == null) + if (_byteBuffer is null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; @@ -586,7 +586,7 @@ internal static void FillFromString(NameValueCollection nvc, string s, bool urle if (urlencoded) nvc.Add( - name == null ? null : UrlDecodeStringFromStringInternal(name, encoding), + name is null ? null : UrlDecodeStringFromStringInternal(name, encoding), UrlDecodeStringFromStringInternal(value, encoding)); else nvc.Add(name, value); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs index 18c6106b27cde5..2d050032322438 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs @@ -71,7 +71,7 @@ private Uri Build() { BuildRequestUriUsingRawPath(); - if (_requestUri == null) + if (_requestUri is null) { BuildRequestUriUsingCookedPath(); } @@ -134,7 +134,7 @@ private static Encoding GetEncoding(EncodingType type) private ParsingResult BuildRequestUriUsingRawPath(Encoding encoding) { - Debug.Assert(encoding != null, "'encoding' must be assigned."); + Debug.Assert(encoding is not null, "'encoding' must be assigned."); Debug.Assert(!string.IsNullOrEmpty(_rawPath), "'rawPath' must have at least one character."); _rawOctets = new List(); @@ -170,11 +170,11 @@ private ParsingResult BuildRequestUriUsingRawPath(Encoding encoding) private ParsingResult ParseRawPath(Encoding encoding) { - Debug.Assert(encoding != null, "'encoding' must be assigned."); + Debug.Assert(encoding is not null, "'encoding' must be assigned."); int index = 0; char current = '\0'; - Debug.Assert(_rawPath != null); + Debug.Assert(_rawPath is not null); while (index < _rawPath.Length) { current = _rawPath[index]; @@ -221,7 +221,7 @@ private ParsingResult ParseRawPath(Encoding encoding) return ParsingResult.EncodingError; } // Append the current character to the result. - Debug.Assert(_requestUriString != null); + Debug.Assert(_requestUriString is not null); _requestUriString!.Append(current); index++; } @@ -280,7 +280,7 @@ private bool AddPercentEncodedOctetToRawOctetsList(Encoding encoding, string esc return false; } - Debug.Assert(_rawOctets != null); + Debug.Assert(_rawOctets is not null); _rawOctets!.Add(encodedValue); return true; @@ -358,7 +358,7 @@ private static string GetOctetsAsString(IEnumerable octets) private static string GetPath(string uriString) { - Debug.Assert(uriString != null, "uriString must not be null"); + Debug.Assert(uriString is not null, "uriString must not be null"); Debug.Assert(uriString.Length > 0, "uriString must not be empty"); int pathStartIndex = 0; @@ -421,13 +421,13 @@ private static string GetPath(string uriString) queryIndex = uriString.Length; } - // will always return a != null string. + // will always return a is not null string. return AddSlashToAsteriskOnlyPath(uriString.Substring(pathStartIndex, queryIndex - pathStartIndex)); } private static string AddSlashToAsteriskOnlyPath(string path) { - Debug.Assert(path != null, "'path' must not be null"); + Debug.Assert(path is not null, "'path' must not be null"); // If a request like "OPTIONS * HTTP/1.1" is sent to the listener, then the request Uri // should be "http[s]://server[:port]/*" to be compatible with pre-4.0 behavior. 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 6b7ddc839b3030..71b3bb5b423768 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -160,13 +160,13 @@ public string StatusDescription { get { - if (_statusDescription == null) + if (_statusDescription is null) { // if the user hasn't set this, generated on the fly, if possible. // We know this one is safe, no need to verify it as in the setter. _statusDescription = HttpStatusDescription.Get(StatusCode); } - if (_statusDescription == null) + if (_statusDescription is null) { _statusDescription = string.Empty; } @@ -175,7 +175,7 @@ public string StatusDescription set { CheckDisposed(); - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -209,7 +209,7 @@ public void AppendHeader(string name, string value) public void AppendCookie(Cookie cookie) { - if (cookie == null) + if (cookie is null) { throw new ArgumentNullException(nameof(cookie)); } @@ -221,7 +221,7 @@ private void ComputeCookies() { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Entering Set-Cookie: {Headers[HttpResponseHeader.SetCookie]}, Set-Cookie2: {Headers[HttpKnownHeaderNames.SetCookie2]}"); - if (_cookies != null) + if (_cookies is not null) { // now go through the collection, and concatenate all the cookies in per-variant strings string? setCookie2 = null, setCookie = null; @@ -229,18 +229,18 @@ private void ComputeCookies() { Cookie cookie = _cookies[index]; string cookieString = cookie.ToServerString(); - if (cookieString == null || cookieString.Length == 0) + if (cookieString is null || cookieString.Length == 0) { continue; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Now looking at index:{index} cookie: {cookie}"); if (cookie.IsRfc2965Variant()) { - setCookie2 = setCookie2 == null ? cookieString : setCookie2 + ", " + cookieString; + setCookie2 = setCookie2 is null ? cookieString : setCookie2 + ", " + cookieString; } else { - setCookie = setCookie == null ? cookieString : setCookie + ", " + cookieString; + setCookie = setCookie is null ? cookieString : setCookie + ", " + cookieString; } } @@ -276,7 +276,7 @@ public void Redirect(string url) public void SetCookie(Cookie cookie) { - if (cookie == null) + if (cookie is null) { throw new ArgumentNullException(nameof(cookie)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs index f8890573c0f2c7..e93a7b98eeee0d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs @@ -17,7 +17,7 @@ public override int Read(byte[] buffer, int offset, int size) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -41,7 +41,7 @@ public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, Asyn { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs index e51f8027e603d5..b3a2acb07bdd18 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs @@ -44,7 +44,7 @@ public override void Write(byte[] buffer, int offset, int size) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -67,7 +67,7 @@ public override void Write(byte[] buffer, int offset, int size) public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -87,7 +87,7 @@ public override void EndWrite(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult:{asyncResult}"); - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs index 9590c689a2be4e..15b7d22d2decbe 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs @@ -197,7 +197,7 @@ public bool DataAvailable for (int i = 0; i < count; i++) { Chunk ch = _chunks[i]; - if (ch == null || ch.Bytes == null) + if (ch is null || ch.Bytes is null) continue; if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length) return (_state != State.Body); @@ -383,7 +383,7 @@ private State ReadTrailer(byte[] buffer, ref int offset, int size) StringReader reader = new StringReader(_saved.ToString()); string? line; - while ((line = reader.ReadLine()) != null && line != "") + while ((line = reader.ReadLine()) is not null && line != "") _headers.Add(line); return State.None; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs index 3b8e200302db5e..92e12327033cc7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs @@ -151,11 +151,11 @@ private void OnRead(IAsyncResult base_ares) public override int EndRead(IAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) throw new ArgumentNullException(nameof(asyncResult)); HttpStreamAsyncResult? ares = asyncResult as HttpStreamAsyncResult; - if (ares == null || !ReferenceEquals(this, ares._parent)) + if (ares is null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -168,7 +168,7 @@ public override int EndRead(IAsyncResult asyncResult) if (!asyncResult.IsCompleted) asyncResult.AsyncWaitHandle.WaitOne(); - if (ares._error != null) + if (ares._error is not null) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.Format(SR.net_io_operation_aborted, ares._error.Message)); return ares._count; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index 2ea835a7edd6b7..0ac79d81477521 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -86,13 +86,13 @@ public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Ce #pragma warning disable CA5359 _sslStream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) => { - if (c == null) + if (c is null) { return true; } var c2 = c as X509Certificate2; - if (c2 == null) + if (c2 is null) { c2 = new X509Certificate2(c.GetRawCertData()); } @@ -107,7 +107,7 @@ public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Ce } _timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite); - if (_sslStream != null) { + if (_sslStream is not null) { _sslStream.AuthenticateAsServer (_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false); } Init(); @@ -148,7 +148,7 @@ private void Init() public bool IsClosed { - get { return (_socket == null); } + get { return (_socket is null); } } public int Reuses @@ -160,7 +160,7 @@ public IPEndPoint? LocalEndPoint { get { - if (_localEndPoint != null) + if (_localEndPoint is not null) return _localEndPoint; _localEndPoint = (IPEndPoint?)_socket!.LocalEndPoint; @@ -192,7 +192,7 @@ private void OnTimeout(object? unused) public void BeginReadRequest() { - if (_buffer == null) + if (_buffer is null) _buffer = new byte[BufferSize]; try { @@ -211,7 +211,7 @@ public void BeginReadRequest() public HttpRequestStream GetRequestStream(bool chunked, long contentlength) { - if (_requestStream == null) + if (_requestStream is null) { byte[] buffer = _memoryStream!.GetBuffer(); int length = (int)_memoryStream!.Length; @@ -232,11 +232,11 @@ public HttpRequestStream GetRequestStream(bool chunked, long contentlength) public HttpResponseStream GetResponseStream() { - if (_responseStream == null) + if (_responseStream is null) { HttpListener? listener = _context._listener; - if (listener == null) + if (listener is null) return new HttpResponseStream(_stream, _context.Response, true); _responseStream = new HttpResponseStream(_stream, _context.Response, listener.IgnoreWriteExceptions); @@ -267,9 +267,9 @@ private void OnReadInternal(IAsyncResult ares) } catch { - if (_memoryStream != null && _memoryStream.Length > 0) + if (_memoryStream is not null && _memoryStream.Length > 0) SendError(); - if (_socket != null) + if (_socket is not null) { CloseSocket(); Unbind(); @@ -320,7 +320,7 @@ private void OnReadInternal(IAsyncResult ares) private void RemoveConnection() { - if (_lastListener == null) + if (_lastListener is null) _epl.RemoveConnection(this); else _lastListener.RemoveConnection(this); @@ -368,7 +368,7 @@ private bool ProcessInput(MemoryStream ms) return true; } - if (line == null) + if (line is null) break; if (line == "") @@ -410,7 +410,7 @@ private bool ProcessInput(MemoryStream ms) private string? ReadLine(byte[] buffer, int offset, int len, ref int used) { - if (_currentLine == null) + if (_currentLine is null) _currentLine = new StringBuilder(128); int last = offset + len; used = 0; @@ -452,7 +452,7 @@ public void SendError(string? msg, int status) response.ContentType = "text/html"; string? description = HttpStatusDescription.Get(status); string str; - if (msg != null) + if (msg is not null) str = string.Format("

{0} ({1})

", description, msg); else str = string.Format("

{0}

", description); @@ -487,7 +487,7 @@ public void Close() private void CloseSocket() { - if (_socket == null) + if (_socket is null) return; try @@ -505,16 +505,16 @@ private void CloseSocket() internal void Close(bool force) { - if (_socket != null) + if (_socket is not null) { Stream st = GetResponseStream(); - if (st != null) + if (st is not null) st.Close(); _responseStream = null; } - if (_socket != null) + if (_socket is not null) { force |= !_context.Request.KeepAlive; if (!force) @@ -543,7 +543,7 @@ internal void Close(bool force) _socket = null; try { - if (s != null) + if (s is not null) s.Shutdown(SocketShutdown.Both); } catch @@ -551,7 +551,7 @@ internal void Close(bool force) } finally { - if (s != null) + if (s is not null) s.Close(); } Unbind(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs index f385c79a651a21..ff7ad2270550b3 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs @@ -108,10 +108,10 @@ private static void ProcessAccept(SocketAsyncEventArgs args) Socket? accepted = args.SocketError == SocketError.Success ? args.AcceptSocket : null; epl.Accept(args); - if (accepted == null) + if (accepted is null) return; - if (epl._secure && epl._cert == null) + if (epl._secure && epl._cert is null) { accepted.Close(); return; @@ -153,7 +153,7 @@ public bool BindContext(HttpListenerContext context) HttpListenerRequest req = context.Request; ListenerPrefix? prefix; HttpListener? listener = SearchListener(req.Url, out prefix); - if (listener == null) + if (listener is null) return false; context._listener = listener; @@ -163,7 +163,7 @@ public bool BindContext(HttpListenerContext context) public void UnbindContext(HttpListenerContext context) { - if (context == null || context.Request == null) + if (context is null || context.Request is null) return; context._listener!.UnregisterContext(context); @@ -172,7 +172,7 @@ public void UnbindContext(HttpListenerContext context) private HttpListener? SearchListener(Uri? uri, out ListenerPrefix? prefix) { prefix = null; - if (uri == null) + if (uri is null) return null; string host = uri.Host; @@ -183,7 +183,7 @@ public void UnbindContext(HttpListenerContext context) HttpListener? bestMatch = null; int bestLength = -1; - if (host != null && host != "") + if (host is not null && host != "") { Dictionary localPrefixes = _prefixes; foreach (ListenerPrefix p in localPrefixes.Keys) @@ -209,19 +209,19 @@ public void UnbindContext(HttpListenerContext context) List? list = _unhandledPrefixes; bestMatch = MatchFromList(host, path, list, out prefix); - if (path != pathSlash && bestMatch == null) + if (path != pathSlash && bestMatch is null) bestMatch = MatchFromList(host, pathSlash, list, out prefix); - if (bestMatch != null) + if (bestMatch is not null) return bestMatch; list = _allPrefixes; bestMatch = MatchFromList(host, path, list, out prefix); - if (path != pathSlash && bestMatch == null) + if (path != pathSlash && bestMatch is null) bestMatch = MatchFromList(host, pathSlash, list, out prefix); - if (bestMatch != null) + if (bestMatch is not null) return bestMatch; return null; @@ -230,7 +230,7 @@ public void UnbindContext(HttpListenerContext context) private HttpListener? MatchFromList(string? host, string path, List? list, out ListenerPrefix? prefix) { prefix = null; - if (list == null) + if (list is null) return null; HttpListener? bestMatch = null; @@ -255,7 +255,7 @@ public void UnbindContext(HttpListenerContext context) private void AddSpecial(List list, ListenerPrefix prefix) { - if (list == null) + if (list is null) return; foreach (ListenerPrefix p in list) @@ -268,7 +268,7 @@ private void AddSpecial(List list, ListenerPrefix prefix) private bool RemoveSpecial(List list, ListenerPrefix prefix) { - if (list == null) + if (list is null) return false; int c = list.Count; @@ -290,11 +290,11 @@ private void CheckIfRemove() return; List? list = _unhandledPrefixes; - if (list != null && list.Count > 0) + if (list is not null && list.Count > 0) return; list = _allPrefixes; - if (list != null && list.Count > 0) + if (list is not null && list.Count > 0) return; HttpEndPointManager.RemoveEndPoint(this, _endpoint); @@ -323,7 +323,7 @@ public void AddPrefix(ListenerPrefix prefix, HttpListener listener) do { current = _unhandledPrefixes; - future = current != null ? new List(current) : new List(); + future = current is not null ? new List(current) : new List(); prefix._listener = listener; AddSpecial(future, prefix); } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current); @@ -335,7 +335,7 @@ public void AddPrefix(ListenerPrefix prefix, HttpListener listener) do { current = _allPrefixes; - future = current != null ? new List(current) : new List(); + future = current is not null ? new List(current) : new List(); prefix._listener = listener; AddSpecial(future, prefix); } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current); @@ -364,7 +364,7 @@ public void RemovePrefix(ListenerPrefix prefix, HttpListener listener) do { current = _unhandledPrefixes; - future = current != null ? new List(current) : new List(); + future = current is not null ? new List(current) : new List(); if (!RemoveSpecial(future, prefix)) break; // Prefix not found } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current); @@ -378,7 +378,7 @@ public void RemovePrefix(ListenerPrefix prefix, HttpListener listener) do { current = _allPrefixes; - future = current != null ? new List(current) : new List(); + future = current is not null ? new List(current) : new List(); if (!RemoveSpecial(future, prefix)) break; // Prefix not found } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs index 3839b27cff25b4..1eabe52b0ff6de 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs @@ -207,7 +207,7 @@ internal void RegisterContext(HttpListenerContext context) } } - if (ares != null) + if (ares is not null) { ares.Complete(context); } @@ -289,7 +289,7 @@ public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state) lock ((_contextQueue as ICollection).SyncRoot) { HttpListenerContext? ctx = GetContextFromQueue(); - if (ctx != null) + if (ctx is not null) { ares.Complete(ctx, true); return ares; @@ -305,13 +305,13 @@ public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state) public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { CheckDisposed(); - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } ListenerAsyncResult? ares = asyncResult as ListenerAsyncResult; - if (ares == null || !ReferenceEquals(this, ares._parent)) + if (ares is null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -339,7 +339,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context) { - return AuthenticationSchemeSelectorDelegate != null ? AuthenticationSchemeSelectorDelegate(context.Request) : _authenticationScheme; + return AuthenticationSchemeSelectorDelegate is not null ? AuthenticationSchemeSelectorDelegate(context.Request) : _authenticationScheme; } public HttpListenerContext GetContext() diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs index 8abb640e5c79f4..cff1eeebbcc426 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs @@ -26,7 +26,7 @@ internal HttpListenerContext(HttpConnection connection) internal string? ErrorMessage { get; set; } - internal bool HaveError => ErrorMessage != null; + internal bool HaveError => ErrorMessage is not null; internal HttpConnection Connection => _connection; 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 a29021d572f659..95a7dd0944da5a 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 @@ -145,7 +145,7 @@ private static bool MaybeUri(string s) private static bool IsPredefinedScheme(string scheme) { - if (scheme == null || scheme.Length < 3) + if (scheme is null || scheme.Length < 3) return false; char c = scheme[0]; @@ -172,7 +172,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 && (host is null || host.Length == 0)) { _context.ErrorMessage = "Invalid host name"; return; @@ -180,16 +180,16 @@ internal void FinishInitialization() string path; Uri? raw_uri = null; - Debug.Assert(_rawUrl != null); + Debug.Assert(_rawUrl is not null); if (MaybeUri(_rawUrl!.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri)) path = raw_uri.PathAndQuery; else path = _rawUrl; - if ((host == null || host.Length == 0)) + if ((host is null || host.Length == 0)) host = UserHostAddress; - if (raw_uri != null) + if (raw_uri is not null) host = raw_uri.Host; int colon = host.IndexOf(':'); @@ -210,9 +210,9 @@ internal void FinishInitialization() if (_version >= HttpVersion.Version11) { string? t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding]; - _isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase)); + _isChunked = (t_encoding is not null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase)); // 'identity' is not valid! - if (t_encoding != null && !_isChunked) + if (t_encoding is not null && !_isChunked) { _context.Connection.SendError(null, 501); return; @@ -279,14 +279,14 @@ internal void AddHeader(string header) } else if (name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase)) { - if (Headers[HttpKnownHeaderNames.TransferEncoding] != null) + if (Headers[HttpKnownHeaderNames.TransferEncoding] is not null) { _context.ErrorStatus = (int)HttpStatusCode.NotImplemented; _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.NotImplemented); } } - if (_context.ErrorMessage == null) + if (_context.ErrorMessage is null) { _headers.Set(name, val); } @@ -330,10 +330,10 @@ internal bool FlushInput() private int GetClientCertificateErrorCore() { HttpConnection cnc = _context.Connection; - if (cnc.ClientCertificate == null) + if (cnc.ClientCertificate is null) return 0; int[]? errors = cnc.ClientCertificateErrors; - if (errors != null && errors.Length > 0) + if (errors is not null && errors.Length > 0) return errors[0]; return 0; } @@ -359,7 +359,7 @@ public Stream InputStream { get { - if (_inputStream == null) + if (_inputStream is null) { if (_isChunked || _contentLength > 0) _inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength); @@ -397,11 +397,11 @@ private IAsyncResult BeginGetClientCertificateCore(AsyncCallback? requestCallbac public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) throw new ArgumentNullException(nameof(asyncResult)); GetClientCertificateAsyncResult? clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; - if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) + if (clientCertAsyncResult is null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs index 4de98bf987c458..3cc747db19c83d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs @@ -53,7 +53,7 @@ internal HttpListenerResponse(HttpListenerContext context) private void EnsureResponseStream() { - if (_responseStream == null) + if (_responseStream is null) { _responseStream = _httpContext!.Connection.GetResponseStream(); } @@ -65,7 +65,7 @@ public Version ProtocolVersion set { CheckDisposed(); - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -123,7 +123,7 @@ public void Close(byte[] responseEntity, bool willBlock) { CheckDisposed(); - if (responseEntity == null) + if (responseEntity is null) { throw new ArgumentNullException(nameof(responseEntity)); } @@ -176,12 +176,12 @@ internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandsha { if (!isWebSocketHandshake) { - if (_webHeaders[HttpKnownHeaderNames.Server] == null) + if (_webHeaders[HttpKnownHeaderNames.Server] is null) { _webHeaders.Set(HttpKnownHeaderNames.Server, HttpHeaderStrings.NetCoreServerName); } - if (_webHeaders[HttpKnownHeaderNames.Date] == null) + if (_webHeaders[HttpKnownHeaderNames.Date] is null) { _webHeaders.Set(HttpKnownHeaderNames.Date, DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs index bdfb7f3f8c869e..ca4d31b398c7c5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs @@ -163,7 +163,7 @@ protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size public override int EndRead(IAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) throw new ArgumentNullException(nameof(asyncResult)); if (asyncResult is HttpStreamAsyncResult r) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs index b084166107dfe3..ab2fbb4a111a41 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs @@ -62,7 +62,7 @@ private void DisposeCore() { try { - if (ms != null) + if (ms is not null) { long start = ms.Position; if (chunked && !_trailer_sent) @@ -175,7 +175,7 @@ private void WriteCore(byte[] buffer, int offset, int size) byte[]? bytes = null; MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; - if (ms != null) + if (ms is not null) { long start = ms.Position; // After the possible preamble for the encoding ms.Position = ms.Length; @@ -219,7 +219,7 @@ private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCa byte[]? bytes = null; MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; - if (ms != null) + if (ms is not null) { long start = ms.Position; ms.Position = ms.Length; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs index 349fb288a28251..0736af6e240c50 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs @@ -69,10 +69,10 @@ public void Complete() return; _completed = true; - if (_handle != null) + if (_handle is not null) _handle.Set(); - if (_callback != null) + if (_callback is not null) Task.Run(() => _callback(this)); } } @@ -88,7 +88,7 @@ public WaitHandle AsyncWaitHandle { lock (_locker) { - if (_handle == null) + if (_handle is null) _handle = new ManualResetEvent(_completed); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs index d5c2f56cd1aa07..9564387f1a9dad 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs @@ -60,7 +60,7 @@ public ListenerAsyncResult(HttpListener parent, AsyncCallback? cb, object? state internal void Complete(Exception exc) { - if (_forward != null) + if (_forward is not null) { _forward.Complete(exc); return; @@ -71,10 +71,10 @@ internal void Complete(Exception exc) lock (_locker) { _completed = true; - if (_handle != null) + if (_handle is not null) _handle.Set(); - if (_cb != null) + if (_cb is not null) ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this); } } @@ -83,7 +83,7 @@ internal void Complete(Exception exc) private static void InvokeCallback(object o) { ListenerAsyncResult ares = (ListenerAsyncResult)o!; - if (ares._forward != null) + if (ares._forward is not null) { InvokeCallback(ares._forward); return; @@ -104,7 +104,7 @@ internal void Complete(HttpListenerContext context) internal void Complete(HttpListenerContext context, bool synch) { - if (_forward != null) + if (_forward is not null) { _forward.Complete(context, synch); return; @@ -140,7 +140,7 @@ internal void Complete(HttpListenerContext context, bool synch) { HttpStatusCode errorCode = HttpStatusCode.Unauthorized; string? authHeader = context.Request.Headers["Authorization"]; - if (authHeader == null || + if (authHeader is null || !HttpListenerContext.IsBasicHeader(authHeader) || authHeader.Length < AuthenticationTypes.Basic.Length + 2 || !HttpListenerContext.TryParseBasicAuth(authHeader.Substring(AuthenticationTypes.Basic.Length + 1), out errorCode, out _, out _)) @@ -161,11 +161,11 @@ internal void Complete(HttpListenerContext context, bool synch) _forward = (ListenerAsyncResult)ares; lock (_forward._locker) { - if (_handle != null) + if (_handle is not null) _forward._handle = _handle; } ListenerAsyncResult next = _forward; - for (int i = 0; next._forward != null; i++) + for (int i = 0; next._forward is not null; i++) { if (i > 20) Complete(new HttpListenerException((int)HttpStatusCode.Unauthorized, SR.net_listener_auth_errors)); @@ -177,10 +177,10 @@ internal void Complete(HttpListenerContext context, bool synch) _completed = true; _synch = false; - if (_handle != null) + if (_handle is not null) _handle.Set(); - if (_cb != null) + if (_cb is not null) ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this); } } @@ -188,12 +188,12 @@ internal void Complete(HttpListenerContext context, bool synch) internal HttpListenerContext? GetContext() { - if (_forward != null) + if (_forward is not null) { return _forward.GetContext(); } - if (_exception != null) + if (_exception is not null) { ExceptionDispatchInfo.Throw(_exception); } @@ -205,7 +205,7 @@ public object? AsyncState { get { - if (_forward != null) + if (_forward is not null) return _forward.AsyncState; return _state; } @@ -215,12 +215,12 @@ public WaitHandle AsyncWaitHandle { get { - if (_forward != null) + if (_forward is not null) return _forward.AsyncWaitHandle; lock (_locker) { - if (_handle == null) + if (_handle is null) _handle = new ManualResetEvent(_completed); } @@ -232,7 +232,7 @@ public bool CompletedSynchronously { get { - if (_forward != null) + if (_forward is not null) return _forward.CompletedSynchronously; return _synch; } @@ -242,7 +242,7 @@ public bool IsCompleted { get { - if (_forward != null) + if (_forward is not null) return _forward.IsCompleted; lock (_locker) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs index 172877a4019780..f25f20ace0f864 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs @@ -82,7 +82,7 @@ public string? Path public override bool Equals(object? o) { ListenerPrefix? other = o as ListenerPrefix; - if (other == null) + if (other is null) return false; return (_original == other._original); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs index bd3e39231cda68..7817314862cbdb 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs @@ -68,7 +68,7 @@ internal static async Task AcceptWebSocketAsyncCor request.IsLocal, request.IsSecureConnection, origin!, - secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty(), + secWebSocketProtocols is not null ? secWebSocketProtocols : Array.Empty(), secWebSocketVersion!, secWebSocketKey!, webSocket); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs index 9c92cf20bb5a5c..796a1b8cd16fb8 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs @@ -18,7 +18,7 @@ public ServiceNameCollection ServiceNames { get { - if (_serviceNameCollection == null) + if (_serviceNameCollection is null) { _serviceNameCollection = new ServiceNameCollection(_serviceNames); } @@ -205,7 +205,7 @@ public bool Remove(string uriPrefix) // Assumes already normalized private bool Contains(string? newServiceName) { - if (newServiceName == null) + if (newServiceName is null) { return false; } @@ -268,7 +268,7 @@ public void Clear() { string? hostname = ExtractHostname(uriPrefix, false); - if (hostname != null) + if (hostname is not null) { return "HTTP/" + hostname; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs index 31134051bf0e6c..b32e984b747e73 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs @@ -39,11 +39,11 @@ internal HttpListenerWebSocketContext( string secWebSocketKey, WebSocket webSocket) { - Debug.Assert(requestUri != null, "requestUri shouldn't be null"); - Debug.Assert(headers != null, "headers shouldn't be null"); - Debug.Assert(cookieCollection != null, "cookieCollection shouldn't be null"); - Debug.Assert(secWebSocketProtocols != null, "secWebSocketProtocols shouldn't be null"); - Debug.Assert(webSocket != null, "webSocket shouldn't be null"); + Debug.Assert(requestUri is not null, "requestUri shouldn't be null"); + Debug.Assert(headers is not null, "headers shouldn't be null"); + Debug.Assert(cookieCollection is not null, "cookieCollection shouldn't be null"); + Debug.Assert(secWebSocketProtocols is not null, "secWebSocketProtocols shouldn't be null"); + Debug.Assert(webSocket is not null, "webSocket shouldn't be null"); _cookieCollection = new CookieCollection(); _cookieCollection.Add(cookieCollection); @@ -88,7 +88,7 @@ internal HttpListenerWebSocketContext( private static IPrincipal? CopyPrincipal(IPrincipal user) { - if (user != null) + if (user is not null) { if (!(user is WindowsPrincipal)) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs index 56a11e43b1afe1..92f239eefadbc3 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs @@ -35,7 +35,7 @@ internal static bool ProcessWebSocketProtocolHeader(string? clientSecWebSocketPr if (string.IsNullOrEmpty(clientSecWebSocketProtocol)) { // client hasn't specified any Sec-WebSocket-Protocol header - if (subProtocol != null) + if (subProtocol is not null) { // If the server specified _anything_ this isn't valid. throw new WebSocketException(WebSocketError.UnsupportedProtocol, @@ -47,7 +47,7 @@ internal static bool ProcessWebSocketProtocolHeader(string? clientSecWebSocketPr // here, we know the client specified something and it's non-empty. - if (subProtocol == null) + if (subProtocol is null) { // client specified some protocols, server specified 'null'. So server should send headers. return true; @@ -78,7 +78,7 @@ internal static bool ProcessWebSocketProtocolHeader(string? clientSecWebSocketPr internal static void ValidateOptions(string subProtocol, int receiveBufferSize, int sendBufferSize, TimeSpan keepAliveInterval) { - if (subProtocol != null) + if (subProtocol is not null) { WebSocketValidate.ValidateSubprotocol(subProtocol); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs index 8af3aa485366f7..0f6971f150c24f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs @@ -38,7 +38,7 @@ internal AsyncRequestContext(ThreadPoolBoundHandle boundHandle, ListenerAsyncRes private Interop.HttpApi.HTTP_REQUEST* Allocate(ThreadPoolBoundHandle boundHandle, uint size) { uint newSize = size != 0 ? size : RequestBuffer == IntPtr.Zero ? 4096 : Size; - if (_nativeOverlapped != null) + if (_nativeOverlapped is not null) { #if DEBUG DebugRefCountReleaseNativeOverlapped(); @@ -67,7 +67,7 @@ internal void Reset(ThreadPoolBoundHandle boundHandle, ulong requestId, uint siz protected override void OnReleasePins() { - if (_nativeOverlapped != null) + if (_nativeOverlapped is not null) { #if DEBUG DebugRefCountReleaseNativeOverlapped(); @@ -81,7 +81,7 @@ protected override void OnReleasePins() protected override void Dispose(bool disposing) { - if (_nativeOverlapped != null) + if (_nativeOverlapped is not null) { Debug.Assert(!disposing, "AsyncRequestContext::Dispose()|Must call ReleasePins() before calling Dispose()."); if (!Environment.HasShutdownStarted || disposing) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs index 20e1fad79890ff..8a0b6547d2efc3 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs @@ -15,7 +15,7 @@ internal static class CookieExtensions public static string ToServerString(this Cookie cookie) { s_toServerStringFunc ??= (Func)typeof(Cookie).GetMethod("ToServerString", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); - Debug.Assert(s_toServerStringFunc != null, "Reflection failed for Cookie.ToServerString()."); + Debug.Assert(s_toServerStringFunc is not null, "Reflection failed for Cookie.ToServerString()."); return s_toServerStringFunc(cookie); } @@ -24,7 +24,7 @@ public static string ToServerString(this Cookie cookie) public static Cookie Clone(this Cookie cookie) { s_cloneFunc ??= (Func)typeof(Cookie).GetMethod("Clone", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); - Debug.Assert(s_cloneFunc != null, "Reflection failed for Cookie.Clone()."); + Debug.Assert(s_cloneFunc is not null, "Reflection failed for Cookie.Clone()."); return s_cloneFunc(cookie); } @@ -42,7 +42,7 @@ private enum CookieVariant public static bool IsRfc2965Variant(this Cookie cookie) { s_getVariantFunc ??= (Func)typeof(Cookie).GetProperty("Variant", BindingFlags.Instance | BindingFlags.NonPublic)!.GetGetMethod(true)!.CreateDelegate(typeof(Func)); - Debug.Assert(s_getVariantFunc != null, "Reflection failed for Cookie.Variant."); + Debug.Assert(s_getVariantFunc is not null, "Reflection failed for Cookie.Variant."); return s_getVariantFunc(cookie) == CookieVariant.Rfc2965; } } @@ -54,7 +54,7 @@ internal static class CookieCollectionExtensions public static int InternalAdd(this CookieCollection cookieCollection, Cookie cookie, bool isStrict) { s_internalAddFunc ??= (Func)typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); - Debug.Assert(s_internalAddFunc != null, "Reflection failed for CookieCollection.InternalAdd()."); + Debug.Assert(s_internalAddFunc is not null, "Reflection failed for CookieCollection.InternalAdd()."); return s_internalAddFunc(cookieCollection, cookie, isStrict); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 2d47b0ff70c401..784b59b615b695 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -146,7 +146,7 @@ public HttpListenerTimeoutManager TimeoutManager get { ValidateV2Property(); - Debug.Assert(_timeoutManager != null, "Timeout manager is not assigned"); + Debug.Assert(_timeoutManager is not null, "Timeout manager is not assigned"); return _timeoutManager; } } @@ -298,7 +298,7 @@ private void CleanupV2Config() } _urlGroupId = 0; - Debug.Assert(_serverSessionHandle != null, "ServerSessionHandle is null in CloseV2Config"); + Debug.Assert(_serverSessionHandle is not null, "ServerSessionHandle is null in CloseV2Config"); Debug.Assert(!_serverSessionHandle.IsInvalid, "ServerSessionHandle is invalid in CloseV2Config"); _serverSessionHandle.Dispose(); @@ -567,13 +567,13 @@ public HttpListenerContext GetContext() } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, ":HandleAuthentication() returned httpContext" + httpContext); // if the request survived authentication, return it to the user - if (httpContext != null) + if (httpContext is not null) { return httpContext; } // HandleAuthentication may have cleaned this up. - if (memoryBlob == null) + if (memoryBlob is null) { memoryBlob = new SyncRequestContext(checked((int)size)); } @@ -588,7 +588,7 @@ public HttpListenerContext GetContext() } finally { - if (memoryBlob != null && !stoleBlob) + if (memoryBlob is not null && !stoleBlob) { memoryBlob.ReleasePins(); memoryBlob.Close(); @@ -645,7 +645,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) try { CheckDisposed(); - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -660,7 +660,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } castedAsyncResult.EndCalled = true; httpContext = castedAsyncResult.InternalWaitForCompletion() as HttpListenerContext; - if (httpContext == null) + if (httpContext is null) { Debug.Assert(castedAsyncResult.Result is Exception, "EndGetContext|The result is neither a HttpListenerContext nor an Exception."); ExceptionDispatchInfo.Throw((castedAsyncResult.Result as Exception)!); @@ -685,7 +685,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) string? authorizationHeader = Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, (int)HttpRequestHeader.Authorization); ulong connectionId = memoryBlob.RequestBlob->ConnectionId; ulong requestId = memoryBlob.RequestBlob->RequestId; - bool isSecureConnection = memoryBlob.RequestBlob->pSslInfo != null; + bool isSecureConnection = memoryBlob.RequestBlob->pSslInfo is not null; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"HandleAuthentication() authorizationHeader: ({authorizationHeader})"); @@ -698,10 +698,10 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) DisconnectResults.TryGetValue(connectionId, out disconnectResult); if (UnsafeConnectionNtlmAuthentication) { - if (authorizationHeader == null) + if (authorizationHeader is null) { WindowsPrincipal? principal = disconnectResult?.AuthenticatedConnection; - if (principal != null) + if (principal is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Principal: {principal} principal.Identity.Name: {principal.Identity.Name} creating request"); stoleBlob = true; @@ -715,7 +715,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { // They sent an authorization - destroy their previous credentials. if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Clearing principal cache"); - if (disconnectResult != null) + if (disconnectResult is not null) { disconnectResult.AuthenticatedConnection = null; } @@ -734,14 +734,14 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) try { // Take over handling disconnects for now. - if (disconnectResult != null && !disconnectResult.StartOwningDisconnectHandling()) + if (disconnectResult is not null && !disconnectResult.StartOwningDisconnectHandling()) { // Just disconnected just then. Pretend we didn't see the disconnectResult. disconnectResult = null; } // Pick out the old context now. By default, it'll be removed in the finally, unless context is set somewhere. - if (disconnectResult != null) + if (disconnectResult is not null) { oldContext = disconnectResult.Session; } @@ -749,7 +749,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) httpContext = new HttpListenerContext(session, memoryBlob); AuthenticationSchemeSelector? authenticationSelector = _authenticationDelegate; - if (authenticationSelector != null) + if (authenticationSelector is not null) { try { @@ -779,11 +779,11 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } ExtendedProtectionSelector? extendedProtectionSelector = _extendedProtectionSelectorDelegate; - if (extendedProtectionSelector != null) + if (extendedProtectionSelector is not null) { extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request); - if (extendedProtectionPolicy == null) + if (extendedProtectionPolicy is null) { extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } @@ -793,7 +793,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) // Then figure out what scheme they're trying (if any are allowed) int index = -1; - if (authorizationHeader != null && (authenticationScheme & ~AuthenticationSchemes.Anonymous) != AuthenticationSchemes.None) + if (authorizationHeader is not null && (authenticationScheme & ~AuthenticationSchemes.Anonymous) != AuthenticationSchemes.None) { // Find the end of the scheme name. Trust that HTTP.SYS parsed out just our header ok. for (index = 0; index < authorizationHeader.Length; index++) @@ -837,7 +837,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) // See if we found an acceptable auth header if (headerScheme == AuthenticationSchemes.None) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, SR.Format(SR.net_log_listener_unmatched_authentication_scheme, authenticationScheme.ToString(), (authorizationHeader == null ? "" : authorizationHeader))); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, SR.Format(SR.net_log_listener_unmatched_authentication_scheme, authenticationScheme.ToString(), (authorizationHeader is null ? "" : authorizationHeader))); // If anonymous is allowed, just return the context. Otherwise go for the 401. if ((authenticationScheme & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.None) @@ -861,7 +861,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) string? outBlob = null; // Find the beginning of the blob. Trust that HTTP.SYS parsed out just our header ok. - Debug.Assert(authorizationHeader != null); + Debug.Assert(authorizationHeader is not null); for (index++; index < authorizationHeader!.Length; index++) { if (authorizationHeader[index] != ' ' && authorizationHeader[index] != '\t' && @@ -883,7 +883,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"context: {oldContext} for connectionId: {connectionId}"); string package = headerScheme == AuthenticationSchemes.Ntlm ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Negotiate; - if (oldContext != null && oldContext.Package == package) + if (oldContext is not null && oldContext.Package == package) { context = oldContext; } @@ -914,7 +914,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) // SSPI Workaround // If a client sends up a blob on the initial request, Negotiate returns SEC_E_INVALID_HANDLE // when it should return SEC_E_INVALID_TOKEN. - if (statusCodeNew.ErrorCode == SecurityStatusPalErrorCode.InvalidHandle && oldContext == null && bytes != null && bytes.Length > 0) + if (statusCodeNew.ErrorCode == SecurityStatusPalErrorCode.InvalidHandle && oldContext is null && bytes is not null && bytes.Length > 0) { statusCodeNew = new SecurityStatusPal(SecurityStatusPalErrorCode.InvalidToken); } @@ -923,7 +923,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } } - if (decodedOutgoingBlob != null) + if (decodedOutgoingBlob is not null) { // Prefix SPNEGO token/NTLM challenge with scheme per RFC 4559, MS-NTHT outBlob = string.Format("{0} {1}", @@ -981,11 +981,11 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } // We may need to call WaitForDisconnect. - if (disconnectResult == null) + if (disconnectResult is null) { RegisterForDisconnectNotification(session, connectionId, ref disconnectResult); } - if (disconnectResult != null) + if (disconnectResult is not null) { lock ((DisconnectResults as ICollection).SyncRoot) { @@ -1009,7 +1009,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } finally { - if (userContext != null) + if (userContext is not null) { userContext.Close(); } @@ -1060,7 +1060,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) break; } - if (principal != null) + if (principal is not null) { if (NetEventSource.Log.IsEnabled()) { @@ -1082,17 +1082,17 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) // if we're not giving a request to the application, we need to send an error ArrayList? challenges = null; - if (httpContext == null) + if (httpContext is null) { // If we already have a challenge, just use it. Otherwise put a challenge for each acceptable scheme. - if (challenge != null) + if (challenge is not null) { AddChallenge(ref challenges, challenge); } else { // We're starting over. Any context SSPI might have wanted us to keep is useless. - if (newContext != null) + if (newContext is not null) { if (newContext == context) { @@ -1125,14 +1125,14 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } // Check if we need to call WaitForDisconnect, because if we do and it fails, we want to send a 500 instead. - if (disconnectResult == null && newContext != null) + if (disconnectResult is null && newContext is not null) { RegisterForDisconnectNotification(session, connectionId, ref disconnectResult); // Failed - send 500. - if (disconnectResult == null) + if (disconnectResult is null) { - if (newContext != null) + if (newContext is not null) { if (newContext == context) { @@ -1170,19 +1170,19 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) NTAuthentication? toClose = oldContext; oldContext = newContext; // TODO: Can disconnectResult be null here? - Debug.Assert(disconnectResult != null); + Debug.Assert(disconnectResult is not null); disconnectResult!.Session = newContext; - if (toClose != null) + if (toClose is not null) { toClose.CloseContext(); } } // Send the 401 here. - if (httpContext == null) + if (httpContext is null) { - SendError(session, requestId, challenges != null && challenges.Count > 0 ? HttpStatusCode.Unauthorized : HttpStatusCode.Forbidden, challenges); + SendError(session, requestId, challenges is not null && challenges.Count > 0 ? HttpStatusCode.Unauthorized : HttpStatusCode.Forbidden, challenges); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Scheme:" + authenticationScheme); return null; } @@ -1197,7 +1197,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) catch { FreeContext(ref httpContext, memoryBlob); - if (newContext != null) + if (newContext is not null) { if (newContext == context) { @@ -1223,10 +1223,10 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) try { // Clean up the previous context if necessary. - if (oldContext != null && oldContext != newContext) + if (oldContext is not null && oldContext != newContext) { // Clear out Session if it wasn't already. - if (newContext == null && disconnectResult != null) + if (newContext is null && disconnectResult is not null) { disconnectResult.Session = null; } @@ -1235,7 +1235,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } // Delete any context created but not stored. - if (context != null && oldContext != context && newContext != context) + if (context is not null && oldContext != context && newContext != context) { context.CloseContext(); } @@ -1244,7 +1244,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { // Check if the connection got deleted while in this method, and clear out the hashtables if it did. // In a nested finally because if this doesn't happen, we leak. - if (disconnectResult != null) + if (disconnectResult is not null) { disconnectResult.FinishOwningDisconnectHandling(); } @@ -1254,7 +1254,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) private static void FreeContext(ref HttpListenerContext? httpContext, RequestContextBase memoryBlob) { - if (httpContext != null) + if (httpContext is not null) { httpContext.Request.DetachBlob(memoryBlob); httpContext.Close(); @@ -1267,7 +1267,7 @@ private static void FreeContext(ref HttpListenerContext? httpContext, RequestCon // is required for this request. internal void SetAuthenticationHeaders(HttpListenerContext context) { - Debug.Assert(context != null, "Null Context"); + Debug.Assert(context is not null, "Null Context"); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; @@ -1279,7 +1279,7 @@ internal void SetAuthenticationHeaders(HttpListenerContext context) // Setting 401 without setting WWW-Authenticate is a protocol violation // but throwing from HttpListener would be a breaking change. - if (challenges != null) // null == Anonymous + if (challenges is not null) // Anonymous is null { // Add the new WWW-Authenticate headers foreach (string challenge in challenges) @@ -1311,7 +1311,7 @@ internal void SetAuthenticationHeaders(HttpListenerContext context) ChannelBinding? result = GetChannelBindingFromTls(session, connectionId); - if (NetEventSource.Log.IsEnabled() && result != null) + if (NetEventSource.Log.IsEnabled() && result is not null) NetEventSource.Info(this, "GetChannelBindingFromTls returned null even though OS supposedly supports Extended Protection"); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, SR.net_log_listener_cbt); return result; @@ -1429,7 +1429,7 @@ private ServiceNameCollection GetServiceNames(ExtendedProtectionPolicy policy) { ServiceNameCollection serviceNames; - if (policy.CustomServiceNames == null) + if (policy.CustomServiceNames is null) { if (_defaultServiceNames.ServiceNames.Count == 0) { @@ -1517,13 +1517,13 @@ internal static bool IsClientFault(SecurityStatusPalErrorCode error) private static void AddChallenge(ref ArrayList? challenges, string challenge) { - if (challenge != null) + if (challenge is not null) { challenge = challenge.Trim(); if (challenge.Length > 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "challenge:" + challenge); - if (challenges == null) + if (challenges is null) { challenges = new ArrayList(4); } @@ -1559,7 +1559,7 @@ private static void AddChallenge(ref ArrayList? challenges, string challenge) private static void RegisterForDisconnectNotification(HttpListenerSession session, ulong connectionId, ref DisconnectAsyncResult? disconnectResult) { - Debug.Assert(disconnectResult == null); + Debug.Assert(disconnectResult is null); try { @@ -1619,7 +1619,7 @@ private static void SendError(HttpListenerSession session, ulong requestId, Http (&httpResponse.Headers.KnownHeaders)[(int)HttpResponseHeader.ContentLength].pRawValue = (sbyte*)pContentLength; (&httpResponse.Headers.KnownHeaders)[(int)HttpResponseHeader.ContentLength].RawValueLength = (ushort)byteContentLength.Length; - httpResponse.Headers.UnknownHeaderCount = checked((ushort)(challenges == null ? 0 : challenges.Count)); + httpResponse.Headers.UnknownHeaderCount = checked((ushort)(challenges is null ? 0 : challenges.Count)); GCHandle[]? challengeHandles = null; Interop.HttpApi.HTTP_UNKNOWN_HEADER[]? headersArray = null; GCHandle headersArrayHandle = default; @@ -1674,7 +1674,7 @@ private static void SendError(HttpListenerSession session, ulong requestId, Http { wwwAuthenticateHandle.Free(); } - if (challengeHandles != null) + if (challengeHandles is not null) { for (int i = 0; i < challengeHandles.Length; i++) { @@ -1895,7 +1895,7 @@ private void HandleDisconnect() if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DisconnectResults {listener.DisconnectResults} removing for _connectionId: {_connectionId}"); listener.DisconnectResults.Remove(_connectionId); - if (_session != null) + if (_session is not null) { _session.CloseContext(); } @@ -1903,8 +1903,8 @@ private void HandleDisconnect() // Clean up the identity. This is for scenarios where identity was not cleaned up before due to // identity caching for unsafe ntlm authentication - IDisposable? identity = _authenticatedConnection == null ? null : _authenticatedConnection.Identity as IDisposable; - if ((identity != null) && + IDisposable? identity = _authenticatedConnection is null ? null : _authenticatedConnection.Identity as IDisposable; + if ((identity is not null) && (_authenticatedConnection!.Identity.AuthenticationType == AuthenticationTypes.NTLM) && (listener.UnsafeConnectionNtlmAuthentication)) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs index e3ff6294afaa7e..f172b5cbefd800 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs @@ -32,7 +32,7 @@ internal void SetIdentity(IPrincipal principal, string? mutualAuthentication) { _mutualAuthentication = mutualAuthentication; _user = principal; - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"mutual: {(mutualAuthentication == null ? "" : mutualAuthentication)}, Principal: {principal}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"mutual: {(mutualAuthentication is null ? "" : mutualAuthentication)}, Principal: {principal}"); } // This can be used to cache the results of HttpListener.ExtendedProtectionSelectorDelegate. @@ -88,10 +88,10 @@ internal void Close() } finally { - IDisposable? user = _user == null ? null : _user.Identity as IDisposable; + IDisposable? user = _user is null ? null : _user.Identity as IDisposable; // For unsafe connection ntlm auth we dont dispose this identity as yet since its cached - if ((user != null) && + if ((user is not null) && (_user!.Identity!.AuthenticationType != NegotiationInfoClass.NTLM) && (!_listener!.UnsafeConnectionNtlmAuthentication)) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index b49eb2c1f1a21c..410bf927b67b91 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -60,24 +60,24 @@ internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase // Set up some of these now to avoid refcounting on memory blob later. _requestId = memoryBlob.RequestBlob->RequestId; _connectionId = memoryBlob.RequestBlob->ConnectionId; - _sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure : + _sslStatus = memoryBlob.RequestBlob->pSslInfo is null ? SslStatus.Insecure : memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert : SslStatus.ClientCert; - if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0) + if (memoryBlob.RequestBlob->pRawUrl is not null && memoryBlob.RequestBlob->RawUrlLength > 0) { _rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength); } Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl; - if (cookedUrl.pHost != null && cookedUrl.HostLength > 0) + if (cookedUrl.pHost is not null && cookedUrl.HostLength > 0) { _cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2); } - if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0) + if (cookedUrl.pAbsPath is not null && cookedUrl.AbsPathLength > 0) { _cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2); } - if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0) + if (cookedUrl.pQueryString is not null && cookedUrl.QueryStringLength > 0) { _cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2); } @@ -130,7 +130,7 @@ internal IntPtr OriginalBlobAddress // disposed. internal void DetachBlob(RequestContextBase memoryBlob) { - if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob!) + if (memoryBlob is not null && (object)memoryBlob == (object)_memoryBlob!) { _memoryBlob = null; } @@ -161,7 +161,7 @@ public long ContentLength64 if (_boundaryType == BoundaryType.None) { string? transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding]; - if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase)) + if (transferEncodingHeader is not null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase)) { _boundaryType = BoundaryType.Chunked; _contentLength = -1; @@ -171,7 +171,7 @@ public long ContentLength64 _contentLength = 0; _boundaryType = BoundaryType.ContentLength; string? length = Headers[HttpKnownHeaderNames.ContentLength]; - if (length != null) + if (length is not null) { bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength); if (!success) @@ -191,7 +191,7 @@ public NameValueCollection Headers { get { - if (_webHeaders == null) + if (_webHeaders is null) { _webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress); } @@ -204,7 +204,7 @@ public string HttpMethod { get { - if (_httpMethod == null) + if (_httpMethod is null) { _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); } @@ -217,7 +217,7 @@ public Stream InputStream { get { - if (_requestStream == null) + if (_requestStream is null) { _requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; } @@ -230,7 +230,7 @@ public bool IsAuthenticated get { IPrincipal? user = HttpListenerContext.User; - return user != null && user.Identity != null && user.Identity.IsAuthenticated; + return user is not null && user.Identity is not null && user.Identity.IsAuthenticated; } } @@ -257,12 +257,12 @@ internal void SetClientCertificateError(int clientCertificateError) { X509Certificate2? clientCertificate = null; - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; - if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) + if (clientCertAsyncResult is null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -294,7 +294,7 @@ public IPEndPoint RemoteEndPoint { get { - if (_remoteEndPoint == null) + if (_remoteEndPoint is null) { _remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); } @@ -308,7 +308,7 @@ public IPEndPoint LocalEndPoint { get { - if (_localEndPoint == null) + if (_localEndPoint is null) { _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); } @@ -321,7 +321,7 @@ public IPEndPoint LocalEndPoint internal void Close() { RequestContextBase? memoryBlob = _memoryBlob; - if (memoryBlob != null) + if (memoryBlob is not null) { memoryBlob.Close(); _memoryBlob = null; @@ -494,12 +494,12 @@ private void GetClientCertificateCore() } else if (statusCode == Interop.HttpApi.ERROR_SUCCESS) { - if (pClientCertInfo != null) + if (pClientCertInfo is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}"); - if (pClientCertInfo->pCertEncoded != null) + if (pClientCertInfo->pCertEncoded is not null) { try { @@ -534,7 +534,7 @@ private Uri RequestUri { get { - if (_requestUri == null) + if (_requestUri is null) { _requestUri = HttpListenerRequestUriBuilder.GetRequestUri( _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs index d49bc4aff1a7f0..92b5fad81d35ef 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs @@ -13,7 +13,7 @@ internal class HttpListenerRequestContext : TransportContext internal HttpListenerRequestContext(HttpListenerRequest request) { - Debug.Assert(request != null, "HttpListenerRequestContext..ctor(): Not expecting a null request!"); + Debug.Assert(request is not null, "HttpListenerRequestContext..ctor(): Not expecting a null request!"); _request = request; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs index 40d72e8af468b8..95fbea6a73406c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs @@ -83,7 +83,7 @@ public Version ProtocolVersion set { CheckDisposed(); - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -125,7 +125,7 @@ public void Close() public void Close(byte[] responseEntity, bool willBlock) { CheckDisposed(); - if (responseEntity == null) + if (responseEntity is null) { throw new ArgumentNullException(nameof(responseEntity)); } @@ -135,7 +135,7 @@ public void Close(byte[] responseEntity, bool willBlock) ContentLength64 = responseEntity.Length; } EnsureResponseStream(); - Debug.Assert(_responseStream != null); + Debug.Assert(_responseStream is not null); if (willBlock) { try @@ -175,7 +175,7 @@ private void Dispose() private void EnsureResponseStream() { - if (_responseStream == null) + if (_responseStream is null) { _responseStream = new HttpResponseStream(HttpListenerContext!); } @@ -259,12 +259,12 @@ internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk, List? pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake); try { - if (pDataChunk != null) + if (pDataChunk is not null) { _nativeResponse.EntityChunkCount = 1; _nativeResponse.pEntityChunks = pDataChunk; } - else if (asyncResult != null && asyncResult.pDataChunks != null) + else if (asyncResult is not null && asyncResult.pDataChunks is not null) { _nativeResponse.EntityChunkCount = asyncResult.dataChunkCount; _nativeResponse.pEntityChunks = asyncResult.pDataChunks; @@ -295,10 +295,10 @@ internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk, &bytesSent, SafeLocalAllocHandle.Zero, 0, - asyncResult == null ? null : asyncResult._pOverlapped, + asyncResult is null ? null : asyncResult._pOverlapped, null); - if (asyncResult != null && + if (asyncResult is not null && statusCode == Interop.HttpApi.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { @@ -322,10 +322,10 @@ internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk, &bytesSent, SafeLocalAllocHandle.Zero, 0, - asyncResult == null ? null : asyncResult._pOverlapped, + asyncResult is null ? null : asyncResult._pOverlapped, null); - if (asyncResult != null && + if (asyncResult is not null && statusCode == Interop.HttpApi.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { @@ -418,7 +418,7 @@ internal Interop.HttpApi.HTTP_FLAGS ComputeHeaders() // This method handles the shared response header processing between normal HTTP responses and WebSocket responses. internal void ComputeCoreHeaders() { - if (HttpListenerContext.MutualAuthentication != null && HttpListenerContext.MutualAuthentication.Length > 0) + if (HttpListenerContext.MutualAuthentication is not null && HttpListenerContext.MutualAuthentication.Length > 0) { Headers[HttpResponseHeader.WwwAuthenticate] = HttpListenerContext.MutualAuthentication; } @@ -519,7 +519,7 @@ internal void ComputeCoreHeaders() $"index={index},headers.count={Headers.Count},headerName:{headerName},lookup:{lookup} headerValue:{headerValue}"); if (lookup == -1) { - if (unknownHeaders == null) + if (unknownHeaders is null) { unknownHeaders = new Interop.HttpApi.HTTP_UNKNOWN_HEADER[numUnknownHeaders]; gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned); @@ -557,7 +557,7 @@ internal void ComputeCoreHeaders() else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"HttpResponseHeader[{lookup}]:{((HttpResponseHeader)lookup)} headerValue:{headerValue}"); - if (headerValue != null) + if (headerValue is not null) { bytes = new byte[WebHeaderEncoding.GetByteCount(headerValue)]; pKnownHeaders[lookup].RawValueLength = (ushort)bytes.Length; @@ -584,7 +584,7 @@ internal void ComputeCoreHeaders() private void FreePinnedHeaders(List? pinnedHeaders) { - if (pinnedHeaders != null) + if (pinnedHeaders is not null) { foreach (GCHandle gcHandle in pinnedHeaders) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs index 777335be91a983..3fcd407d86c7ee 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs @@ -16,11 +16,11 @@ public ThreadPoolBoundHandle RequestQueueBoundHandle { get { - if (_requestQueueBoundHandle == null) + if (_requestQueueBoundHandle is null) { lock (this) { - if (_requestQueueBoundHandle == null) + if (_requestQueueBoundHandle is null) { _requestQueueBoundHandle = ThreadPoolBoundHandle.BindHandle(RequestQueueHandle); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"ThreadPoolBoundHandle.BindHandle({RequestQueueHandle}) -> {_requestQueueBoundHandle}"); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 3eadb3cf7e5e4a..4a957af829b288 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -219,12 +219,12 @@ public override int EndRead(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult: {asyncResult}"); - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } HttpRequestStreamAsyncResult? castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -236,7 +236,7 @@ public override int EndRead(IAsyncResult asyncResult) // wait & then check for errors object? returnValue = castedAsyncResult.InternalWaitForCompletion(); Exception? exception = returnValue as Exception; - if (exception != null) + if (exception is not null) { if (NetEventSource.Log.IsEnabled()) { @@ -342,7 +342,7 @@ private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlap protected override void Cleanup() { base.Cleanup(); - if (_pOverlapped != null) + if (_pOverlapped is not null) { _boundHandle!.FreeNativeOverlapped(_pOverlapped); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs index 6ab2f5bd54e459..7626c7a9c21876 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs @@ -239,7 +239,7 @@ private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCa private void EndWriteCore(IAsyncResult asyncResult) { HttpResponseStreamAsyncResult? castedAsyncResult = asyncResult as HttpResponseStreamAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -252,7 +252,7 @@ private void EndWriteCore(IAsyncResult asyncResult) object? returnValue = castedAsyncResult.InternalWaitForCompletion(); Exception? exception = returnValue as Exception; - if (exception != null) + if (exception is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "Rethrowing exception:" + exception); _closed = true; @@ -328,7 +328,7 @@ private void DisposeCore() _httpContext.RequestQueueHandle, _httpContext.RequestId, (uint)flags, - pDataChunk != null ? (ushort)1 : (ushort)0, + pDataChunk is not null ? (ushort)1 : (ushort)0, pDataChunk, null, SafeLocalAllocHandle.Zero, @@ -377,7 +377,7 @@ internal void SwitchToOpaqueMode() internal void CancelLastWrite(SafeHandle requestQueueHandle) { HttpResponseStreamAsyncResult? asyncState = _lastWrite; - if (asyncState != null && !asyncState.IsCompleted) + if (asyncState is not null && !asyncState.IsCompleted) { // It is safe to ignore the return value on a cancel operation because the connection is being closed Interop.Kernel32.CancelIoEx(requestQueueHandle, asyncState._pOverlapped); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index 5a41b0ddeed6a9..6ee0c9ac7bdc55 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -19,7 +19,7 @@ internal ushort dataChunkCount { get { - if (_dataChunks == null) + if (_dataChunks is null) { return 0; } @@ -34,7 +34,7 @@ internal Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunks { get { - if (_dataChunks == null) + if (_dataChunks is null) { return null; } @@ -197,7 +197,7 @@ private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint else { // if we sent headers and body together, numBytes will be the total, but we need to only account for the data - if (asyncResult._dataChunks == null) + if (asyncResult._dataChunks is null) { result = (uint)0; if (NetEventSource.Log.IsEnabled()) { NetEventSource.DumpBuffer(null, IntPtr.Zero, 0); } @@ -230,7 +230,7 @@ private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlap protected override void Cleanup() { base.Cleanup(); - if (_pOverlapped != null) + if (_pOverlapped is not null) { _boundHandle!.FreeNativeOverlapped(_pOverlapped); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs index b36252e9de8222..8fc71f18e71e1b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs @@ -52,7 +52,7 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, if (stoleBlob) { // The request has been handed to the user, which means this code can't reuse the blob. Reset it here. - asyncResult._requestContext = result == null ? new AsyncRequestContext(listenerSession.RequestQueueBoundHandle, asyncResult) : null; + asyncResult._requestContext = result is null ? new AsyncRequestContext(listenerSession.RequestQueueBoundHandle, asyncResult) : null; } else { @@ -66,7 +66,7 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, } // We need to issue a new request, either because auth failed, or because our buffer was too small the first time. - if (result == null) + if (result is null) { uint statusCode = asyncResult.QueueBeginGetContext(); if (statusCode != Interop.HttpApi.ERROR_SUCCESS && @@ -77,7 +77,7 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, result = new HttpListenerException((int)statusCode); } } - if (result == null) + if (result is null) { return; } @@ -105,10 +105,10 @@ internal uint QueueBeginGetContext() uint statusCode = Interop.HttpApi.ERROR_SUCCESS; while (true) { - Debug.Assert(_requestContext != null); + Debug.Assert(_requestContext is not null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling Interop.HttpApi.HttpReceiveHttpRequest RequestId: {_requestContext.RequestBlob->RequestId}Buffer:0x {((IntPtr)_requestContext.RequestBlob).ToString("x")} Size: {_requestContext.Size}"); uint bytesTransferred = 0; - Debug.Assert(AsyncObject != null); + Debug.Assert(AsyncObject is not null); HttpListenerSession listenerSession = (HttpListenerSession)AsyncObject!; statusCode = Interop.HttpApi.HttpReceiveHttpRequest( listenerSession.RequestQueueHandle, @@ -147,7 +147,7 @@ internal uint QueueBeginGetContext() // Will be called from the base class upon InvokeCallback() protected override void Cleanup() { - if (_requestContext != null) + if (_requestContext is not null) { _requestContext.ReleasePins(); _requestContext.Close(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs index 50521139e7619c..a83abee57893f4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs @@ -112,12 +112,12 @@ private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult else { Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult._memoryBlob; - if (pClientCertInfo != null) + if (pClientCertInfo is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}"); - if (pClientCertInfo->pCertEncoded != null) + if (pClientCertInfo->pCertEncoded is not null) { try { @@ -170,7 +170,7 @@ private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOve // Will be called from the base class upon InvokeCallback() protected override void Cleanup() { - if (_pOverlapped != null) + if (_pOverlapped is not null) { _memoryBlob = null; _boundHandle!.FreeNativeOverlapped(_pOverlapped); @@ -183,7 +183,7 @@ protected override void Cleanup() ~ListenerClientCertAsyncResult() { - if (_pOverlapped != null && !Environment.HasShutdownStarted) + if (_pOverlapped is not null && !Environment.HasShutdownStarted) { _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize(). diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/RequestContextBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/RequestContextBase.cs index 5b3ef0aeb551a2..10fec22c22aa24 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/RequestContextBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/RequestContextBase.cs @@ -17,7 +17,7 @@ internal abstract unsafe class RequestContextBase : IDisposable // Must call this from derived class' constructors. protected void BaseConstruction(Interop.HttpApi.HTTP_REQUEST* requestBlob) { - if (requestBlob != null) + if (requestBlob is not null) { _memoryBlob = requestBlob; } @@ -27,7 +27,7 @@ protected void BaseConstruction(Interop.HttpApi.HTTP_REQUEST* requestBlob) // before an object (HttpListenerRequest) which closes the RequestContext on demand is returned to the application. internal void ReleasePins() { - Debug.Assert(_memoryBlob != null || _backingBuffer == IntPtr.Zero, "RequestContextBase::ReleasePins()|ReleasePins() called twice."); + Debug.Assert(_memoryBlob is not null || _backingBuffer == IntPtr.Zero, "RequestContextBase::ReleasePins()|ReleasePins() called twice."); _originalBlobAddress = _memoryBlob; UnsetBlob(); OnReleasePins(); @@ -42,7 +42,7 @@ public void Close() public void Dispose() { - Debug.Assert(_memoryBlob == null, "RequestContextBase::Dispose()|Dispose() called before ReleasePins()."); + Debug.Assert(_memoryBlob is null, "RequestContextBase::Dispose()|Dispose() called before ReleasePins()."); Dispose(true); GC.SuppressFinalize(this); } @@ -65,7 +65,7 @@ internal Interop.HttpApi.HTTP_REQUEST* RequestBlob { get { - Debug.Assert(_memoryBlob != null || _backingBuffer == IntPtr.Zero, "RequestContextBase::Dispose()|RequestBlob requested after ReleasePins()."); + Debug.Assert(_memoryBlob is not null || _backingBuffer == IntPtr.Zero, "RequestContextBase::Dispose()|RequestBlob requested after ReleasePins()."); return _memoryBlob; } } @@ -91,14 +91,14 @@ internal IntPtr OriginalBlobAddress get { Interop.HttpApi.HTTP_REQUEST* blob = _memoryBlob; - return (IntPtr)(blob == null ? _originalBlobAddress : blob); + return (IntPtr)(blob is null ? _originalBlobAddress : blob); } } protected void SetBlob(Interop.HttpApi.HTTP_REQUEST* requestBlob) { - Debug.Assert(_memoryBlob != null || _backingBuffer == IntPtr.Zero, "RequestContextBase::Dispose()|SetBlob() called after ReleasePins()."); - if (requestBlob == null) + Debug.Assert(_memoryBlob is not null || _backingBuffer == IntPtr.Zero, "RequestContextBase::Dispose()|SetBlob() called after ReleasePins()."); + if (requestBlob is null) { UnsetBlob(); return; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs index 6eb7bd071ff8df..a11f8f8969e1ab 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs @@ -93,7 +93,7 @@ private static async Task AcceptWebSocketAsyncCore await response.OutputStream.FlushAsync().SuppressContextFlow(); HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream)!; - Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream."); + Debug.Assert(responseStream is not null, "'responseStream' MUST be castable to System.Net.HttpResponseStream."); ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode(); HttpRequestStream requestStream = new HttpRequestStream(context); requestStream.SwitchToOpaqueMode(); @@ -173,7 +173,7 @@ private static unsafe ulong SendWebSocketHeaders(HttpListenerResponse response) internal static void ValidateInnerStream(Stream innerStream) { - if (innerStream == null) + if (innerStream is null) { throw new ArgumentNullException(nameof(innerStream)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/ServerWebSocket.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/ServerWebSocket.cs index 20c9a3b71466b9..adab843f2405cb 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/ServerWebSocket.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/ServerWebSocket.cs @@ -47,7 +47,7 @@ public ServerWebSocket(Stream innerStream, _properties = InternalBuffer.CreateProperties(false); _sessionHandle = CreateWebSocketHandle(); - if (_sessionHandle == null || _sessionHandle.IsInvalid) + if (_sessionHandle is null || _sessionHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } @@ -59,20 +59,20 @@ internal override SafeHandle SessionHandle { get { - Debug.Assert(_sessionHandle != null, "'_sessionHandle MUST NOT be NULL."); + Debug.Assert(_sessionHandle is not null, "'_sessionHandle MUST NOT be NULL."); return _sessionHandle; } } private SafeHandle CreateWebSocketHandle() { - Debug.Assert(_properties != null, "'_properties' MUST NOT be NULL."); + Debug.Assert(_properties is not null, "'_properties' MUST NOT be NULL."); SafeWebSocketHandle sessionHandle; WebSocketProtocolComponent.WebSocketCreateServerHandle( _properties, _properties.Length, out sessionHandle); - Debug.Assert(sessionHandle != null, "'sessionHandle MUST NOT be NULL."); + Debug.Assert(sessionHandle is not null, "'sessionHandle MUST NOT be NULL."); return sessionHandle; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index 3213e1eb8d71a5..1d46cb5e7dd55e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -58,7 +58,7 @@ protected WebSocketBase(Stream innerStream, TimeSpan keepAliveInterval, WebSocketBuffer internalBuffer) { - Debug.Assert(internalBuffer != null, "'internalBuffer' MUST NOT be NULL."); + Debug.Assert(internalBuffer is not null, "'internalBuffer' MUST NOT be NULL."); HttpWebSocket.ValidateInnerStream(innerStream); HttpWebSocket.ValidateOptions(subProtocol, internalBuffer.ReceiveBufferSize, internalBuffer.SendBufferSize, keepAliveInterval); @@ -97,7 +97,7 @@ protected WebSocketBase(Stream innerStream, _closeStatus = null; _closeStatusDescription = null; _innerStreamAsWebSocketStream = innerStream as IWebSocketStream; - if (_innerStreamAsWebSocketStream != null) + if (_innerStreamAsWebSocketStream is not null) { _innerStreamAsWebSocketStream.SwitchToOpaqueMode(this); } @@ -141,7 +141,7 @@ internal WebSocketBuffer InternalBuffer { get { - Debug.Assert(_internalBuffer != null, "'_internalBuffer' MUST NOT be NULL."); + Debug.Assert(_internalBuffer is not null, "'_internalBuffer' MUST NOT be NULL."); return _internalBuffer; } } @@ -249,7 +249,7 @@ private async Task SendAsyncCore(ArraySegment buffer, { Debug.Assert(messageType == WebSocketMessageType.Binary || messageType == WebSocketMessageType.Text, "'messageType' MUST be either 'WebSocketMessageType.Binary' or 'WebSocketMessageType.Text'."); - Debug.Assert(buffer.Array != null); + Debug.Assert(buffer.Array is not null); string inputParameter = string.Empty; if (NetEventSource.Log.IsEnabled()) @@ -276,7 +276,7 @@ private async Task SendAsyncCore(ArraySegment buffer, { keepAliveTask = _keepAliveTask; - if (keepAliveTask == null) + if (keepAliveTask is null) { // Check whether there is still another outstanding send operation // Potentially the keepAlive operation has completed before this thread @@ -331,7 +331,7 @@ private async Task SendFrameAsync(IList> sendBuffers, Cancell sendFrameLockTaken = true; if (sendBuffers.Count > 1 && - _innerStreamAsWebSocketStream != null && + _innerStreamAsWebSocketStream is not null && _innerStreamAsWebSocketStream.SupportsMultipleWrite) { await _innerStreamAsWebSocketStream.MultipleWriteAsync(sendBuffers, @@ -386,7 +386,7 @@ public override void Abort() _state = WebSocketState.Aborted; // Abort any outstanding IO operations. - if (SessionHandle != null && !SessionHandle.IsClosed && !SessionHandle.IsInvalid) + if (SessionHandle is not null && !SessionHandle.IsClosed && !SessionHandle.IsInvalid) { WebSocketProtocolComponent.WebSocketAbortHandle(SessionHandle); } @@ -395,7 +395,7 @@ public override void Abort() _sendOutstandingOperationHelper.CancelIO(); _closeOutputOutstandingOperationHelper.CancelIO(); _closeOutstandingOperationHelper.CancelIO(); - if (_innerStreamAsWebSocketStream != null) + if (_innerStreamAsWebSocketStream is not null) { _innerStreamAsWebSocketStream.Abort(); } @@ -460,7 +460,7 @@ private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, { Task? closeOutputTask = _closeOutputTask; - if (closeOutputTask != null) + if (closeOutputTask is not null) { ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken); await closeOutputTask.SuppressContextFlow(); @@ -474,7 +474,7 @@ private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))) { - if (_keepAliveTask != null) + if (_keepAliveTask is not null) { Task keepAliveTask = _keepAliveTask; @@ -589,14 +589,14 @@ private async Task StartOnCloseCompleted(bool thisLockTakenSnapshot, _state = WebSocketState.Closed; - if (_innerStreamAsWebSocketStream != null) + if (_innerStreamAsWebSocketStream is not null) { bool thisLockTaken = thisLockTakenSnapshot; bool sessionHandleLockTaken = sessionHandleLockTakenSnapshot; try { - if (_closeNetworkConnectionTask == null) + if (_closeNetworkConnectionTask is null) { _closeNetworkConnectionTask = _innerStreamAsWebSocketStream.CloseNetworkConnectionAsync(cancellationToken); @@ -684,7 +684,7 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, if (ownsCloseCancellationTokenSource) { closeOutputTask = _closeOutputTask; - if (closeOutputTask == null && State != WebSocketState.CloseSent) + if (closeOutputTask is null && State != WebSocketState.CloseSent) { _closeReceivedTaskCompletionSource ??= new TaskCompletionSource(); @@ -695,11 +695,11 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, } else { - Debug.Assert(_closeReceivedTaskCompletionSource != null, "'_closeReceivedTaskCompletionSource' MUST NOT be NULL."); + Debug.Assert(_closeReceivedTaskCompletionSource is not null, "'_closeReceivedTaskCompletionSource' MUST NOT be NULL."); closeOutputTask = _closeReceivedTaskCompletionSource.Task; } - if (closeOutputTask != null) + if (closeOutputTask is not null) { ReleaseLock(_thisLock, ref lockTaken); try @@ -720,7 +720,7 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, } } - // When closeOutputTask != null and an exception thrown from await closeOutputTask is handled, + // When closeOutputTask is not null and an exception thrown from await closeOutputTask is handled, // the lock will be taken in the catch-block. So the logic here avoids taking the lock twice. if (!lockTaken) { @@ -795,7 +795,7 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, // - but in the close code path we handle some exception if another thread was able to tranistion // the state into Closed successfully. In this case receiveResult can be NULL and it is safe to // skip the statements in the if-block. - if (receiveResult != null) + if (receiveResult is not null) { if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0) { @@ -918,7 +918,7 @@ public override void Dispose() private void ResetFlagAndTakeLock(object lockObject, ref bool thisLockTaken) { - Debug.Assert(lockObject != null, "'lockObject' MUST NOT be NULL."); + Debug.Assert(lockObject is not null, "'lockObject' MUST NOT be NULL."); thisLockTaken = false; Monitor.Enter(lockObject, ref thisLockTaken); } @@ -932,8 +932,8 @@ private void ResetFlagsAndTakeLocks(ref bool thisLockTaken, ref bool sessionHand private void TakeLocks(ref bool thisLockTaken, ref bool sessionHandleLockTaken) { - Debug.Assert(_thisLock != null, "'_thisLock' MUST NOT be NULL."); - Debug.Assert(SessionHandle != null, "'SessionHandle' MUST NOT be NULL."); + Debug.Assert(_thisLock is not null, "'_thisLock' MUST NOT be NULL."); + Debug.Assert(SessionHandle is not null, "'SessionHandle' MUST NOT be NULL."); Monitor.Enter(SessionHandle, ref sessionHandleLockTaken); Monitor.Enter(_thisLock, ref thisLockTaken); @@ -941,8 +941,8 @@ private void TakeLocks(ref bool thisLockTaken, ref bool sessionHandleLockTaken) private void ReleaseLocks(ref bool thisLockTaken, ref bool sessionHandleLockTaken) { - Debug.Assert(_thisLock != null, "'_thisLock' MUST NOT be NULL."); - Debug.Assert(SessionHandle != null, "'SessionHandle' MUST NOT be NULL."); + Debug.Assert(_thisLock is not null, "'_thisLock' MUST NOT be NULL."); + Debug.Assert(SessionHandle is not null, "'SessionHandle' MUST NOT be NULL."); if (thisLockTaken) { @@ -959,11 +959,11 @@ private void ReleaseLocks(ref bool thisLockTaken, ref bool sessionHandleLockTake private void EnsureReceiveOperation() { - if (_receiveOperation == null) + if (_receiveOperation is null) { lock (_thisLock) { - if (_receiveOperation == null) + if (_receiveOperation is null) { _receiveOperation = new WebSocketOperation.ReceiveOperation(this); } @@ -973,11 +973,11 @@ private void EnsureReceiveOperation() private void EnsureSendOperation() { - if (_sendOperation == null) + if (_sendOperation is null) { lock (_thisLock) { - if (_sendOperation == null) + if (_sendOperation is null) { _sendOperation = new WebSocketOperation.SendOperation(this); } @@ -987,11 +987,11 @@ private void EnsureSendOperation() private void EnsureKeepAliveOperation() { - if (_keepAliveOperation == null) + if (_keepAliveOperation is null) { lock (_thisLock) { - if (_keepAliveOperation == null) + if (_keepAliveOperation is null) { WebSocketOperation.SendOperation keepAliveOperation = new WebSocketOperation.SendOperation(this); keepAliveOperation.BufferType = WebSocketProtocolComponent.BufferType.UnsolicitedPong; @@ -1003,11 +1003,11 @@ private void EnsureKeepAliveOperation() private void EnsureCloseOutputOperation() { - if (_closeOutputOperation == null) + if (_closeOutputOperation is null) { lock (_thisLock) { - if (_closeOutputOperation == null) + if (_closeOutputOperation is null) { _closeOutputOperation = new WebSocketOperation.CloseOutputOperation(this); } @@ -1017,7 +1017,7 @@ private void EnsureCloseOutputOperation() private static void ReleaseLock(object lockObject, ref bool lockTaken) { - Debug.Assert(lockObject != null, "'lockObject' MUST NOT be NULL."); + Debug.Assert(lockObject is not null, "'lockObject' MUST NOT be NULL."); if (lockTaken) { Monitor.Exit(lockObject); @@ -1107,7 +1107,7 @@ private void ThrowIfAborted(bool aborted, Exception innerException) private bool CanHandleExceptionDuringClose(Exception error) { - Debug.Assert(error != null, "'error' MUST NOT be NULL."); + Debug.Assert(error is not null, "'error' MUST NOT be NULL."); if (State != WebSocketState.Closed) { @@ -1129,7 +1129,7 @@ private void ThrowIfConvertibleException(string? methodName, CancellationToken cancellationToken, bool aborted) { - Debug.Assert(exception != null, "'exception' MUST NOT be NULL."); + Debug.Assert(exception is not null, "'exception' MUST NOT be NULL."); if (NetEventSource.Log.IsEnabled() && !string.IsNullOrEmpty(methodName)) { @@ -1137,7 +1137,7 @@ private void ThrowIfConvertibleException(string? methodName, } OperationCanceledException? operationCanceledException = exception as OperationCanceledException; - if (operationCanceledException != null) + if (operationCanceledException is not null) { if (cancellationToken.IsCancellationRequested || !aborted) @@ -1148,7 +1148,7 @@ private void ThrowIfConvertibleException(string? methodName, } WebSocketException? convertedException = exception as WebSocketException; - if (convertedException != null) + if (convertedException is not null) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfAborted(aborted, convertedException); @@ -1156,28 +1156,28 @@ private void ThrowIfConvertibleException(string? methodName, } SocketException? socketException = exception as SocketException; - if (socketException != null) + if (socketException is not null) { convertedException = new WebSocketException(socketException.NativeErrorCode, socketException); } HttpListenerException? httpListenerException = exception as HttpListenerException; - if (httpListenerException != null) + if (httpListenerException is not null) { convertedException = new WebSocketException(httpListenerException.ErrorCode, httpListenerException); } IOException? ioException = exception as IOException; - if (ioException != null) + if (ioException is not null) { socketException = exception.InnerException as SocketException; - if (socketException != null) + if (socketException is not null) { convertedException = new WebSocketException(socketException.NativeErrorCode, ioException); } } - if (convertedException != null) + if (convertedException is not null) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfAborted(aborted, convertedException); @@ -1185,7 +1185,7 @@ private void ThrowIfConvertibleException(string? methodName, } AggregateException? aggregateException = exception as AggregateException; - if (aggregateException != null) + if (aggregateException is not null) { // Collapse possibly nested graph into a flat list. // Empty inner exception list is unlikely but possible via public api. @@ -1212,37 +1212,37 @@ private void CleanUp() _cleanedUp = true; - if (SessionHandle != null) + if (SessionHandle is not null) { SessionHandle.Dispose(); } - if (_internalBuffer != null) + if (_internalBuffer is not null) { _internalBuffer.Dispose(this.State); } - if (_receiveOutstandingOperationHelper != null) + if (_receiveOutstandingOperationHelper is not null) { _receiveOutstandingOperationHelper.Dispose(); } - if (_sendOutstandingOperationHelper != null) + if (_sendOutstandingOperationHelper is not null) { _sendOutstandingOperationHelper.Dispose(); } - if (_closeOutputOutstandingOperationHelper != null) + if (_closeOutputOutstandingOperationHelper is not null) { _closeOutputOutstandingOperationHelper.Dispose(); } - if (_closeOutstandingOperationHelper != null) + if (_closeOutstandingOperationHelper is not null) { _closeOutstandingOperationHelper.Dispose(); } - if (_innerStream != null) + if (_innerStream is not null) { try { @@ -1267,7 +1267,7 @@ private void CleanUp() private void OnBackgroundTaskException(Exception exception) { - if (Interlocked.CompareExchange(ref _pendingException!, exception, null!) == null) + if (Interlocked.CompareExchange(ref _pendingException!, exception, null!) is null) { if (NetEventSource.Log.IsEnabled()) { @@ -1280,7 +1280,7 @@ private void OnBackgroundTaskException(Exception exception) private void ThrowIfPendingException() { Exception pendingException = Interlocked.Exchange(ref _pendingException!, null!); - if (pendingException != null) + if (pendingException is not null) { throw new WebSocketException(WebSocketError.Faulted, pendingException); } @@ -1349,8 +1349,8 @@ private void FinishOnCloseReceived(WebSocketCloseStatus closeStatus, private static async void OnKeepAlive(object? sender) { - Debug.Assert(sender != null, "'sender' MUST NOT be NULL."); - Debug.Assert((sender as WebSocketBase) != null, "'sender as WebSocketBase' MUST NOT be NULL."); + Debug.Assert(sender is not null, "'sender' MUST NOT be NULL."); + Debug.Assert((sender as WebSocketBase) is not null, "'sender as WebSocketBase' MUST NOT be NULL."); WebSocketBase? thisPtr = (sender as WebSocketBase)!; bool lockTaken = false; @@ -1362,7 +1362,7 @@ private static async void OnKeepAlive(object? sender) if (thisPtr._isDisposed || thisPtr._state != WebSocketState.Open || - thisPtr._closeOutputTask != null) + thisPtr._closeOutputTask is not null) { return; } @@ -1422,7 +1422,7 @@ private abstract class WebSocketOperation internal WebSocketOperation(WebSocketBase webSocket) { - Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL."); + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL."); _webSocket = webSocket; AsyncOperationCompleted = false; } @@ -1496,7 +1496,7 @@ protected virtual void ProcessAction_IndicateReceiveComplete( // A close frame was received Debug.Assert(ReceiveResult!.Count == 0, "'receiveResult.Count' MUST be 0."); - Debug.Assert(ReceiveResult.CloseStatus != null, "'receiveResult.CloseStatus' MUST NOT be NULL for message type 'Close'."); + Debug.Assert(ReceiveResult.CloseStatus is not null, "'receiveResult.CloseStatus' MUST NOT be NULL for message type 'Close'."); bool thisLockTaken = false; try { @@ -1711,7 +1711,7 @@ protected override int BufferCount protected override void Initialize(Nullable> buffer, CancellationToken cancellationToken) { - Debug.Assert(buffer != null, "'buffer' MUST NOT be NULL."); + Debug.Assert(buffer is not null, "'buffer' MUST NOT be NULL."); _pongReceived = false; _receiveCompleted = false; _webSocket.ThrowIfDisposed(); @@ -1771,7 +1771,7 @@ protected override bool ProcessAction_NoAction() return false; } - Debug.Assert(ReceiveResult != null, + Debug.Assert(ReceiveResult is not null, "'ReceiveResult' MUST NOT be NULL."); _receiveCompleted = true; @@ -1791,7 +1791,7 @@ protected override void ProcessAction_IndicateReceiveComplete( uint dataBufferCount, IntPtr actionContext) { - Debug.Assert(buffer != null, "'buffer MUST NOT be NULL."); + Debug.Assert(buffer is not null, "'buffer MUST NOT be NULL."); int bytesTransferred = 0; _pongReceived = false; @@ -1884,7 +1884,7 @@ protected override int BufferCount protected virtual Nullable CreateBuffer(Nullable> buffer) { - if (buffer == null) + if (buffer is null) { return null; } @@ -1921,7 +1921,7 @@ protected override void Initialize(Nullable> buffer, _webSocket.ThrowIfPendingException(); Nullable payloadBuffer = CreateBuffer(buffer); - if (payloadBuffer != null) + if (payloadBuffer is not null) { WebSocketProtocolComponent.WebSocketSend(_webSocket, BufferType, payloadBuffer.Value); } @@ -1933,7 +1933,7 @@ protected override void Initialize(Nullable> buffer, protected override bool ShouldContinue(CancellationToken cancellationToken) { - Debug.Assert(ReceiveResult == null, "'ReceiveResult' MUST be NULL."); + Debug.Assert(ReceiveResult is null, "'ReceiveResult' MUST be NULL."); if (AsyncOperationCompleted) { return false; @@ -1957,7 +1957,7 @@ public CloseOutputOperation(WebSocketBase webSocket) protected override Nullable CreateBuffer(Nullable> buffer) { - Debug.Assert(buffer == null, "'buffer' MUST BE NULL."); + Debug.Assert(buffer is null, "'buffer' MUST BE NULL."); _webSocket.ThrowIfDisposed(); _webSocket.ThrowIfPendingException(); @@ -1967,7 +1967,7 @@ public CloseOutputOperation(WebSocketBase webSocket) } Interop.WebSocket.Buffer payloadBuffer = default; - if (CloseReason != null) + if (CloseReason is not null) { byte[] blob = Encoding.UTF8.GetBytes(CloseReason); Debug.Assert(blob.Length <= WebSocketValidate.MaxControlFramePayloadLength, @@ -2065,8 +2065,8 @@ public override void ResetTimer() public override void StartTimer(WebSocketBase webSocket) { - Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL."); - Debug.Assert(webSocket._keepAliveTracker != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL."); + Debug.Assert(webSocket._keepAliveTracker is not null, "'webSocket._KeepAliveTracker' MUST NOT be NULL at this point."); int keepAliveIntervalMilliseconds = (int)_keepAliveInterval.TotalMilliseconds; Debug.Assert(keepAliveIntervalMilliseconds > 0, "'keepAliveIntervalMilliseconds' MUST be POSITIVE."); @@ -2177,7 +2177,7 @@ public void CompleteOperation(bool ownsCancellationTokenSource) } } - if (snapshot != null) + if (snapshot is not null) { snapshot.Dispose(); } @@ -2188,7 +2188,7 @@ private CancellationToken CreateLinkedCancellationToken(CancellationToken cancel { var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - Debug.Assert(_cancellationTokenSource == null, "'_cancellationTokenSource' MUST be NULL."); + Debug.Assert(_cancellationTokenSource is null, "'_cancellationTokenSource' MUST be NULL."); _cancellationTokenSource = linkedCancellationTokenSource; return linkedCancellationTokenSource.Token; @@ -2208,7 +2208,7 @@ public void CancelIO() cancellationTokenSourceSnapshot = _cancellationTokenSource; } - if (cancellationTokenSourceSnapshot != null) + if (cancellationTokenSourceSnapshot is not null) { try { @@ -2242,7 +2242,7 @@ public void Dispose() _cancellationTokenSource = null; } - if (snapshot != null) + if (snapshot is not null) { snapshot.Dispose(); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs index aa217407e66832..9e57f3e59260d8 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs @@ -48,7 +48,7 @@ internal class WebSocketBuffer : IDisposable private WebSocketBuffer(ArraySegment internalBuffer, int receiveBufferSize, int sendBufferSize) { - Debug.Assert(internalBuffer.Array != null, "'internalBuffer.Array' MUST NOT be NULL."); + Debug.Assert(internalBuffer.Array is not null, "'internalBuffer.Array' MUST NOT be NULL."); Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, "'receiveBufferSize' MUST be at least " + HttpWebSocket.MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, @@ -303,7 +303,7 @@ internal void BufferPayload(ArraySegment payload, Debug.Assert(_payloadOffset == 0, "'m_PayloadOffset' MUST be '0' at this point."); - Debug.Assert(_bufferedPayloadReceiveResult == null || _bufferedPayloadReceiveResult.Count == 0, + Debug.Assert(_bufferedPayloadReceiveResult is null || _bufferedPayloadReceiveResult.Count == 0, "'_bufferedPayloadReceiveResult.Count' MUST be '0' at this point."); Buffer.BlockCopy(payload.Array!, @@ -431,7 +431,7 @@ internal void ValidateNativeBuffers(WebSocketProtocolComponent.Action action, { Debug.Assert(dataBufferCount <= (uint)int.MaxValue, "'dataBufferCount' MUST NOT be bigger than Int32.MaxValue."); - Debug.Assert(dataBuffers != null, "'dataBuffers' MUST NOT be NULL."); + Debug.Assert(dataBuffers is not null, "'dataBuffers' MUST NOT be NULL."); ThrowIfDisposed(); if (dataBufferCount > dataBuffers.Length) @@ -551,7 +551,7 @@ private void ThrowIfDisposed() [Conditional("DEBUG")] private void ValidateBufferedPayload() { - Debug.Assert(_bufferedPayloadReceiveResult != null, + Debug.Assert(_bufferedPayloadReceiveResult is not null, "'_bufferedPayloadReceiveResult' MUST NOT be NULL."); Debug.Assert(_bufferedPayloadReceiveResult.Count >= 0, "'_bufferedPayloadReceiveResult.Count' MUST NOT be negative."); @@ -580,8 +580,8 @@ private int GetMaxBufferSize() // within m_NativeBuffer not m_InternalBuffer internal bool IsInternalBuffer(byte[] buffer, int offset, int count) { - Debug.Assert(buffer != null, "'buffer' MUST NOT be NULL."); - Debug.Assert(_nativeBuffer.Array != null, "'m_NativeBuffer.Array' MUST NOT be NULL."); + Debug.Assert(buffer is not null, "'buffer' MUST NOT be NULL."); + Debug.Assert(_nativeBuffer.Array is not null, "'m_NativeBuffer.Array' MUST NOT be NULL."); Debug.Assert(offset >= 0, "'offset' MUST NOT be negative."); Debug.Assert(count >= 0, "'count' MUST NOT be negative."); Debug.Assert(offset + count <= buffer.Length, "'offset + count' MUST NOT exceed 'buffer.Length'."); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index 1a07f99cb8686b..b8d6d5bf9206aa 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -44,9 +44,9 @@ public WebSocketHttpListenerDuplexStream(HttpRequestStream inputStream, HttpResponseStream outputStream, HttpListenerContext context) { - Debug.Assert(inputStream != null, "'inputStream' MUST NOT be NULL."); - Debug.Assert(outputStream != null, "'outputStream' MUST NOT be NULL."); - Debug.Assert(context != null, "'context' MUST NOT be NULL."); + Debug.Assert(inputStream is not null, "'inputStream' MUST NOT be NULL."); + Debug.Assert(outputStream is not null, "'outputStream' MUST NOT be NULL."); + Debug.Assert(context is not null, "'context' MUST NOT be NULL."); Debug.Assert(inputStream.CanRead, "'inputStream' MUST support read operations."); Debug.Assert(outputStream.CanWrite, "'outputStream' MUST support write operations."); @@ -154,7 +154,7 @@ private async Task ReadAsyncCore(byte[] buffer, int offset, int count, Canc _readEventArgs!.SetBuffer(buffer, offset, count); if (!ReadAsyncFast(_readEventArgs)) { - if (_readEventArgs.Exception != null) + if (_readEventArgs.Exception is not null) { throw _readEventArgs.Exception; } @@ -196,7 +196,7 @@ private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs) bool completedAsynchronouslyOrWithError = false; try { - Debug.Assert(eventArgs.Buffer != null, "'BufferList' is not supported for read operations."); + Debug.Assert(eventArgs.Buffer is not null, "'BufferList' is not supported for read operations."); if (eventArgs.Count == 0 || _inputStream.Closed) { eventArgs.FinishOperationSuccess(0, true); @@ -316,7 +316,7 @@ public override int EndRead(IAsyncResult asyncResult) public Task MultipleWriteAsync(IList> sendBuffers, CancellationToken cancellationToken) { Debug.Assert(_inOpaqueMode, "The stream MUST be in opaque mode at this point."); - Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL."); + Debug.Assert(sendBuffers is not null, "'sendBuffers' MUST NOT be NULL."); Debug.Assert(sendBuffers.Count == 1 || sendBuffers.Count == 2, "'sendBuffers.Count' MUST be either '1' or '2'."); @@ -331,7 +331,7 @@ public Task MultipleWriteAsync(IList> sendBuffers, Cancellati private async Task MultipleWriteAsyncCore(IList> sendBuffers, CancellationToken cancellationToken) { - Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL."); + Debug.Assert(sendBuffers is not null, "'sendBuffers' MUST NOT be NULL."); Debug.Assert(sendBuffers.Count == 2, "'sendBuffers.Count' MUST be '2' at this point."); CancellationTokenRegistration cancellationTokenRegistration = default; @@ -447,7 +447,7 @@ private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs) try { if (_outputStream.Closed || - (eventArgs.Buffer != null && eventArgs.Count == 0)) + (eventArgs.Buffer is not null && eventArgs.Count == 0)) { eventArgs.FinishOperationSuccess(eventArgs.Count, true); return false; @@ -596,19 +596,19 @@ protected override void Dispose(bool disposing) { if (disposing && Interlocked.Exchange(ref _cleanedUp, 1) == 0) { - if (_readTaskCompletionSource != null) + if (_readTaskCompletionSource is not null) { _readTaskCompletionSource.TrySetCanceled(); } _writeTaskCompletionSource?.TrySetCanceled(); - if (_readEventArgs != null) + if (_readEventArgs is not null) { _readEventArgs.Dispose(); } - if (_writeEventArgs != null) + if (_writeEventArgs is not null) { _writeEventArgs.Dispose(); } @@ -638,9 +638,9 @@ error is ObjectDisposedException || private static void OnCancel(object? state) { - Debug.Assert(state != null, "'state' MUST NOT be NULL."); + Debug.Assert(state is not null, "'state' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = (state as WebSocketHttpListenerDuplexStream)!; - Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); + Debug.Assert(thisPtr is not null, "'thisPtr' MUST NOT be NULL."); try { @@ -655,11 +655,11 @@ private static void OnCancel(object? state) public void SwitchToOpaqueMode(WebSocketBase webSocket) { - Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL."); - Debug.Assert(_outputStream != null, "'m_OutputStream' MUST NOT be NULL."); - Debug.Assert(_outputStream.InternalHttpContext != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL."); + Debug.Assert(_outputStream is not null, "'m_OutputStream' MUST NOT be NULL."); + Debug.Assert(_outputStream.InternalHttpContext is not null, "'m_OutputStream.InternalHttpContext' MUST NOT be NULL."); - Debug.Assert(_outputStream.InternalHttpContext.Response != null, + Debug.Assert(_outputStream.InternalHttpContext.Response is not null, "'m_OutputStream.InternalHttpContext.Response' MUST NOT be NULL."); Debug.Assert(_outputStream.InternalHttpContext.Response.SentHeaders, "Headers MUST have been sent at this point."); @@ -685,15 +685,15 @@ public void SwitchToOpaqueMode(WebSocketBase webSocket) private static void OnWriteCompleted(object? sender, HttpListenerAsyncEventArgs eventArgs) { - Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); + Debug.Assert(eventArgs is not null, "'eventArgs' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream; - Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); + Debug.Assert(thisPtr is not null, "'thisPtr' MUST NOT be NULL."); #if DEBUG Debug.Assert(Interlocked.Decrement(ref thisPtr._outstandingOperations._writes) >= 0, "'thisPtr.m_OutstandingOperations.m_Writes' MUST NOT be negative."); #endif - if (eventArgs.Exception != null) + if (eventArgs.Exception is not null) { thisPtr._writeTaskCompletionSource!.TrySetException(eventArgs.Exception); } @@ -705,15 +705,15 @@ private static void OnWriteCompleted(object? sender, HttpListenerAsyncEventArgs private static void OnReadCompleted(object? sender, HttpListenerAsyncEventArgs eventArgs) { - Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); + Debug.Assert(eventArgs is not null, "'eventArgs' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream; - Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); + Debug.Assert(thisPtr is not null, "'thisPtr' MUST NOT be NULL."); #if DEBUG Debug.Assert(Interlocked.Decrement(ref thisPtr._outstandingOperations._reads) >= 0, "'thisPtr.m_OutstandingOperations.m_Reads' MUST NOT be negative."); #endif - if (eventArgs.Exception != null) + if (eventArgs.Exception is not null) { thisPtr._readTaskCompletionSource!.TrySetException(eventArgs.Exception); } @@ -790,11 +790,11 @@ public IList>? BufferList set { Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point."); - Debug.Assert(value == null || _buffer == null, + Debug.Assert(value is null || _buffer is null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); Debug.Assert(_operating == Free, "This property can only be modified if no IO operation is outstanding."); - Debug.Assert(value == null || value.Count == 2, + Debug.Assert(value is null || value.Count == 2, "This list can only be 'NULL' or MUST have exactly '2' items."); _bufferList = value; } @@ -824,7 +824,7 @@ public ushort EntityChunkCount { get { - if (_dataChunks == null) + if (_dataChunks is null) { return 0; } @@ -848,7 +848,7 @@ public IntPtr EntityChunks { get { - if (_dataChunks == null) + if (_dataChunks is null) { return IntPtr.Zero; } @@ -917,7 +917,7 @@ private unsafe void FreeOverlapped(bool checkForShutdown) if (!checkForShutdown || !Environment.HasShutdownStarted) { // Free the overlapped object - if (_ptrNativeOverlapped != null) + if (_ptrNativeOverlapped is not null) { #if DEBUG DebugRefCountReleaseNativeOverlapped(); @@ -981,7 +981,7 @@ internal void StartOperationSend() public void SetBuffer(byte[]? buffer, int offset, int count) { Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point."); - Debug.Assert(buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); + Debug.Assert(buffer is null || _bufferList is null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); _buffer = buffer; _offset = offset; _count = count; @@ -989,7 +989,7 @@ public void SetBuffer(byte[]? buffer, int offset, int count) private unsafe void UpdateDataChunk() { - if (_dataChunks == null) + if (_dataChunks is null) { _dataChunks = new Interop.HttpApi.HTTP_DATA_CHUNK[2]; _dataChunksGCHandle = GCHandle.Alloc(_dataChunks, GCHandleType.Pinned); @@ -999,19 +999,19 @@ private unsafe void UpdateDataChunk() _dataChunks[1].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory; } - Debug.Assert(_buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); - Debug.Assert(_shouldCloseOutput || _buffer != null || _bufferList != null, "Either 'm_Buffer' or 'm_BufferList' MUST NOT be NULL."); + Debug.Assert(_buffer is null || _bufferList is null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); + Debug.Assert(_shouldCloseOutput || _buffer is not null || _bufferList is not null, "Either 'm_Buffer' or 'm_BufferList' MUST NOT be NULL."); // The underlying byte[] m_Buffer or each m_BufferList[].Array are pinned already - if (_buffer != null) + if (_buffer is not null) { UpdateDataChunk(0, _buffer, _offset, _count); UpdateDataChunk(1, null, 0, 0); _dataChunkCount = 1; } - else if (_bufferList != null) + else if (_bufferList is not null) { - Debug.Assert(_bufferList != null && _bufferList.Count == 2, + Debug.Assert(_bufferList is not null && _bufferList.Count == 2, "'m_BufferList' MUST NOT be NULL and have exactly '2' items at this point."); UpdateDataChunk(0, _bufferList[0].Array, _bufferList[0].Offset, _bufferList[0].Count); UpdateDataChunk(1, _bufferList[1].Array, _bufferList[1].Offset, _bufferList[1].Count); @@ -1026,7 +1026,7 @@ private unsafe void UpdateDataChunk() private unsafe void UpdateDataChunk(int index, byte[]? buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { _dataChunks![index].pBuffer = null; _dataChunks![index].BufferLength = 0; @@ -1090,12 +1090,12 @@ internal void FinishOperationSuccess(int bytesTransferred, bool syncCompletion) if (NetEventSource.Log.IsEnabled()) { - if (_buffer != null && NetEventSource.Log.IsEnabled()) + if (_buffer is not null && NetEventSource.Log.IsEnabled()) { string methodName = _completedOperation == HttpListenerAsyncOperation.Receive ? nameof(ReadAsyncFast) : nameof(WriteAsyncFast); NetEventSource.DumpBuffer(_currentStream, _buffer, _offset, bytesTransferred, methodName); } - else if (_bufferList != null) + else if (_bufferList is not null) { Debug.Assert(_completedOperation == HttpListenerAsyncOperation.Send, "'BufferList' is only supported for send operations."); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs index 2402dd36c0f09e..95291e69da0c6b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs @@ -156,7 +156,7 @@ internal static string GetSupportedVersion() int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null!, 0, out webSocketHandle); ThrowOnError(errorCode); - if (webSocketHandle == null || + if (webSocketHandle is null || webSocketHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); @@ -189,13 +189,13 @@ internal static string GetSupportedVersion() break; } } - Debug.Assert(version != null, "'version' MUST NOT be NULL."); + Debug.Assert(version is not null, "'version' MUST NOT be NULL."); return version; } finally { - if (webSocketHandle != null) + if (webSocketHandle is not null) { webSocketHandle.Dispose(); } @@ -207,8 +207,8 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr out SafeWebSocketHandle webSocketHandle) { Debug.Assert(propertyCount >= 0, "'propertyCount' MUST NOT be negative."); - Debug.Assert((properties == null && propertyCount == 0) || - (properties != null && propertyCount == properties.Length), + Debug.Assert((properties is null && propertyCount == 0) || + (properties is not null && propertyCount == properties.Length), "'propertyCount' MUST MATCH 'properties.Length'."); if (!IsSupported) @@ -219,7 +219,7 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties!, (uint)propertyCount, out webSocketHandle); ThrowOnError(errorCode); - if (webSocketHandle == null || + if (webSocketHandle is null || webSocketHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); @@ -252,12 +252,12 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr ThrowOnError(errorCode); - Debug.Assert(webSocketHandle != null, "'webSocketHandle' MUST NOT be NULL at this point."); + Debug.Assert(webSocketHandle is not null, "'webSocketHandle' MUST NOT be NULL at this point."); } internal static void WebSocketAbortHandle(SafeHandle webSocketHandle) { - Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, + Debug.Assert(webSocketHandle is not null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); Interop.WebSocket.WebSocketAbortHandle(webSocketHandle); @@ -276,9 +276,9 @@ internal static void WebSocketSend(WebSocketBase webSocket, BufferType bufferType, Interop.WebSocket.Buffer buffer) { - Debug.Assert(webSocket != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL or INVALID."); - Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, + Debug.Assert(webSocket.SessionHandle is not null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); @@ -299,9 +299,9 @@ internal static void WebSocketSend(WebSocketBase webSocket, internal static void WebSocketSendWithoutBody(WebSocketBase webSocket, BufferType bufferType) { - Debug.Assert(webSocket != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL or INVALID."); - Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, + Debug.Assert(webSocket.SessionHandle is not null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); @@ -321,9 +321,9 @@ internal static void WebSocketSendWithoutBody(WebSocketBase webSocket, internal static void WebSocketReceive(WebSocketBase webSocket) { - Debug.Assert(webSocket != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL or INVALID."); - Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, + Debug.Assert(webSocket.SessionHandle is not null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); @@ -349,13 +349,13 @@ internal static void WebSocketGetAction(WebSocketBase webSocket, out BufferType bufferType, out IntPtr actionContext) { - Debug.Assert(webSocket != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL or INVALID."); - Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, + Debug.Assert(webSocket.SessionHandle is not null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(dataBufferCount >= 0, "'dataBufferCount' MUST NOT be negative."); - Debug.Assert((dataBuffers == null && dataBufferCount == 0) || - (dataBuffers != null && dataBufferCount == dataBuffers.Length), + Debug.Assert((dataBuffers is null && dataBufferCount == 0) || + (dataBuffers is not null && dataBufferCount == dataBuffers.Length), "'dataBufferCount' MUST MATCH 'dataBuffers.Length'."); action = Action.NoAction; @@ -386,7 +386,7 @@ internal static void WebSocketGetAction(WebSocketBase webSocket, webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers!, dataBufferCount); Debug.Assert(dataBufferCount >= 0); - Debug.Assert((dataBufferCount == 0 && dataBuffers == null) || + Debug.Assert((dataBufferCount == 0 && dataBuffers is null) || (dataBufferCount <= dataBuffers!.Length)); } @@ -394,9 +394,9 @@ internal static void WebSocketCompleteAction(WebSocketBase webSocket, IntPtr actionContext, int bytesTransferred) { - Debug.Assert(webSocket != null, + Debug.Assert(webSocket is not null, "'webSocket' MUST NOT be NULL or INVALID."); - Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, + Debug.Assert(webSocket.SessionHandle is not null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(actionContext != IntPtr.Zero, "'actionContext' MUST NOT be IntPtr.Zero."); Debug.Assert(bytesTransferred >= 0, "'bytesTransferred' MUST NOT be negative."); @@ -417,7 +417,7 @@ internal static void WebSocketCompleteAction(WebSocketBase webSocket, private static void DrainActionQueue(SafeHandle webSocketHandle, ActionQueue actionQueue) { - Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, + Debug.Assert(webSocketHandle is not null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); IntPtr actionContext; @@ -468,8 +468,8 @@ private static void MarshalAndVerifyHttpHeader(IntPtr httpHeaderPtr, httpHeader.Name = Marshal.PtrToStringAnsi(httpHeaderNamePtr, length); } - if ((httpHeader.Name == null && length != 0) || - (httpHeader.Name != null && length != httpHeader.Name.Length)) + if ((httpHeader.Name is null && length != 0) || + (httpHeader.Name is not null && length != httpHeader.Name.Length)) { Debug.Fail("The length of 'httpHeader.Name' MUST MATCH 'length'."); throw new AccessViolationException(); @@ -491,8 +491,8 @@ private static void MarshalAndVerifyHttpHeader(IntPtr httpHeaderPtr, length = Marshal.ReadInt32(lengthPtr); httpHeader.Value = Marshal.PtrToStringAnsi(httpHeaderValuePtr, (int)length); - if ((httpHeader.Value == null && length != 0) || - (httpHeader.Value != null && length != httpHeader.Value.Length)) + if ((httpHeader.Value is null && length != 0) || + (httpHeader.Value is not null && length != httpHeader.Value.Length)) { Debug.Fail("The length of 'httpHeader.Value' MUST MATCH 'length'."); throw new AccessViolationException(); @@ -524,7 +524,7 @@ private static Interop.WebSocket.HttpHeader[] MarshalHttpHeaders(IntPtr nativeHe MarshalAndVerifyHttpHeader(currentHttpHeaderPtr, ref httpHeaders[i]); } - Debug.Assert(httpHeaders != null); + Debug.Assert(httpHeaders is not null); Debug.Assert(httpHeaders.Length == nativeHeaderCount); return httpHeaders; diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs index 942db43c71bd8b..b4bdccd5c8d461 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs @@ -352,7 +352,7 @@ private static object GetHostEntryOrAddressesCore(IPAddress address, bool justAd if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(address, $"{address} DNS lookup failed with {errorCode}"); throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode); } - Debug.Assert(name != null); + Debug.Assert(name is not null); } catch when (LogFailure(stopwatch)) { diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs index add10313ccd448..2fc365df046204 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs @@ -47,7 +47,7 @@ private static unsafe void ParseHostEntry(Interop.Sys.HostEntry hostEntry, bool { try { - hostName = !justAddresses && hostEntry.CanonicalName != null ? + hostName = !justAddresses && hostEntry.CanonicalName is not null ? Marshal.PtrToStringAnsi((IntPtr)hostEntry.CanonicalName) : null; @@ -89,10 +89,10 @@ private static unsafe void ParseHostEntry(Interop.Sys.HostEntry hostEntry, bool } string[] localAliases = Array.Empty(); - if (!justAddresses && hostEntry.Aliases != null) + if (!justAddresses && hostEntry.Aliases is not null) { int numAliases = 0; - while (hostEntry.Aliases[numAliases] != null) + while (hostEntry.Aliases[numAliases] is not null) { numAliases++; } diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs index 1de610f86e5724..11539badfe1c1d 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs @@ -71,7 +71,7 @@ public static unsafe SocketError TryGetAddrInfo(string name, bool justAddresses, } finally { - if (result != null) + if (result is not null) { Interop.Winsock.FreeAddrInfoW(result); } @@ -208,11 +208,11 @@ private static unsafe void ProcessResult(SocketError errorCode, GetAddrInfoExCon private static unsafe IPAddress[] ParseAddressInfo(Interop.Winsock.AddressInfo* addressInfoPtr, bool justAddresses, out string? hostName) { - Debug.Assert(addressInfoPtr != null); + Debug.Assert(addressInfoPtr is not null); // Count how many results we have. int addressCount = 0; - for (Interop.Winsock.AddressInfo* result = addressInfoPtr; result != null; result = result->ai_next) + for (Interop.Winsock.AddressInfo* result = addressInfoPtr; result is not null; result = result->ai_next) { int addressLength = (int)result->ai_addrlen; @@ -236,9 +236,9 @@ private static unsafe IPAddress[] ParseAddressInfo(Interop.Winsock.AddressInfo* var addresses = new IPAddress[addressCount]; addressCount = 0; string? canonicalName = justAddresses ? "NONNULLSENTINEL" : null; - for (Interop.Winsock.AddressInfo* result = addressInfoPtr; result != null; result = result->ai_next) + for (Interop.Winsock.AddressInfo* result = addressInfoPtr; result is not null; result = result->ai_next) { - if (canonicalName == null && result->ai_canonname != null) + if (canonicalName is null && result->ai_canonname is not null) { canonicalName = Marshal.PtrToStringUni((IntPtr)result->ai_canonname); } @@ -268,11 +268,11 @@ private static unsafe IPAddress[] ParseAddressInfo(Interop.Winsock.AddressInfo* private static unsafe IPAddress[] ParseAddressInfoEx(Interop.Winsock.AddressInfoEx* addressInfoExPtr, bool justAddresses, out string? hostName) { - Debug.Assert(addressInfoExPtr != null); + Debug.Assert(addressInfoExPtr is not null); // First count how many address results we have. int addressCount = 0; - for (Interop.Winsock.AddressInfoEx* result = addressInfoExPtr; result != null; result = result->ai_next) + for (Interop.Winsock.AddressInfoEx* result = addressInfoExPtr; result is not null; result = result->ai_next) { int addressLength = (int)result->ai_addrlen; @@ -296,9 +296,9 @@ private static unsafe IPAddress[] ParseAddressInfoEx(Interop.Winsock.AddressInfo var addresses = new IPAddress[addressCount]; addressCount = 0; string? canonicalName = justAddresses ? "NONNULLSENTINEL" : null; - for (Interop.Winsock.AddressInfoEx* result = addressInfoExPtr; result != null; result = result->ai_next) + for (Interop.Winsock.AddressInfoEx* result = addressInfoExPtr; result is not null; result = result->ai_next) { - if (canonicalName == null && result->ai_canonname != IntPtr.Zero) + if (canonicalName is null && result->ai_canonname != IntPtr.Zero) { canonicalName = Marshal.PtrToStringUni(result->ai_canonname); } @@ -434,7 +434,7 @@ private unsafe struct GetAddrInfoExContext public static void FreeContext(GetAddrInfoExContext* context) { - if (context->Result != null) + if (context->Result is not null) { Interop.Winsock.FreeAddrInfoExW(context->Result); } diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionTelemetry.cs b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionTelemetry.cs index 81cc5f62597c39..6972481c048f8b 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionTelemetry.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionTelemetry.cs @@ -57,7 +57,7 @@ protected override void OnEventCommand(EventCommandEventArgs command) [NonEvent] public ValueStopwatch BeforeResolution(string hostNameOrAddress) { - Debug.Assert(hostNameOrAddress != null); + Debug.Assert(hostNameOrAddress is not null); if (IsEnabled()) { @@ -77,7 +77,7 @@ public ValueStopwatch BeforeResolution(string hostNameOrAddress) [NonEvent] public ValueStopwatch BeforeResolution(IPAddress address) { - Debug.Assert(address != null); + Debug.Assert(address is not null); if (IsEnabled()) { @@ -117,7 +117,7 @@ public void AfterResolution(ValueStopwatch stopwatch, bool successful) [NonEvent] private static Span FormatIPAddressNullTerminated(IPAddress address, Span destination) { - Debug.Assert(address != null); + Debug.Assert(address is not null); bool success = address.TryFormat(destination, out int charsWritten); Debug.Assert(success); diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs index ed79226a7574f6..5eb1d635267f5e 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs @@ -55,7 +55,7 @@ public static unsafe NetworkInterface[] GetBsdNetworkInterfaces() } catch (Exception e) { - if (exceptions == null) + if (exceptions is null) { exceptions = new List(); } @@ -71,7 +71,7 @@ public static unsafe NetworkInterface[] GetBsdNetworkInterfaces() } catch (Exception e) { - if (exceptions == null) + if (exceptions is null) { exceptions = new List(); } @@ -87,14 +87,14 @@ public static unsafe NetworkInterface[] GetBsdNetworkInterfaces() } catch (Exception e) { - if (exceptions == null) + if (exceptions is null) { exceptions = new List(); } exceptions.Add(e); } }); - if (exceptions != null) + if (exceptions is not null) { throw new NetworkInformationException(SR.net_PInvokeError, new AggregateException(exceptions)); } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs index aae4821a4490b3..a3a6045a3d50da 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs @@ -54,12 +54,12 @@ public GatewayIPAddressInformationCollection GetGatewayAddresses(LinuxNetworkInt { List collection = new List(); - if (systemProperties.IPv4Routes != null) + if (systemProperties.IPv4Routes is not null) { StringParsingHelpers.ParseIPv4GatewayAddressesFromRouteFile(collection, systemProperties.IPv4Routes, _linuxNetworkInterface.Name); } - if (systemProperties.IPv6Routes != null) + if (systemProperties.IPv6Routes is not null) { StringParsingHelpers.ParseIPv6GatewayAddressesFromRouteFile(collection, systemProperties.IPv6Routes, _linuxNetworkInterface.Name, _linuxNetworkInterface.Index); } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.OSX.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.OSX.cs index 5ffb9297f77deb..d718be7531587a 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.OSX.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.OSX.cs @@ -44,7 +44,7 @@ public static event NetworkAddressChangedEventHandler? NetworkAddressChanged { add { - if (value != null) + if (value is not null) { lock (s_lockObj) { @@ -60,7 +60,7 @@ public static event NetworkAddressChangedEventHandler? NetworkAddressChanged } remove { - if (value != null) + if (value is not null) { lock (s_lockObj) { @@ -81,7 +81,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC { add { - if (value != null) + if (value is not null) { lock (s_lockObj) { @@ -101,7 +101,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC } remove { - if (value != null) + if (value is not null) { lock (s_lockObj) { @@ -121,7 +121,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC private static unsafe void CreateAndStartRunLoop() { - Debug.Assert(s_dynamicStoreRef == null); + Debug.Assert(s_dynamicStoreRef is null); Interop.SystemConfiguration.SCDynamicStoreContext storeContext = default; using (SafeCreateHandle storeName = Interop.CoreFoundation.CFStringCreateWithCString("NetworkAddressChange.OSX")) @@ -217,8 +217,8 @@ private static void RunLoopThreadStart() private static void StopRunLoop() { Debug.Assert(s_runLoop != IntPtr.Zero); - Debug.Assert(s_runLoopSource != null); - Debug.Assert(s_dynamicStoreRef != null); + Debug.Assert(s_runLoopSource is not null); + Debug.Assert(s_dynamicStoreRef is not null); // Allow RunLoop to finish current processing. SpinWait.SpinUntil(() => Interop.RunLoop.CFRunLoopIsWaiting(s_runLoop)); @@ -244,7 +244,7 @@ private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr in } } - if (addressChangedSubscribers != null) + if (addressChangedSubscribers is not null) { foreach (KeyValuePair subscriber in addressChangedSubscribers) @@ -252,7 +252,7 @@ private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr in NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext? ec = subscriber.Value; - if (ec == null) // Flow supressed + if (ec is null) // Flow supressed { handler(null, EventArgs.Empty); } @@ -263,7 +263,7 @@ private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr in } } - if (availabilityChangedSubscribers != null) + if (availabilityChangedSubscribers is not null) { bool isAvailable = NetworkInterface.GetIsNetworkAvailable(); NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; @@ -274,7 +274,7 @@ private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr in NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext? ec = subscriber.Value; - if (ec == null) // Flow supressed + if (ec is null) // Flow supressed { handler(null, args); } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs index ac4ccb1b36d31b..c4329ef6bd9f2c 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs @@ -30,7 +30,7 @@ public static event NetworkAddressChangedEventHandler? NetworkAddressChanged { add { - if (value != null) + if (value is not null) { lock (s_gate) { @@ -45,7 +45,7 @@ public static event NetworkAddressChangedEventHandler? NetworkAddressChanged } remove { - if (value != null) + if (value is not null) { lock (s_gate) { @@ -70,7 +70,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC { add { - if (value != null) + if (value is not null) { lock (s_gate) { @@ -79,7 +79,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC CreateSocket(); } - if (s_availabilityTimer == null) + if (s_availabilityTimer is null) { // Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever bool restoreFlow = false; @@ -107,7 +107,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC } remove { - if (value != null) + if (value is not null) { lock (s_gate) { @@ -121,7 +121,7 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC s_availabilityChangedSubscribers.Remove(value); if (s_availabilityChangedSubscribers.Count == 0) { - if (s_availabilityTimer != null) + if (s_availabilityTimer is not null) { s_availabilityTimer.Dispose(); s_availabilityTimer = null; @@ -200,7 +200,7 @@ private static void OnSocketEvent(Interop.Sys.NetworkChangeKind kind) case Interop.Sys.NetworkChangeKind.AvailabilityChanged: lock (s_gate) { - if (s_availabilityTimer != null) + if (s_availabilityTimer is not null) { if (!s_availabilityHasChanged) { @@ -225,7 +225,7 @@ private static void OnAddressChanged() } } - if (addressChangedSubscribers != null) + if (addressChangedSubscribers is not null) { foreach (KeyValuePair subscriber in addressChangedSubscribers) @@ -233,7 +233,7 @@ private static void OnAddressChanged() NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext? ec = subscriber.Value; - if (ec == null) // Flow supressed + if (ec is null) // Flow supressed { handler(null, EventArgs.Empty); } @@ -263,7 +263,7 @@ private static void OnAvailabilityTimerFired(object? state) } } - if (availabilityChangedSubscribers != null) + if (availabilityChangedSubscribers is not null) { bool isAvailable = NetworkInterface.GetIsNetworkAvailable(); NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; @@ -275,7 +275,7 @@ private static void OnAvailabilityTimerFired(object? state) NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext? ec = subscriber.Value; - if (ec == null) // Flow supressed + if (ec is null) // Flow supressed { handler(null, args); } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs index 6f644daafe4923..2040adad7cc01b 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs @@ -63,7 +63,7 @@ private static void ChangedAddress(object? sender, EventArgs eventArgs) } // Executing user callbacks if Availability Change event occured. - if (availabilityChangedSubscribers != null) + if (availabilityChangedSubscribers is not null) { bool isAvailable = s_isAvailable; NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; @@ -75,7 +75,7 @@ private static void ChangedAddress(object? sender, EventArgs eventArgs) NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext? ec = subscriber.Value; - if (ec == null) // Flow supressed + if (ec is null) // Flow supressed { handler(null, args); } @@ -89,7 +89,7 @@ private static void ChangedAddress(object? sender, EventArgs eventArgs) internal static void Start(NetworkAvailabilityChangedEventHandler? caller) { - if (caller != null) + if (caller is not null) { lock (s_globalLock) { @@ -106,7 +106,7 @@ internal static void Start(NetworkAvailabilityChangedEventHandler? caller) internal static void Stop(NetworkAvailabilityChangedEventHandler? caller) { - if (caller != null) + if (caller is not null) { lock (s_globalLock) { @@ -166,7 +166,7 @@ private static void AddressChangedCallback(object? stateObject, bool signaled) } // Release the lock before calling into user callback. - if (addressChangedSubscribers != null) + if (addressChangedSubscribers is not null) { foreach (KeyValuePair subscriber in addressChangedSubscribers) @@ -174,7 +174,7 @@ private static void AddressChangedCallback(object? stateObject, bool signaled) NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext? ec = subscriber.Value; - if (ec == null) // Flow supressed + if (ec is null) // Flow supressed { handler(null, EventArgs.Empty); } @@ -201,7 +201,7 @@ private static void StartHelper(NetworkAddressChangedEventHandler? caller, bool lock (s_globalLock) { // Setup changedEvent and native overlapped struct. - if (s_ipv4Socket == null) + if (s_ipv4Socket is null) { // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) @@ -217,7 +217,7 @@ private static void StartHelper(NetworkAddressChangedEventHandler? caller, bool } } - if (caller != null) + if (caller is not null) { s_addressChangedSubscribers.TryAdd(caller, captureContext ? ExecutionContext.Capture() : null); } @@ -309,7 +309,7 @@ private static void StartHelper(NetworkAddressChangedEventHandler? caller, bool internal static void Stop(NetworkAddressChangedEventHandler? caller) { - if (caller != null) + if (caller is not null) { lock (s_globalLock) { diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/PhysicalAddress.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/PhysicalAddress.cs index f2203d56bfe080..a44222bdec1564 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/PhysicalAddress.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/PhysicalAddress.cs @@ -62,7 +62,7 @@ public override int GetHashCode() public override bool Equals(object? comparand) { PhysicalAddress? address = comparand as PhysicalAddress; - if (address == null) + if (address is null) { return false; } @@ -98,7 +98,7 @@ public byte[] GetAddressBytes() return (byte[])_address.Clone(); } - public static PhysicalAddress Parse(string? address) => address != null ? Parse(address.AsSpan()) : None; + public static PhysicalAddress Parse(string? address) => address is not null ? Parse(address.AsSpan()) : None; public static PhysicalAddress Parse(ReadOnlySpan address) { @@ -110,7 +110,7 @@ public static PhysicalAddress Parse(ReadOnlySpan address) public static bool TryParse(string? address, [NotNullWhen(true)] out PhysicalAddress? value) { - if (address == null) + if (address is null) { value = None; return true; diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Misc.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Misc.cs index 54487eb46b22b1..df01d9e35a747d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Misc.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Misc.cs @@ -75,7 +75,7 @@ internal static int ParseRawHexFileAsInt(string filePath) private static int CountOccurrences(string value, string candidate) { - Debug.Assert(candidate != null, "CountOccurrences: Candidate string was null."); + Debug.Assert(candidate is not null, "CountOccurrences: Candidate string was null."); int index = 0; int occurrences = 0; while (index != -1) diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs index 1b74bf1869b105..8163991896364f 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs @@ -54,7 +54,7 @@ private TeredoHelper(Action callback, object state) // 'Unsafe' because it does not flow ExecutionContext to the callback. public static bool UnsafeNotifyStableUnicastIpAddressTable(Action callback, object state) { - if (callback == null) + if (callback is null) { NetEventSource.Fail(null, "UnsafeNotifyStableUnicastIpAddressTable called without specifying callback!"); } @@ -77,7 +77,7 @@ public static bool UnsafeNotifyStableUnicastIpAddressTable(Action callba err = Interop.IpHlpApi.NotifyStableUnicastIpAddressTable(AddressFamily.Unspecified, out table, helper._onStabilizedDelegate, IntPtr.Zero, out helper._cancelHandle); - if (table != null) + if (table is not null) { table.Dispose(); } @@ -130,7 +130,7 @@ private void RunCallback(object? o) s_pendingNotifications.Remove(this); #endif - if ((_cancelHandle == null || _cancelHandle.IsInvalid)) + if ((_cancelHandle is null || _cancelHandle.IsInvalid)) { NetEventSource.Fail(null, "Invalid cancelHandle in RunCallback"); } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPInterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPInterfaceProperties.cs index ebef09314021be..ca8f7acf64db4d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPInterfaceProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPInterfaceProperties.cs @@ -45,7 +45,7 @@ public override bool IsDnsEnabled { get { - if (_dnsAddresses == null) + if (_dnsAddresses is null) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } @@ -58,7 +58,7 @@ public sealed override string DnsSuffix { get { - if (_dnsSuffix == null) + if (_dnsSuffix is null) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } @@ -71,7 +71,7 @@ public sealed override IPAddressCollection DnsAddresses { get { - if (_dnsAddresses == null) + if (_dnsAddresses is null) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } @@ -95,7 +95,7 @@ private static MulticastIPAddressInformationCollection GetMulticastAddresses(Uni { var collection = new MulticastIPAddressInformationCollection(); - if (uni.MulticastAddresess != null) + if (uni.MulticastAddresess is not null) { foreach (IPAddress address in uni.MulticastAddresess) { diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs index d248c72b6930cf..8a4a13aaf8f05d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs @@ -69,7 +69,7 @@ protected void AddAddress(IPAddress ipAddress, int prefix) { if (IPAddressUtil.IsMulticast(ipAddress)) { - if (_multicastAddresses == null) + if (_multicastAddresses is null) { // Deferred initialization. _multicastAddresses = new List(); diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs index 44ac5729415f56..82dde82f28b65c 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs @@ -56,7 +56,7 @@ private unsafe SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, in IpHeader iph = default; bool ipv4 = address.AddressFamily == AddressFamily.InterNetwork; - bool sendIpHeader = ipv4 && options != null && SendIpHeader; + bool sendIpHeader = ipv4 && options is not null && SendIpHeader; if (sendIpHeader) { @@ -96,12 +96,12 @@ private Socket GetRawSocket(SocketConfig socketConfig) socket.DualMode = false; } - if (socketConfig.Options != null && socketConfig.Options.Ttl > 0) + if (socketConfig.Options is not null && socketConfig.Options.Ttl > 0) { socket.Ttl = (short)socketConfig.Options.Ttl; } - if (socketConfig.Options != null && addrFamily == AddressFamily.InterNetwork) + if (socketConfig.Options is not null && addrFamily == AddressFamily.InterNetwork) { if (SendIpHeader) { @@ -281,13 +281,13 @@ private Process GetPingProcess(IPAddress address, byte[] buffer, int timeout, Pi { bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork; string? pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath; - if (pingExecutable == null) + if (pingExecutable is null) { throw new PlatformNotSupportedException(SR.net_ping_utility_not_found); } UnixCommandLinePing.PingFragmentOptions fragmentOption = UnixCommandLinePing.PingFragmentOptions.Default; - if (options != null && address.AddressFamily == AddressFamily.InterNetwork) + if (options is not null && address.AddressFamily == AddressFamily.InterNetwork) { fragmentOption = options.DontFragment ? UnixCommandLinePing.PingFragmentOptions.Do : UnixCommandLinePing.PingFragmentOptions.Dont; } diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs index 3ded687bcf4a3a..71ec5be23baa1d 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs @@ -57,7 +57,7 @@ private Task DoSendPingCore(IPAddress address, byte[] buffer, int tim // Cache correct handle. InitialiseIcmpHandle(); - if (_replyBuffer == null) + if (_replyBuffer is null) { _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket); } @@ -94,7 +94,7 @@ private Task DoSendPingCore(IPAddress address, byte[] buffer, int tim } } - if (tcs != null) + if (tcs is not null) { return tcs.Task; } @@ -105,7 +105,7 @@ private Task DoSendPingCore(IPAddress address, byte[] buffer, int tim private void RegisterWaitHandle() { - if (_pingEvent == null) + if (_pingEvent is null) { _pingEvent = new ManualResetEvent(false); } @@ -121,7 +121,7 @@ private void UnregisterWaitHandle() { lock (_lockObject) { - if (_registeredWait != null) + if (_registeredWait is not null) { // If Unregister returns false, it is sufficient to nullify registeredWait // and let its own finalizer clean up later. @@ -143,7 +143,7 @@ private SafeWaitHandle GetWaitHandle(bool async) private void InitialiseIcmpHandle() { - if (!_ipv6 && _handlePingV4 == null) + if (!_ipv6 && _handlePingV4 is null) { _handlePingV4 = Interop.IpHlpApi.IcmpCreateFile(); if (_handlePingV4.IsInvalid) @@ -152,7 +152,7 @@ private void InitialiseIcmpHandle() throw new Win32Exception(); // Gets last error. } } - else if (_ipv6 && _handlePingV6 == null) + else if (_ipv6 && _handlePingV6 is null) { _handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile(); if (_handlePingV6.IsInvalid) @@ -230,13 +230,13 @@ private void Cleanup(bool isAsync) partial void InternalDisposeCore() { - if (_handlePingV4 != null) + if (_handlePingV4 is not null) { _handlePingV4.Dispose(); _handlePingV4 = null; } - if (_handlePingV6 != null) + if (_handlePingV6 is not null) { _handlePingV6.Dispose(); _handlePingV6 = null; @@ -244,13 +244,13 @@ partial void InternalDisposeCore() UnregisterWaitHandle(); - if (_pingEvent != null) + if (_pingEvent is not null) { _pingEvent.Dispose(); _pingEvent = null; } - if (_replyBuffer != null) + if (_replyBuffer is not null) { _replyBuffer.Dispose(); _replyBuffer = null; @@ -262,7 +262,7 @@ private void PingCallback() { TaskCompletionSource? tcs = _taskCompletionSource; _taskCompletionSource = null; - Debug.Assert(tcs != null); + Debug.Assert(tcs is not null); PingReply? reply = null; Exception? error = null; @@ -292,13 +292,13 @@ private void PingCallback() { tcs.SetCanceled(); } - else if (reply != null) + else if (reply is not null) { tcs.SetResult(reply); } else { - Debug.Assert(error != null); + Debug.Assert(error is not null); tcs.SetException(error); } } @@ -317,7 +317,7 @@ private unsafe void SetUnmanagedStructures(byte[] buffer) // Releases the unmanaged memory after ping completion. private void FreeUnmanagedStructures() { - if (_requestBuffer != null) + if (_requestBuffer is not null) { _requestBuffer.Dispose(); _requestBuffer = null; diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs index fb16acbb3ec516..149cad4aa23398 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs @@ -42,7 +42,7 @@ public Ping() private void CheckArgs(int timeout, byte[] buffer, PingOptions? options) { CheckDisposed(); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -62,7 +62,7 @@ private void CheckArgs(IPAddress address, int timeout, byte[] buffer, PingOption { CheckArgs(timeout, buffer, options); - if (address == null) + if (address is null) { throw new ArgumentNullException(nameof(address)); } @@ -440,7 +440,7 @@ private byte[] DefaultSendBuffer { get { - if (_defaultSendBuffer == null) + if (_defaultSendBuffer is null) { _defaultSendBuffer = new byte[DefaultSendBufferSize]; for (int i = 0; i < DefaultSendBufferSize; i++) diff --git a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs index dc694bc09ecde7..0bb2d25af339b8 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs @@ -230,7 +230,7 @@ public string Name { if (string.IsNullOrEmpty(value) || !InternalSetName(value)) { - throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value == null ? "" : value)); + throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value is null ? "" : value)); } } } @@ -344,24 +344,24 @@ internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDoma { if (shouldThrow) { - throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", m_name == null ? "" : m_name)); + throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", m_name is null ? "" : m_name)); } return false; } // Check the value - if (m_value == null || + if (m_value is null || (!(m_value.Length > 2 && m_value[0] == '\"' && m_value[m_value.Length - 1] == '\"') && m_value.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { - throw new CookieException(SR.Format(SR.net_cookie_attribute, "Value", m_value == null ? "" : m_value)); + throw new CookieException(SR.Format(SR.net_cookie_attribute, "Value", m_value is null ? "" : m_value)); } return false; } // Check Comment syntax - if (Comment != null && !(Comment.Length > 2 && Comment[0] == '\"' && Comment[Comment.Length - 1] == '\"') + if (Comment is not null && !(Comment.Length > 2 && Comment[0] == '\"' && Comment[Comment.Length - 1] == '\"') && (Comment.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) @@ -372,7 +372,7 @@ internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDoma } // Check Path syntax - if (Path != null && !(Path.Length > 2 && Path[0] == '\"' && Path[Path.Length - 1] == '\"') + if (Path is not null && !(Path.Length > 2 && Path[0] == '\"' && Path[Path.Length - 1] == '\"') && (Path.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) @@ -406,7 +406,7 @@ internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDoma { if (shouldThrow) { - throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, domain == null ? "" : domain)); + throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, domain is null ? "" : domain)); } return false; } @@ -555,7 +555,7 @@ internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDoma // as per RFC 952 (relaxed on first char could be a digit and string can have '_'). private static bool DomainCharsTest(string name) { - if (name == null || name.Length == 0) + if (name is null || name.Length == 0) { return false; } @@ -714,7 +714,7 @@ public override bool Equals(object? comparand) { Cookie? other = comparand as Cookie; - return other != null + return other is not null && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(Value, other.Value, StringComparison.Ordinal) && string.Equals(Path, other.Path, StringComparison.Ordinal) @@ -793,11 +793,11 @@ internal void ToString(StringBuilder sb) internal string? ToServerString() { string result = Name + EqualsLiteral + Value; - if (m_comment != null && m_comment.Length > 0) + if (m_comment is not null && m_comment.Length > 0) { result += SeparatorLiteral + CookieFields.CommentAttributeName + EqualsLiteral + m_comment; } - if (m_commentUri != null) + if (m_commentUri is not null) { result += SeparatorLiteral + CookieFields.CommentUrlAttributeName + EqualsLiteral + QuotesLiteral + m_commentUri.ToString() + QuotesLiteral; } @@ -805,7 +805,7 @@ internal void ToString(StringBuilder sb) { result += SeparatorLiteral + CookieFields.DiscardAttributeName; } - if (!m_domain_implicit && m_domain != null && m_domain.Length > 0) + if (!m_domain_implicit && m_domain is not null && m_domain.Length > 0) { result += SeparatorLiteral + CookieFields.DomainAttributeName + EqualsLiteral + m_domain; } @@ -820,11 +820,11 @@ internal void ToString(StringBuilder sb) } result += SeparatorLiteral + CookieFields.MaxAgeAttributeName + EqualsLiteral + seconds.ToString(NumberFormatInfo.InvariantInfo); } - if (!m_path_implicit && m_path != null && m_path.Length > 0) + if (!m_path_implicit && m_path is not null && m_path.Length > 0) { result += SeparatorLiteral + CookieFields.PathAttributeName + EqualsLiteral + m_path; } - if (!Plain && !m_port_implicit && m_port != null && m_port.Length > 0) + if (!Plain && !m_port_implicit && m_port is not null && m_port.Length > 0) { // QuotesLiteral are included in _port. result += SeparatorLiteral + CookieFields.PortAttributeName + EqualsLiteral + m_port; diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs index 4f6cac5bd156d0..3606ef5e04f9e1 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs @@ -68,7 +68,7 @@ private void OnSerializing(StreamingContext context) public void Add(Cookie cookie) { - if (cookie == null) + if (cookie is null) { throw new ArgumentNullException(nameof(cookie)); } @@ -85,7 +85,7 @@ public void Add(Cookie cookie) public void Add(CookieCollection cookies) { - if (cookies == null) + if (cookies is null) { throw new ArgumentNullException(nameof(cookies)); } 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 9728030b8cd4d6..cdf9991f00eba2 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -140,7 +140,7 @@ public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : private static string CreateFqdnMyDomain() { string domain = HostInformation.DomainName; - return domain != null && domain.Length > 1 ? + return domain is not null && domain.Length > 1 ? '.' + domain : string.Empty; } @@ -221,7 +221,7 @@ public int PerDomainCapacity // This method will construct a faked URI: the Domain property is required for param. public void Add(Cookie cookie) { - if (cookie == null) + if (cookie is null) { throw new ArgumentNullException(nameof(cookie)); } @@ -252,7 +252,7 @@ public void Add(Cookie cookie) // Either keep Port as implicit or set it according to original cookie. - if (cookie.PortList != null) + if (cookie.PortList is not null) { uriSb.Append(':').Append(cookie.PortList[0]); } @@ -290,7 +290,7 @@ internal void Add(Cookie cookie, bool throwOnError) lock (m_domainTable.SyncRoot) { pathList = (PathList?)m_domainTable[cookie.DomainKey]; - if (pathList == null) + if (pathList is null) { m_domainTable[cookie.DomainKey] = (pathList = new PathList()); } @@ -302,7 +302,7 @@ internal void Add(Cookie cookie, bool throwOnError) { cookies = (CookieCollection?)pathList[cookie.Path]!; - if (cookies == null) + if (cookies is null) { cookies = new CookieCollection(); pathList[cookie.Path] = cookies; @@ -368,7 +368,7 @@ internal void Add(Cookie cookie, bool throwOnError) // Also note that expired cookies are also removed during request preparation // (this.GetCookies method). // - // Param. 'domain' == null means to age in the whole container. + // Param. 'domain' is null means to age in the whole container. private bool AgeCookies(string? domain) { Debug.Assert(m_maxCookies != 0); @@ -399,7 +399,7 @@ private bool AgeCookies(string? domain) foreach (object item in m_domainTable) { DictionaryEntry entry = (DictionaryEntry)item; - if (domain == null) + if (domain is null) { tempDomain = (string)entry.Key; pathList = (PathList)entry.Value!; // Aliasing to trick foreach @@ -415,7 +415,7 @@ private bool AgeCookies(string? domain) { foreach (CookieCollection? cc in pathList.Values) { - Debug.Assert(cc != null); + Debug.Assert(cc is not null); itemp = ExpireCollection(cc); removed += itemp; m_count -= itemp; // Update this container's count @@ -473,7 +473,7 @@ private bool AgeCookies(string? domain) } } - if (domain_count > min_count && domain != null) + if (domain_count > min_count && domain is not null) { // Cannot complete aging of explicit domain (no cookie adding allowed). return false; @@ -483,7 +483,7 @@ private bool AgeCookies(string? domain) } // We have completed aging of the specified domain. - if (domain != null) + if (domain is not null) { return true; } @@ -585,7 +585,7 @@ private int ExpireCollection(CookieCollection cc) public void Add(CookieCollection cookies) { - if (cookies == null) + if (cookies is null) { throw new ArgumentNullException(nameof(cookies)); } @@ -596,7 +596,7 @@ public void Add(CookieCollection cookies) } // This will try (if needed) get the full domain name of the host given the Uri. - // NEVER call this function from internal methods with 'fqdnRemote' == null. + // NEVER call this function from internal methods with 'fqdnRemote' is null. // Since this method counts security issue for DNS and hence will slow // the performance. internal bool IsLocalDomain(string host) @@ -623,7 +623,7 @@ internal bool IsLocalDomain(string host) // Test for "127.###.###.###" without using regex. string[] ipParts = host.Split('.'); - if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127") + if (ipParts is not null && ipParts.Length == 4 && ipParts[0] == "127") { int i; for (i = 1; i < ipParts.Length; i++) @@ -665,11 +665,11 @@ internal bool IsLocalDomain(string host) public void Add(Uri uri, Cookie cookie) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } - if (cookie == null) + if (cookie is null) { throw new ArgumentNullException(nameof(cookie)); } @@ -681,11 +681,11 @@ public void Add(Uri uri, Cookie cookie) public void Add(Uri uri, CookieCollection cookies) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } - if (cookies == null) + if (cookies is null) { throw new ArgumentNullException(nameof(cookies)); } @@ -705,7 +705,7 @@ internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCo CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; - if (headerName == null) + if (headerName is null) { variant = CookieVariant.Default; } @@ -729,7 +729,7 @@ internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCo Cookie? cookie = parser.Get(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}"); - if (cookie == null) + if (cookie is null) { if (parser.EndofHeader()) { @@ -783,7 +783,7 @@ internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCo public CookieCollection GetCookies(Uri uri) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } @@ -817,7 +817,7 @@ public CookieCollection GetCookies(Uri uri) // 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 (m_fqdnMyDomain is not null && m_fqdnMyDomain.Length != 0) { domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + m_fqdnMyDomain); // Grab the local domain itself @@ -844,7 +844,7 @@ public CookieCollection GetCookies(Uri uri) { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1) { - if (domainAttributeMatchOnlyCookieVariantPlain == null) + if (domainAttributeMatchOnlyCookieVariantPlain is null) { domainAttributeMatchOnlyCookieVariantPlain = new System.Collections.Generic.List(); } @@ -857,7 +857,7 @@ public CookieCollection GetCookies(Uri uri) } BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchAnyCookieVariant, false); - if (domainAttributeMatchOnlyCookieVariantPlain != null) + if (domainAttributeMatchOnlyCookieVariantPlain is not null) { BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchOnlyCookieVariantPlain, true); } @@ -873,7 +873,7 @@ private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int lock (m_domainTable.SyncRoot) { pathList = (PathList)m_domainTable[domainAttribute[i]]!; - if (pathList == null) + if (pathList is null) { continue; } @@ -952,7 +952,7 @@ private void MergeUpdateCollections(ref CookieCollection? destination, CookieCol { ; // Don't add } - else if (cookie.PortList != null) + else if (cookie.PortList is not null) { foreach (int p in cookie.PortList) { @@ -980,7 +980,7 @@ private void MergeUpdateCollections(ref CookieCollection? destination, CookieCol // In 'source' are already ordered. // If two same cookies come from different 'source' then they // will follow (not replace) each other. - if (destination == null) + if (destination is null) { destination = new CookieCollection(); } @@ -993,7 +993,7 @@ private void MergeUpdateCollections(ref CookieCollection? destination, CookieCol public string GetCookieHeader(Uri uri) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } @@ -1005,7 +1005,7 @@ public string GetCookieHeader(Uri uri) internal string GetCookieHeader(Uri uri, out string optCookie2) { CookieCollection? cookies = InternalGetCookies(uri); - if (cookies == null) + if (cookies is null) { optCookie2 = string.Empty; return string.Empty; @@ -1033,11 +1033,11 @@ internal string GetCookieHeader(Uri uri, out string optCookie2) public void SetCookies(Uri uri, string cookieHeader) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } - if (cookieHeader == null) + if (cookieHeader is null) { throw new ArgumentNullException(nameof(cookieHeader)); } @@ -1093,7 +1093,7 @@ internal object? this[string s] { lock (SyncRoot) { - Debug.Assert(value != null); + Debug.Assert(value is not null); m_list[s] = value; } } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs index ff3f6af1422969..0b387cda372932 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -22,11 +22,11 @@ public CredentialCache() public void Add(Uri uriPrefix, string authType, NetworkCredential cred) { - if (uriPrefix == null) + if (uriPrefix is null) { throw new ArgumentNullException(nameof(uriPrefix)); } - if (authType == null) + if (authType is null) { throw new ArgumentNullException(nameof(authType)); } @@ -46,7 +46,7 @@ public void Add(Uri uriPrefix, string authType, NetworkCredential cred) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{cred.Domain}],[{cred.UserName}]"); - if (_cache == null) + if (_cache is null) { _cache = new Dictionary(); } @@ -56,12 +56,12 @@ public void Add(Uri uriPrefix, string authType, NetworkCredential cred) public void Add(string host, int port, string authenticationType, NetworkCredential credential) { - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } - if (authenticationType == null) + if (authenticationType is null) { throw new ArgumentNullException(nameof(authenticationType)); } @@ -91,7 +91,7 @@ public void Add(string host, int port, string authenticationType, NetworkCredent if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{credential.Domain}],[{credential.UserName}]"); - if (_cacheForHosts == null) + if (_cacheForHosts is null) { _cacheForHosts = new Dictionary(); } @@ -101,14 +101,14 @@ public void Add(string host, int port, string authenticationType, NetworkCredent public void Remove(Uri? uriPrefix, string? authType) { - if (uriPrefix == null || authType == null) + if (uriPrefix is null || authType is null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } - if (_cache == null) + if (_cache is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Short-circuiting because the dictionary is null."); return; @@ -125,7 +125,7 @@ public void Remove(Uri? uriPrefix, string? authType) public void Remove(string? host, int port, string? authenticationType) { - if (host == null || authenticationType == null) + if (host is null || authenticationType is null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). @@ -137,7 +137,7 @@ public void Remove(string? host, int port, string? authenticationType) return; } - if (_cacheForHosts == null) + if (_cacheForHosts is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Short-circuiting because the dictionary is null."); return; @@ -154,16 +154,16 @@ public void Remove(string? host, int port, string? authenticationType) public NetworkCredential? GetCredential(Uri uriPrefix, string authType) { - if (uriPrefix == null) + if (uriPrefix is null) { throw new ArgumentNullException(nameof(uriPrefix)); } - if (authType == null) + if (authType is null) { throw new ArgumentNullException(nameof(authType)); } - if (_cache == null) + if (_cache is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null."); return null; @@ -192,18 +192,18 @@ public void Remove(string? host, int port, string? authenticationType) } } - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Returning {(mostSpecificMatch == null ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Returning {(mostSpecificMatch is null ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")}"); return mostSpecificMatch; } public NetworkCredential? GetCredential(string host, int port, string authenticationType) { - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } - if (authenticationType == null) + if (authenticationType is null) { throw new ArgumentNullException(nameof(authenticationType)); } @@ -216,7 +216,7 @@ public void Remove(string? host, int port, string? authenticationType) throw new ArgumentOutOfRangeException(nameof(port)); } - if (_cacheForHosts == null) + if (_cacheForHosts is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null."); return null; @@ -227,7 +227,7 @@ public void Remove(string? host, int port, string? authenticationType) NetworkCredential? match = null; _cacheForHosts.TryGetValue(key, out match); - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Returning {((match is null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}"); return match; } @@ -242,17 +242,17 @@ private class CredentialEnumerator : IEnumerator { internal static CredentialEnumerator Create(CredentialCache cache) { - Debug.Assert(cache != null); + Debug.Assert(cache is not null); - if (cache._cache != null) + if (cache._cache is not null) { - return cache._cacheForHosts != null ? + return cache._cacheForHosts is not null ? new DoubleTableCredentialEnumerator(cache) : new SingleTableCredentialEnumerator(cache, cache._cache); } else { - return cache._cacheForHosts != null ? + return cache._cacheForHosts is not null ? new SingleTableCredentialEnumerator(cache, cache._cacheForHosts) : new CredentialEnumerator(cache); } @@ -265,7 +265,7 @@ internal static CredentialEnumerator Create(CredentialCache cache) private CredentialEnumerator(CredentialCache cache) { - Debug.Assert(cache != null); + Debug.Assert(cache is not null); _cache = cache; _version = cache._version; @@ -315,7 +315,7 @@ private class SingleTableCredentialEnumerator : CredentialEnumerator where public SingleTableCredentialEnumerator(CredentialCache cache, Dictionary table) : base(cache) { - Debug.Assert(table != null); + Debug.Assert(table is not null); // Despite the ValueCollection allocation, ValueCollection's enumerator is faster // than Dictionary's enumerator for enumerating the values because it avoids @@ -340,7 +340,7 @@ private sealed class DoubleTableCredentialEnumerator : SingleTableCredentialEnum public DoubleTableCredentialEnumerator(CredentialCache cache) : base(cache, cache._cache!) { - Debug.Assert(cache._cacheForHosts != null); + Debug.Assert(cache._cacheForHosts is not null); // Despite the ValueCollection allocation, ValueCollection's enumerator is faster // than Dictionary's enumerator for enumerating the values because it avoids @@ -423,7 +423,7 @@ internal CredentialHostKey(string host, int port, string authenticationType) { Debug.Assert(!string.IsNullOrEmpty(host)); Debug.Assert(port >= 0); - Debug.Assert(authenticationType != null); + Debug.Assert(authenticationType is not null); Host = host; Port = port; @@ -462,8 +462,8 @@ internal sealed class CredentialKey : IEquatable internal CredentialKey(Uri uriPrefix, string authenticationType) { - Debug.Assert(uriPrefix != null); - Debug.Assert(authenticationType != null); + Debug.Assert(uriPrefix is not null); + Debug.Assert(authenticationType is not null); UriPrefix = uriPrefix; UriPrefixLength = UriPrefix.ToString().Length; @@ -472,7 +472,7 @@ internal CredentialKey(Uri uriPrefix, string authenticationType) internal bool Match(Uri uri, string authenticationType) { - if (uri == null || authenticationType == null) + if (uri is null || authenticationType is null) { return false; } @@ -502,8 +502,8 @@ internal bool Match(Uri uri, string authenticationType) // True if is a prefix of this URI private static bool IsPrefix(Uri uri, Uri prefixUri) { - Debug.Assert(uri != null); - Debug.Assert(prefixUri != null); + Debug.Assert(uri is not null); + Debug.Assert(prefixUri is not null); if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port) { @@ -525,7 +525,7 @@ public override int GetHashCode() => public bool Equals(CredentialKey? other) { - if (other == null) + if (other is null) { return false; } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/DnsEndPoint.cs b/src/libraries/System.Net.Primitives/src/System/Net/DnsEndPoint.cs index 0fb78438f5dc8f..b2a05c2935c819 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/DnsEndPoint.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/DnsEndPoint.cs @@ -15,7 +15,7 @@ public DnsEndPoint(string host, int port) : this(host, port, AddressFamily.Unspe public DnsEndPoint(string host, int port, AddressFamily addressFamily) { - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } @@ -46,7 +46,7 @@ public override bool Equals(object? comparand) { DnsEndPoint? dnsComparand = comparand as DnsEndPoint; - if (dnsComparand == null) + if (dnsComparand is null) { return false; } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs index b69763441d75fa..0c2c1a88ed0ba2 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs @@ -57,12 +57,12 @@ public class IPAddress private bool IsIPv4 { - get { return _numbers == null; } + get { return _numbers is null; } } private bool IsIPv6 { - get { return _numbers != null; } + get { return _numbers is not null; } } private uint PrivateAddress @@ -149,7 +149,6 @@ public IPAddress(ReadOnlySpan address, long scopeid) internal IPAddress(ReadOnlySpan numbers, uint scopeid) { - Debug.Assert(numbers != null); Debug.Assert(numbers.Length == NumberOfLabels); var arr = new ushort[NumberOfLabels]; @@ -164,7 +163,7 @@ internal IPAddress(ReadOnlySpan numbers, uint scopeid) private IPAddress(ushort[] numbers, uint scopeid) { - Debug.Assert(numbers != null); + Debug.Assert(numbers is not null); Debug.Assert(numbers.Length == NumberOfLabels); _numbers = numbers; @@ -216,25 +215,25 @@ internal IPAddress(int newAddress) /// public static bool TryParse([NotNullWhen(true)] string? ipString, [NotNullWhen(true)] out IPAddress? address) { - if (ipString == null) + if (ipString is null) { address = null; return false; } address = IPAddressParser.Parse(ipString.AsSpan(), tryParse: true); - return (address != null); + return (address is not null); } public static bool TryParse(ReadOnlySpan ipSpan, [NotNullWhen(true)] out IPAddress? address) { address = IPAddressParser.Parse(ipSpan, tryParse: true); - return (address != null); + return (address is not null); } public static IPAddress Parse(string ipString) { - if (ipString == null) + if (ipString is null) { throw new ArgumentNullException(nameof(ipString)); } @@ -278,7 +277,7 @@ public bool TryWriteBytes(Span destination, out int bytesWritten) [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteIPv6Bytes(Span destination) { - Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels); + Debug.Assert(_numbers is not null && _numbers.Length == NumberOfLabels); int j = 0; for (int i = 0; i < NumberOfLabels; i++) { @@ -306,7 +305,7 @@ public byte[] GetAddressBytes() { if (IsIPv6) { - Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels); + Debug.Assert(_numbers is not null && _numbers.Length == NumberOfLabels); byte[] bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; WriteIPv6Bytes(bytes); return bytes; @@ -371,7 +370,7 @@ public long ScopeId /// public override string ToString() { - if (_toString == null) + if (_toString is null) { _toString = IsIPv4 ? IPAddressParser.IPv4AddressToString(PrivateAddress) : @@ -420,7 +419,7 @@ public static short NetworkToHostOrder(short network) public static bool IsLoopback(IPAddress address) { - if (address == null) + if (address is null) { ThrowAddressNullException(); } @@ -553,7 +552,7 @@ public override bool Equals(object? comparand) internal bool Equals(IPAddress comparand) { - Debug.Assert(comparand != null); + Debug.Assert(comparand is not null); // Compare families before address representations if (AddressFamily != comparand.AddressFamily) diff --git a/src/libraries/System.Net.Primitives/src/System/Net/IPAddressParser.cs b/src/libraries/System.Net.Primitives/src/System/Net/IPAddressParser.cs index 69748554f6d235..4964a76f6b6755 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPAddressParser.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPAddressParser.cs @@ -90,7 +90,7 @@ private static unsafe int IPv4AddressToStringHelper(uint address, char* addressS internal static string IPv6AddressToString(ushort[] address, uint scopeId) { - Debug.Assert(address != null); + Debug.Assert(address is not null); Debug.Assert(address.Length == IPAddressParserStatics.IPv6AddressShorts); StringBuilder buffer = IPv6AddressToStringHelper(address, scopeId); @@ -100,7 +100,7 @@ internal static string IPv6AddressToString(ushort[] address, uint scopeId) internal static bool IPv6AddressToString(ushort[] address, uint scopeId, Span destination, out int charsWritten) { - Debug.Assert(address != null); + Debug.Assert(address is not null); Debug.Assert(address.Length == IPAddressParserStatics.IPv6AddressShorts); StringBuilder buffer = IPv6AddressToStringHelper(address, scopeId); @@ -198,7 +198,6 @@ public static unsafe bool Ipv4StringToAddress(ReadOnlySpan ipSpan, out lon public static unsafe bool Ipv6StringToAddress(ReadOnlySpan ipSpan, Span numbers, int numbersLength, out uint scope) { - Debug.Assert(numbers != null); Debug.Assert(numbersLength >= IPAddressParserStatics.IPv6AddressShorts); int end = ipSpan.Length; diff --git a/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs b/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs index 921f22af6db04c..e8c308d2389ffe 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs @@ -47,7 +47,7 @@ public IPEndPoint(long address, int port) /// public IPEndPoint(IPAddress address, int port) { - if (address == null) + if (address is null) { throw new ArgumentNullException(nameof(address)); } @@ -128,7 +128,7 @@ public static bool TryParse(ReadOnlySpan s, [NotNullWhen(true)] out IPEndP public static IPEndPoint Parse(string s) { - if (s == null) + if (s is null) { throw new ArgumentNullException(nameof(s)); } @@ -156,7 +156,7 @@ public override string ToString() public override EndPoint Create(SocketAddress socketAddress) { - if (socketAddress == null) + if (socketAddress is null) { throw new ArgumentNullException(nameof(socketAddress)); } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs b/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs index da5cb26e81662f..f7fd0eb234c895 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs @@ -85,7 +85,7 @@ public string Password get { SecureString? sstr = _password as SecureString; - if (sstr != null) + if (sstr is not null) { return MarshalToString(sstr); } @@ -106,12 +106,12 @@ public SecureString SecurePassword get { string? str = _password as string; - if (str != null) + if (str is not null) { return MarshalToSecureString(str); } SecureString? sstr = _password as SecureString; - return sstr != null ? sstr.Copy() : new SecureString(); + return sstr is not null ? sstr.Copy() : new SecureString(); } set { @@ -153,7 +153,7 @@ public NetworkCredential GetCredential(string? host, int port, string? authentic private string MarshalToString(SecureString sstr) { - if (sstr == null || sstr.Length == 0) + if (sstr is null || sstr.Length == 0) { return string.Empty; } diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs index 5fb4031b316782..3d10b238ddfda1 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs @@ -87,7 +87,7 @@ internal override bool Connected { CheckDisposed(); - return _state != null; + return _state is not null; } } diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs index d90b7beedebf48..52d575e88c8a22 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs @@ -238,7 +238,7 @@ internal unsafe uint UnsafeGetParam( try { - if (certFilePath != null && privateKeyFilePath != null) + if (certFilePath is not null && privateKeyFilePath is not null) { fileParams = new MsQuicNativeMethods.CertFileParams { @@ -257,7 +257,7 @@ internal unsafe uint UnsafeGetParam( IntPtr.Zero, SecCfgCreateCallbackHandler); } - else if (certificate != null) + else if (certificate is not null) { createConfigStatus = SecConfigCreateDelegate( _registrationContext, diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs index 3a0a353fe73093..676df2e7d06c1a 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs @@ -71,7 +71,7 @@ internal sealed class MsQuicStream : QuicStreamProvider // Creates a new MsQuicStream internal MsQuicStream(MsQuicConnection connection, QUIC_STREAM_OPEN_FLAG flags, IntPtr nativeObjPtr, bool inbound) { - Debug.Assert(connection != null); + Debug.Assert(connection is not null); _ptr = nativeObjPtr; diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicStream.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicStream.cs index 2fe5d79af3fdd3..f8e504911ffaac 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicStream.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicStream.cs @@ -43,7 +43,7 @@ public override void EndWrite(IAsyncResult asyncResult) => private static void ValidateBufferArgs(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs b/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs index b40c800945898f..50f6e5315219c0 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs @@ -34,7 +34,7 @@ internal Authorization(string? token, bool finished, string? connectionGroupId, public string[]? ProtectionRealm { get { return _protectionRealm; } - set { _protectionRealm = value != null && value.Length != 0 ? value : null; } + set { _protectionRealm = value is not null && value.Length != 0 ? value : null; } } public bool MutuallyAuthenticated diff --git a/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs b/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs index 0031514161017e..7cfe960370ba41 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs @@ -59,7 +59,7 @@ internal virtual void Abort(Exception e) } finally { - if (e != null) + if (e is not null) { InvokeRequestCallback(e); } @@ -84,7 +84,7 @@ protected override void Dispose(bool disposing) protected void InvokeRequestCallback(object? obj) { WebRequest? webRequest = _request; - if (webRequest != null) + if (webRequest is not null) { FtpWebRequest ftpWebRequest = (FtpWebRequest)webRequest; ftpWebRequest.RequestCallback(obj); @@ -305,7 +305,7 @@ private bool PostReadCommandProcessing(ref Stream? stream) // Final QUIT command may get exceptions since the connection // may be already closed by the server. So there is no response // to process, just advance the pipeline to continue. - if (_currentResponseDescription == null && entry!.Command == "QUIT\r\n") + if (_currentResponseDescription is null && entry!.Command == "QUIT\r\n") result = PipelineInstruction.Advance; else result = PipelineCallback(entry, _currentResponseDescription, false, ref stream); @@ -663,7 +663,7 @@ private void ReceiveCommandResponseCallback(ReceiveState state, int bytesRead) if (_isAsync) { // Tell who is listening what was received. - if (state.Resp != null) + if (state.Resp is not null) { _currentResponseDescription = state.Resp; } 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 86cb50a5012cb0..f54f7a3c4846df 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs @@ -126,7 +126,7 @@ private void CheckAndMarkAsyncGetRequestStreamPending() throw new ProtocolViolationException(SR.net_nouploadonget); } - if (_response != null) + if (_response is not null) { throw new InvalidOperationException(SR.net_reqsubmitted); } @@ -145,7 +145,7 @@ private Stream CreateWriteStream() { try { - if (_stream == null) + if (_stream is null) { _stream = new WebFileStream(this, _uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read); _fileAccess = FileAccess.Write; diff --git a/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs index 4e311a1a6fcf27..22cfb01f19fd07 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs @@ -114,7 +114,7 @@ public override void Close() _closed = true; Stream? chkStream = _stream; - if (chkStream != null) + if (chkStream is not null) { chkStream.Close(); _stream = null!; diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs index 4fb863569a6b65..5a8ea3adc0fb19 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -52,7 +52,7 @@ internal NetworkCredential? Credentials { get { - if (_credentials != null && _credentials.IsAlive) + if (_credentials is not null && _credentials.IsAlive) { return (NetworkCredential?)_credentials.Target; } @@ -63,7 +63,7 @@ internal NetworkCredential? Credentials } set { - if (_credentials == null) + if (_credentials is null) { _credentials = new WeakReference(null); } @@ -86,7 +86,7 @@ internal FtpControlStream(TcpClient client) internal void AbortConnect() { Socket? socket = _dataSocket; - if (socket != null) + if (socket is not null) { try { @@ -163,13 +163,13 @@ private static void SSLHandshakeCallback(IAsyncResult asyncResult) // In case SSL and ASYNC we delay sigaling the user stream until the handshake is done. private PipelineInstruction QueueOrCreateFtpDataStream(ref Stream? stream) { - if (_dataSocket == null) + if (_dataSocket is null) throw new InternalException(); // // Re-entered pipeline with completed read on the TlsStream // - if (_tlsStream != null) + if (_tlsStream is not null) { stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request!, IsFtpDataStreamWriteable()); _tlsStream = null; @@ -225,7 +225,7 @@ protected override PipelineInstruction PipelineCallback(PipelineEntry? entry, Re if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}"); // null response is not expected - if (response == null) + if (response is null) return PipelineInstruction.Abort; FtpStatusCode status = (FtpStatusCode)response.Status; @@ -329,7 +329,7 @@ protected override PipelineInstruction PipelineCallback(PipelineEntry? entry, Re // if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen) { - if (_dataSocket == null) + if (_dataSocket is null) { return PipelineInstruction.Abort; } @@ -484,7 +484,7 @@ protected override PipelineEntry[] BuildCommandsList(WebRequest req) string domainUserName = string.Empty; string password = string.Empty; - if (Credentials != null) + if (Credentials is not null) { domainUserName = Credentials.UserName; string domain = Credentials.Domain; @@ -543,7 +543,7 @@ protected override PipelineEntry[] BuildCommandsList(WebRequest req) // our relative paths work right and reduces unnecessary CWD commands. // Usually, we don't change the working directory except for some FTP commands. If necessary, // we need to reset our working directory back to the login directory. - if (_establishedServerDirectory != null && _loginDirectory != null && _establishedServerDirectory != _loginDirectory) + if (_establishedServerDirectory is not null && _loginDirectory is not null && _establishedServerDirectory != _loginDirectory) { commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", _loginDirectory), PipelineEntryFlags.UserCommand)); _requestedServerDirectory = _loginDirectory; @@ -687,7 +687,7 @@ private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, Resp PipelineInstruction result; - if (_passiveEndPoint != null) + if (_passiveEndPoint is not null) { IPEndPoint passiveEndPoint = _passiveEndPoint; _passiveEndPoint = null; @@ -849,7 +849,7 @@ internal string? BannerMessage { get { - return (_bannerMessage != null) ? _bannerMessage.ToString() : null; + return (_bannerMessage is not null) ? _bannerMessage.ToString() : null; } } @@ -860,7 +860,7 @@ internal string? WelcomeMessage { get { - return (_welcomeMessage != null) ? _welcomeMessage.ToString() : null; + return (_welcomeMessage is not null) ? _welcomeMessage.ToString() : null; } } @@ -871,7 +871,7 @@ internal string? ExitMessage { get { - return (_exitMessage != null) ? _exitMessage.ToString() : null; + return (_exitMessage is not null) ? _exitMessage.ToString() : null; } } @@ -1123,7 +1123,7 @@ private string GetPortCommandLine(FtpWebRequest request) /// private string FormatFtpCommand(string command, string? parameter) { - StringBuilder stringBuilder = new StringBuilder(command.Length + ((parameter != null) ? parameter.Length : 0) + 3 /*size of ' ' \r\n*/); + StringBuilder stringBuilder = new StringBuilder(command.Length + ((parameter is not null) ? parameter.Length : 0) + 3 /*size of ' ' \r\n*/); stringBuilder.Append(command); if (!string.IsNullOrEmpty(parameter)) { @@ -1228,7 +1228,7 @@ protected override bool CheckValid(ResponseDescription response, ref int validTh private TriState IsFtpDataStreamWriteable() { FtpWebRequest? request = _request as FtpWebRequest; - if (request != null) + if (request is not null) { if (request.MethodInfo.IsUpload) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs index 10fafe3c0b5b11..7b3e7e52025e2e 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs @@ -88,10 +88,10 @@ void ICloseEx.CloseEx(CloseExState closeState) { bool doThrow = true; WebException? webException = exception as WebException; - if (webException != null) + if (webException is not null) { FtpWebResponse? response = webException.Response as FtpWebResponse; - if (response != null) + if (response is not null) { if (!_isFullyRead && response.StatusCode == FtpStatusCode.ConnectionClosed) 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 70de06c5a1c87e..ae5eeccc6eefe0 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -324,7 +324,7 @@ public override ICredentials? Credentials { throw new InvalidOperationException(SR.net_reqsubmitted); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -506,7 +506,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 (_uri.UserInfo is not null && _uri.UserInfo.Length != 0) { string userInfo = _uri.UserInfo; string username = userInfo; @@ -520,7 +520,7 @@ internal FtpWebRequest(Uri uri) } networkCredential = new NetworkCredential(username, password); } - if (networkCredential == null) + if (networkCredential is null) { networkCredential = s_defaultFtpNetworkCredential; } @@ -538,7 +538,7 @@ public override WebResponse GetResponse() { CheckError(); - if (_ftpWebResponse != null) + if (_ftpWebResponse is not null) { return _ftpWebResponse; } @@ -575,7 +575,7 @@ public override WebResponse GetResponse() } // GetRequeststream or BeginGetRequestStream has not finished yet - if (_readAsyncResult != null) + if (_readAsyncResult is not null) _readAsyncResult.InternalWaitForCompletion(); CheckError(); @@ -597,10 +597,10 @@ public override WebResponse GetResponse() { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception); - // if _exception == null, we are about to throw an exception to the user + // if _exception is null, we are about to throw an exception to the user // and we haven't saved the exception, which also means we haven't dealt // with it. So just release the connection and log this for investigation. - if (_exception == null) + if (_exception is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception); SetException(exception); @@ -622,7 +622,7 @@ public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? s try { - if (_ftpWebResponse != null) + if (_ftpWebResponse is not null) { asyncResult = new ContextAwareResult(this, state, callback); asyncResult.InvokeCallback(_ftpWebResponse); @@ -658,7 +658,7 @@ public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? s } } - if (asyncResult == null) + if (asyncResult is null) { // need to complete it now asyncResult = (ContextAwareResult)_readAsyncResult; @@ -694,12 +694,12 @@ public override WebResponse EndGetResponse(IAsyncResult asyncResult) try { // parameter validation - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; - if (castedAsyncResult == null) + if (castedAsyncResult is null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -818,14 +818,14 @@ public override Stream EndGetRequestStream(IAsyncResult asyncResult) Stream? requestStream = null; try { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; - if (castedAsyncResult == null) + if (castedAsyncResult is null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -874,7 +874,7 @@ private void SubmitRequest(bool isAsync) { FtpControlStream? connection = _connection; - if (connection == null) + if (connection is null) { if (isAsync) { @@ -1013,7 +1013,7 @@ private FtpControlStream CreateConnection() if (isAsync) { // non-null in the case of re-submit (recovery) - if (_requestCompleteAsyncResult == null) + if (_requestCompleteAsyncResult is null) _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null); return _connection!.SubmitRequest(this, true, true)!; } @@ -1042,7 +1042,7 @@ private FtpControlStream CreateConnection() throw ExceptionHelper.TimeoutException; } - if (stream != null) + if (stream is not null) { lock (_syncObject) { @@ -1067,7 +1067,7 @@ private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object? con if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this); FtpControlStream? connection = _connection; - if (connection != null) + if (connection is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "aborting connection"); connection.AbortConnect(); @@ -1078,7 +1078,7 @@ private TimerThread.Queue TimerQueue { get { - if (_timerQueue == null) + if (_timerQueue is null) { _timerQueue = TimerThread.GetOrCreateQueue(RemainingTimeout); } @@ -1096,7 +1096,7 @@ private bool AttemptedRecovery(Exception e) || _onceFailed || _aborted || _timedOut - || _connection == null + || _connection is null || !_connection.RecoverableFailure) { return false; @@ -1105,7 +1105,7 @@ private bool AttemptedRecovery(Exception e) lock (_syncObject) { - if (_connection != null) + if (_connection is not null) { _connection.CloseSocket(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Releasing connection: {_connection}"); @@ -1133,7 +1133,7 @@ private void SetException(Exception exception) } FtpControlStream? connection = _connection; - if (_exception == null) + if (_exception is null) { if (exception is WebException) { @@ -1144,7 +1144,7 @@ private void SetException(Exception exception) { _exception = exception; } - else if (connection != null && connection.StatusCode != FtpStatusCode.Undefined) + else if (connection is not null && connection.StatusCode != FtpStatusCode.Undefined) { EnsureFtpWebResponse(exception); _exception = new WebException(SR.Format(SR.net_ftp_servererror, connection.StatusLine), exception, WebExceptionStatus.ProtocolError, _ftpWebResponse); @@ -1154,7 +1154,7 @@ private void SetException(Exception exception) _exception = new WebException(exception.Message, exception); } - if (connection != null && _ftpWebResponse != null) + if (connection is not null && _ftpWebResponse is not null) _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } } @@ -1164,7 +1164,7 @@ private void SetException(Exception exception) /// private void CheckError() { - if (_exception != null) + if (_exception is not null) { ExceptionDispatchInfo.Throw(_exception); } @@ -1187,12 +1187,12 @@ private void SyncRequestCallback(object? obj) RequestStage stageMode = RequestStage.CheckForError; try { - bool completedRequest = obj == null; + bool completedRequest = obj is null; Exception? exception = obj as Exception; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"exp:{exception} completedRequest:{completedRequest}"); - if (exception != null) + if (exception is not null) { SetException(exception); } @@ -1204,7 +1204,7 @@ private void SyncRequestCallback(object? obj) { FtpControlStream? connection = _connection; - if (connection != null) + if (connection is not null) { EnsureFtpWebResponse(null); @@ -1240,29 +1240,29 @@ private void AsyncRequestCallback(object? obj) FtpDataStream? stream = obj as FtpDataStream; Exception? exception = obj as Exception; - bool completedRequest = (obj == null); + bool completedRequest = (obj is null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"stream:{stream} conn:{connection} exp:{exception} completedRequest:{completedRequest}"); while (true) { - if (exception != null) + if (exception is not null) { if (AttemptedRecovery(exception)) { connection = CreateConnection(); - if (connection == null) + if (connection is null) return; exception = null; } - if (exception != null) + if (exception is not null) { SetException(exception); break; } } - if (connection != null) + if (connection is not null) { lock (_syncObject) { @@ -1287,7 +1287,7 @@ private void AsyncRequestCallback(object? obj) } return; } - else if (stream != null) + else if (stream is not null) { lock (_syncObject) { @@ -1308,7 +1308,7 @@ private void AsyncRequestCallback(object? obj) { connection = _connection; - if (connection != null) + if (connection is not null) { EnsureFtpWebResponse(null); @@ -1352,7 +1352,7 @@ private RequestStage FinishRequestStage(RequestStage stage) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"state:{stage}"); - if (_exception != null) + if (_exception is not null) stage = RequestStage.ReleaseConnection; RequestStage prev; @@ -1385,7 +1385,7 @@ private RequestStage FinishRequestStage(RequestStage stage) if (stage == RequestStage.ReleaseConnection) { - if (_exception == null && + if (_exception is null && !_aborted && prev != RequestStage.ReadReady && _methodInfo.IsDownload && @@ -1403,11 +1403,11 @@ private RequestStage FinishRequestStage(RequestStage stage) // First check to see on releasing the connection if ((stage == RequestStage.ReleaseConnection || prev == RequestStage.ReleaseConnection) - && connection != null) + && connection is not null) { try { - if (_exception != null) + if (_exception is not null) { connection.Abort(_exception); } @@ -1417,7 +1417,7 @@ private RequestStage FinishRequestStage(RequestStage stage) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Releasing connection: {connection}"); connection.CloseSocket(); if (_async) - if (_requestCompleteAsyncResult != null) + if (_requestCompleteAsyncResult is not null) _requestCompleteAsyncResult.InvokeCallback(); } } @@ -1430,24 +1430,24 @@ private RequestStage FinishRequestStage(RequestStage stage) // In any case we want to signal the writer if came here if (stage >= RequestStage.WriteReady) { - // If writeResult == null and this is an upload request, it means + // If writeResult is null and this is an upload request, it means // that the user has called GetResponse() without calling // GetRequestStream() first. So they are not interested in a // stream. Therefore we close the stream so that the // request/pipeline can continue if (_methodInfo.IsUpload && !_getRequestStreamStarted) { - if (_stream != null) + if (_stream is not null) _stream.Close(); } - else if (writeResult != null && !writeResult.InternalPeekCompleted) + else if (writeResult is not null && !writeResult.InternalPeekCompleted) writeResult.InvokeCallback(); } } finally { // The response is ready either with or without a stream - if (stage >= RequestStage.ReadReady && readResult != null && !readResult.InternalPeekCompleted) + if (stage >= RequestStage.ReadReady && readResult is not null && !readResult.InternalPeekCompleted) readResult.InvokeCallback(); } } @@ -1476,7 +1476,7 @@ public override void Abort() _exception = ExceptionHelper.RequestAbortedException; } - if (stream != null) + if (stream is not null) { if (!(stream is ICloseEx)) { @@ -1485,7 +1485,7 @@ public override void Abort() ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); } - if (connection != null) + if (connection is not null) connection.Abort(ExceptionHelper.RequestAbortedException); } catch (Exception exception) @@ -1572,7 +1572,7 @@ public X509CertificateCollection ClientCertificates } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1603,7 +1603,7 @@ public override WebHeaderCollection Headers { get { - if (_ftpRequestHeaders == null) + if (_ftpRequestHeaders is null) { _ftpRequestHeaders = new WebHeaderCollection(); } @@ -1677,11 +1677,11 @@ private bool InUse /// private void EnsureFtpWebResponse(Exception? exception) { - if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) + if (_ftpWebResponse is null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream is not null)) { lock (_syncObject) { - if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) + if (_ftpWebResponse is null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream is not null)) { Stream? responseStream = _stream; @@ -1690,16 +1690,16 @@ private void EnsureFtpWebResponse(Exception? exception) responseStream = null; } - if (_stream != null && _stream.CanRead && _stream.CanTimeout) + if (_stream is not null && _stream.CanRead && _stream.CanTimeout) { _stream.ReadTimeout = ReadWriteTimeout; _stream.WriteTimeout = ReadWriteTimeout; } FtpControlStream? connection = _connection; - long contentLength = connection != null ? connection.ContentLength : -1; + long contentLength = connection is not null ? connection.ContentLength : -1; - if (responseStream == null) + if (responseStream is null) { // If the last command was SIZE, we set the ContentLength on // the FtpControlStream to be the size of the file returned in the @@ -1710,13 +1710,13 @@ private void EnsureFtpWebResponse(Exception? exception) contentLength = 0; } - if (_ftpWebResponse != null) + if (_ftpWebResponse is not null) { _ftpWebResponse.SetResponseStream(responseStream); } else { - if (connection != null) + if (connection is not null) _ftpWebResponse = new FtpWebResponse(responseStream, contentLength, connection.ResponseUri, connection.StatusCode, connection.StatusLine, connection.LastModified, connection.BannerMessage, connection.WelcomeMessage, connection.ExitMessage); else _ftpWebResponse = new FtpWebResponse(responseStream, -1, _uri, FtpStatusCode.Undefined, null, DateTime.Now, null, null, null); @@ -1736,7 +1736,7 @@ internal void DataStreamClosed(CloseExState closeState) { if (!_async) { - if (_connection != null) + if (_connection is not null) _connection.CheckContinuePipeline(); } else @@ -1748,7 +1748,7 @@ internal void DataStreamClosed(CloseExState closeState) else { FtpControlStream? connection = _connection; - if (connection != null) + if (connection is not null) connection.Abort(ExceptionHelper.RequestAbortedException); } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs index fd0f63ba3baf59..78b4f39b8df971 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs @@ -24,7 +24,7 @@ public class FtpWebResponse : WebResponse, IDisposable internal FtpWebResponse(Stream? responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string? statusLine, DateTime lastModified, string? bannerMessage, string? welcomeMessage, string? exitMessage) { _responseStream = responseStream; - if (responseStream == null && contentLength < 0) + if (responseStream is null && contentLength < 0) { contentLength = 0; } @@ -49,7 +49,7 @@ public override Stream GetResponseStream() { Stream? responseStream = null; - if (_responseStream != null) + if (_responseStream is not null) { responseStream = _responseStream; } @@ -69,7 +69,7 @@ internal EmptyStream() : base(Array.Empty(), false) internal void SetResponseStream(Stream? stream) { - if (stream == null || stream == Stream.Null || stream is EmptyStream) + if (stream is null || stream == Stream.Null || stream is EmptyStream) return; _responseStream = stream; } @@ -97,11 +97,11 @@ public override WebHeaderCollection Headers { get { - if (_ftpRequestHeaders == null) + if (_ftpRequestHeaders is null) { lock (this) { - if (_ftpRequestHeaders == null) + if (_ftpRequestHeaders is null) { _ftpRequestHeaders = new WebHeaderCollection(); } 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 7beaa7996cca75..3dea0eb87171eb 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -149,11 +149,11 @@ public bool Matches(HttpClientParameters requestParameters) public bool AreParametersAcceptableForCaching() { - return Credentials == null + return Credentials is null && ReferenceEquals(Proxy, DefaultWebProxy) - && ServerCertificateValidationCallback == null - && ClientCertificates == null - && CookieContainer == null; + && ServerCertificateValidationCallback is null + && ClientCertificates is null + && CookieContainer is null; } } @@ -345,7 +345,7 @@ public string Host get { Uri hostUri = _hostUri ?? Address; - return (_hostUri == null || !_hostHasPort) && Address.IsDefaultPort ? + return (_hostUri is null || !_hostHasPort) && Address.IsDefaultPort ? hostUri.Host : hostUri.Host + ":" + hostUri.Port; } @@ -355,7 +355,7 @@ public string Host { throw new InvalidOperationException(SR.net_writestarted); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -849,7 +849,7 @@ public virtual bool HaveResponse { get { - return (_sendRequestTask != null) && (_sendRequestTask.IsCompletedSuccessfully); + return (_sendRequestTask is not null) && (_sendRequestTask.IsCompletedSuccessfully); } } @@ -973,20 +973,20 @@ public override void Abort() // already in the terminal state and the callback has already been invoked // via the async task continuation. - if (_responseOperation != null) + if (_responseOperation is not null) { - if (_responseOperation.TrySetCanceled() && _responseCallback != null) + if (_responseOperation.TrySetCanceled() && _responseCallback is not null) { _responseCallback(_responseOperation.Task); } // Cancel the underlying send operation. - Debug.Assert(_sendRequestCts != null); + Debug.Assert(_sendRequestCts is not null); _sendRequestCts.Cancel(); } - else if (_requestStreamOperation != null) + else if (_requestStreamOperation is not null) { - if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null) + if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback is not null) { _requestStreamCallback(_requestStreamOperation.Task); } @@ -1086,7 +1086,7 @@ public override Stream EndGetRequestStream(IAsyncResult asyncResult) { CheckAbort(); - if (asyncResult == null || !(asyncResult is Task)) + if (asyncResult is null || !(asyncResult is Task)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -1123,13 +1123,13 @@ private async Task SendRequest(bool async) try { client = GetCachedOrCreateHttpClient(out disposeRequired); - if (_requestStream != null) + if (_requestStream is not null) { ArraySegment bytes = _requestStream.GetBuffer(); request.Content = new ByteArrayContent(bytes.Array!, bytes.Offset, bytes.Count); } - if (_hostUri != null) + if (_hostUri is not null) { request.Headers.Host = Host; } @@ -1143,7 +1143,7 @@ private async Task SendRequest(bool async) // are only allowed in the request headers collection and not in the request content headers collection. if (IsWellKnownContentHeader(headerName)) { - if (request.Content == null) + if (request.Content is null) { // Create empty content so that we can send the entity-body header. request.Content = new ByteArrayContent(Array.Empty()); @@ -1219,7 +1219,7 @@ public override WebResponse EndGetResponse(IAsyncResult asyncResult) { CheckAbort(); - if (asyncResult == null || !(asyncResult is Task)) + if (asyncResult is null || !(asyncResult is Task)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -1301,7 +1301,7 @@ public void AddRange(string rangeSpecifier, long from, long to) // Do some range checking before assembling the header // - if (rangeSpecifier == null) + if (rangeSpecifier is null) { throw new ArgumentNullException(nameof(rangeSpecifier)); } @@ -1330,7 +1330,7 @@ public void AddRange(string rangeSpecifier, int range) public void AddRange(string rangeSpecifier, long range) { - if (rangeSpecifier == null) + if (rangeSpecifier is null) { throw new ArgumentNullException(nameof(rangeSpecifier)); } @@ -1348,7 +1348,7 @@ private bool AddRange(string rangeSpecifier, string from, string? to) { string? curRange = _webHeaderCollection[HttpKnownHeaderNames.Range]; - if ((curRange == null) || (curRange.Length == 0)) + if ((curRange is null) || (curRange.Length == 0)) { curRange = rangeSpecifier + "="; } @@ -1361,7 +1361,7 @@ private bool AddRange(string rangeSpecifier, string from, string? to) curRange = string.Empty; } curRange += from.ToString(); - if (to != null) + if (to is not null) { curRange += "-" + to; } @@ -1373,7 +1373,7 @@ private bool RequestSubmitted { get { - return _sendRequestTask != null; + return _sendRequestTask is not null; } } @@ -1415,7 +1415,7 @@ private DateTime GetDateHeaderHelper(string headerName) { string? headerValue = _webHeaderCollection[headerName]; - if (headerValue == null) + if (headerValue is null) { return DateTime.MinValue; // MinValue means header is not present } @@ -1449,11 +1449,11 @@ private HttpClient GetCachedOrCreateHttpClient(out bool disposeRequired) if (parameters.AreParametersAcceptableForCaching()) { disposeRequired = false; - if (s_cachedHttpClient == null) + if (s_cachedHttpClient is null) { lock (s_syncRoot) { - if (s_cachedHttpClient == null) + if (s_cachedHttpClient is null) { s_cachedHttpClientParameters = parameters; s_cachedHttpClient = CreateHttpClient(parameters, null); @@ -1487,7 +1487,7 @@ private static HttpClient CreateHttpClient(HttpClientParameters parameters, Http handler.PreAuthenticate = parameters.PreAuthenticate; client.Timeout = parameters.Timeout; - if (parameters.CookieContainer != null) + if (parameters.CookieContainer is not null) { handler.CookieContainer = parameters.CookieContainer; Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true. @@ -1498,10 +1498,10 @@ private static HttpClient CreateHttpClient(HttpClientParameters parameters, Http } Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true. - Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null. + Debug.Assert(handler.Proxy is null); // Default of handler.Proxy is null. // HttpClientHandler default is to use a proxy which is the system proxy. - // This is indicated by the properties 'UseProxy == true' and 'Proxy == null'. + // This is indicated by the properties 'UseProxy == true' and 'Proxy is null'. // // However, HttpWebRequest doesn't have a separate 'UseProxy' property. Instead, // the default of the 'Proxy' property is a non-null IWebProxy object which is the @@ -1510,7 +1510,7 @@ private static HttpClient CreateHttpClient(HttpClientParameters parameters, Http // // So, we need to map the desired HttpWebRequest proxy settings to equivalent // HttpClientHandler settings. - if (parameters.Proxy == null) + if (parameters.Proxy is null) { handler.UseProxy = false; } @@ -1526,7 +1526,7 @@ private static HttpClient CreateHttpClient(HttpClientParameters parameters, Http handler.DefaultProxyCredentials = parameters.Proxy.Credentials; } - if (parameters.ClientCertificates != null) + if (parameters.ClientCertificates is not null) { handler.ClientCertificates.AddRange(parameters.ClientCertificates); } @@ -1535,7 +1535,7 @@ private static HttpClient CreateHttpClient(HttpClientParameters parameters, Http handler.SslProtocols = (SslProtocols)parameters.SslProtocols; handler.CheckCertificateRevocationList = parameters.CheckCertificateRevocationList; RemoteCertificateValidationCallback? rcvc = parameters.ServerCertificateValidationCallback; - if (rcvc != null) + if (rcvc is not null) { RemoteCertificateValidationCallback localRcvc = rcvc; HttpWebRequest localRequest = request!; diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs index e1fadb3116d6f3..f9a18d73e69157 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs @@ -56,7 +56,7 @@ internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieCon _requestUri = requestUri; // Match Desktop behavior. If the request didn't set a CookieContainer, we don't populate the response's CookieCollection. - if (cookieContainer != null) + if (cookieContainer is not null) { _cookies = cookieContainer.GetCookies(requestUri); } @@ -92,7 +92,7 @@ public override string ContentType // We use TryGetValues() instead of the strongly type Headers.ContentType property so that // we return a string regardless of it being fully RFC conformant. This matches current // .NET Framework behavior. - if (_httpResponseMessage.Content != null && _httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out IEnumerable? values)) + if (_httpResponseMessage.Content is not null && _httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out IEnumerable? values)) { // In most cases, there is only one media type value as per RFC. But for completeness, we // return all values in cases of overly malformed strings. @@ -123,7 +123,7 @@ public string ContentEncoding get { CheckDisposed(); - if (_httpResponseMessage.Content != null) + if (_httpResponseMessage.Content is not null) { return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding); } @@ -205,7 +205,7 @@ public override WebHeaderCollection Headers get { CheckDisposed(); - if (_webHeaderCollection == null) + if (_webHeaderCollection is null) { _webHeaderCollection = new WebHeaderCollection(); @@ -214,7 +214,7 @@ public override WebHeaderCollection Headers _webHeaderCollection[header.Key] = GetHeaderValueAsString(header.Value); } - if (_httpResponseMessage.Content != null) + if (_httpResponseMessage.Content is not null) { foreach (var header in _httpResponseMessage.Content.Headers) { @@ -275,7 +275,7 @@ public string? CharacterSet CheckDisposed(); string? contentType = Headers["Content-Type"]; - if (_characterSet == null && !string.IsNullOrWhiteSpace(contentType)) + if (_characterSet is null && !string.IsNullOrWhiteSpace(contentType)) { //sets characterset so the branch is never executed again. _characterSet = string.Empty; @@ -346,7 +346,7 @@ public override bool SupportsHeaders public override Stream GetResponseStream() { CheckDisposed(); - if (_httpResponseMessage.Content != null) + if (_httpResponseMessage.Content is not null) { return _httpResponseMessage.Content.ReadAsStream(); } @@ -358,7 +358,7 @@ public string GetResponseHeader(string headerName) { CheckDisposed(); string? headerValue = Headers[headerName]; - return (headerValue == null) ? string.Empty : headerValue; + return (headerValue is null) ? string.Empty : headerValue; } public override void Close() @@ -369,7 +369,7 @@ public override void Close() protected override void Dispose(bool disposing) { var httpResponseMessage = _httpResponseMessage; - if (httpResponseMessage != null) + if (httpResponseMessage is not null) { httpResponseMessage.Dispose(); _httpResponseMessage = null!; @@ -378,7 +378,7 @@ protected override void Dispose(bool disposing) private void CheckDisposed() { - if (_httpResponseMessage == null) + if (_httpResponseMessage is null) { throw new ObjectDisposedException(this.GetType().ToString()); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs b/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs index 59d54a1b71ff6e..f16cc34ba39d95 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs @@ -64,7 +64,7 @@ public static string GetWebStatusCodeString(FtpStatusCode statusCode, string? st break; } - if (statusMessage != null && statusMessage.Length > 0) + if (statusMessage is not null && statusMessage.Length > 0) { webStatusCode += " " + statusMessage; } @@ -73,7 +73,7 @@ public static string GetWebStatusCodeString(FtpStatusCode statusCode, string? st // // Otherwise try to map the base status. // - if (statusDescription != null && statusDescription.Length > 0) + if (statusDescription is not null && statusDescription.Length > 0) { webStatusCode += " " + statusDescription; } diff --git a/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs b/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs index 41ca7f6120308d..2014fe8cd310f4 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs @@ -95,7 +95,7 @@ public override void SetLength(long value) public override void Write(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -112,7 +112,7 @@ public override void Write(byte[] buffer, int offset, int count) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -129,7 +129,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs b/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs index ddf2365014ba79..d14ea47505a313 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs @@ -38,7 +38,7 @@ public static TaskCompletionSource ToApm( // already transitioned to a Canceled state via a previous HttpWebRequest.Abort() call. if (shouldInvokeCallback) { - if (callback != null) + if (callback is not null) { callback(tcs.Task); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs b/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs index c21afc9003089e..fd51f3033b3083 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs @@ -119,12 +119,12 @@ internal static Queue GetOrCreateQueue(int durationMilliseconds) TimerQueue? queue; object key = durationMilliseconds; // Box once. WeakReference? weakQueue = (WeakReference?)s_queuesCache[key]; - if (weakQueue == null || (queue = (TimerQueue?)weakQueue.Target) == null) + if (weakQueue is null || (queue = (TimerQueue?)weakQueue.Target) is null) { lock (s_newQueues) { weakQueue = (WeakReference?)s_queuesCache[key]; - if (weakQueue == null || (queue = (TimerQueue?)weakQueue.Target) == null) + if (weakQueue is null || (queue = (TimerQueue?)weakQueue.Target) is null) { queue = new TimerQueue(durationMilliseconds); weakQueue = new WeakReference(queue); @@ -140,7 +140,7 @@ internal static Queue GetOrCreateQueue(int durationMilliseconds) while (e.MoveNext()) { DictionaryEntry pair = e.Entry; - if (((WeakReference)pair.Value!).Target == null) + if (((WeakReference)pair.Value!).Target is null) { garbage.Add(pair.Key); } @@ -306,7 +306,7 @@ private enum TimerState internal TimerNode(Callback callback, object? context, int durationMilliseconds, object queueLock) : base(durationMilliseconds) { - if (callback != null) + if (callback is not null) { _callback = callback; _context = context; @@ -410,7 +410,7 @@ internal bool Fire() Next = null; Prev = null; - needCallback = _callback != null; + needCallback = _callback is not null; } } @@ -510,7 +510,7 @@ private static void ThreadProc() { lock (s_newQueues) { - for (LinkedListNode? node = s_newQueues.First; node != null; node = s_newQueues.First) + for (LinkedListNode? node = s_newQueues.First; node is not null; node = s_newQueues.First) { s_newQueues.Remove(node); s_queues.AddLast(node); @@ -521,10 +521,10 @@ private static void ThreadProc() int now = Environment.TickCount; int nextTick = 0; bool haveNextTick = false; - for (LinkedListNode? node = s_queues.First; node != null; /* node = node.Next must be done in the body */) + for (LinkedListNode? node = s_queues.First; node is not null; /* node = node.Next must be done in the body */) { TimerQueue? queue = (TimerQueue?)node.Value.Target; - if (queue == null) + if (queue is null) { LinkedListNode? next = node.Next; s_queues.Remove(node); diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebException.cs b/src/libraries/System.Net.Requests/src/System/Net/WebException.cs index 06f2207308a6b2..29887d2629885b 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebException.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebException.cs @@ -46,7 +46,7 @@ public WebException(string? message, _status = status; _response = response; - if (innerException != null) + if (innerException is not null) { HResult = innerException.HResult; } @@ -73,7 +73,7 @@ public override void GetObjectData(SerializationInfo serializationInfo, Streamin internal static Exception CreateCompatibleException(Exception exception) { - Debug.Assert(exception != null); + Debug.Assert(exception is not null); if (exception is HttpRequestException hre) { return new WebException( diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs index bcdce17c44bf88..06115e220ba473 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs @@ -145,7 +145,7 @@ private static WebRequest Create(Uri requestUri, bool useUriBase) [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public static WebRequest Create(string requestUriString) { - if (requestUriString == null) + if (requestUriString is null) { throw new ArgumentNullException(nameof(requestUriString)); } @@ -166,7 +166,7 @@ public static WebRequest Create(string requestUriString) [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public static WebRequest Create(Uri requestUri) { - if (requestUri == null) + if (requestUri is null) { throw new ArgumentNullException(nameof(requestUri)); } @@ -188,7 +188,7 @@ public static WebRequest Create(Uri requestUri) [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public static WebRequest CreateDefault(Uri requestUri) { - if (requestUri == null) + if (requestUri is null) { throw new ArgumentNullException(nameof(requestUri)); } @@ -199,7 +199,7 @@ public static WebRequest CreateDefault(Uri requestUri) [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public static HttpWebRequest CreateHttp(string requestUriString) { - if (requestUriString == null) + if (requestUriString is null) { throw new ArgumentNullException(nameof(requestUriString)); } @@ -209,7 +209,7 @@ public static HttpWebRequest CreateHttp(string requestUriString) [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public static HttpWebRequest CreateHttp(Uri requestUri) { - if (requestUri == null) + if (requestUri is null) { throw new ArgumentNullException(nameof(requestUri)); } @@ -243,11 +243,11 @@ public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) int i; WebRequestPrefixElement Current; - if (prefix == null) + if (prefix is null) { throw new ArgumentNullException(nameof(prefix)); } - if (creator == null) + if (creator is null) { throw new ArgumentNullException(nameof(creator)); } diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs index f1fef45e081264..b49975ad981924 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs @@ -19,7 +19,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( { SslPolicyErrors errors = SslPolicyErrors.None; - if (remoteCertificate == null) + if (remoteCertificate is null) { errors |= SslPolicyErrors.RemoteCertificateNotAvailable; } @@ -59,7 +59,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( SafeDeleteContext? securityContext, out X509Certificate2Collection? remoteCertificateStore) { - if (securityContext == null) + if (securityContext is null) { remoteCertificateStore = null; return null; @@ -73,14 +73,14 @@ internal static SslPolicyErrors VerifyCertificateProperties( SafeDeleteContext securityContext, X509Certificate2Collection? remoteCertificateStore) { - if (securityContext == null) + if (securityContext is null) { return null; } SafeSslHandle sslContext = ((SafeDeleteSslContext)securityContext).SslContext; - if (sslContext == null) + if (sslContext is null) { return null; } @@ -91,7 +91,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( { long chainSize = Interop.AppleCrypto.X509ChainGetChainSize(chainHandle); - if (remoteCertificateStore != null) + if (remoteCertificateStore is not null) { for (int i = 0; i < chainSize; i++) { @@ -121,7 +121,7 @@ internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext secu { SafeSslHandle sslContext = ((SafeDeleteSslContext)securityContext).SslContext; - if (sslContext == null) + if (sslContext is null) { return Array.Empty(); } diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs index 34386aec2631e0..a075fa0fa46c7b 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs @@ -33,7 +33,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( SafeDeleteContext? securityContext, out X509Certificate2Collection? remoteCertificateStore) { - if (securityContext == null) + if (securityContext is null) { remoteCertificateStore = null; return null; @@ -47,7 +47,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( { bool gotReference = false; - if (securityContext == null) + if (securityContext is null) { return null; } @@ -58,13 +58,13 @@ internal static SslPolicyErrors VerifyCertificateProperties( { QueryContextRemoteCertificate(securityContext, out remoteContext); - if (remoteContext != null && !remoteContext.IsInvalid) + if (remoteContext is not null && !remoteContext.IsInvalid) { remoteContext.DangerousAddRef(ref gotReference); result = new X509Certificate2(remoteContext.DangerousGetHandle()); } - if (remoteCertificateStore != null) + if (remoteCertificateStore is not null) { using (SafeSharedX509StackHandle chainStack = Interop.OpenSsl.GetPeerCertificateChain(((SafeDeleteSslContext)securityContext).SslContext)) @@ -95,7 +95,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( } finally { - if (remoteContext != null) + if (remoteContext is not null) { if (gotReference) { diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs index 557b2e2e4e0904..cdc10be107bdd3 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs @@ -91,7 +91,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( { remoteCertificateCollection = null; - if (securityContext == null) + if (securityContext is null) { return null; } @@ -101,14 +101,14 @@ internal static SslPolicyErrors VerifyCertificateProperties( try { remoteContext = SSPIWrapper.QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(GlobalSSPI.SSPISecureChannel, securityContext); - if (remoteContext != null && !remoteContext.IsInvalid) + if (remoteContext is not null && !remoteContext.IsInvalid) { result = new X509Certificate2(remoteContext.DangerousGetHandle()); } } finally { - if (remoteContext != null && !remoteContext.IsInvalid) + if (remoteContext is not null && !remoteContext.IsInvalid) { if (retrieveCollection) { diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs index 9d9ee929754294..9fa9e97fa49b7e 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs @@ -20,7 +20,7 @@ internal static partial class CertificateValidationPal { X509Store? store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; - if (store == null) + if (store is null) { StoreLocation storeLocation = isMachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; @@ -40,7 +40,7 @@ internal static partial class CertificateValidationPal { store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; - if (store == null) + if (store is null) { try { diff --git a/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs b/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs index 3fb11880265f70..9c5bd905d5764e 100644 --- a/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs +++ b/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs @@ -77,7 +77,7 @@ internal bool IsNTLM { get { - if (_lastProtocolName == null) + if (_lastProtocolName is null) { _lastProtocolName = ProtocolName; } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs index 4e913bc3db9bff..09994bed8b8281 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs @@ -14,7 +14,7 @@ public abstract class AuthenticatedStream : Stream protected AuthenticatedStream(Stream innerStream, bool leaveInnerStreamOpen) { - if (innerStream == null || innerStream == Stream.Null) + if (innerStream is null || innerStream == Stream.Null) { throw new ArgumentNullException(nameof(innerStream)); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs index b077c9856dc7a7..f448ffbb01cd2d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs @@ -15,7 +15,7 @@ public sealed partial class CipherSuitesPolicy [CLSCompliant(false)] public CipherSuitesPolicy(IEnumerable allowedCipherSuites) { - if (allowedCipherSuites == null) + if (allowedCipherSuites is null) { throw new ArgumentNullException(nameof(allowedCipherSuites)); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs index 0cbeb85dbd331b..fe82232c00a0f9 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs @@ -57,7 +57,7 @@ internal CipherSuitesPolicyPal(IEnumerable allowedCipherSuites) cs, out bool isTls12OrLower); - if (name == null) + if (name is null) { // we do not have a corresponding name // allowing less than user requested is OK @@ -87,7 +87,7 @@ internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy? policy, EncryptionP return true; } - if (policy == null) + if (policy is null) { // null means default, by default OpenSSL will choose if it wants to opt-out or not return false; @@ -104,7 +104,7 @@ internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy? policy, EncryptionP internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { - if (policy == null) + if (policy is null) { // null means default, by default OpenSSL will choose if it wants to opt-out or not return false; @@ -136,7 +136,7 @@ internal static bool WantsTls13(SslProtocols protocols) return null; } - if (policy == null) + if (policy is null) { return CipherListFromEncryptionPolicy(encryptionPolicy); } @@ -154,7 +154,7 @@ internal static bool WantsTls13(SslProtocols protocols) SslProtocols protocols, EncryptionPolicy encryptionPolicy) { - if (!WantsTls13(protocols) || policy == null) + if (!WantsTls13(protocols) || policy is null) { // do not call TLS 1.3 API, let OpenSSL choose what to do return null; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs index 45ea9a02e07452..b511f6d33ac0a2 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs @@ -215,7 +215,7 @@ public virtual Task AuthenticateAsServerAsync( public override bool IsAuthenticated => IsAuthenticatedCore; [MemberNotNullWhen(true, nameof(_context))] - private bool IsAuthenticatedCore => _context != null && HandshakeComplete && _exception == null && _remoteOk; + private bool IsAuthenticatedCore => _context is not null && HandshakeComplete && _exception is null && _remoteOk; public override bool IsMutuallyAuthenticated => IsAuthenticatedCore && @@ -226,7 +226,7 @@ public virtual Task AuthenticateAsServerAsync( public override bool IsSigned => IsAuthenticatedCore && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag); - public override bool IsServer => _context != null && _context.IsServer; + public override bool IsServer => _context is not null && _context.IsServer; public virtual TokenImpersonationLevel ImpersonationLevel { @@ -536,7 +536,7 @@ public override void EndWrite(IAsyncResult asyncResult) => private void ThrowIfExceptional() { ExceptionDispatchInfo? e = _exception; - if (e != null) + if (e is not null) { ThrowExceptional(e); } @@ -559,7 +559,7 @@ static void ThrowExceptional(ExceptionDispatchInfo e) /// Validates user parameters for all Read/Write methods. private static void ValidateParameters(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -588,10 +588,10 @@ private void ValidateCreateContext( ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { - if (policy != null) + if (policy is not null) { // One of these must be set if EP is turned on - if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null) + if (policy.CustomChannelBinding is null && policy.CustomServiceNames is null) { throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy)); } @@ -620,23 +620,23 @@ private void ValidateCreateContext( ThrowIfExceptional(); } - if (_context != null && _context.IsValidContext) + if (_context is not null && _context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } - if (credential == null) + if (credential is null) { throw new ArgumentNullException(nameof(credential)); } - if (servicePrincipalName == null) + if (servicePrincipalName is null) { throw new ArgumentNullException(nameof(servicePrincipalName)); } NegotiateStreamPal.ValidateImpersonationLevel(impersonationLevel); - if (_context != null && IsServer != isServer) + if (_context is not null && IsServer != isServer) { throw new InvalidOperationException(SR.net_auth_client_server); } @@ -714,7 +714,7 @@ private void ValidateCreateContext( private void SetFailed(Exception e) { - if (_exception == null || !(_exception.SourceException is ObjectDisposedException)) + if (_exception is null || !(_exception.SourceException is ObjectDisposedException)) { _exception = ExceptionDispatchInfo.Capture(e); } @@ -734,7 +734,7 @@ private void ThrowIfFailed(bool authSuccessCheck) private async Task AuthenticateAsync(TAdapter adapter, [CallerMemberName] string? callerName = null) where TAdapter : IReadWriteAdapter { - Debug.Assert(_context != null); + Debug.Assert(_context is not null); ThrowIfFailed(authSuccessCheck: false); if (Interlocked.Exchange(ref _authInProgress, 1) == 1) @@ -761,11 +761,11 @@ private async Task AuthenticateAsync(TAdapter adapter, [CallerMemberNa private bool CheckSpn() { - Debug.Assert(_context != null); + Debug.Assert(_context is not null); if (_context.IsKerberos || _extendedProtectionPolicy!.PolicyEnforcement == PolicyEnforcement.Never || - _extendedProtectionPolicy.CustomServiceNames == null) + _extendedProtectionPolicy.CustomServiceNames is null) { return true; } @@ -783,7 +783,7 @@ private bool CheckSpn() // Client authentication starts here, but server also loops through this method. private async Task SendBlobAsync(TAdapter adapter, byte[]? message) where TAdapter : IReadWriteAdapter { - Debug.Assert(_context != null); + Debug.Assert(_context is not null); Exception? exception = null; if (message != s_emptyMessage) @@ -791,7 +791,7 @@ private async Task SendBlobAsync(TAdapter adapter, byte[]? message) wh message = GetOutgoingBlob(message, ref exception); } - if (exception != null) + if (exception is not null) { // Signal remote side on a failed attempt. await SendAuthResetSignalAndThrowAsync(adapter, message!, exception).ConfigureAwait(false); @@ -862,12 +862,12 @@ private async Task SendBlobAsync(TAdapter adapter, byte[]? message) wh message ??= s_emptyMessage; } } - else if (message == null || message == s_emptyMessage) + else if (message is null || message == s_emptyMessage) { throw new InternalException(); } - if (message != null) + if (message is not null) { //even if we are completed, there could be a blob for sending. await _framer!.WriteMessageAsync(adapter, message).ConfigureAwait(false); @@ -885,10 +885,10 @@ private async Task SendBlobAsync(TAdapter adapter, byte[]? message) wh // Server authentication starts here, but client also loops through this method. private async Task ReceiveBlobAsync(TAdapter adapter) where TAdapter : IReadWriteAdapter { - Debug.Assert(_framer != null); + Debug.Assert(_framer is not null); byte[]? message = await _framer.ReadMessageAsync(adapter).ConfigureAwait(false); - if (message == null) + if (message is null) { // This is an EOF otherwise we would get at least *empty* message but not a null one. throw new AuthenticationException(SR.net_auth_eof); @@ -963,7 +963,7 @@ private static bool IsError(SecurityStatusPal status) => private unsafe byte[]? GetOutgoingBlob(byte[]? incomingBlob, ref Exception? e) { - Debug.Assert(_context != null); + Debug.Assert(_context is not null); byte[]? message = _context.GetOutgoingBlob(incomingBlob, false, out SecurityStatusPal statusCode); @@ -980,7 +980,7 @@ private static bool IsError(SecurityStatusPal status) => } } - if (message != null && message.Length == 0) + if (message is not null && message.Length == 0) { message = s_emptyMessage; } @@ -990,7 +990,7 @@ private static bool IsError(SecurityStatusPal status) => private int EncryptData(ReadOnlySpan buffer, [NotNull] ref byte[]? outBuffer) { - Debug.Assert(_context != null); + Debug.Assert(_context is not null); ThrowIfFailed(authSuccessCheck: true); // SSPI seems to ignore this sequence number. @@ -1000,7 +1000,7 @@ private int EncryptData(ReadOnlySpan buffer, [NotNull] ref byte[]? outBuff private int DecryptData(byte[] buffer, int offset, int count, out int newOffset) { - Debug.Assert(_context != null); + Debug.Assert(_context is not null); ThrowIfFailed(authSuccessCheck: true); // SSPI seems to ignore this sequence number. diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs index e21530a82c854d..dbd60b6bd47a88 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -111,7 +111,7 @@ internal static int Encrypt( } int resultSize = buffer.Length + sizes.cbSecurityTrailer + sizes.cbBlockSize; - if (output == null || output.Length < resultSize + 4) + if (output is null || output.Length < resultSize + 4) { output = new byte[resultSize + 4]; } @@ -185,13 +185,13 @@ internal static int Decrypt( out int newOffset, uint sequenceNumber) { - if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) + if (offset < 0 || offset > (buffer is null ? 0 : buffer.Length)) { NetEventSource.Fail(null, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } - if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) + if (count < 0 || count > (buffer is null ? 0 : buffer.Length - offset)) { NetEventSource.Fail(null, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs index 0f2c58d0a18a0f..ed51c5a5a2b8c6 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs @@ -66,7 +66,7 @@ public void SslStreamCtor(SslStream sslStream, Stream innerStream) string? remoteId = null; NetworkStream? ns = innerStream as NetworkStream; - if (ns != null) + if (ns is not null) { try { @@ -77,7 +77,7 @@ public void SslStreamCtor(SslStream sslStream, Stream innerStream) catch { }; } - if (localId == null) + if (localId is null) { localId = IdOf(innerStream); } @@ -389,7 +389,7 @@ private void ReceivedFrame(string sslStream, string tlsFrame, int isComplete) => static partial void AdditionalCustomizedToString(T value, ref string? result) { X509Certificate? cert = value as X509Certificate; - if (cert != null) + if (cert is not null) { result = cert.ToString(fVerbose: true); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs index 702d70455f455c..26ca20ea81b96d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs @@ -13,7 +13,7 @@ internal static class EndpointChannelBindingToken { using (X509Certificate2? cert = CertificateValidationPal.GetRemoteCertificate(securityContext)) { - if (cert == null) + if (cert is null) return null; SafeChannelBindingHandle bindingHandle = new SafeChannelBindingHandle(ChannelBindingKind.Endpoint); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs index 0308355c8898f9..293db123cb1304 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs @@ -22,7 +22,7 @@ internal sealed class SafeChannelBindingHandle : ChannelBinding internal void SetCertHash(byte[] certHashBytes) { - Debug.Assert(certHashBytes != null, "check certHashBytes is not null"); + Debug.Assert(certHashBytes is not null, "check certHashBytes is not null"); Debug.Assert(certHashBytes.Length <= CertHashMaxSize); int length = certHashBytes.Length; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs index 06ecc8d9ed1d72..9193587d42d8c1 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs @@ -25,7 +25,7 @@ internal sealed class SafeDeleteSslContext : SafeDeleteContext public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions) : base(credential) { - Debug.Assert((null != credential) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext"); + Debug.Assert((credential is not null) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext"); try { @@ -49,7 +49,7 @@ public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthentication throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus); } - if (sslAuthenticationOptions.CipherSuitesPolicy != null) + if (sslAuthenticationOptions.CipherSuitesPolicy is not null) { uint[] tlsCipherSuites = sslAuthenticationOptions.CipherSuitesPolicy.Pal.TlsCipherSuites; @@ -70,7 +70,7 @@ public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthentication } } - if (sslAuthenticationOptions.ApplicationProtocols != null) + if (sslAuthenticationOptions.ApplicationProtocols is not null) { // On OSX coretls supports only client side. For server, we will silently ignore the option. if (!sslAuthenticationOptions.IsServer) @@ -118,7 +118,7 @@ private static SafeSslHandle CreateSslContext(SafeFreeSslCredentials credential, SetProtocols(sslContext, credential.Protocols); } - if (credential.CertificateContext != null) + if (credential.CertificateContext is not null) { SetCertificate(sslContext, credential.CertificateContext); } @@ -142,7 +142,7 @@ protected override void Dispose(bool disposing) if (disposing) { SafeSslHandle sslContext = _sslContext; - if (null != sslContext) + if (sslContext is not null) { _inputBuffer.Dispose(); _outputBuffer.Dispose(); @@ -223,7 +223,7 @@ internal void Write(ReadOnlySpan buf) internal int ReadPendingWrites(byte[] buf, int offset, int count) { - Debug.Assert(buf != null); + Debug.Assert(buf is not null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(count <= buf.Length - offset); @@ -317,7 +317,7 @@ private static void SetProtocols(SafeSslHandle sslContext, SslProtocols protocol private static void SetCertificate(SafeSslHandle sslContext, SslStreamCertificateContext context) { - Debug.Assert(sslContext != null, "sslContext != null"); + Debug.Assert(sslContext is not null, "sslContext is not null"); IntPtr[] ptrs = new IntPtr[context!.IntermediateCertificates!.Length + 1]; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs index 24a4e7be7843a6..12aeee5990c8df 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs @@ -13,7 +13,7 @@ internal sealed class SafeFreeSslCredentials : SafeFreeCredentials public SafeFreeSslCredentials(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy) : base(IntPtr.Zero, true) { - if (certificateContext != null) + if (certificateContext is not null) { // Make a defensive copy of the certificate. In some async cases the // certificate can have been disposed before being provided to the handshake. diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs index 2261580a31512b..2dd33c69d57cb7 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs @@ -48,9 +48,9 @@ internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions, SslStr SslStreamPal.VerifyPackageInfo(); - if (sslAuthenticationOptions.TargetHost == null) + if (sslAuthenticationOptions.TargetHost is null) { - NetEventSource.Fail(this, "sslAuthenticationOptions.TargetHost == null"); + NetEventSource.Fail(this, "sslAuthenticationOptions.TargetHost is null"); } _securityContext = null; @@ -88,7 +88,7 @@ internal bool IsRemoteCertificateAvailable { get { - return _remoteCertificate != null; + return _remoteCertificate is not null; } } @@ -104,7 +104,7 @@ internal X509Certificate? RemoteCertificate internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { ChannelBinding? result = null; - if (_securityContext != null) + if (_securityContext is not null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); } @@ -141,7 +141,7 @@ internal bool IsValidContext [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - return !(_securityContext == null || _securityContext.IsInvalid); + return !(_securityContext is null || _securityContext.IsInvalid); } } @@ -194,7 +194,7 @@ internal void Close() // internal static X509Certificate2? FindCertificateWithPrivateKey(object instance, bool isServer, X509Certificate certificate) { - if (certificate == null) + if (certificate is null) { return null; } @@ -207,7 +207,7 @@ internal void Close() // Protecting from X509Certificate2 derived classes. X509Certificate2? certEx = MakeEx(certificate); - if (certEx != null) + if (certEx is not null) { if (certEx.HasPrivateKey) { @@ -229,7 +229,7 @@ internal void Close() // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store? store = CertificateValidationPal.EnsureStoreOpened(isServer); - if (store != null) + if (store is not null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) @@ -241,7 +241,7 @@ internal void Close() } store = CertificateValidationPal.EnsureStoreOpened(!isServer); - if (store != null) + if (store is not null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) @@ -263,7 +263,7 @@ internal void Close() private static X509Certificate2? MakeEx(X509Certificate certificate) { - Debug.Assert(certificate != null, "certificate != null"); + Debug.Assert(certificate is not null, "certificate is not null"); if (certificate.GetType() == typeof(X509Certificate2)) { @@ -345,7 +345,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds. - if (_sslAuthenticationOptions.CertSelectionDelegate != null) + if (_sslAuthenticationOptions.CertSelectionDelegate is not null) { issuers = GetRequestCertificateAuthorities(); @@ -356,7 +356,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) try { remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext!); - if (_sslAuthenticationOptions.ClientCertificates == null) + if (_sslAuthenticationOptions.ClientCertificates is null) { _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); } @@ -368,9 +368,9 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } - if (clientCertificate != null) + if (clientCertificate is not null) { - if (_credentialsHandle == null) + if (_credentialsHandle is null) { sessionRestartAttempt = true; } @@ -381,7 +381,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } else { - if (_sslAuthenticationOptions.ClientCertificates == null || _sslAuthenticationOptions.ClientCertificates.Count == 0) + if (_sslAuthenticationOptions.ClientCertificates is null || _sslAuthenticationOptions.ClientCertificates.Count == 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NoDelegateNoClientCert(this); @@ -395,13 +395,13 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } } } - else if (_credentialsHandle == null && _sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) + else if (_credentialsHandle is null && _sslAuthenticationOptions.ClientCertificates is not null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = _sslAuthenticationOptions.ClientCertificates[0]; sessionRestartAttempt = true; - if (clientCertificate != null) + if (clientCertificate is not null) { EnsureInitialized(ref filteredCerts).Add(clientCertificate); } @@ -409,7 +409,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this); } - else if (_sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) + else if (_sslAuthenticationOptions.ClientCertificates is not null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. @@ -418,7 +418,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) if (NetEventSource.Log.IsEnabled()) { - if (issuers == null || issuers.Length == 0) + if (issuers is null || issuers.Length == 0) { NetEventSource.Log.NoIssuersTryAllCerts(this); } @@ -434,14 +434,14 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // - if (issuers != null && issuers.Length != 0) + if (issuers is not null && issuers.Length != 0) { X509Certificate2? certificateEx = null; X509Chain? chain = null; try { certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]); - if (certificateEx == null) + if (certificateEx is null) { continue; } @@ -484,7 +484,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } finally { - if (chain != null) + if (chain is not null) { chain.Dispose(); @@ -495,7 +495,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } } - if (certificateEx != null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i]) + if (certificateEx is not null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i]) { certificateEx.Dispose(); } @@ -516,7 +516,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) if (NetEventSource.Log.IsEnabled()) { - if (filteredCerts != null && filteredCerts.Count != 0) + if (filteredCerts is not null && filteredCerts.Count != 0) { NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this); NetEventSource.Log.FindingMatchingCerts(this); @@ -535,12 +535,12 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // FindCertificateWithPrivateKey should do the right demand for us. - if (filteredCerts != null) + if (filteredCerts is not null) { for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i]; - if ((selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, clientCertificate)) != null) + if ((selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, clientCertificate)) is not null) { break; } @@ -571,8 +571,8 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && - cachedCredentialHandle == null && - selectedCert != null && + cachedCredentialHandle is null && + selectedCert is not null && SslStreamPal.StartMutualAuthAsAnonymous) { if (NetEventSource.Log.IsEnabled()) @@ -592,7 +592,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) clientCertificate = null; } - if (cachedCredentialHandle != null) + if (cachedCredentialHandle is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.UsingCachedCredential(this); @@ -602,7 +602,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } else { - if (selectedCert != null) + if (selectedCert is not null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert!); } @@ -616,7 +616,7 @@ private bool AcquireClientCredentials(ref byte[]? thumbPrint) } finally { - if (selectedCert != null && _sslAuthenticationOptions.CertificateContext != null) + if (selectedCert is not null && _sslAuthenticationOptions.CertificateContext is not null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert); } @@ -640,10 +640,10 @@ private bool AcquireServerCredentials(ref byte[]? thumbPrint) // selecting which to use, we prioritize the new ServerCertSelectionDelegate // API. If the new API isn't used we call LocalCertSelectionCallback (for compat // with .NET Framework), and if neither is set we fall back to using CertificateContext. - if (_sslAuthenticationOptions.ServerCertSelectionDelegate != null) + if (_sslAuthenticationOptions.ServerCertSelectionDelegate is not null) { localCertificate = _sslAuthenticationOptions.ServerCertSelectionDelegate(_sslAuthenticationOptions.TargetHost); - if (localCertificate == null) + if (localCertificate is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ServerCertSelectionDelegate returned no certificaete for '{_sslAuthenticationOptions.TargetHost}'."); @@ -653,13 +653,13 @@ private bool AcquireServerCredentials(ref byte[]? thumbPrint) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "ServerCertSelectionDelegate selected Cert"); } - else if (_sslAuthenticationOptions.CertSelectionDelegate != null) + else if (_sslAuthenticationOptions.CertSelectionDelegate is not null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_sslAuthenticationOptions.CertificateContext!.Certificate!); // We pass string.Empty here to maintain strict compatibility with .NET Framework. localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty()); - if (localCertificate == null) + if (localCertificate is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"CertSelectionDelegate returned no certificaete for '{_sslAuthenticationOptions.TargetHost}'."); @@ -669,16 +669,16 @@ private bool AcquireServerCredentials(ref byte[]? thumbPrint) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CertSelectionDelegate selected Cert"); } - else if (_sslAuthenticationOptions.CertificateContext != null) + else if (_sslAuthenticationOptions.CertificateContext is not null) { selectedCert = _sslAuthenticationOptions.CertificateContext.Certificate; } - if (selectedCert == null) + if (selectedCert is null) { // We will get here if certificate was selected via legacy callback using X509Certificate // Fail immediately if no certificate was given. - if (localCertificate == null) + if (localCertificate is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "Certiticate callback returned no certificaete."); @@ -690,7 +690,7 @@ private bool AcquireServerCredentials(ref byte[]? thumbPrint) // EnsurePrivateKey should do the right demand for us. selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, localCertificate); - if (selectedCert == null) + if (selectedCert is null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } @@ -709,7 +709,7 @@ private bool AcquireServerCredentials(ref byte[]? thumbPrint) byte[] guessedThumbPrint = selectedCert.GetCertHash(); SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); - if (cachedCredentialHandle != null) + if (cachedCredentialHandle is not null) { _credentialsHandle = cachedCredentialHandle; cachedCred = true; @@ -808,7 +808,7 @@ private SecurityStatusPal GenerateToken(ReadOnlySpan inputBuffer, ref byte ref result, _sslAuthenticationOptions); } - } while (cachedCreds && _credentialsHandle == null); + } while (cachedCreds && _credentialsHandle is null); } finally { @@ -826,7 +826,7 @@ private SecurityStatusPal GenerateToken(ReadOnlySpan inputBuffer, ref byte // This call may bump up the credential reference count further. // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert. // - if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid) + if (!cachedCreds && _securityContext is not null && !_securityContext.IsInvalid && _credentialsHandle is not null && !_credentialsHandle.IsInvalid) { SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); } @@ -851,7 +851,7 @@ internal void ProcessHandshakeSuccess() { // try to get ALPN info unless we already have it. (renegotiation) byte[]? alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext!); - _negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false); + _negotiatedApplicationProtocol = alpnResult is null ? default : new SslApplicationProtocol(alpnResult, false); } SslStreamPal.QueryContextStreamSizes(_securityContext!, out StreamSizes streamSizes); @@ -913,13 +913,13 @@ internal SecurityStatusPal Encrypt(ReadOnlyMemory buffer, ref byte[] outpu internal SecurityStatusPal Decrypt(byte[]? payload, ref int offset, ref int count) { - if ((uint)offset > (uint)(payload == null ? 0 : payload.Length)) + if ((uint)offset > (uint)(payload is null ? 0 : payload.Length)) { NetEventSource.Fail(this, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } - if ((uint)count > (uint)(payload == null ? 0 : payload.Length - offset)) + if ((uint)count > (uint)(payload is null ? 0 : payload.Length - offset)) { NetEventSource.Fail(this, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); @@ -956,7 +956,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot { X509Certificate2? certificate = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore); - if (_remoteCertificate != null && certificate != null && + if (_remoteCertificate is not null && certificate is not null && certificate.RawData.AsSpan().SequenceEqual(_remoteCertificate.RawData)) { // This is renegotiation or TLS 1.3 and the certificate did not change. @@ -966,7 +966,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot _remoteCertificate = certificate; - if (_remoteCertificate == null) + if (_remoteCertificate is null) { if (NetEventSource.Log.IsEnabled() && RemoteCertRequired) NetEventSource.Error(this, $"Remote certificate required, but no remote certificate received"); sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; @@ -980,7 +980,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client). chain.ChainPolicy.ApplicationPolicy.Add(_sslAuthenticationOptions.IsServer ? s_clientAuthOid : s_serverAuthOid); - if (remoteCertificateStore != null) + if (remoteCertificateStore is not null) { chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore); } @@ -994,10 +994,10 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot _sslAuthenticationOptions.TargetHost); } - if (remoteCertValidationCallback != null) + if (remoteCertValidationCallback is not null) { object? sender = _ssl; - if (sender == null) + if (sender is null) { throw new ObjectDisposedException(nameof(SslStream)); } @@ -1023,7 +1023,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot if (!success) { alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain!); - if (chain != null) + if (chain is not null) { foreach (X509ChainStatus status in chain.ChainStatus) { @@ -1037,7 +1037,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot // At least on Win2k server the chain is found to have dependencies on the original cert context. // So it should be closed first. - if (chain != null) + if (chain is not null) { int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) @@ -1048,7 +1048,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot chain.Dispose(); } - if (remoteCertificateStore != null) + if (remoteCertificateStore is not null) { int certCount = remoteCertificateStore.Count; for (int i = 0; i < certCount; i++) @@ -1090,7 +1090,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); - if (status.Exception != null) + if (status.Exception is not null) { ExceptionDispatchInfo.Throw(status.Exception); } @@ -1111,7 +1111,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); - if (status.Exception != null) + if (status.Exception is not null) { ExceptionDispatchInfo.Throw(status.Exception); } @@ -1212,7 +1212,7 @@ private void LogCertificateValidation(RemoteCertificateValidationCallback? remot if (success) { - if (remoteCertValidationCallback != null) + if (remoteCertValidationCallback is not null) { NetEventSource.Log.RemoteCertDeclaredValid(this); } @@ -1223,7 +1223,7 @@ private void LogCertificateValidation(RemoteCertificateValidationCallback? remot } else { - if (remoteCertValidationCallback != null) + if (remoteCertValidationCallback is not null) { NetEventSource.Log.RemoteCertUserDeclaredInvalid(this); } @@ -1274,7 +1274,7 @@ internal ProtocolToken(byte[]? data, SecurityStatusPal status) { Status = status; Payload = data; - Size = data != null ? data.Length : 0; + Size = data is not null ? data.Length : 0; } internal Exception? GetException() diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs index 6b1a912588065f..6b96f052e86ff5 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs @@ -23,7 +23,7 @@ namespace System.Net.Security internal SslApplicationProtocol(byte[] protocol, bool copy) { - Debug.Assert(protocol != null); + Debug.Assert(protocol is not null); // RFC 7301 states protocol size <= 255 bytes. if (protocol.Length == 0 || protocol.Length > 255) @@ -56,7 +56,7 @@ public bool Equals(SslApplicationProtocol other) => public override int GetHashCode() { byte[] arr = _readOnlyProtocol; - if (arr == null) + if (arr is null) { return 0; } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs index d3f99e6e9b4154..fe6f4d8e4afc7e 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs @@ -12,7 +12,7 @@ internal class SslAuthenticationOptions { internal SslAuthenticationOptions(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertificateValidationCallback? remoteCallback, LocalCertSelectionCallback? localCallback) { - Debug.Assert(sslClientAuthenticationOptions.TargetHost != null); + Debug.Assert(sslClientAuthenticationOptions.TargetHost is not null); // Common options. AllowRenegotiation = sslClientAuthenticationOptions.AllowRenegotiation; @@ -52,15 +52,15 @@ internal SslAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthen CipherSuitesPolicy = sslServerAuthenticationOptions.CipherSuitesPolicy; CertificateRevocationCheckMode = sslServerAuthenticationOptions.CertificateRevocationCheckMode; - if (sslServerAuthenticationOptions.ServerCertificateContext != null) + if (sslServerAuthenticationOptions.ServerCertificateContext is not null) { CertificateContext = sslServerAuthenticationOptions.ServerCertificateContext; } - else if (sslServerAuthenticationOptions.ServerCertificate != null) + else if (sslServerAuthenticationOptions.ServerCertificate is not null) { X509Certificate2? certificateWithKey = sslServerAuthenticationOptions.ServerCertificate as X509Certificate2; - if (certificateWithKey != null && certificateWithKey.HasPrivateKey) + if (certificateWithKey is not null && certificateWithKey.HasPrivateKey) { // given cert is X509Certificate2 with key. We can use it directly. CertificateContext = SslStreamCertificateContext.Create(certificateWithKey, null); @@ -70,7 +70,7 @@ internal SslAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthen // This is legacy fix-up. If the Certificate did not have key, we will search stores and we // will try to find one with matching hash. certificateWithKey = SecureChannel.FindCertificateWithPrivateKey(this, true, sslServerAuthenticationOptions.ServerCertificate); - if (certificateWithKey == null) + if (certificateWithKey is null) { throw new AuthenticationException(SR.net_ssl_io_no_server_cert); } @@ -79,7 +79,7 @@ internal SslAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthen } } - if (sslServerAuthenticationOptions.RemoteCertificateValidationCallback != null) + if (sslServerAuthenticationOptions.RemoteCertificateValidationCallback is not null) { CertValidationDelegate = sslServerAuthenticationOptions.RemoteCertificateValidationCallback; } @@ -104,7 +104,7 @@ internal void UpdateOptions(SslServerAuthenticationOptions sslServerAuthenticati RemoteCertRequired = sslServerAuthenticationOptions.ClientCertificateRequired; CipherSuitesPolicy = sslServerAuthenticationOptions.CipherSuitesPolicy; CertificateRevocationCheckMode = sslServerAuthenticationOptions.CertificateRevocationCheckMode; - if (sslServerAuthenticationOptions.ServerCertificateContext != null) + if (sslServerAuthenticationOptions.ServerCertificateContext is not null) { CertificateContext = sslServerAuthenticationOptions.ServerCertificateContext; } @@ -115,7 +115,7 @@ internal void UpdateOptions(SslServerAuthenticationOptions sslServerAuthenticati CertificateContext = SslStreamCertificateContext.Create(certificateWithKey); } - if (sslServerAuthenticationOptions.RemoteCertificateValidationCallback != null) + if (sslServerAuthenticationOptions.RemoteCertificateValidationCallback is not null) { CertValidationDelegate = sslServerAuthenticationOptions.RemoteCertificateValidationCallback; } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs index eccd25b2e0c875..20ecbd948e23ca 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs @@ -142,9 +142,9 @@ public bool Equals(SslCredKey other) // internal static void CacheCredential(SafeFreeCredentials creds, byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { - if (creds == null) + if (creds is null) { - NetEventSource.Fail(null, "creds == null"); + NetEventSource.Fail(null, "creds is null"); } if (creds!.IsInvalid) @@ -165,7 +165,7 @@ internal static void CacheCredential(SafeFreeCredentials creds, byte[]? thumbPri { cached = SafeCredentialReference.CreateReference(creds); - if (cached == null) + if (cached is null) { // Means the handle got closed in between, return it back and let caller deal with the issue. return; @@ -192,12 +192,12 @@ internal static void CacheCredential(SafeFreeCredentials creds, byte[]? thumbPri { cached = toRemoveAttempt[i].Value; - if (cached != null) + if (cached is not null) { creds = cached.Target; cached.Dispose(); - if (!creds.IsClosed && !creds.IsInvalid && (cached = SafeCredentialReference.CreateReference(creds)) != null) + if (!creds.IsClosed && !creds.IsInvalid && (cached = SafeCredentialReference.CreateReference(creds)) is not null) { s_cachedCreds[toRemoveAttempt[i].Key] = cached; } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs index e2b6f1f8be9104..e27e93f1fee2ac 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs @@ -52,17 +52,17 @@ private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthe { ThrowIfExceptional(); - if (_context != null && _context.IsValidContext) + if (_context is not null && _context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } - if (_context != null && IsServer) + if (_context is not null && IsServer) { throw new InvalidOperationException(SR.net_auth_client_server); } - if (sslClientAuthenticationOptions.TargetHost == null) + if (sslClientAuthenticationOptions.TargetHost is null) { throw new ArgumentNullException(nameof(sslClientAuthenticationOptions.TargetHost)); } @@ -83,12 +83,12 @@ private void ValidateCreateContext(SslAuthenticationOptions sslAuthenticationOpt { ThrowIfExceptional(); - if (_context != null && _context.IsValidContext) + if (_context is not null && _context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } - if (_context != null && !IsServer) + if (_context is not null && !IsServer) { throw new InvalidOperationException(SR.net_auth_client_server); } @@ -106,7 +106,7 @@ private void ValidateCreateContext(SslAuthenticationOptions sslAuthenticationOpt } } - private bool RemoteCertRequired => _context == null || _context.RemoteCertRequired; + private bool RemoteCertRequired => _context is null || _context.RemoteCertRequired; private object? SyncLock => _context; @@ -114,9 +114,9 @@ private void ValidateCreateContext(SslAuthenticationOptions sslAuthenticationOpt private void SetException(Exception e) { - Debug.Assert(e != null, $"Expected non-null Exception to be passed to {nameof(SetException)}"); + Debug.Assert(e is not null, $"Expected non-null Exception to be passed to {nameof(SetException)}"); - if (_exception == null) + if (_exception is null) { _exception = ExceptionDispatchInfo.Capture(e); } @@ -139,7 +139,7 @@ private void CloseInternal() if (Interlocked.CompareExchange(ref _nestedRead, 1, 0) == 0) { byte[]? buffer = _internalBuffer; - if (buffer != null) + if (buffer is not null) { _internalBuffer = null; _internalBufferCount = 0; @@ -148,7 +148,7 @@ private void CloseInternal() } } - if (_internalBuffer == null) + if (_internalBuffer is null) { // Suppress finalizer if the read buffer was returned. GC.SuppressFinalize(this); @@ -170,7 +170,7 @@ private SecurityStatusPal EncryptData(ReadOnlyMemory buffer, ref byte[] ou lock (_handshakeLock) { - if (_handshakeWaiter != null) + if (_handshakeWaiter is not null) { outSize = 0; // avoid waiting under lock. @@ -310,7 +310,7 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool ProtocolToken message; bool handshakeCompleted = false; - if (reAuthenticationData == null) + if (reAuthenticationData is null) { // prevent nesting only when authentication functions are called explicitly. e.g. handle renegotiation transparently. if (Interlocked.Exchange(ref _nestedAuth, 1) == 1) @@ -369,7 +369,7 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool size = payload.Length; } - if (payload != null && size > 0) + if (payload is not null && size > 0) { // If there is message send it out even if call failed. It may contain TLS Alert. await adapter.WriteAsync(payload!, 0, size).ConfigureAwait(false); @@ -410,7 +410,7 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool ProtocolToken? alertToken = null; if (!CompleteHandshake(ref alertToken, out SslPolicyErrors sslPolicyErrors, out X509ChainStatusFlags chainStatus)) { - if (_sslAuthenticationOptions!.CertValidationDelegate != null) + if (_sslAuthenticationOptions!.CertValidationDelegate is not null) { // there may be some chain errors but the decision was made by custom callback. Details should be tracing if enabled. SendAuthResetSignal(alertToken, ExceptionDispatchInfo.Capture(new AuthenticationException(SR.net_ssl_io_cert_custom_validation, null))); @@ -430,7 +430,7 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool finally { _handshakeBuffer.Dispose(); - if (reAuthenticationData == null) + if (reAuthenticationData is null) { _nestedAuth = 0; } @@ -499,8 +499,8 @@ private async ValueTask ReceiveBlobAsync(TIOAdapter a else if (_lastFrame.Header.Type == TlsContentType.Handshake) { if (_handshakeBuffer.ActiveReadOnlySpan[TlsFrameHelper.HeaderSize] == (byte)TlsHandshakeType.ClientHello && - (_sslAuthenticationOptions!.ServerCertSelectionDelegate != null || - _sslAuthenticationOptions!.ServerOptionDelegate != null)) + (_sslAuthenticationOptions!.ServerCertSelectionDelegate is not null || + _sslAuthenticationOptions!.ServerOptionDelegate is not null)) { TlsFrameHelper.ProcessingOptions options = NetEventSource.Log.IsEnabled() ? TlsFrameHelper.ProcessingOptions.All : @@ -515,12 +515,12 @@ private async ValueTask ReceiveBlobAsync(TIOAdapter a if (_lastFrame.HandshakeType == TlsHandshakeType.ClientHello) { // SNI if it exist. Even if we could not parse the hello, we can fall-back to default certificate. - if (_lastFrame.TargetName != null) + if (_lastFrame.TargetName is not null) { _sslAuthenticationOptions!.TargetHost = _lastFrame.TargetName; } - if (_sslAuthenticationOptions.ServerOptionDelegate != null) + if (_sslAuthenticationOptions.ServerOptionDelegate is not null) { SslServerAuthenticationOptions userOptions = await _sslAuthenticationOptions.ServerOptionDelegate(this, new SslClientHelloInfo(_sslAuthenticationOptions.TargetHost, _lastFrame.SupportedVersions), @@ -584,7 +584,7 @@ private void SendAuthResetSignal(ProtocolToken? message, ExceptionDispatchInfo e { SetException(exception.SourceException); - if (message == null || message.Size == 0) + if (message is null || message.Size == 0) { // // We don't have an alert to send so cannot retry and fail prematurely. @@ -649,7 +649,7 @@ private ValueTask WriteSingleChunk(TIOAdapter writeAdapter, ReadOnly } TaskCompletionSource? waiter = _handshakeWaiter; - if (waiter != null) + if (waiter is not null) { Task waiterTask = writeAdapter.WaitAsync(waiter); // We finished synchronously waiting for renegotiation. We can try again immediately. @@ -710,7 +710,7 @@ async ValueTask WaitAndWriteAsync(TIOAdapter writeAdapter, ReadOnlyMemory } finally { - if (bufferToReturn != null) + if (bufferToReturn is not null) { ArrayPool.Shared.Return(bufferToReturn); } @@ -735,7 +735,7 @@ async ValueTask CompleteWriteAsync(ValueTask writeTask, byte[] bufferToReturn) // private void ValidateParameters(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -765,7 +765,7 @@ private void ValidateParameters(byte[] buffer, int offset, int count) // actually contains no decrypted or encrypted bytes private void ReturnReadBufferIfEmpty() { - if (_internalBuffer != null && _decryptedBytesCount == 0 && _internalBufferCount == 0) + if (_internalBuffer is not null && _decryptedBytesCount == 0 && _internalBufferCount == 0) { ArrayPool.Shared.Return(_internalBuffer); _internalBuffer = null; @@ -885,7 +885,7 @@ private async ValueTask ReadAsyncInternal(TIOAdapter adapter, M if (status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate) { // We determine above that we will not process it. - if (_handshakeWaiter == null) + if (_handshakeWaiter is null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Fail(this, "Renegotiation was requested but it is disallowed"); throw new IOException(SR.net_ssl_io_renego); @@ -1061,7 +1061,7 @@ private void ResetReadBuffer() { Debug.Assert(_decryptedBytesCount == 0); - if (_internalBuffer == null) + if (_internalBuffer is null) { _internalBuffer = ArrayPool.Shared.Rent(ReadBufferSize); } @@ -1077,11 +1077,11 @@ private void ResetReadBuffer() private static byte[] EnsureBufferSize(byte[] buffer, int copyCount, int size) { - if (buffer == null || buffer.Length < size) + if (buffer is null || buffer.Length < size) { byte[]? saved = buffer; buffer = new byte[size]; - if (saved != null && copyCount != 0) + if (saved is not null && copyCount != 0) { Buffer.BlockCopy(saved, 0, buffer, 0, copyCount); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs index 03cf0a8d90f54e..b9c20e6c1cef5d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs @@ -101,7 +101,7 @@ public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificat _userCertificateValidationCallback = userCertificateValidationCallback; _userCertificateSelectionCallback = userCertificateSelectionCallback; _encryptionPolicy = encryptionPolicy; - _certSelectionDelegate = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); + _certSelectionDelegate = userCertificateSelectionCallback is null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); _innerStream = innerStream; @@ -112,7 +112,7 @@ public SslApplicationProtocol NegotiatedApplicationProtocol { get { - if (_context == null) + if (_context is null) return default; return _context.NegotiatedApplicationProtocol; @@ -121,11 +121,11 @@ public SslApplicationProtocol NegotiatedApplicationProtocol private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback? callback) { - if (_userCertificateValidationCallback == null) + if (_userCertificateValidationCallback is null) { _userCertificateValidationCallback = callback; } - else if (callback != null && _userCertificateValidationCallback != callback) + else if (callback is not null && _userCertificateValidationCallback != callback) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(RemoteCertificateValidationCallback))); } @@ -133,12 +133,12 @@ private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback? private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback? callback) { - if (_userCertificateSelectionCallback == null) + if (_userCertificateSelectionCallback is null) { _userCertificateSelectionCallback = callback; - _certSelectionDelegate = _userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); + _certSelectionDelegate = _userCertificateSelectionCallback is null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); } - else if (callback != null && _userCertificateSelectionCallback != callback) + else if (callback is not null && _userCertificateSelectionCallback != callback) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(LocalCertificateSelectionCallback))); } @@ -153,13 +153,13 @@ private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509 private SslAuthenticationOptions CreateAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthenticationOptions) { - if (sslServerAuthenticationOptions.ServerCertificate == null && sslServerAuthenticationOptions.ServerCertificateContext == null && - sslServerAuthenticationOptions.ServerCertificateSelectionCallback == null && _certSelectionDelegate == null) + if (sslServerAuthenticationOptions.ServerCertificate is null && sslServerAuthenticationOptions.ServerCertificateContext is null && + sslServerAuthenticationOptions.ServerCertificateSelectionCallback is null && _certSelectionDelegate is null) { throw new ArgumentNullException(nameof(sslServerAuthenticationOptions.ServerCertificate)); } - if ((sslServerAuthenticationOptions.ServerCertificate != null || sslServerAuthenticationOptions.ServerCertificateContext != null || _certSelectionDelegate != null) && sslServerAuthenticationOptions.ServerCertificateSelectionCallback != null) + if ((sslServerAuthenticationOptions.ServerCertificate is not null || sslServerAuthenticationOptions.ServerCertificateContext is not null || _certSelectionDelegate is not null) && sslServerAuthenticationOptions.ServerCertificateSelectionCallback is not null) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(ServerCertificateSelectionCallback))); } @@ -167,7 +167,7 @@ private SslAuthenticationOptions CreateAuthenticationOptions(SslServerAuthentica var authOptions = new SslAuthenticationOptions(sslServerAuthenticationOptions); _userServerCertificateSelectionCallback = sslServerAuthenticationOptions.ServerCertificateSelectionCallback; - authOptions.ServerCertSelectionDelegate = _userServerCertificateSelectionCallback == null ? null : new ServerCertSelectionCallback(ServerCertSelectionCallbackWrapper); + authOptions.ServerCertSelectionDelegate = _userServerCertificateSelectionCallback is null ? null : new ServerCertSelectionCallback(ServerCertSelectionCallbackWrapper); authOptions.CertValidationDelegate = _userCertificateValidationCallback; authOptions.CertSelectionDelegate = _certSelectionDelegate; @@ -285,7 +285,7 @@ public virtual void AuthenticateAsClient(string targetHost, X509CertificateColle public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions) { - if (sslClientAuthenticationOptions == null) + if (sslClientAuthenticationOptions is null) { throw new ArgumentNullException(nameof(sslClientAuthenticationOptions)); } @@ -323,7 +323,7 @@ public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions) { - if (sslServerAuthenticationOptions == null) + if (sslServerAuthenticationOptions is null) { throw new ArgumentNullException(nameof(sslServerAuthenticationOptions)); } @@ -356,7 +356,7 @@ public virtual Task AuthenticateAsClientAsync(string targetHost, X509Certificate public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken = default) { - if (sslClientAuthenticationOptions == null) + if (sslClientAuthenticationOptions is null) { throw new ArgumentNullException(nameof(sslClientAuthenticationOptions)); } @@ -411,7 +411,7 @@ public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken = default) { - if (sslServerAuthenticationOptions == null) + if (sslServerAuthenticationOptions is null) { throw new ArgumentNullException(nameof(sslServerAuthenticationOptions)); } @@ -446,7 +446,7 @@ public virtual Task ShutdownAsync() } #endregion - public override bool IsAuthenticated => _context != null && _context.IsValidContext && _exception == null && _handshakeCompleted; + public override bool IsAuthenticated => _context is not null && _context.IsValidContext && _exception is null && _handshakeCompleted; public override bool IsMutuallyAuthenticated { @@ -454,7 +454,7 @@ public override bool IsMutuallyAuthenticated { return IsAuthenticated && - (_context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate) != null && + (_context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate) is not null && _context.IsRemoteCertificateAvailable; /* does not work: Context.IsMutualAuthFlag;*/ } } @@ -463,7 +463,7 @@ public override bool IsMutuallyAuthenticated public override bool IsSigned => IsAuthenticated; - public override bool IsServer => _context != null && _context.IsServer; + public override bool IsServer => _context is not null && _context.IsServer; public virtual SslProtocols SslProtocol { @@ -478,7 +478,7 @@ public virtual SslProtocols SslProtocol private SslProtocols GetSslProtocolInternal() { SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return SslProtocols.None; } @@ -522,7 +522,7 @@ private SslProtocols GetSslProtocolInternal() return ret; } - public virtual bool CheckCertRevocationStatus => _context != null && _context.CheckCertRevocationStatus != X509RevocationMode.NoCheck; + public virtual bool CheckCertRevocationStatus => _context is not null && _context.CheckCertRevocationStatus != X509RevocationMode.NoCheck; // // This will return selected local cert for both client/server streams @@ -561,7 +561,7 @@ public virtual CipherAlgorithmType CipherAlgorithm { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return CipherAlgorithmType.None; } @@ -575,7 +575,7 @@ public virtual int CipherStrength { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return 0; } @@ -590,7 +590,7 @@ public virtual HashAlgorithmType HashAlgorithm { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return (HashAlgorithmType)0; } @@ -604,7 +604,7 @@ public virtual int HashStrength { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return 0; } @@ -619,7 +619,7 @@ public virtual ExchangeAlgorithmType KeyExchangeAlgorithm { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return (ExchangeAlgorithmType)0; } @@ -634,7 +634,7 @@ public virtual int KeyExchangeStrength { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; - if (info == null) + if (info is null) { return 0; } @@ -647,7 +647,7 @@ public string TargetHostName { get { - return _sslAuthenticationOptions != null ? _sslAuthenticationOptions.TargetHost : string.Empty; + return _sslAuthenticationOptions is not null ? _sslAuthenticationOptions.TargetHost : string.Empty; } } @@ -824,7 +824,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken private void ThrowIfExceptional() { ExceptionDispatchInfo? e = _exception; - if (e != null) + if (e is not null) { ThrowExceptional(e); } @@ -860,7 +860,7 @@ private void ThrowIfExceptionalOrNotHandshake() { ThrowIfExceptional(); - if (!IsAuthenticated && _context?.ConnectionInfo == null) + if (!IsAuthenticated && _context?.ConnectionInfo is null) { ThrowNotAuthenticated(); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.Windows.cs index 0827eca16d572e..3848793ac5f6e8 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.Windows.cs @@ -69,7 +69,7 @@ private SslStreamCertificateContext(X509Certificate2 target, X509Certificate2[] } } - if (store != null) + if (store is not null) { using (store) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.cs index 4cba3232be530f..b321ac251e8baf 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamCertificateContext.cs @@ -20,7 +20,7 @@ public static SslStreamCertificateContext Create(X509Certificate2 target, X509Ce X509Certificate2[] intermediates = Array.Empty(); using (X509Chain chain = new X509Chain()) { - if (additionalCertificates != null) + if (additionalCertificates is not null) { foreach (X509Certificate cert in additionalCertificates) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs index 5f1c1bb346676e..df96c61fc79041 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs @@ -63,7 +63,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle( internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext? context) { - if (context == null) + if (context is null) return null; return Interop.AppleCrypto.SslGetAlpnSelected(((SafeDeleteSslContext)context).SslContext); @@ -231,7 +231,7 @@ private static SecurityStatusPal HandshakeInternal( { SafeDeleteSslContext? sslContext = ((SafeDeleteSslContext?)context); - if ((null == context) || context.IsInvalid) + if ((context is null) || context.IsInvalid) { sslContext = new SafeDeleteSslContext((credential as SafeFreeSslCredentials)!, sslAuthenticationOptions); context = sslContext; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs index aeae1edc9fe946..08c959f74a5505 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs @@ -66,7 +66,7 @@ public static SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext { bindingHandle = EndpointChannelBindingToken.Build(securityContext); - if (bindingHandle == null) + if (bindingHandle is null) { throw Interop.OpenSsl.CreateSslException(SR.net_ssl_invalid_certificate); } @@ -106,7 +106,7 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia try { - if ((null == context) || context.IsInvalid) + if ((context is null) || context.IsInvalid) { context = new SafeDeleteSslContext((credential as SafeFreeSslCredentials)!, sslAuthenticationOptions); } @@ -118,7 +118,7 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia // We have this workaround, as openssl supports terminating handshake only from version 1.1.0, // whereas ALPN is supported from version 1.0.2. SafeSslHandle sslContext = ((SafeDeleteSslContext)context).SslContext; - if (done && sslAuthenticationOptions.IsServer && sslAuthenticationOptions.ApplicationProtocols != null && sslContext.AlpnHandle.IsAllocated && sslContext.AlpnHandle.Target == null) + if (done && sslAuthenticationOptions.IsServer && sslAuthenticationOptions.ApplicationProtocols is not null && sslContext.AlpnHandle.IsAllocated && sslContext.AlpnHandle.Target is null) { return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, Interop.OpenSsl.CreateSslException(SR.net_alpn_failed)); } @@ -144,7 +144,7 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext? context) { - if (context == null) + if (context is null) return null; return Interop.Ssl.SslGetAlpnSelected(((SafeDeleteSslContext)context).SslContext); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs index 4c3c2c22db42e0..9b22fd785a030f 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs @@ -58,7 +58,7 @@ public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials? c inputBuffers.SetNextBuffer(new InputSecurityBuffer(inputBuffer, SecurityBufferType.SECBUFFER_TOKEN)); inputBuffers.SetNextBuffer(new InputSecurityBuffer(default, SecurityBufferType.SECBUFFER_EMPTY)); - if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) + if (sslAuthenticationOptions.ApplicationProtocols is not null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); inputBuffers.SetNextBuffer(new InputSecurityBuffer(new ReadOnlySpan(alpnBytes), SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS)); @@ -87,7 +87,7 @@ public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredential InputSecurityBuffers inputBuffers = default; inputBuffers.SetNextBuffer(new InputSecurityBuffer(inputBuffer, SecurityBufferType.SECBUFFER_TOKEN)); inputBuffers.SetNextBuffer(new InputSecurityBuffer(default, SecurityBufferType.SECBUFFER_EMPTY)); - if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) + if (sslAuthenticationOptions.ApplicationProtocols is not null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); inputBuffers.SetNextBuffer(new InputSecurityBuffer(new ReadOnlySpan(alpnBytes), SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS)); @@ -155,7 +155,7 @@ public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchannelCred(X5 policy); Interop.Crypt32.CERT_CONTEXT* certificateHandle = null; - if (certificate != null) + if (certificate is not null) { secureCredential.cCreds = 1; certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; @@ -209,7 +209,7 @@ public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchCredentials( credential.dwFlags = flags; Interop.Crypt32.CERT_CONTEXT *certificateHandle = null; - if (certificate != null) + if (certificate is not null) { credential.cCreds = 1; certificateHandle = (Interop.Crypt32.CERT_CONTEXT *)certificate.Handle; @@ -260,7 +260,7 @@ public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteSslContext secur NetEventSource.Fail(securityContext, "Arguments out of range"); throw; } - if (output == null || output.Length < bufferSizeNeeded) + if (output is null || output.Length < bufferSizeNeeded) { output = new byte[bufferSizeNeeded]; } diff --git a/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs b/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs index dd28c356dc22ad..d1394fcf5b86ac 100644 --- a/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs +++ b/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs @@ -13,7 +13,7 @@ internal sealed class SslStreamContext : TransportContext internal SslStreamContext(SslStream sslStream) { - Debug.Assert(sslStream != null); + Debug.Assert(sslStream is not null); _sslStream = sslStream!; } diff --git a/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs b/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs index 9d7f648d87205f..b05b59e24aac4e 100644 --- a/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs +++ b/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs @@ -75,7 +75,7 @@ internal sealed class StreamFramer public async Task WriteMessageAsync(TAdapter adapter, byte[] message) where TAdapter : IReadWriteAdapter { - if (message == null) + if (message is null) { throw new ArgumentNullException(nameof(message)); } diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs index fe69152dc10a6b..4f0c46f089cbd6 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs @@ -28,7 +28,7 @@ public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, throw new ArgumentException(SR.security_ExtendedProtectionPolicy_UseDifferentConstructorForNever, nameof(policyEnforcement)); } - if (customServiceNames != null && customServiceNames.Count == 0) + if (customServiceNames is not null && customServiceNames.Count == 0) { throw new ArgumentException(SR.security_ExtendedProtectionPolicy_NoEmptyServiceNameCollection, nameof(customServiceNames)); } @@ -42,7 +42,7 @@ public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, ProtectionScenario protectionScenario, ICollection? customServiceNames) : this(policyEnforcement, protectionScenario, - customServiceNames == null ? (ServiceNameCollection?)null : new ServiceNameCollection(customServiceNames)) + customServiceNames is null ? (ServiceNameCollection?)null : new ServiceNameCollection(customServiceNames)) { } @@ -54,7 +54,7 @@ public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, throw new ArgumentException(SR.security_ExtendedProtectionPolicy_UseDifferentConstructorForNever, nameof(policyEnforcement)); } - if (customChannelBinding == null) + if (customChannelBinding is null) { throw new ArgumentNullException(nameof(customChannelBinding)); } @@ -110,7 +110,7 @@ public override string ToString() sb.Append(_policyEnforcement.ToString()); sb.Append("; CustomChannelBinding="); - if (_customChannelBinding == null) + if (_customChannelBinding is null) { sb.Append(""); } @@ -120,7 +120,7 @@ public override string ToString() } sb.Append("; ServiceNames="); - if (_customServiceNames == null) + if (_customServiceNames is null) { sb.Append(""); } diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs index 8797f31cf589e6..93a643859535a9 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs @@ -14,7 +14,7 @@ public class ServiceNameCollection : ReadOnlyCollectionBase { public ServiceNameCollection(ICollection items) { - if (items == null) + if (items is null) { throw new ArgumentNullException(nameof(items)); } @@ -45,7 +45,7 @@ private ServiceNameCollection(IList list, IEnumerable serviceNames) private ServiceNameCollection(IList list, int additionalCapacity) { - Debug.Assert(list != null); + Debug.Assert(list is not null); Debug.Assert(additionalCapacity >= 0); foreach (string? item in list) @@ -79,14 +79,14 @@ public bool Contains(string? searchServiceName) private void AddIfNew(IEnumerable serviceNames, bool expectStrings) { List? list = serviceNames as List; - if (list != null) + if (list is not null) { AddIfNew(list); return; } ServiceNameCollection? snc = serviceNames as ServiceNameCollection; - if (snc != null) + if (snc is not null) { AddIfNew(snc.InnerList); return; @@ -109,7 +109,7 @@ private void AddIfNew(IEnumerable serviceNames, bool expectStrings) /// private void AddIfNew(List serviceNames) { - Debug.Assert(serviceNames != null); + Debug.Assert(serviceNames is not null); foreach (string serviceName in serviceNames) { @@ -122,7 +122,7 @@ private void AddIfNew(List serviceNames) /// private void AddIfNew(IList serviceNames) { - Debug.Assert(serviceNames != null); + Debug.Assert(serviceNames is not null); foreach (string serviceName in serviceNames) { @@ -154,7 +154,7 @@ private void AddIfNew(string serviceName) private static int GetCountOrOne(IEnumerable collection) { ICollection? c = collection as ICollection; - return c != null ? c.Count : 1; + return c is not null ? c.Count : 1; } // Normalizes any punycode to Unicode in an Service Name (SPN) host. diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Unix.cs index 657544b27c319c..991039b4d1f4dc 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Unix.cs @@ -21,7 +21,7 @@ internal Socket? AcceptSocket { // *nix does not support the reuse of an existing socket as the accepted // socket. - Debug.Assert(value == null, $"Unexpected value: {value}"); + Debug.Assert(value is null, $"Unexpected value: {value}"); } } @@ -32,7 +32,7 @@ public void CompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddre if (errorCode == SocketError.Success) { - Debug.Assert(_listenSocket._rightEndPoint != null); + Debug.Assert(_listenSocket._rightEndPoint is not null); Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint); System.Buffer.BlockCopy(socketAddress, 0, remoteSocketAddress.Buffer, 0, socketAddressLen); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs index d85b2bfc8c4aff..054e584fbe9eb2 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs @@ -39,7 +39,7 @@ internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncR safeHandle.DangerousAddRef(ref refAdded); IntPtr handle = safeHandle.DangerousGetHandle(); - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); _listenSocket.GetAcceptExSockaddrs( Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, 0), _buffer.Length - (_addressBufferLength * 2), @@ -111,7 +111,7 @@ private void LogBuffer(long size) // condition where tracing is disabled between a calling check and here, in which case the assert // may fire erroneously. Debug.Assert(NetEventSource.Log.IsEnabled()); - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); if (size > -1) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs index d431c2447514d6..87176ee79613aa 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs @@ -38,8 +38,8 @@ internal void SetUnmanagedStructures(object? objectsToPin) Socket s = (Socket)AsyncObject!; // Bind the Win32 Socket Handle to the ThreadPool - Debug.Assert(s != null, "m_CurrentSocket is null"); - Debug.Assert(s.SafeHandle != null, "m_CurrentSocket.SafeHandle is null"); + Debug.Assert(s is not null, "m_CurrentSocket is null"); + Debug.Assert(s.SafeHandle is not null, "m_CurrentSocket.SafeHandle is null"); if (s.SafeHandle.IsInvalid) { @@ -81,7 +81,7 @@ private static unsafe void CompletionPortCallback(uint errorCode, uint numBytes, // be other differences as well." Socket? socket = asyncResult.AsyncObject as Socket; - if (socket == null) + if (socket is null) { socketError = SocketError.NotSocket; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs index 26ad1a249db2ef..45b75f42f08fe3 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs @@ -24,7 +24,7 @@ internal sealed class IOControlKeepAlive public static SocketError Get(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds, ref int optionLength) { - if (optionValueSeconds == null || + if (optionValueSeconds is null || !BitConverter.TryWriteBytes(optionValueSeconds.AsSpan(), Get(handle, optionName))) { return SocketError.Fault; @@ -50,7 +50,7 @@ public static int Get(SafeSocketHandle handle, SocketOptionName optionName) public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds) { - if (optionValueSeconds == null || + if (optionValueSeconds is null || optionValueSeconds.Length < sizeof(int)) { return SocketError.Fault; @@ -111,7 +111,7 @@ private static bool SupportsKeepAliveViaSocketOption() private void Fill(byte[] buffer) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(buffer.Length == 3 * sizeof(uint)); const uint OnOff = 1u; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IPPacketInformation.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IPPacketInformation.cs index 23da276cb53b25..fb81eefb0d7f1d 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IPPacketInformation.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IPPacketInformation.cs @@ -33,8 +33,8 @@ public int Interface public static bool operator ==(IPPacketInformation packetInformation1, IPPacketInformation packetInformation2) { return packetInformation1._networkInterface == packetInformation2._networkInterface && - ((packetInformation1._address == null && packetInformation2._address == null) || - (packetInformation1._address != null && packetInformation1._address.Equals(packetInformation2._address))); + ((packetInformation1._address is null && packetInformation2._address is null) || + (packetInformation1._address is not null && packetInformation1._address.Equals(packetInformation2._address))); } public static bool operator !=(IPPacketInformation packetInformation1, IPPacketInformation packetInformation2) @@ -48,7 +48,7 @@ public override bool Equals(object? comparand) => public override int GetHashCode() { return unchecked(_networkInterface.GetHashCode() * (int)0xA5555529) + - (_address == null ? 0 : _address.GetHashCode()); + (_address is null ? 0 : _address.GetHashCode()); } } } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs index 19e8b5ef80dff9..87312453f2fbeb 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs @@ -14,12 +14,12 @@ public class MulticastOption // group and local address. public MulticastOption(IPAddress group, IPAddress mcint) { - if (group == null) + if (group is null) { throw new ArgumentNullException(nameof(group)); } - if (mcint == null) + if (mcint is null) { throw new ArgumentNullException(nameof(mcint)); } @@ -30,7 +30,7 @@ public MulticastOption(IPAddress group, IPAddress mcint) public MulticastOption(IPAddress group, int interfaceIndex) { - if (group == null) + if (group is null) { throw new ArgumentNullException(nameof(group)); } @@ -47,7 +47,7 @@ public MulticastOption(IPAddress group, int interfaceIndex) // Creates a new version of the MulticastOption class for the specified group. public MulticastOption(IPAddress group) { - if (group == null) + if (group is null) { throw new ArgumentNullException(nameof(group)); } @@ -113,7 +113,7 @@ public class IPv6MulticastOption // address group and local address. public IPv6MulticastOption(IPAddress group, long ifindex) { - if (group == null) + if (group is null) { throw new ArgumentNullException(nameof(group)); } @@ -131,7 +131,7 @@ public IPv6MulticastOption(IPAddress group, long ifindex) // group. public IPv6MulticastOption(IPAddress group) { - if (group == null) + if (group is null) { throw new ArgumentNullException(nameof(group)); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs index ff10fb26745153..48932b24833497 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs @@ -114,7 +114,7 @@ private bool DoDnsCallback(IAsyncResult result, bool sync) try { _addressList = Dns.EndGetHostAddresses(result); - if (_addressList == null) + if (_addressList is null) { NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!"); } @@ -126,7 +126,7 @@ private bool DoDnsCallback(IAsyncResult result, bool sync) } // If the dns query succeeded, try to connect to the first address - if (exception == null) + if (exception is null) { _state = State.ConnectAttempt; @@ -136,7 +136,7 @@ private bool DoDnsCallback(IAsyncResult result, bool sync) (exception, pending) = AttemptConnection(); - if (exception != null) + if (exception is not null) { // There was a synchronous error while connecting _state = State.Completed; @@ -145,7 +145,7 @@ private bool DoDnsCallback(IAsyncResult result, bool sync) } // Call this outside of the lock because it might call the user's callback. - if (exception != null) + if (exception is not null) { return Fail(sync, exception); } @@ -210,7 +210,7 @@ private bool DoConnectCallback(SocketAsyncEventArgs args, bool sync) (Exception? connectException, bool pending) = AttemptConnection(); - if (connectException == null) + if (connectException is null) { if (pending) { @@ -224,7 +224,7 @@ private bool DoConnectCallback(SocketAsyncEventArgs args, bool sync) else { SocketException? socketException = connectException as SocketException; - if (socketException != null && socketException.SocketErrorCode == SocketError.NoData) + if (socketException is not null && socketException.SocketErrorCode == SocketError.NoData) { // If the error is NoData, that means there are no more IPAddresses to attempt // a connection to. Return the last error from an actual connection instead. @@ -243,7 +243,7 @@ private bool DoConnectCallback(SocketAsyncEventArgs args, bool sync) } } - if (exception != null) + if (exception is not null) { return Fail(sync, exception); } @@ -261,11 +261,11 @@ private bool DoConnectCallback(SocketAsyncEventArgs args, bool sync) try { IPAddress? attemptAddress = GetNextAddress(out Socket? attemptSocket); - if (attemptAddress == null) + if (attemptAddress is null) { return (new SocketException((int)SocketError.NoData), false); } - Debug.Assert(attemptSocket != null); + Debug.Assert(attemptSocket is not null); SocketAsyncEventArgs args = _internalArgs!; args.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint!.Port); @@ -322,13 +322,13 @@ private void SyncFail(Exception e) { OnFail(false); - if (_internalArgs != null) + if (_internalArgs is not null) { _internalArgs.Dispose(); } SocketException? socketException = e as SocketException; - if (socketException != null) + if (socketException is not null) { _userArgs!.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None); } @@ -342,7 +342,7 @@ private void AsyncFail(Exception e) { OnFail(false); - if (_internalArgs != null) + if (_internalArgs is not null) { _internalArgs.Dispose(); } @@ -491,7 +491,7 @@ public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protoc IPAddress? rval = null; attemptSocket = null; - while (attemptSocket == null) + while (attemptSocket is null) { if (_nextAddress >= _addressList!.Length) { @@ -518,11 +518,11 @@ public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protoc // on success, close the socket that wasn't used protected override void OnSucceed() { - if (_socket4 != null && !_socket4.Connected) + if (_socket4 is not null && !_socket4.Connected) { _socket4.Dispose(); } - if (_socket6 != null && !_socket6.Connected) + if (_socket6 is not null && !_socket6.Connected) { _socket6.Dispose(); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs index 7ee46c5546819e..f3ac72fbb58fdf 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs @@ -40,7 +40,7 @@ public NetworkStream(Socket socket, FileAccess access) public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) { - if (socket == null) + if (socket is null) { throw new ArgumentNullException(nameof(socket)); } @@ -224,7 +224,7 @@ public override int Read(byte[] buffer, int offset, int size) } // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -305,7 +305,7 @@ public override void Write(byte[] buffer, int offset, int size) } // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -424,7 +424,7 @@ public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, Asyn } // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -470,7 +470,7 @@ public override int EndRead(IAsyncResult asyncResult) ThrowIfDisposed(); // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -513,7 +513,7 @@ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, Asy } // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -556,7 +556,7 @@ public override void EndWrite(IAsyncResult asyncResult) ThrowIfDisposed(); // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -600,7 +600,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int size, Cancell } // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -683,7 +683,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int size, Cancellatio } // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Unix.cs index 49cb1262b3d1bc..5fec04e9a87f0d 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Unix.cs @@ -20,9 +20,9 @@ internal int GetSocketAddressSize() public void CompletionCallback(int numBytes, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode) { - if (_socketAddress != null) + if (_socketAddress is not null) { - Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socket address: {socketAddress}"); + Debug.Assert(socketAddress is null || _socketAddress.Buffer == socketAddress, $"Unexpected socket address: {socketAddress}"); _socketAddressSize = socketAddressSize; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs index dced861318f9f9..b5401618f844c0 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs @@ -41,7 +41,7 @@ internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, Intern { // Fill in Buffer Array structure that will be used for our send/recv Buffer _socketAddress = socketAddress; - if (_socketAddress != null) + if (_socketAddress is not null) { object[] objectsToPin = new object[2]; objectsToPin[0] = buffer; @@ -115,7 +115,7 @@ private void LogBuffer(int size) if (size > -1) { - if (_wsaBuffers != null) + if (_wsaBuffers is not null) { foreach (WSABuffer wsaBuffer in _wsaBuffers) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Unix.cs index aa596b291b015e..30cd357c0a3cc7 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Unix.cs @@ -16,8 +16,8 @@ internal int GetSocketAddressSize() public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { - Debug.Assert(_socketAddress != null, "_socketAddress was null"); - Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); + Debug.Assert(_socketAddress is not null, "_socketAddress was null"); + Debug.Assert(socketAddress is null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _socketFlags = receivedFlags; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs index 5aa6bf3289876c..acc39d6ac95cd3 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs @@ -49,7 +49,7 @@ internal unsafe void SetUnmanagedStructures(byte[] buffer, int offset, int size, } // Pin buffers. - object[] objectsToPin = new object[(_controlBuffer != null) ? 5 : 4]; + object[] objectsToPin = new object[(_controlBuffer is not null) ? 5 : 4]; objectsToPin[0] = buffer; objectsToPin[1] = _messageBuffer; objectsToPin[2] = _wsaBufferArray; @@ -59,7 +59,7 @@ internal unsafe void SetUnmanagedStructures(byte[] buffer, int offset, int size, _socketAddress.CopyAddressSizeIntoBuffer(); objectsToPin[3] = _socketAddress.Buffer; - if (_controlBuffer != null) + if (_controlBuffer is not null) { objectsToPin[4] = _controlBuffer; } @@ -79,7 +79,7 @@ internal unsafe void SetUnmanagedStructures(byte[] buffer, int offset, int size, _message->buffers = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0); _message->count = 1; - if (_controlBuffer != null) + if (_controlBuffer is not null) { _message->controlBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0); _message->controlBuffer.Length = _controlBuffer.Length; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Unix.cs index d554a150ef3c1c..9fd02a61dcef73 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Unix.cs @@ -99,7 +99,7 @@ internal SocketAsyncContext AsyncContext { get { - if (Volatile.Read(ref _asyncContext) == null) + if (Volatile.Read(ref _asyncContext) is null) { Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs index ad59c2e65dbc27..abd437a8dc441b 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs @@ -32,7 +32,7 @@ internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCo ThrowSocketDisposedException(); } - if (_iocpBoundHandle != null) + if (_iocpBoundHandle is not null) { return _iocpBoundHandle; } @@ -41,7 +41,7 @@ internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCo { ThreadPoolBoundHandle? boundHandle = _iocpBoundHandle; - if (boundHandle == null) + if (boundHandle is null) { // Bind the socket native _handle to the ThreadPool. if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "calling ThreadPool.BindHandle()"); @@ -94,7 +94,7 @@ internal bool SkipCompletionPortOnSuccess { get { - Debug.Assert(_iocpBoundHandle != null); + Debug.Assert(_iocpBoundHandle is not null); return _skipCompletionPortOnSuccess; } } @@ -104,7 +104,7 @@ private bool OnHandleClose() { // Keep m_IocpBoundHandle around after disposing it to allow freeing NativeOverlapped. // ThreadPoolBoundHandle allows FreeNativeOverlapped even after it has been disposed. - if (_iocpBoundHandle != null) + if (_iocpBoundHandle is not null) { Debug.Assert(OperatingSystem.IsWindows()); _iocpBoundHandle.Dispose(); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs index f800906120ce28..7b719b283283e6 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs @@ -28,7 +28,7 @@ public SendPacketsElement(string filepath, long offset, int count) : public SendPacketsElement(string filepath, long offset, int count, bool endOfPacket) { // We will validate if the file exists on send. - if (filepath == null) + if (filepath is null) { throw new ArgumentNullException(nameof(filepath)); } @@ -57,7 +57,7 @@ public SendPacketsElement(FileStream fileStream, long offset, int count) : public SendPacketsElement(FileStream fileStream, long offset, int count, bool endOfPacket) { // We will validate if the fileStream exists on send. - if (fileStream == null) + if (fileStream is null) { throw new ArgumentNullException(nameof(fileStream)); } @@ -80,7 +80,7 @@ public SendPacketsElement(FileStream fileStream, long offset, int count, bool en // Constructors for buffer elements. public SendPacketsElement(byte[] buffer) : - this(buffer, 0, (buffer != null ? buffer.Length : 0), false) + this(buffer, 0, (buffer is not null ? buffer.Length : 0), false) { } public SendPacketsElement(byte[] buffer, int offset, int count) : @@ -89,7 +89,7 @@ public SendPacketsElement(byte[] buffer, int offset, int count) : public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs index 2318077011db88..c4deed0872f87a 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs @@ -128,7 +128,7 @@ static async ValueTask WaitForConnectWithCancellation(AwaitableSocketAsyncEventA internal ValueTask ConnectAsync(IPAddress[] addresses, int port, CancellationToken cancellationToken) { - if (addresses == null) + if (addresses is null) { throw new ArgumentNullException(nameof(addresses)); } @@ -156,7 +156,7 @@ private async ValueTask DoConnectAsync(IPAddress[] addresses, int port, Cancella } } - Debug.Assert(lastException != null); + Debug.Assert(lastException is not null); ExceptionDispatchInfo.Throw(lastException); } @@ -164,7 +164,7 @@ private async ValueTask DoConnectAsync(IPAddress[] addresses, int port, Cancella internal ValueTask ConnectAsync(string host, int port, CancellationToken cancellationToken) { - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } @@ -192,7 +192,7 @@ internal ValueTask ReceiveAsync(Memory buffer, SocketFlags socketFlag Interlocked.Exchange(ref _singleBufferReceiveEventArgs, null) ?? new AwaitableSocketAsyncEventArgs(this, isReceiveForCaching: true); - Debug.Assert(saea.BufferList == null); + Debug.Assert(saea.BufferList is null); saea.SetBuffer(buffer); saea.SocketFlags = socketFlags; saea.WrapExceptionsForNetworkStream = fromNetworkStream; @@ -275,7 +275,7 @@ internal ValueTask SendAsync(ReadOnlyMemory buffer, SocketFlags socke Interlocked.Exchange(ref _singleBufferSendEventArgs, null) ?? new AwaitableSocketAsyncEventArgs(this, isReceiveForCaching: false); - Debug.Assert(saea.BufferList == null); + Debug.Assert(saea.BufferList is null); saea.SetBuffer(MemoryMarshal.AsMemory(buffer)); saea.SocketFlags = socketFlags; saea.WrapExceptionsForNetworkStream = false; @@ -293,7 +293,7 @@ internal ValueTask SendAsyncForNetworkStream(ReadOnlyMemory buffer, Socket Interlocked.Exchange(ref _singleBufferSendEventArgs, null) ?? new AwaitableSocketAsyncEventArgs(this, isReceiveForCaching: false); - Debug.Assert(saea.BufferList == null); + Debug.Assert(saea.BufferList is null); saea.SetBuffer(MemoryMarshal.AsMemory(buffer)); saea.SocketFlags = socketFlags; saea.WrapExceptionsForNetworkStream = true; @@ -331,7 +331,7 @@ internal Task SendToAsync(ArraySegment buffer, SocketFlags socketFlag /// Validates the supplied array segment, throwing if its array or indices are null or out-of-bounds, respectively. private static void ValidateBuffer(ArraySegment buffer) { - if (buffer.Array == null) + if (buffer.Array is null) { throw new ArgumentNullException(nameof(buffer.Array)); } @@ -348,7 +348,7 @@ private static void ValidateBuffer(ArraySegment buffer) /// Validates the supplied buffer list, throwing if it's null or empty. private static void ValidateBuffersList(IList> buffers) { - if (buffers == null) + if (buffers is null) { throw new ArgumentNullException(nameof(buffers)); } @@ -497,7 +497,7 @@ private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs saea, bool // Write this instance back as a cached instance, only if there isn't currently one cached. ref TaskSocketAsyncEventArgs? cache = ref isReceive ? ref _multiBufferReceiveEventArgs : ref _multiBufferSendEventArgs; - if (Interlocked.CompareExchange(ref cache, saea, null) != null) + if (Interlocked.CompareExchange(ref cache, saea, null) is not null) { saea.Dispose(); } @@ -515,7 +515,7 @@ private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs saea) saea._builder = default; // Write this instance back as a cached instance, only if there isn't currently one cached. - if (Interlocked.CompareExchange(ref _acceptEventArgs, saea, null) != null) + if (Interlocked.CompareExchange(ref _acceptEventArgs, saea, null) is not null) { // Couldn't return it, so dispose it. saea.Dispose(); @@ -627,7 +627,7 @@ private void Release() _continuation = null; ref AwaitableSocketAsyncEventArgs? cache = ref _isReadForCaching ? ref _owner._singleBufferReceiveEventArgs : ref _owner._singleBufferSendEventArgs; - if (Interlocked.CompareExchange(ref cache, this, null) != null) + if (Interlocked.CompareExchange(ref cache, this, null) is not null) { Dispose(); } @@ -638,7 +638,7 @@ protected override void OnCompleted(SocketAsyncEventArgs _) // When the operation completes, see if OnCompleted was already called to hook up a continuation. // If it was, invoke the continuation. Action? c = _continuation; - if (c != null || (c = Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)) != null) + if (c is not null || (c = Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)) is not null) { Debug.Assert(c != s_completedSentinel, "The delegate should not have been the completed sentinel."); @@ -647,7 +647,7 @@ protected override void OnCompleted(SocketAsyncEventArgs _) _continuation = s_completedSentinel; // in case someone's polling IsCompleted ExecutionContext? ec = _executionContext; - if (ec == null) + if (ec is null) { InvokeContinuation(c, continuationState, forceAsync: false, requiresExecutionContextFlow: false); } @@ -670,7 +670,7 @@ protected override void OnCompleted(SocketAsyncEventArgs _) /// This instance. public ValueTask ReceiveAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use"); + Debug.Assert(Volatile.Read(ref _continuation) is null, $"Expected null continuation to indicate reserved for use"); if (socket.ReceiveAsync(this, cancellationToken)) { @@ -692,7 +692,7 @@ public ValueTask ReceiveAsync(Socket socket, CancellationToken cancellation /// This instance. public ValueTask SendAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use"); + Debug.Assert(Volatile.Read(ref _continuation) is null, $"Expected null continuation to indicate reserved for use"); if (socket.SendAsync(this, cancellationToken)) { @@ -712,7 +712,7 @@ public ValueTask SendAsync(Socket socket, CancellationToken cancellationTok public ValueTask SendAsyncForNetworkStream(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use"); + Debug.Assert(Volatile.Read(ref _continuation) is null, $"Expected null continuation to indicate reserved for use"); if (socket.SendAsync(this, cancellationToken)) { @@ -731,7 +731,7 @@ public ValueTask SendAsyncForNetworkStream(Socket socket, CancellationToken canc public ValueTask ConnectAsync(Socket socket) { - Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use"); + Debug.Assert(Volatile.Read(ref _continuation) is null, $"Expected null continuation to indicate reserved for use"); try { @@ -785,7 +785,7 @@ public void OnCompleted(Action continuation, object? state, short token if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext? sc = SynchronizationContext.Current; - if (sc != null && sc.GetType() != typeof(SynchronizationContext)) + if (sc is not null && sc.GetType() != typeof(SynchronizationContext)) { _scheduler = sc; } @@ -808,12 +808,12 @@ public void OnCompleted(Action continuation, object? state, short token // avoid a stack dive. However, since all of the queueing mechanisms flow // ExecutionContext, and since we're still in the same context where we // captured it, we can just ignore the one we captured. - bool requiresExecutionContextFlow = _executionContext != null; + bool requiresExecutionContextFlow = _executionContext is not null; _executionContext = null; UserToken = null; // we have the state in "state"; no need for the one in UserToken InvokeContinuation(continuation, state, forceAsync: true, requiresExecutionContextFlow); } - else if (prevContinuation != null) + else if (prevContinuation is not null) { // Flag errors with the continuation being hooked up multiple times. // This is purely to help alert a developer to a bug they need to fix. @@ -826,7 +826,7 @@ private void InvokeContinuation(Action continuation, object? state, boo object? scheduler = _scheduler; _scheduler = null; - if (scheduler != null) + if (scheduler is not null) { if (scheduler is SynchronizationContext sc) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs index fd9a6c80fcf417..ab45b7e034b3ec 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs @@ -176,7 +176,7 @@ private static void ThrowMultiConnectNotSupported() private Socket? GetOrCreateAcceptSocket(Socket? acceptSocket, bool unused, string propertyName, out SafeSocketHandle? handle) { // AcceptSocket is not supported on Unix. - if (acceptSocket != null) + if (acceptSocket is not null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_AcceptSocket); } @@ -208,13 +208,13 @@ private void SendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postB { // Send the preBuffer, if any // This will throw on error - if (preBuffer != null && preBuffer.Length > 0) + if (preBuffer is not null && preBuffer.Length > 0) { Send(preBuffer); } // Send the file, if any - if (fileStream != null) + if (fileStream is not null) { // This can throw ObjectDisposedException. errorCode = SocketPal.SendFile(_handle, fileStream); @@ -230,7 +230,7 @@ private void SendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postB // Send the postBuffer, if any // This will throw on error - if (postBuffer != null && postBuffer.Length > 0) + if (postBuffer is not null && postBuffer.Length > 0) { Send(postBuffer); } @@ -243,14 +243,14 @@ private async Task SendFileInternalAsync(FileStream? fileStream, byte[]? preBuff { // Send the preBuffer, if any // This will throw on error - if (preBuffer != null && preBuffer.Length > 0) + if (preBuffer is not null && preBuffer.Length > 0) { // Using "this." makes the extension method kick in await this.SendAsync(new ArraySegment(preBuffer), SocketFlags.None).ConfigureAwait(false); } // Send the file, if any - if (fileStream != null) + if (fileStream is not null) { var tcs = new TaskCompletionSource(); errorCode = SocketPal.SendFileAsync(_handle, fileStream, (_, socketError) => tcs.SetResult(socketError)); @@ -269,7 +269,7 @@ private async Task SendFileInternalAsync(FileStream? fileStream, byte[]? preBuff // Send the postBuffer, if any // This will throw on error - if (postBuffer != null && postBuffer.Length > 0) + if (postBuffer is not null && postBuffer.Length > 0) { // Using "this." makes the extension method kick in await this.SendAsync(new ArraySegment(postBuffer), SocketFlags.None).ConfigureAwait(false); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs index 4432190294bc52..2e301734dd763b 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs @@ -216,7 +216,7 @@ internal unsafe bool DisconnectExBlocking(SafeSocketHandle socketHandle, int fla partial void WildcardBindForConnectIfNecessary(AddressFamily addressFamily) { - if (_rightEndPoint != null) + if (_rightEndPoint is not null) { return; } @@ -281,7 +281,7 @@ internal unsafe bool TransmitPackets(SafeSocketHandle socketHandle, IntPtr packe internal static void SocketListToFileDescriptorSet(IList? socketList, Span fileDescriptorSet, ref int refsAdded) { int count; - if (socketList == null || (count = socketList.Count) == 0) + if (socketList is null || (count = socketList.Count) == 0) { return; } @@ -313,7 +313,7 @@ internal static void SelectFileDescriptor(IList? socketList, Span fileDe // when the socket is removed, advancing occurs automatically as the // other elements are shifted down. int count; - if (socketList == null || (count = socketList.Count) == 0) + if (socketList is null || (count = socketList.Count) == 0) { return; } @@ -336,7 +336,7 @@ internal static void SelectFileDescriptor(IList? socketList, Span fileDe for (int currentSocket = 0; currentSocket < count; currentSocket++) { Socket? socket = socketList[currentSocket] as Socket; - Debug.Assert(socket != null); + Debug.Assert(socket is not null); // Look for the file descriptor in the array. int currentFileDescriptor; @@ -363,11 +363,11 @@ internal static void SelectFileDescriptor(IList? socketList, Span fileDe private Socket GetOrCreateAcceptSocket(Socket? acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle handle) { // If an acceptSocket isn't specified, then we need to create one. - if (acceptSocket == null) + if (acceptSocket is null) { acceptSocket = new Socket(_addressFamily, _socketType, _protocolType); } - else if (acceptSocket._rightEndPoint != null && (!checkDisconnected || !acceptSocket._isDisconnected)) + else if (acceptSocket._rightEndPoint is not null && (!checkDisconnected || !acceptSocket._isDisconnected)) { throw new InvalidOperationException(SR.Format(SR.net_sockets_namedmustnotbebound, propertyName)); } @@ -430,7 +430,7 @@ private IAsyncResult BeginSendFileInternal(string? fileName, byte[]? preBuffer, private void EndSendFileInternal(IAsyncResult asyncResult) { TransmitFileAsyncResult? castedAsyncResult = asyncResult as TransmitFileAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index 2e8671d874d5fb..20340a7aa45894 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -183,7 +183,7 @@ private unsafe Socket(SafeSocketHandle handle, bool loadPropertiesFromHandle) // Try to determine if we're connected, based on querying for a peer, just as we would in RemoteEndPoint, // but ignoring any failures; this is best-effort (RemoteEndPoint also does a catch-all around the Create call). - if (_rightEndPoint != null) + if (_rightEndPoint is not null) { try { @@ -298,12 +298,12 @@ public EndPoint? LocalEndPoint _nonBlockingConnectInProgress = false; } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { return null; } - if (_localEndPoint == null) + if (_localEndPoint is null) { Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(_rightEndPoint); @@ -334,7 +334,7 @@ public EndPoint? RemoteEndPoint { ThrowIfDisposed(); - if (_remoteEndPoint == null) + if (_remoteEndPoint is null) { if (_nonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite)) { @@ -345,7 +345,7 @@ public EndPoint? RemoteEndPoint _nonBlockingConnectInProgress = false; } - if (_rightEndPoint == null || !_isConnected) + if (_rightEndPoint is null || !_isConnected) { return null; } @@ -492,7 +492,7 @@ public bool IsBound { get { - return (_rightEndPoint != null); + return (_rightEndPoint is not null); } } @@ -779,7 +779,7 @@ public void Bind(EndPoint localEP) ThrowIfDisposed(); // Validate input parameters. - if (localEP == null) + if (localEP is null) { throw new ArgumentNullException(nameof(localEP)); } @@ -794,7 +794,7 @@ private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAdd { // Mitigation for Blue Screen of Death (Win7, maybe others). IPEndPoint? ipEndPoint = endPointSnapshot as IPEndPoint; - if (!OSSupportsIPv4 && ipEndPoint != null && ipEndPoint.Address.IsIPv4MappedToIPv6) + if (!OSSupportsIPv4 && ipEndPoint is not null && ipEndPoint.Address.IsIPv4MappedToIPv6) { UpdateStatusAfterSocketErrorAndThrowException(SocketError.InvalidArgument); } @@ -812,7 +812,7 @@ private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAdd UpdateStatusAfterSocketErrorAndThrowException(errorCode); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = endPointSnapshot; @@ -825,7 +825,7 @@ public void Connect(EndPoint remoteEP) ThrowIfDisposed(); // Validate input parameters. - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -850,7 +850,7 @@ public void Connect(EndPoint remoteEP) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DST:{remoteEP}"); DnsEndPoint? dnsEP = remoteEP as DnsEndPoint; - if (dnsEP != null) + if (dnsEP is not null) { ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call @@ -880,7 +880,7 @@ public void Connect(IPAddress address, int port) { ThrowIfDisposed(); - if (address == null) + if (address is null) { throw new ArgumentNullException(nameof(address)); } @@ -910,7 +910,7 @@ public void Connect(string host, int port) { ThrowIfDisposed(); - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } @@ -942,7 +942,7 @@ public void Connect(IPAddress[] addresses, int port) { ThrowIfDisposed(); - if (addresses == null) + if (addresses is null) { throw new ArgumentNullException(nameof(addresses)); } @@ -1048,7 +1048,7 @@ public Socket Accept() ThrowIfDisposed(); - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -1122,12 +1122,12 @@ public int Send(byte[] buffer, int size, SocketFlags socketFlags) public int Send(byte[] buffer, SocketFlags socketFlags) { - return Send(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags); + return Send(buffer, 0, buffer is not null ? buffer.Length : 0, socketFlags); } public int Send(byte[] buffer) { - return Send(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None); + return Send(buffer, 0, buffer is not null ? buffer.Length : 0, SocketFlags.None); } public int Send(IList> buffers) @@ -1150,7 +1150,7 @@ public int Send(IList> buffers, SocketFlags socketFlags, out { ThrowIfDisposed(); - if (buffers == null) + if (buffers is null) { throw new ArgumentNullException(nameof(buffers)); } @@ -1202,7 +1202,7 @@ public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, ou ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -1310,11 +1310,11 @@ public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -1348,7 +1348,7 @@ public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, if (SocketType == SocketType.Dgram) SocketsTelemetry.Log.DatagramSent(); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = remoteEP; @@ -1366,12 +1366,12 @@ public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint rem public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP) { - return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, remoteEP); + return SendTo(buffer, 0, buffer is not null ? buffer.Length : 0, socketFlags, remoteEP); } public int SendTo(byte[] buffer, EndPoint remoteEP) { - return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, remoteEP); + return SendTo(buffer, 0, buffer is not null ? buffer.Length : 0, SocketFlags.None, remoteEP); } // Receives data from a connected socket. @@ -1382,12 +1382,12 @@ public int Receive(byte[] buffer, int size, SocketFlags socketFlags) public int Receive(byte[] buffer, SocketFlags socketFlags) { - return Receive(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags); + return Receive(buffer, 0, buffer is not null ? buffer.Length : 0, socketFlags); } public int Receive(byte[] buffer) { - return Receive(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None); + return Receive(buffer, 0, buffer is not null ? buffer.Length : 0, SocketFlags.None); } // Receives data from a connected socket into a specific location of the receive buffer. @@ -1407,7 +1407,7 @@ public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -1501,7 +1501,7 @@ public int Receive(IList> buffers, SocketFlags socketFlags, o { ThrowIfDisposed(); - if (buffers == null) + if (buffers is null) { throw new ArgumentNullException(nameof(buffers)); } @@ -1541,11 +1541,11 @@ public int Receive(IList> buffers, SocketFlags socketFlags, o public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation) { ThrowIfDisposed(); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -1561,7 +1561,7 @@ public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFla { throw new ArgumentOutOfRangeException(nameof(size)); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -1605,7 +1605,7 @@ public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFla catch { } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = endPointSnapshot; @@ -1623,11 +1623,11 @@ public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFl ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -1644,7 +1644,7 @@ public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFl { throw new ArgumentOutOfRangeException(nameof(size)); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -1693,14 +1693,14 @@ public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFl catch { } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = endPointSnapshot; } } - if (socketException != null) + if (socketException is not null) { throw socketException; } @@ -1717,12 +1717,12 @@ public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref End public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP) { - return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, ref remoteEP); + return ReceiveFrom(buffer, 0, buffer is not null ? buffer.Length : 0, socketFlags, ref remoteEP); } public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP) { - return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, ref remoteEP); + return ReceiveFrom(buffer, 0, buffer is not null ? buffer.Length : 0, SocketFlags.None, ref remoteEP); } public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) @@ -1792,7 +1792,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti ThrowIfDisposed(); // Validate input parameters. - if (optionValue == null) + if (optionValue is null) { throw new ArgumentNullException(nameof(optionValue)); } @@ -1802,7 +1802,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger) { LingerOption? lingerOption = optionValue as LingerOption; - if (lingerOption == null) + if (lingerOption is null) { throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "LingerOption"), nameof(optionValue)); } @@ -1815,7 +1815,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) { MulticastOption? multicastOption = optionValue as MulticastOption; - if (multicastOption == null) + if (multicastOption is null) { throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "MulticastOption"), nameof(optionValue)); } @@ -1825,7 +1825,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti { // IPv6 Changes: Handle IPv6 Multicast Add / Drop IPv6MulticastOption? multicastOption = optionValue as IPv6MulticastOption; - if (multicastOption == null) + if (multicastOption is null) { throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "IPv6MulticastOption"), nameof(optionValue)); } @@ -1904,7 +1904,7 @@ public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti { ThrowIfDisposed(); - int optionLength = optionValue != null ? optionValue.Length : 0; + int optionLength = optionValue is not null ? optionValue.Length : 0; // This can throw ObjectDisposedException. SocketError errorCode = SocketPal.GetSockOpt( @@ -2029,20 +2029,20 @@ public bool Poll(int microSeconds, SelectMode mode) public static void Select(IList? checkRead, IList? checkWrite, IList? checkError, int microSeconds) { // Validate input parameters. - if ((checkRead == null || checkRead.Count == 0) && (checkWrite == null || checkWrite.Count == 0) && (checkError == null || checkError.Count == 0)) + if ((checkRead is null || checkRead.Count == 0) && (checkWrite is null || checkWrite.Count == 0) && (checkError is null || checkError.Count == 0)) { throw new ArgumentNullException(null, SR.net_sockets_empty_select); } const int MaxSelect = 65536; - if (checkRead != null && checkRead.Count > MaxSelect) + if (checkRead is not null && checkRead.Count > MaxSelect) { throw new ArgumentOutOfRangeException(nameof(checkRead), SR.Format(SR.net_sockets_toolarge_select, nameof(checkRead), MaxSelect.ToString())); } - if (checkWrite != null && checkWrite.Count > MaxSelect) + if (checkWrite is not null && checkWrite.Count > MaxSelect) { throw new ArgumentOutOfRangeException(nameof(checkWrite), SR.Format(SR.net_sockets_toolarge_select, nameof(checkWrite), MaxSelect.ToString())); } - if (checkError != null && checkError.Count > MaxSelect) + if (checkError is not null && checkError.Count > MaxSelect) { throw new ArgumentOutOfRangeException(nameof(checkError), SR.Format(SR.net_sockets_toolarge_select, nameof(checkError), MaxSelect.ToString())); } @@ -2074,7 +2074,7 @@ public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback? callback, obj // Validate input parameters. ThrowIfDisposed(); - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -2091,7 +2091,7 @@ public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback? callback, obj DnsEndPoint? dnsEP = remoteEP as DnsEndPoint; - if (dnsEP != null) + if (dnsEP is not null) { ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call @@ -2117,7 +2117,7 @@ private bool CanUseConnectEx(EndPoint remoteEP) // Unix sockets are not supported by ConnectEx. return (_socketType == SocketType.Stream) && - (_rightEndPoint != null || remoteEP.GetType() == typeof(IPEndPoint)) && + (_rightEndPoint is not null || remoteEP.GetType() == typeof(IPEndPoint)) && (remoteEP.AddressFamily != AddressFamily.Unix); } @@ -2144,7 +2144,7 @@ public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCa { ThrowIfDisposed(); - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } @@ -2198,7 +2198,7 @@ public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? req { ThrowIfDisposed(); - if (address == null) + if (address is null) { throw new ArgumentNullException(nameof(address)); } @@ -2226,7 +2226,7 @@ public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? { ThrowIfDisposed(); - if (addresses == null) + if (addresses is null) { throw new ArgumentNullException(nameof(addresses)); } @@ -2363,7 +2363,7 @@ public void EndConnect(IAsyncResult asyncResult) } // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -2373,7 +2373,7 @@ asyncResult as ConnectOverlappedAsyncResult ?? asyncResult as MultipleAddressConnectAsyncResult ?? (ContextAwareResult?)(asyncResult as ConnectAsyncResult); - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -2389,11 +2389,11 @@ asyncResult as MultipleAddressConnectAsyncResult ?? Exception? ex = castedAsyncResult.Result as Exception; - if (ex != null || (SocketError)castedAsyncResult.ErrorCode != SocketError.Success) + if (ex is not null || (SocketError)castedAsyncResult.ErrorCode != SocketError.Success) { SocketError errorCode = (SocketError)castedAsyncResult.ErrorCode; - if (ex == null) + if (ex is null) { UpdateConnectSocketErrorForDisposed(ref errorCode); // Update the internal state of this socket according to the error before throwing. @@ -2423,14 +2423,14 @@ public void EndDisconnect(IAsyncResult asyncResult) { ThrowIfDisposed(); - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } //get async result and check for errors LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -2488,7 +2488,7 @@ public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags s ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -2555,7 +2555,7 @@ public IAsyncResult BeginSend(IList> buffers, SocketFlags soc ThrowIfDisposed(); // Validate input parameters. - if (buffers == null) + if (buffers is null) { throw new ArgumentNullException(nameof(buffers)); } @@ -2629,13 +2629,13 @@ public int EndSend(IAsyncResult asyncResult, out SocketError errorCode) ThrowIfDisposed(); // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -2692,7 +2692,7 @@ public void EndSendFile(IAsyncResult asyncResult) { ThrowIfDisposed(); - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -2725,11 +2725,11 @@ public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -2768,7 +2768,7 @@ private void DoBeginSendTo(byte[] buffer, int offset, int size, SocketFlags sock SocketError errorCode = SocketError.SocketError; try { - if (_rightEndPoint == null) + if (_rightEndPoint is null) { _rightEndPoint = endPointSnapshot; } @@ -2815,13 +2815,13 @@ public int EndSendTo(IAsyncResult asyncResult) ThrowIfDisposed(); // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -2889,7 +2889,7 @@ public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlag ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -2963,7 +2963,7 @@ public IAsyncResult BeginReceive(IList> buffers, SocketFlags ThrowIfDisposed(); // Validate input parameters. - if (buffers == null) + if (buffers is null) { throw new ArgumentNullException(nameof(buffers)); } @@ -3054,13 +3054,13 @@ public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode) ThrowIfDisposed(); // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -3096,11 +3096,11 @@ public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"size:{size}"); ThrowIfDisposed(); - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -3116,7 +3116,7 @@ public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, { throw new ArgumentOutOfRangeException(nameof(size)); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -3145,7 +3145,7 @@ public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SetReceivingPacketInformation(); - if (_rightEndPoint == null) + if (_rightEndPoint is null) { _rightEndPoint = remoteEP; } @@ -3207,7 +3207,7 @@ public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socke { ThrowIfDisposed(); - if (endPoint == null) + if (endPoint is null) { throw new ArgumentNullException(nameof(endPoint)); } @@ -3215,13 +3215,13 @@ public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socke { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint)); } - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } ReceiveMessageOverlappedAsyncResult? castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -3299,11 +3299,11 @@ public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, Socket ThrowIfDisposed(); // Validate input parameters. - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -3319,7 +3319,7 @@ public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, Socket { throw new ArgumentOutOfRangeException(nameof(size)); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -3369,7 +3369,7 @@ private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags // Save a copy of the original EndPoint in the asyncResult. asyncResult.SocketAddressOriginal = IPEndPointExtensions.Serialize(endPointSnapshot); - if (_rightEndPoint == null) + if (_rightEndPoint is null) { _rightEndPoint = endPointSnapshot; } @@ -3417,7 +3417,7 @@ public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) ThrowIfDisposed(); // Validate input parameters. - if (endPoint == null) + if (endPoint is null) { throw new ArgumentNullException(nameof(endPoint)); } @@ -3425,13 +3425,13 @@ public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint)); } - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -3521,7 +3521,7 @@ private IAsyncResult BeginAcceptCommon(Socket? acceptSocket, int receiveSize, As asyncResult.StartPostingAsyncOp(false); // Start the accept. - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -3598,12 +3598,12 @@ private Socket EndAcceptCommon(out byte[]? buffer, out int bytesTransferred, IAs } // Validate input parameters. - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } AcceptOverlappedAsyncResult? castedAsyncResult = asyncResult as AcceptOverlappedAsyncResult; - if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) + if (castedAsyncResult is null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -3665,7 +3665,7 @@ public bool AcceptAsync(SocketAsyncEventArgs e) { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -3673,7 +3673,7 @@ public bool AcceptAsync(SocketAsyncEventArgs e) { throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); } - if (_rightEndPoint == null) + if (_rightEndPoint is null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } @@ -3720,7 +3720,7 @@ private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket) ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -3728,7 +3728,7 @@ private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket) { throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); } - if (e.RemoteEndPoint == null) + if (e.RemoteEndPoint is null) { throw new ArgumentNullException("remoteEP"); } @@ -3746,7 +3746,7 @@ private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket) EndPoint? endPointSnapshot = e.RemoteEndPoint; DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint; - if (dnsEP != null) + if (dnsEP is not null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.ConnectedAsyncDns(this); @@ -3788,7 +3788,7 @@ private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket) // Save the old RightEndPoint and prep new RightEndPoint. EndPoint? oldEndPoint = _rightEndPoint; - if (_rightEndPoint == null) + if (_rightEndPoint is null) { _rightEndPoint = endPointSnapshot; } @@ -3841,7 +3841,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType { bool pending; - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -3849,7 +3849,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType { throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); } - if (e.RemoteEndPoint == null) + if (e.RemoteEndPoint is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } @@ -3857,7 +3857,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint; - if (dnsEP != null) + if (dnsEP is not null) { Socket? attemptSocket = null; MultipleConnectAsync? multipleConnectAsync = null; @@ -3901,7 +3901,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType public static void CancelConnectAsync(SocketAsyncEventArgs e) { - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -3913,7 +3913,7 @@ public bool DisconnectAsync(SocketAsyncEventArgs e) // Throw if socket disposed ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -3941,7 +3941,7 @@ private bool ReceiveAsync(SocketAsyncEventArgs e, CancellationToken cancellation { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -3967,11 +3967,11 @@ public bool ReceiveFromAsync(SocketAsyncEventArgs e) { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } - if (e.RemoteEndPoint == null) + if (e.RemoteEndPoint is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } @@ -4014,11 +4014,11 @@ public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } - if (e.RemoteEndPoint == null) + if (e.RemoteEndPoint is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } @@ -4064,7 +4064,7 @@ private bool SendAsync(SocketAsyncEventArgs e, CancellationToken cancellationTok { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } @@ -4090,11 +4090,11 @@ public bool SendPacketsAsync(SocketAsyncEventArgs e) { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } - if (e.SendPacketsElements == null) + if (e.SendPacketsElements is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.SendPacketsElements"), nameof(e)); } @@ -4124,11 +4124,11 @@ public bool SendToAsync(SocketAsyncEventArgs e) { ThrowIfDisposed(); - if (e == null) + if (e is null) { throw new ArgumentNullException(nameof(e)); } - if (e.RemoteEndPoint == null) + if (e.RemoteEndPoint is null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } @@ -4141,7 +4141,7 @@ public bool SendToAsync(SocketAsyncEventArgs e) e.StartOperationCommon(this, SocketAsyncOperation.SendTo); EndPoint? oldEndPoint = _rightEndPoint; - if (_rightEndPoint == null) + if (_rightEndPoint is null) { _rightEndPoint = endPointSnapshot; } @@ -4177,7 +4177,7 @@ private CacheSet Caches { get { - if (_caches == null) + if (_caches is null) { // It's not too bad if extra of these are created and lost. _caches = new CacheSet(); @@ -4261,7 +4261,7 @@ private void DoConnect(EndPoint endPointSnapshot, Internals.SocketAddress socket if (SocketsTelemetry.Log.IsEnabled()) SocketsTelemetry.Log.AfterConnect(SocketError.Success); - if (_rightEndPoint == null) + if (_rightEndPoint is null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = endPointSnapshot; @@ -4437,20 +4437,20 @@ internal void SetReceivingPacketInformation() // DualMode: When bound to IPv6Any you must enable both socket options. // When bound to an IPv4 mapped IPv6 address you must enable the IPv4 socket option. IPEndPoint? ipEndPoint = _rightEndPoint as IPEndPoint; - IPAddress? boundAddress = (ipEndPoint != null ? ipEndPoint.Address : null); - Debug.Assert(boundAddress != null, "Not Bound"); + IPAddress? boundAddress = (ipEndPoint is not null ? ipEndPoint.Address : null); + Debug.Assert(boundAddress is not null, "Not Bound"); if (_addressFamily == AddressFamily.InterNetwork) { SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); } - if ((boundAddress != null && IsDualMode && (boundAddress.IsIPv4MappedToIPv6 || boundAddress.Equals(IPAddress.IPv6Any)))) + if ((boundAddress is not null && IsDualMode && (boundAddress.IsIPv4MappedToIPv6 || boundAddress.Equals(IPAddress.IPv6Any)))) { SocketPal.SetReceivingDualModeIPv4PacketInformation(this); } if (_addressFamily == AddressFamily.InterNetworkV6 - && (boundAddress == null || !boundAddress.IsIPv4MappedToIPv6)) + && (boundAddress is null || !boundAddress.IsIPv4MappedToIPv6)) { SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true); } @@ -4660,7 +4660,7 @@ private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCa } EndPoint? oldEndPoint = _rightEndPoint; - if (_rightEndPoint == null) + if (_rightEndPoint is null) { _rightEndPoint = endPointSnapshot; } @@ -4780,7 +4780,7 @@ internal override EndPoint? RemoteEndPoint { get { - if (_addresses != null && _index > 0 && _index < _addresses.Length) + if (_addresses is not null && _index > 0 && _index < _addresses.Length) { return new IPEndPoint(_addresses[_index], _port); } @@ -4797,7 +4797,7 @@ private static AsyncCallback CachedMultipleAddressConnectCallback { get { - if (s_multipleAddressConnectCallback == null) + if (s_multipleAddressConnectCallback is null) { s_multipleAddressConnectCallback = new AsyncCallback(MultipleAddressConnectCallback); } @@ -4813,7 +4813,7 @@ private static AsyncCallback CachedMultipleAddressConnectCallback if (!context._socket.CanTryAddressFamily(currentAddressSnapshot.AddressFamily)) { - return context._lastException != null ? context._lastException : new ArgumentException(SR.net_invalidAddressList, nameof(context)); + return context._lastException is not null ? context._lastException : new ArgumentException(SR.net_invalidAddressList, nameof(context)); } try @@ -4866,10 +4866,10 @@ private static void MultipleAddressConnectCallback(IAsyncResult result) // processing should continue whether or not an async step failed. private static bool DoMultipleAddressConnectCallback(object? result, MultipleAddressConnectAsyncResult context) { - while (result != null) + while (result is not null) { Exception? ex = result as Exception; - if (ex == null) + if (ex is null) { try { @@ -4881,7 +4881,7 @@ private static bool DoMultipleAddressConnectCallback(object? result, MultipleAdd } } - if (ex == null) + if (ex is null) { // Don't invoke the callback from here, because we're probably inside // a catch-all block that would eat exceptions from the callback. @@ -4908,7 +4908,7 @@ private static bool DoMultipleAddressConnectCallback(object? result, MultipleAdd internal Socket CreateAcceptSocket(SafeSocketHandle fd, EndPoint remoteEP) { // Internal state of the socket is inherited from listener. - Debug.Assert(fd != null && !fd.IsInvalid); + Debug.Assert(fd is not null && !fd.IsInvalid); Socket socket = new Socket(fd, loadPropertiesFromHandle: false); return UpdateAcceptSocket(socket, remoteEP); } @@ -4977,7 +4977,7 @@ private void UpdateLocalEndPointOnConnect() private bool IsWildcardEndPoint(EndPoint? endPoint) { - if (endPoint == null) + if (endPoint is null) { return false; } @@ -5124,7 +5124,7 @@ private void ThrowIfDisposed() internal static void SocketListDangerousReleaseRefs(IList? socketList, ref int refsAdded) { - if (socketList == null) + if (socketList is null) { return; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs index 4abf6ff75c8127..d4485711d4153f 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs @@ -237,7 +237,7 @@ public bool TryCancel() DoAbort(); ManualResetEventSlim? e = Event; - if (e != null) + if (e is not null) { e.Set(); } @@ -263,7 +263,7 @@ public bool TryCancel() public void Dispatch() { ManualResetEventSlim? e = Event; - if (e != null) + if (e is not null) { // Sync operation. Signal waiting thread to continue processing. e.Set(); @@ -277,7 +277,7 @@ public void Dispatch() public void Schedule() { - Debug.Assert(Event == null); + Debug.Assert(Event is null); // Async operation. Process the IO on the threadpool. ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false); @@ -461,7 +461,7 @@ protected override bool DoTryComplete(SocketAsyncContext context) { // Zero byte read is performed to know when data is available. // We don't have to call receive, our caller is interested in the event. - if (Buffer.Length == 0 && Flags == SocketFlags.None && SocketAddress == null) + if (Buffer.Length == 0 && Flags == SocketFlags.None && SocketAddress is null) { BytesTransferred = 0; ReceivedFlags = SocketFlags.None; @@ -472,7 +472,7 @@ protected override bool DoTryComplete(SocketAsyncContext context) { if (!SetReceivedFlags) { - Debug.Assert(SocketAddress == null); + Debug.Assert(SocketAddress is null); ReceivedFlags = SocketFlags.None; return SocketPal.TryCompleteReceive(context._socket, Buffer.Span, Flags, out BytesTransferred, out ErrorCode); @@ -648,7 +648,7 @@ protected override bool DoTryComplete(SocketAsyncContext context) => public LockToken(object lockObject) { - Debug.Assert(lockObject != null); + Debug.Assert(lockObject is not null); _lockObject = lockObject; @@ -723,7 +723,7 @@ private enum QueueState : int public void Init() { - Debug.Assert(_queueLock == null); + Debug.Assert(_queueLock is null); _queueLock = new object(); _state = QueueState.Ready; @@ -793,10 +793,10 @@ public bool StartAsyncOperation(SocketAsyncContext context, TOperation operation // Enqueue the operation. Debug.Assert(operation.Next == operation, "Expected operation.Next == operation"); - if (_tail == null) + if (_tail is null) { Debug.Assert(!_isNextOperationSynchronous); - _isNextOperationSynchronous = operation.Event != null; + _isNextOperationSynchronous = operation.Event is not null; } else { @@ -818,7 +818,7 @@ public bool StartAsyncOperation(SocketAsyncContext context, TOperation operation return true; case QueueState.Stopped: - Debug.Assert(_tail == null); + Debug.Assert(_tail is null); doAbort = true; break; @@ -854,15 +854,15 @@ public bool StartAsyncOperation(SocketAsyncContext context, TOperation operation switch (_state) { case QueueState.Ready: - Debug.Assert(_tail == null, "State == Ready but queue is not empty!"); + Debug.Assert(_tail is null, "State == Ready but queue is not empty!"); _sequenceNumber++; Trace(context, $"Exit (previously ready)"); return null; case QueueState.Waiting: - Debug.Assert(_tail != null, "State == Waiting but queue is empty!"); + Debug.Assert(_tail is not null, "State == Waiting but queue is empty!"); op = _tail.Next; - Debug.Assert(_isNextOperationSynchronous == (op.Event != null)); + Debug.Assert(_isNextOperationSynchronous == (op.Event is not null)); if (skipAsyncEvents && !_isNextOperationSynchronous) { Debug.Assert(!processAsyncEvents); @@ -876,13 +876,13 @@ public bool StartAsyncOperation(SocketAsyncContext context, TOperation operation break; case QueueState.Processing: - Debug.Assert(_tail != null, "State == Processing but queue is empty!"); + Debug.Assert(_tail is not null, "State == Processing but queue is empty!"); _sequenceNumber++; Trace(context, $"Exit (currently processing)"); return null; case QueueState.Stopped: - Debug.Assert(_tail == null); + Debug.Assert(_tail is null); Trace(context, $"Exit (stopped)"); return null; @@ -893,7 +893,7 @@ public bool StartAsyncOperation(SocketAsyncContext context, TOperation operation } ManualResetEventSlim? e = op.Event; - if (e != null) + if (e is not null) { // Sync operation. Signal waiting thread to continue processing. e.Set(); @@ -916,7 +916,7 @@ internal void ProcessAsyncOperation(TOperation op) { OperationResult result = ProcessQueuedOperation(op); - Debug.Assert(op.Event == null, "Sync operation encountered in ProcessAsyncOperation"); + Debug.Assert(op.Event is null, "Sync operation encountered in ProcessAsyncOperation"); if (result == OperationResult.Completed) { @@ -950,14 +950,14 @@ public OperationResult ProcessQueuedOperation(TOperation op) if (_state == QueueState.Stopped) { - Debug.Assert(_tail == null); + Debug.Assert(_tail is null); Trace(context, $"Exit (stopped)"); return OperationResult.Cancelled; } else { Debug.Assert(_state == QueueState.Processing, $"_state={_state} while processing queue!"); - Debug.Assert(_tail != null, "Unexpected empty queue while processing I/O"); + Debug.Assert(_tail is not null, "Unexpected empty queue while processing I/O"); Debug.Assert(op == _tail.Next, "Operation is not at head of queue???"); observedSequenceNumber = _sequenceNumber; } @@ -990,7 +990,7 @@ public OperationResult ProcessQueuedOperation(TOperation op) { if (_state == QueueState.Stopped) { - Debug.Assert(_tail == null); + Debug.Assert(_tail is null); Trace(context, $"Exit (stopped)"); return OperationResult.Cancelled; } @@ -1022,7 +1022,7 @@ public OperationResult ProcessQueuedOperation(TOperation op) { if (_state == QueueState.Stopped) { - Debug.Assert(_tail == null); + Debug.Assert(_tail is null); Trace(context, $"Exit (stopped)"); } else @@ -1043,7 +1043,7 @@ public OperationResult ProcessQueuedOperation(TOperation op) { // Pop current operation and advance to next nextOp = _tail.Next = op.Next; - _isNextOperationSynchronous = nextOp.Event != null; + _isNextOperationSynchronous = nextOp.Event is not null; } } } @@ -1056,7 +1056,7 @@ public OperationResult ProcessQueuedOperation(TOperation op) public void CancelAndContinueProcessing(TOperation op) { // Note, only sync operations use this method. - Debug.Assert(op.Event != null); + Debug.Assert(op.Event is not null); // Remove operation from queue. // Note it must be there since it can only be processed and removed by the caller. @@ -1065,11 +1065,11 @@ public void CancelAndContinueProcessing(TOperation op) { if (_state == QueueState.Stopped) { - Debug.Assert(_tail == null); + Debug.Assert(_tail is null); } else { - Debug.Assert(_tail != null, "Unexpected empty queue in CancelAndContinueProcessing"); + Debug.Assert(_tail is not null, "Unexpected empty queue in CancelAndContinueProcessing"); if (_tail.Next == op) { @@ -1084,7 +1084,7 @@ public void CancelAndContinueProcessing(TOperation op) { // Pop current operation and advance to next _tail.Next = op.Next; - _isNextOperationSynchronous = op.Next.Event != null; + _isNextOperationSynchronous = op.Next.Event is not null; } // We're the first op in the queue. @@ -1092,7 +1092,7 @@ public void CancelAndContinueProcessing(TOperation op) { // The queue has already handed off execution responsibility to us. // We need to dispatch to the next op. - if (_tail == null) + if (_tail is null) { _state = QueueState.Ready; _sequenceNumber++; @@ -1104,7 +1104,7 @@ public void CancelAndContinueProcessing(TOperation op) } else if (_state == QueueState.Waiting) { - if (_tail == null) + if (_tail is null) { _state = QueueState.Ready; _sequenceNumber++; @@ -1149,7 +1149,7 @@ public bool StopAndAbort(SocketAsyncContext context) _state = QueueState.Stopped; - if (_tail != null) + if (_tail is not null) { AsyncOperation op = _tail; do @@ -1176,7 +1176,7 @@ public void Trace(SocketAsyncContext context, string message, [CallerMemberName] typeof(TOperation) == typeof(WriteOperation) ? "send" : "???"; - OutputTrace($"{IdOf(context)}-{queueType}.{memberName}: {message}, {_state}-{_sequenceNumber}, {((_tail == null) ? "empty" : "not empty")}"); + OutputTrace($"{IdOf(context)}-{queueType}.{memberName}: {message}, {_state}-{_sequenceNumber}, {((_tail is null) ? "empty" : "not empty")}"); } } @@ -1184,7 +1184,7 @@ public void Trace(SocketAsyncContext context, string message, [CallerMemberName] private OperationQueue _receiveQueue; private OperationQueue _sendQueue; private SocketAsyncEngine? _asyncEngine; - private bool IsRegistered => _asyncEngine != null; + private bool IsRegistered => _asyncEngine is not null; private bool _nonBlockingSet; private readonly object _registerLock = new object(); @@ -1210,7 +1210,7 @@ private void Register() Debug.Assert(_nonBlockingSet); lock (_registerLock) { - if (_asyncEngine == null) + if (_asyncEngine is null) { bool addedRef = false; try @@ -1348,7 +1348,7 @@ private bool ShouldRetrySyncOperation(out SocketError errorCode) public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, out IntPtr acceptedFd) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); SocketError errorCode; @@ -1375,9 +1375,9 @@ public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, out In public SocketError AcceptAsync(byte[] socketAddress, ref int socketAddressLen, out IntPtr acceptedFd, Action callback) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); - Debug.Assert(callback != null, "Expected non-null callback"); + Debug.Assert(callback is not null, "Expected non-null callback"); SetNonBlocking(); @@ -1412,7 +1412,7 @@ public SocketError AcceptAsync(byte[] socketAddress, ref int socketAddressLen, o public SocketError Connect(byte[] socketAddress, int socketAddressLen) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); // Connect is different than the usual "readiness" pattern of other operations. @@ -1441,9 +1441,9 @@ public SocketError Connect(byte[] socketAddress, int socketAddressLen) public SocketError ConnectAsync(byte[] socketAddress, int socketAddressLen, Action callback) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); - Debug.Assert(callback != null, "Expected non-null callback"); + Debug.Assert(callback is not null, "Expected non-null callback"); SetNonBlocking(); @@ -2051,14 +2051,14 @@ public Interop.Sys.SocketEvents HandleSyncEventsSpeculatively(Interop.Sys.Socket if ((events & Interop.Sys.SocketEvents.Read) != 0 && _receiveQueue.IsNextOperationSynchronous_Speculative && - _receiveQueue.ProcessSyncEventOrGetAsyncEvent(this, skipAsyncEvents: true) == null) + _receiveQueue.ProcessSyncEventOrGetAsyncEvent(this, skipAsyncEvents: true) is null) { events ^= Interop.Sys.SocketEvents.Read; } if ((events & Interop.Sys.SocketEvents.Write) != 0 && _sendQueue.IsNextOperationSynchronous_Speculative && - _sendQueue.ProcessSyncEventOrGetAsyncEvent(this, skipAsyncEvents: true) == null) + _sendQueue.ProcessSyncEventOrGetAsyncEvent(this, skipAsyncEvents: true) is null) { events ^= Interop.Sys.SocketEvents.Write; } @@ -2102,7 +2102,7 @@ public unsafe void HandleEvents(Interop.Sys.SocketEvents events) // synchronously to avoid an extra thread pool work item. When we have two operations to process, processing both // synchronously may delay the second operation, so schedule one onto the thread pool and process the other // synchronously. There might be better ways of doing this. - if (sendOperation == null) + if (sendOperation is null) { receiveOperation?.Process(); } @@ -2136,6 +2136,6 @@ public static void OutputTrace(string s) #endif } - public static string IdOf(object o) => o == null ? "(null)" : $"{o.GetType().Name}#{o.GetHashCode():X2}"; + public static string IdOf(object o) => o is null ? "(null)" : $"{o.GetType().Name}#{o.GetHashCode():X2}"; } } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEngine.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEngine.Unix.cs index 45d889de23b4dd..df0458d649aa4c 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEngine.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEngine.Unix.cs @@ -276,7 +276,7 @@ void IThreadPoolWorkItem.Execute() private void FreeNativeResources() { - if (_buffer != null) + if (_buffer is not null) { Interop.Sys.FreeSocketEventBuffer(_buffer); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs index 09d688d9e0c70f..cc02df58261e7a 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs @@ -47,7 +47,7 @@ private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] sock private void CompleteAcceptOperation(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { _acceptedFileDescriptor = acceptedFileDescriptor; - Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}"); + Debug.Assert(socketAddress is null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}"); _acceptAddressBufferCount = socketAddressSize; } @@ -60,7 +60,7 @@ internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle ha _acceptedFileDescriptor = (IntPtr)(-1); - Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}"); + Debug.Assert(acceptHandle is null, $"Unexpected acceptHandle: {acceptHandle}"); IntPtr acceptedFd; int socketAddressLen = _acceptAddressBufferCount / 2; @@ -112,7 +112,7 @@ private void TransferCompletionCallbackCore(int bytesTransferred, byte[]? socket private void CompleteTransferOperation(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) { - Debug.Assert(socketAddress == null || socketAddress == _socketAddress!.Buffer, $"Unexpected socketAddress: {socketAddress}"); + Debug.Assert(socketAddress is null || socketAddress == _socketAddress!.Buffer, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; } @@ -125,7 +125,7 @@ internal unsafe SocketError DoOperationReceive(SafeSocketHandle handle, Cancella SocketFlags flags; int bytesReceived; SocketError errorCode; - if (_bufferList == null) + if (_bufferList is null) { // TCP has no out-going receive flags. We can use different syscalls which give better performance. bool noReceivedFlags = _currentSocket!.ProtocolType == ProtocolType.Tcp; @@ -162,7 +162,7 @@ internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle) SocketError errorCode; int bytesReceived = 0; int socketAddressLen = _socketAddress!.Size; - if (_bufferList == null) + if (_bufferList is null) { errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer.Slice(_offset, _count), _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback); } @@ -189,8 +189,8 @@ private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] s private void CompleteReceiveMessageFromOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { - Debug.Assert(_socketAddress != null, "Expected non-null _socketAddress"); - Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); + Debug.Assert(_socketAddress is not null, "Expected non-null _socketAddress"); + Debug.Assert(socketAddress is null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; @@ -226,7 +226,7 @@ internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, Cancellatio int bytesSent; SocketError errorCode; - if (_bufferList == null) + if (_bufferList is null) { errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, _socketFlags, out bytesSent, TransferCompletionCallback, cancellationToken); } @@ -246,7 +246,7 @@ internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, Cancellatio internal SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle) { - Debug.Assert(_sendPacketsElements != null); + Debug.Assert(_sendPacketsElements is not null); SendPacketsElement[] elements = (SendPacketsElement[])_sendPacketsElements.Clone(); FileStream[] files = new FileStream[elements.Length]; @@ -257,7 +257,7 @@ internal SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle hand for (int i = 0; i < elements.Length; i++) { string? path = elements[i]?.FilePath; - if (path != null) + if (path is not null) { files[i] = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true); } @@ -311,7 +311,7 @@ internal SocketError DoOperationSendTo(SafeSocketHandle handle) int bytesSent; int socketAddressLen = _socketAddress!.Size; SocketError errorCode; - if (_bufferList == null) + if (_bufferList is null) { errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback); } @@ -336,11 +336,11 @@ internal void LogBuffer(int size) // may fire erroneously. Debug.Assert(NetEventSource.Log.IsEnabled()); - if (_bufferList == null) + if (_bufferList is null) { NetEventSource.DumpBuffer(this, _buffer, _offset, size); } - else if (_acceptBuffer != null) + else if (_acceptBuffer is not null) { NetEventSource.DumpBuffer(this, _acceptBuffer, 0, size); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs index 7f86d700dc1894..c05118c8f9b557 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs @@ -78,9 +78,9 @@ private void FreeInternals() { Debug.Assert(OperatingSystem.IsWindows()); Debug.Assert(_operating == InProgress, $"Expected {nameof(_operating)} == {nameof(InProgress)}, got {_operating}"); - Debug.Assert(_currentSocket != null, "_currentSocket is null"); - Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null"); - Debug.Assert(_preAllocatedOverlapped != null, "_preAllocatedOverlapped is null"); + Debug.Assert(_currentSocket is not null, "_currentSocket is null"); + Debug.Assert(_currentSocket.SafeHandle is not null, "_currentSocket.SafeHandle is null"); + Debug.Assert(_preAllocatedOverlapped is not null, "_preAllocatedOverlapped is null"); ThreadPoolBoundHandle boundHandle = _currentSocket.GetOrAllocateThreadPoolBoundHandle(); return boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped); @@ -89,12 +89,12 @@ private void FreeInternals() private unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { Debug.Assert(OperatingSystem.IsWindows()); - Debug.Assert(overlapped != null, "overlapped is null"); + Debug.Assert(overlapped is not null, "overlapped is null"); Debug.Assert(_operating == InProgress, $"Expected _operating == InProgress, got {_operating}"); - Debug.Assert(_currentSocket != null, "_currentSocket is null"); - Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null"); - Debug.Assert(_currentSocket.SafeHandle.IOCPBoundHandle != null, "_currentSocket.SafeHandle.IOCPBoundHandle is null"); - Debug.Assert(_preAllocatedOverlapped != null, "_preAllocatedOverlapped is null"); + Debug.Assert(_currentSocket is not null, "_currentSocket is null"); + Debug.Assert(_currentSocket.SafeHandle is not null, "_currentSocket.SafeHandle is null"); + Debug.Assert(_currentSocket.SafeHandle.IOCPBoundHandle is not null, "_currentSocket.SafeHandle.IOCPBoundHandle is null"); + Debug.Assert(_preAllocatedOverlapped is not null, "_preAllocatedOverlapped is null"); _currentSocket.SafeHandle.IOCPBoundHandle.FreeNativeOverlapped(overlapped); } @@ -102,7 +102,7 @@ private unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) private unsafe void RegisterToCancelPendingIO(NativeOverlapped* overlapped, CancellationToken cancellationToken) { Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.InProcess); - Debug.Assert(_pendingOverlappedForCancellation == null); + Debug.Assert(_pendingOverlappedForCancellation is null); _pendingOverlappedForCancellation = overlapped; _registrationToCancelPendingIO = cancellationToken.UnsafeRegister(s => { @@ -346,7 +346,7 @@ internal unsafe SocketError DoOperationDisconnect(Socket socket, SafeSocketHandl } } - internal SocketError DoOperationReceive(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ? + internal SocketError DoOperationReceive(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList is null ? DoOperationReceiveSingleBuffer(handle, cancellationToken) : DoOperationReceiveMultiBuffer(handle); @@ -415,7 +415,7 @@ internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle) // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); - return _bufferList == null ? + return _bufferList is null ? DoOperationReceiveFromSingleBuffer(handle) : DoOperationReceiveFromMultiBuffer(handle); } @@ -491,21 +491,21 @@ internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSoc PinSocketAddressBuffer(); // Create a WSAMessageBuffer if none exists yet. - if (_wsaMessageBufferPinned == null) + if (_wsaMessageBufferPinned is null) { _wsaMessageBufferPinned = GC.AllocateUninitializedArray(sizeof(Interop.Winsock.WSAMsg), pinned: true); } // Create and pin an appropriately sized control buffer if none already IPAddress? ipAddress = (_socketAddress!.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null); - bool ipv4 = (_currentSocket!.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode + bool ipv4 = (_currentSocket!.AddressFamily == AddressFamily.InterNetwork || (ipAddress is not null && ipAddress.IsIPv4MappedToIPv6)); // DualMode bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6; - if (ipv6 && (_controlBufferPinned == null || _controlBufferPinned.Length != sizeof(Interop.Winsock.ControlDataIPv6))) + if (ipv6 && (_controlBufferPinned is null || _controlBufferPinned.Length != sizeof(Interop.Winsock.ControlDataIPv6))) { _controlBufferPinned = GC.AllocateUninitializedArray(sizeof(Interop.Winsock.ControlDataIPv6), pinned: true); } - else if (ipv4 && (_controlBufferPinned == null || _controlBufferPinned.Length != sizeof(Interop.Winsock.ControlData))) + else if (ipv4 && (_controlBufferPinned is null || _controlBufferPinned.Length != sizeof(Interop.Winsock.ControlData))) { _controlBufferPinned = GC.AllocateUninitializedArray(sizeof(Interop.Winsock.ControlData), pinned: true); } @@ -513,9 +513,9 @@ internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSoc // If single buffer we need a single element WSABuffer. WSABuffer[] wsaRecvMsgWSABufferArray; uint wsaRecvMsgWSABufferCount; - if (_bufferList == null) + if (_bufferList is null) { - if (_wsaRecvMsgWSABufferArrayPinned == null) + if (_wsaRecvMsgWSABufferArrayPinned is null) { _wsaRecvMsgWSABufferArrayPinned = GC.AllocateUninitializedArray(1, pinned: true); } @@ -548,7 +548,7 @@ internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSoc } pMessage->count = wsaRecvMsgWSABufferCount; - if (_controlBufferPinned != null) + if (_controlBufferPinned is not null) { Debug.Assert(_controlBufferPinned.Length > 0); fixed (void* ptrControlBuffer = &_controlBufferPinned[0]) @@ -581,7 +581,7 @@ internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSoc } } - internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ? + internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList is null ? DoOperationSendSingleBuffer(handle, cancellationToken) : DoOperationSendMultiBuffer(handle); @@ -642,7 +642,7 @@ internal unsafe SocketError DoOperationSendMultiBuffer(SafeSocketHandle handle) internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle) { // Cache copy to avoid problems with concurrent manipulation during the async operation. - Debug.Assert(_sendPacketsElements != null); + Debug.Assert(_sendPacketsElements is not null); SendPacketsElement[] sendPacketsElementsCopy = (SendPacketsElement[])_sendPacketsElements.Clone(); // TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as @@ -655,17 +655,17 @@ internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHand int sendPacketsElementsFileCount = 0, sendPacketsElementsFileStreamCount = 0, sendPacketsElementsBufferCount = 0; foreach (SendPacketsElement spe in sendPacketsElementsCopy) { - if (spe != null) + if (spe is not null) { - if (spe.FilePath != null) + if (spe.FilePath is not null) { sendPacketsElementsFileCount++; } - else if (spe.FileStream != null) + else if (spe.FileStream is not null) { sendPacketsElementsFileStreamCount++; } - else if (spe.Buffer != null && spe.Count > 0) + else if (spe.Buffer is not null && spe.Count > 0) { sendPacketsElementsBufferCount++; } @@ -688,7 +688,7 @@ internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHand { foreach (SendPacketsElement spe in sendPacketsElementsCopy) { - if (spe?.FilePath != null) + if (spe?.FilePath is not null) { // Create a FileStream to open the file. _sendPacketsFileStreams[index] = @@ -712,7 +712,7 @@ internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHand Interop.Winsock.TransmitPacketsElement[] sendPacketsDescriptorPinned = SetupPinHandlesSendPackets(sendPacketsElementsCopy, sendPacketsElementsFileCount, sendPacketsElementsFileStreamCount, sendPacketsElementsBufferCount); - Debug.Assert(sendPacketsDescriptorPinned != null); + Debug.Assert(sendPacketsDescriptorPinned is not null); Debug.Assert(sendPacketsDescriptorPinned.Length > 0); NativeOverlapped* overlapped = AllocateNativeOverlapped(); @@ -745,7 +745,7 @@ internal unsafe SocketError DoOperationSendTo(SafeSocketHandle handle) // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); - return _bufferList == null ? + return _bufferList is null ? DoOperationSendToSingleBuffer(handle) : DoOperationSendToMultiBuffer(handle); } @@ -811,7 +811,7 @@ internal unsafe SocketError DoOperationSendToMultiBuffer(SafeSocketHandle handle // Ensures Overlapped object exists with appropriate multiple buffers pinned. private void SetupMultipleBuffers() { - if (_bufferListInternal == null || _bufferListInternal.Count == 0) + if (_bufferListInternal is null || _bufferListInternal.Count == 0) { // No buffer list is set so unpin any existing multiple buffer pinning. if (_pinState == PinState.MultipleBuffer) @@ -828,7 +828,7 @@ private void SetupMultipleBuffers() int bufferCount = _bufferListInternal.Count; #if DEBUG - if (_multipleBufferGCHandles != null) + if (_multipleBufferGCHandles is not null) { foreach (GCHandle gcHandle in _multipleBufferGCHandles) { @@ -839,7 +839,7 @@ private void SetupMultipleBuffers() // Number of things to pin is number of buffers. // Ensure we have properly sized object array. - if (_multipleBufferGCHandles == null || (_multipleBufferGCHandles.Length < bufferCount)) + if (_multipleBufferGCHandles is null || (_multipleBufferGCHandles.Length < bufferCount)) { _multipleBufferGCHandles = new GCHandle[bufferCount]; } @@ -851,7 +851,7 @@ private void SetupMultipleBuffers() _multipleBufferGCHandles[i] = GCHandle.Alloc(_bufferListInternal[i].Array, GCHandleType.Pinned); } - if (_wsaBufferArrayPinned == null || _wsaBufferArrayPinned.Length < bufferCount) + if (_wsaBufferArrayPinned is null || _wsaBufferArrayPinned.Length < bufferCount) { _wsaBufferArrayPinned = GC.AllocateUninitializedArray(bufferCount, pinned: true); } @@ -898,8 +898,8 @@ private unsafe IntPtr PtrSocketAddressBuffer { get { - Debug.Assert(_pinnedSocketAddress != null); - Debug.Assert(_pinnedSocketAddress.Buffer != null); + Debug.Assert(_pinnedSocketAddress is not null); + Debug.Assert(_pinnedSocketAddress.Buffer is not null); Debug.Assert(_pinnedSocketAddress.Buffer.Length > 0); Debug.Assert(_socketAddressGCHandle.IsAllocated); Debug.Assert(_socketAddressGCHandle.Target == _pinnedSocketAddress.Buffer); @@ -917,7 +917,7 @@ private void FreeOverlapped() { // Free the preallocated overlapped object. This in turn will unpin // any pinned buffers. - if (_preAllocatedOverlapped != null) + if (_preAllocatedOverlapped is not null) { Debug.Assert(OperatingSystem.IsWindows()); _preAllocatedOverlapped.Dispose(); @@ -935,7 +935,7 @@ private void FreePinHandles() _singleBufferHandle.Dispose(); } - if (_multipleBufferGCHandles != null) + if (_multipleBufferGCHandles is not null) { for (int i = 0; i < _multipleBufferGCHandles.Length; i++) { @@ -970,7 +970,7 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke // Number of things to pin is number of buffers + 1 (native descriptor). // Ensure we have properly sized object array. #if DEBUG - if (_multipleBufferGCHandles != null) + if (_multipleBufferGCHandles is not null) { foreach (GCHandle gcHandle in _multipleBufferGCHandles) { @@ -979,7 +979,7 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke } #endif - if (_multipleBufferGCHandles == null || (_multipleBufferGCHandles.Length < sendPacketsElementsBufferCount)) + if (_multipleBufferGCHandles is null || (_multipleBufferGCHandles.Length < sendPacketsElementsBufferCount)) { _multipleBufferGCHandles = new GCHandle[sendPacketsElementsBufferCount]; } @@ -988,7 +988,7 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke int index = 0; foreach (SendPacketsElement spe in sendPacketsElementsCopy) { - if (spe?.Buffer != null && spe.Count > 0) + if (spe?.Buffer is not null && spe.Count > 0) { Debug.Assert(!_multipleBufferGCHandles[index].IsAllocated); _multipleBufferGCHandles[index] = GCHandle.Alloc(spe.Buffer, GCHandleType.Pinned); @@ -1002,9 +1002,9 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke int fileIndex = 0; foreach (SendPacketsElement spe in sendPacketsElementsCopy) { - if (spe != null) + if (spe is not null) { - if (spe.Buffer != null && spe.Count > 0) + if (spe.Buffer is not null && spe.Count > 0) { // This element is a buffer. sendPacketsDescriptorPinned[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe.Buffer, spe.Offset); @@ -1015,7 +1015,7 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke : 0); descriptorIndex++; } - else if (spe.FilePath != null) + else if (spe.FilePath is not null) { // This element is a file. sendPacketsDescriptorPinned[descriptorIndex].fileHandle = _sendPacketsFileStreams![fileIndex].SafeFileHandle.DangerousGetHandle(); @@ -1028,7 +1028,7 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke fileIndex++; descriptorIndex++; } - else if (spe.FileStream != null) + else if (spe.FileStream is not null) { // This element is a file stream. SendPacketsElement throws if the FileStream is not opened asynchronously; // Synchronously opened FileStream can't be used concurrently (e.g. multiple SendPacketsElements with the same @@ -1057,7 +1057,7 @@ internal void LogBuffer(int size) // may fire erroneously. Debug.Assert(NetEventSource.Log.IsEnabled()); - if (_bufferList != null) + if (_bufferList is not null) { for (int i = 0; i < _bufferListInternal!.Count; i++) { @@ -1222,7 +1222,7 @@ private unsafe void FinishOperationReceiveMessageFrom() private void FinishOperationSendPackets() { // Close the files if open. - if (_sendPacketsFileStreams != null) + if (_sendPacketsFileStreams is not null) { for (int i = 0; i < _sendPacketsFileStreams.Length; i++) { @@ -1238,7 +1238,7 @@ private void FinishOperationSendPackets() Debug.Assert(OperatingSystem.IsWindows()); var saeaBox = (StrongBox)(ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!); - Debug.Assert(saeaBox.Value != null); + Debug.Assert(saeaBox.Value is not null); SocketAsyncEventArgs saea = saeaBox.Value; if ((SocketError)errorCode == SocketError.Success) diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs index e85bb70d70148a..cf00b9d555a90c 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs @@ -147,7 +147,7 @@ public IList>? BufferList StartConfiguring(); try { - if (value != null) + if (value is not null) { if (!_buffer.Equals(default)) { @@ -159,7 +159,7 @@ public IList>? BufferList // so that we are not affected by subsequent changes to the list. // We reuse the existing list so that we can avoid reallocation when possible. int bufferCount = value.Count; - if (_bufferListInternal == null) + if (_bufferListInternal is null) { _bufferListInternal = new List>(bufferCount); } @@ -350,7 +350,7 @@ public void SetBuffer(byte[]? buffer, int offset, int count) StartConfiguring(); try { - if (buffer == null) + if (buffer is null) { // Clear out existing buffer. _buffer = default; @@ -361,7 +361,7 @@ public void SetBuffer(byte[]? buffer, int offset, int count) else { // Can't have both Buffer and BufferList. - if (_bufferList != null) + if (_bufferList is not null) { throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(BufferList))); } @@ -394,7 +394,7 @@ public void SetBuffer(Memory buffer) StartConfiguring(); try { - if (buffer.Length != 0 && _bufferList != null) + if (buffer.Length != 0 && _bufferList is not null) { throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(BufferList))); } @@ -410,7 +410,7 @@ public void SetBuffer(Memory buffer) } } - internal bool HasMultipleBuffers => _bufferList != null; + internal bool HasMultipleBuffers => _bufferList is not null; internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags) { @@ -426,14 +426,14 @@ internal void SetResults(Exception exception, int bytesTransferred, SocketFlags _bytesTransferred = bytesTransferred; _socketFlags = flags; - if (exception == null) + if (exception is null) { _socketError = SocketError.Success; } else { SocketException? socketException = exception as SocketException; - if (socketException != null) + if (socketException is not null) { _socketError = socketException.SocketErrorCode; } @@ -571,7 +571,7 @@ internal void StartOperationAccept() { // Caller didn't specify a buffer so use an internal one. // See if current internal one is big enough, otherwise create a new one. - if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount) + if (_acceptBuffer is null || _acceptBuffer.Length < _acceptAddressBufferCount) { _acceptBuffer = new byte[_acceptAddressBufferCount]; } @@ -590,7 +590,7 @@ internal void CancelConnectAsync() if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect) { MultipleConnectAsync? multipleConnect = _multipleConnect; - if (multipleConnect != null) + if (multipleConnect is not null) { // If a multiple connect is in progress, abort it. multipleConnect.Cancel(); @@ -612,7 +612,7 @@ internal void FinishOperationSyncFailure(SocketError socketError, int bytesTrans // If we're doing a static ConnectAsync to an IPEndPoint, we need to dispose // of the socket, as we manufactured it and the caller has no opportunity to do so. Socket? currentSocket = _currentSocket; - if (currentSocket != null) + if (currentSocket is not null) { currentSocket.UpdateStatusAfterSocketError(socketError); if (_completedOperation == SocketAsyncOperation.Connect && !_userSocket) @@ -650,7 +650,7 @@ internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTran FinishOperationSyncFailure(socketError, bytesTransferred, flags); - if (context == null) + if (context is null) { OnCompletedInternal(); } @@ -666,7 +666,7 @@ internal void FinishConnectByNameAsyncFailure(Exception exception, int bytesTran FinishConnectByNameSyncFailure(exception, bytesTransferred, flags); - if (context == null) + if (context is null) { OnCompletedInternal(); } @@ -694,7 +694,7 @@ internal void FinishWrapperConnectAsyncSuccess(Socket? connectSocket, int bytesT FinishWrapperConnectSyncSuccess(connectSocket, bytesTransferred, flags); - if (context == null) + if (context is null) { OnCompletedInternal(); } @@ -823,7 +823,7 @@ internal void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flag FinishOperationSyncSuccess(bytesTransferred, flags); // Raise completion event. - if (context == null) + if (context is null) { OnCompletedInternal(); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs index 62d5719ea18745..9dac776a2bf7f9 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs @@ -115,10 +115,10 @@ private static unsafe int SysReceive(SafeSocketHandle socket, SocketFlags flags, private static unsafe int SysReceive(SafeSocketHandle socket, SocketFlags flags, Span buffer, byte[]? socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno) { - Debug.Assert(socketAddress != null || socketAddressLen == 0, $"Unexpected values: socketAddress={socketAddress}, socketAddressLen={socketAddressLen}"); + Debug.Assert(socketAddress is not null || socketAddressLen == 0, $"Unexpected values: socketAddress={socketAddress}, socketAddressLen={socketAddressLen}"); long received = 0; - int sockAddrLen = socketAddress != null ? socketAddressLen : 0; + int sockAddrLen = socketAddress is not null ? socketAddressLen : 0; fixed (byte* sockAddr = socketAddress) fixed (byte* b = &MemoryMarshal.GetReference(buffer)) @@ -192,7 +192,7 @@ private static unsafe int SysSend(SafeSocketHandle socket, SocketFlags flags, Re var messageHeader = new Interop.Sys.MessageHeader { SocketAddress = sockAddr, - SocketAddressLen = socketAddress != null ? socketAddressLen : 0, + SocketAddressLen = socketAddress is not null ? socketAddressLen : 0, IOVectors = &iov, IOVectorCount = 1 }; @@ -223,7 +223,7 @@ private static unsafe int SysSend(SafeSocketHandle socket, SocketFlags flags, IL int startIndex = bufferIndex, startOffset = offset; int sockAddrLen = 0; - if (socketAddress != null) + if (socketAddress is not null) { sockAddrLen = socketAddressLen; } @@ -338,7 +338,7 @@ private static unsafe int SysReceive(SafeSocketHandle socket, SocketFlags flags, Span iovecs = allocOnStack ? stackalloc Interop.Sys.IOVector[IovStackThreshold] : new Interop.Sys.IOVector[maxBuffers]; int sockAddrLen = 0; - if (socketAddress != null) + if (socketAddress is not null) { sockAddrLen = socketAddressLen; } @@ -412,7 +412,7 @@ private static unsafe int SysReceive(SafeSocketHandle socket, SocketFlags flags, private static unsafe int SysReceiveMessageFrom(SafeSocketHandle socket, SocketFlags flags, Span buffer, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out Interop.Error errno) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); int cmsgBufferLen = Interop.Sys.GetControlMessageBufferSize(Convert.ToInt32(isIPv4), Convert.ToInt32(isIPv6)); byte* cmsgBuffer = stackalloc byte[cmsgBufferLen]; @@ -465,7 +465,7 @@ private static unsafe int SysReceiveMessageFrom( byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out Interop.Error errno) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); int buffersCount = buffers.Count; bool allocOnStack = buffersCount <= IovStackThreshold; @@ -580,7 +580,7 @@ public static unsafe bool TryCompleteAccept(SafeSocketHandle socket, byte[] sock public static unsafe bool TryStartConnect(SafeSocketHandle socket, byte[] socketAddress, int socketAddressLen, out SocketError errorCode) { - Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); + Debug.Assert(socketAddress is not null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); if (socket.IsDisconnected) @@ -732,7 +732,7 @@ public static unsafe bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span Interop.Error errno; try { - sent = buffers != null ? + sent = buffers is not null ? SysSend(socket, flags, buffers, ref bufferIndex, ref offset, socketAddress, socketAddressLen, out errno) : - socketAddress == null ? SysSend(socket, flags, buffer, ref offset, ref count, out errno) : + socketAddress is null ? SysSend(socket, flags, buffer, ref offset, ref count, out errno) : SysSend(socket, flags, buffer, ref offset, ref count, socketAddress, socketAddressLen, out errno); } catch (ObjectDisposedException) @@ -881,8 +881,8 @@ public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan bytesSent += sent; bool isComplete = sent == 0 || - (buffers == null && count == 0) || - (buffers != null && bufferIndex == buffers.Count); + (buffers is null && count == 0) || + (buffers is not null && bufferIndex == buffers.Count); if (isComplete) { errorCode = SocketError.Success; @@ -1219,7 +1219,7 @@ public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCod case FIONREAD: case SIOCATMARK: - if (optionOutValue == null || optionOutValue.Length < sizeof(int)) + if (optionOutValue is null || optionOutValue.Length < sizeof(int)) { return SocketError.Fault; } @@ -1314,7 +1314,7 @@ public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptio { fixed (byte* pinnedValue = optionValue) { - Interop.Error err = Interop.Sys.SetSockOpt(handle, optionLevel, optionName, pinnedValue, optionValue != null ? optionValue.Length : 0); + Interop.Error err = Interop.Sys.SetSockOpt(handle, optionLevel, optionName, pinnedValue, optionValue is not null ? optionValue.Length : 0); return GetErrorAndTrackSetting(handle, optionLevel, optionName, err); } } @@ -1443,7 +1443,7 @@ public static unsafe SocketError GetSockOpt(SafeSocketHandle handle, SocketOptio int optLen = optionLength; Interop.Error err; - if (optionValue == null || optionValue.Length == 0) + if (optionValue is null || optionValue.Length == 0) { optLen = 0; err = Interop.Sys.GetSockOpt(handle, optionLevel, optionName, null, &optLen); @@ -1590,9 +1590,9 @@ public static unsafe SocketError Poll(SafeSocketHandle handle, int microseconds, public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, IList? checkError, int microseconds) { - int checkReadInitialCount = checkRead != null ? checkRead.Count : 0; - int checkWriteInitialCount = checkWrite != null ? checkWrite.Count : 0; - int checkErrorInitialCount = checkError != null ? checkError.Count : 0; + int checkReadInitialCount = checkRead is not null ? checkRead.Count : 0; + int checkWriteInitialCount = checkWrite is not null ? checkWrite.Count : 0; + int checkErrorInitialCount = checkError is not null ? checkError.Count : 0; int count = checked(checkReadInitialCount + checkWriteInitialCount + checkErrorInitialCount); Debug.Assert(count > 0, $"Expected at least one entry."); @@ -1689,7 +1689,7 @@ private static unsafe SocketError SelectViaPoll( private static unsafe void AddToPollArray(Interop.PollEvent* arr, int arrLength, IList? socketList, ref int arrOffset, Interop.PollEvents events, ref int refsAdded) { - if (socketList == null) + if (socketList is null) return; int listCount = socketList.Count; @@ -1702,7 +1702,7 @@ private static unsafe void AddToPollArray(Interop.PollEvent* arr, int arrLength, } Socket? socket = socketList[i] as Socket; - if (socket == null) + if (socket is null) { throw new ArgumentException(SR.Format(SR.net_sockets_select, socket?.GetType().FullName ?? "null", typeof(Socket).FullName), nameof(socketList)); } @@ -1717,7 +1717,7 @@ private static unsafe void AddToPollArray(Interop.PollEvent* arr, int arrLength, private static unsafe void FilterPollList(IList? socketList, Interop.PollEvent* arr, int arrEndOffset, Interop.PollEvents desiredEvents, ref int refsAdded) { - if (socketList == null) + if (socketList is null) return; // The Select API requires leaving in the input lists only those sockets that were ready. As such, we need to loop @@ -1827,9 +1827,9 @@ public static async void SendPacketsAsync( for (int i = 0; i < elements.Length; i++) { SendPacketsElement e = elements[i]; - if (e != null) + if (e is not null) { - if (e.Buffer != null) + if (e.Buffer is not null) { bytesTransferred += await socket.SendAsync(new ArraySegment(e.Buffer, e.Offset, e.Count), SocketFlags.None).ConfigureAwait(false); } @@ -1963,7 +1963,7 @@ public static SocketError ReceiveMessageFromAsync(Socket socket, SafeSocketHandl public static SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle? acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult) { - Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}"); + Debug.Assert(acceptHandle is null, $"Unexpected acceptHandle: {acceptHandle}"); Debug.Assert(receiveSize == 0, $"Unexpected receiveSize: {receiveSize}"); byte[] socketAddressBuffer = new byte[socketAddressSize]; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs index 8ebb6c42ff738f..ed3855b6fba4bf 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs @@ -60,7 +60,7 @@ public static unsafe SocketError CreateSocket( ref SocketType socketType, ref ProtocolType protocolType) { - if (socketInformation.ProtocolInformation == null || socketInformation.ProtocolInformation.Length < sizeof(Interop.Winsock.WSAPROTOCOL_INFOW)) + if (socketInformation.ProtocolInformation is null || socketInformation.ProtocolInformation.Length < sizeof(Interop.Winsock.WSAPROTOCOL_INFOW)) { throw new ArgumentException(SR.net_sockets_invalid_socketinformation, nameof(socketInformation)); } @@ -556,9 +556,9 @@ public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCod handle, ioControlCode, optionInValue, - optionInValue != null ? optionInValue.Length : 0, + optionInValue is not null ? optionInValue.Length : 0, optionOutValue, - optionOutValue != null ? optionOutValue.Length : 0, + optionOutValue is not null ? optionOutValue.Length : 0, out optionLength, IntPtr.Zero, IntPtr.Zero); @@ -603,7 +603,7 @@ public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptio optionLevel, optionName, optionValuePtr, - optionValue != null ? optionValue.Length : 0); + optionValue is not null ? optionValue.Length : 0); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } } @@ -635,7 +635,7 @@ public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOpti ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address); #pragma warning restore CS0618 - if (optionValue.LocalAddress != null) + if (optionValue.LocalAddress is not null) { #pragma warning disable CS0618 // Address is marked obsolete ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address); @@ -653,7 +653,7 @@ public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOpti (((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) | ((uint) ipmr.MulticastAddress >> 24)); - if (optionValue.LocalAddress != null) + if (optionValue.LocalAddress is not null) { ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) | (((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) | @@ -914,7 +914,7 @@ public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, ILi static bool ShouldStackAlloc(IList? list, ref IntPtr[]? lease, out Span span) { int count; - if (list == null || (count = list.Count) == 0) + if (list is null || (count = list.Count) == 0) { span = default; return false; @@ -999,9 +999,9 @@ static bool ShouldStackAlloc(IList? list, ref IntPtr[]? lease, out Span } finally { - if (leaseRead != null) ArrayPool.Shared.Return(leaseRead); - if (leaseWrite != null) ArrayPool.Shared.Return(leaseWrite); - if (leaseError != null) ArrayPool.Shared.Return(leaseError); + if (leaseRead is not null) ArrayPool.Shared.Return(leaseRead); + if (leaseWrite is not null) ArrayPool.Shared.Return(leaseWrite); + if (leaseError is not null) ArrayPool.Shared.Return(leaseError); // This order matches with the AddToPollArray calls // to release only the handles that were ref'd. @@ -1114,14 +1114,14 @@ private static unsafe bool TransmitFileHelper( bool needTransmitFileBuffers = false; Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers); - if (preBuffer != null && preBuffer.Length > 0) + if (preBuffer is not null && preBuffer.Length > 0) { needTransmitFileBuffers = true; transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0); transmitFileBuffers.HeadLength = preBuffer.Length; } - if (postBuffer != null && postBuffer.Length > 0) + if (postBuffer is not null && postBuffer.Length > 0) { needTransmitFileBuffers = true; transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0); @@ -1132,7 +1132,7 @@ private static unsafe bool TransmitFileHelper( IntPtr fileHandlePtr = IntPtr.Zero; try { - if (fileHandle != null) + if (fileHandle is not null) { fileHandle.DangerousAddRef(ref releaseRef); fileHandlePtr = fileHandle.DangerousGetHandle(); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs index 937d0d008b41e0..9babebe3d2efce 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs @@ -49,7 +49,7 @@ public TcpClient(IPEndPoint localEP) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP); - if (localEP == null) + if (localEP is null) { throw new ArgumentNullException(nameof(localEP)); } @@ -65,7 +65,7 @@ public TcpClient(string hostname, int port) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, hostname); - if (hostname == null) + if (hostname is null) { throw new ArgumentNullException(nameof(hostname)); } @@ -119,7 +119,7 @@ public bool ExclusiveAddressUse get { return Client?.ExclusiveAddressUse ?? false; } set { - if (_clientSocket != null) + if (_clientSocket is not null) { _clientSocket.ExclusiveAddressUse = value; } @@ -132,7 +132,7 @@ public void Connect(string hostname, int port) ThrowIfDisposed(); - if (hostname == null) + if (hostname is null) { throw new ArgumentNullException(nameof(hostname)); } @@ -163,7 +163,7 @@ public void Connect(string hostname, int port) { try { - if (_clientSocket == null) + if (_clientSocket is null) { // We came via the constructor. Set the address family appropriately, // create the socket and try to connect. @@ -224,7 +224,7 @@ public void Connect(IPAddress address, int port) { ThrowIfDisposed(); - if (address == null) + if (address is null) { throw new ArgumentNullException(nameof(address)); } @@ -242,7 +242,7 @@ public void Connect(IPEndPoint remoteEP) { ThrowIfDisposed(); - if (remoteEP == null) + if (remoteEP is null) { throw new ArgumentNullException(nameof(remoteEP)); } @@ -315,7 +315,7 @@ public NetworkStream GetStream() throw new InvalidOperationException(SR.net_notconnected); } - if (_dataStream == null) + if (_dataStream is null) { _dataStream = new NetworkStream(Client, true); } @@ -333,7 +333,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { IDisposable? dataStream = _dataStream; - if (dataStream != null) + if (dataStream is not null) { dataStream.Dispose(); } @@ -344,7 +344,7 @@ protected virtual void Dispose(bool disposing) // we are bound to a local IPEndPoint this will remove the // binding and free up the IPEndPoint for later uses. Socket chkClientSocket = Volatile.Read(ref _clientSocket); - if (chkClientSocket != null) + if (chkClientSocket is not null) { try { @@ -411,7 +411,7 @@ public bool NoDelay private void InitializeClientSocket() { - Debug.Assert(_clientSocket == null); + Debug.Assert(_clientSocket is null); if (_family == AddressFamily.Unknown) { // If AF was not explicitly set try to initialize dual mode socket or fall-back to IPv4. diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs index e6222575ec1ba0..7d66cf53c027f5 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs @@ -23,7 +23,7 @@ public TcpListener(IPEndPoint localEP) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP); - if (localEP == null) + if (localEP is null) { throw new ArgumentNullException(nameof(localEP)); } @@ -37,7 +37,7 @@ public TcpListener(IPAddress localaddr, int port) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localaddr); - if (localaddr == null) + if (localaddr is null) { throw new ArgumentNullException(nameof(localaddr)); } @@ -96,7 +96,7 @@ public bool ExclusiveAddressUse { get { - return _serverSocket != null ? _serverSocket.ExclusiveAddressUse : _exclusiveAddressUse; + return _serverSocket is not null ? _serverSocket.ExclusiveAddressUse : _exclusiveAddressUse; } set { @@ -105,7 +105,7 @@ public bool ExclusiveAddressUse throw new InvalidOperationException(SR.net_tcplistener_mustbestopped); } - if (_serverSocket != null) + if (_serverSocket is not null) { _serverSocket.ExclusiveAddressUse = value; } @@ -121,7 +121,7 @@ public void AllowNatTraversal(bool allowed) throw new InvalidOperationException(SR.net_tcplistener_mustbestopped); } - if (_serverSocket != null) + if (_serverSocket is not null) { SetIPProtectionLevel(allowed); // Set it only for the current socket to preserve existing behavior } @@ -276,7 +276,7 @@ private void CreateNewSocketIfNeeded() _serverSocket.ExclusiveAddressUse = true; } - if (_allowNatTraversal != null) + if (_allowNatTraversal is not null) { Debug.Assert(OperatingSystem.IsWindows()); SetIPProtectionLevel(_allowNatTraversal.GetValueOrDefault()); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TransmitFileAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TransmitFileAsyncResult.Windows.cs index b78ad0637eeba8..a7e08604359940 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TransmitFileAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TransmitFileAsyncResult.Windows.cs @@ -22,10 +22,10 @@ internal void SetUnmanagedStructures(FileStream? fileStream, byte[]? preBuffer, int buffsNumber = 0; - if (preBuffer != null && preBuffer.Length > 0) + if (preBuffer is not null && preBuffer.Length > 0) ++buffsNumber; - if (postBuffer != null && postBuffer.Length > 0) + if (postBuffer is not null && postBuffer.Length > 0) ++buffsNumber; object[]? objectsToPin = null; @@ -33,12 +33,12 @@ internal void SetUnmanagedStructures(FileStream? fileStream, byte[]? preBuffer, { objectsToPin = new object[buffsNumber]; - if (preBuffer != null && preBuffer.Length > 0) + if (preBuffer is not null && preBuffer.Length > 0) { objectsToPin[--buffsNumber] = preBuffer; } - if (postBuffer != null && postBuffer.Length > 0) + if (postBuffer is not null && postBuffer.Length > 0) { objectsToPin[--buffsNumber] = postBuffer; } @@ -49,7 +49,7 @@ internal void SetUnmanagedStructures(FileStream? fileStream, byte[]? preBuffer, protected override void ForceReleaseUnmanagedStructures() { - if (_fileStream != null) + if (_fileStream is not null) { _fileStream.Dispose(); _fileStream = null; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs index e27a77da1f81db..d1a00b09997dff 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs @@ -86,7 +86,7 @@ public UdpClient(int port, AddressFamily family) public UdpClient(IPEndPoint localEP) { // Validate input parameters. - if (localEP == null) + if (localEP is null) { throw new ArgumentNullException(nameof(localEP)); } @@ -238,7 +238,7 @@ protected virtual void Dispose(bool disposing) } Socket chkClientSocket = _clientSocket; - if (chkClientSocket != null) + if (chkClientSocket is not null) { // If the NetworkStream wasn't retrieved, the Socket might // still be there and needs to be closed to release the effect @@ -261,7 +261,7 @@ private void CheckForBroadcast(IPAddress ipAddress) // and in that case we set SocketOptionName.Broadcast on the socket to allow its use. // if the user really wants complete control over Broadcast addresses they need to // inherit from UdpClient and gain control over the Socket and do whatever is appropriate. - if (_clientSocket != null && !_isBroadcast && IsBroadcast(ipAddress)) + if (_clientSocket is not null && !_isBroadcast && IsBroadcast(ipAddress)) { // We need to set the Broadcast socket option. // Note that once we set the option on the Socket we never reset it. @@ -317,7 +317,7 @@ private void ValidateDatagram(byte[] datagram, int bytes, IPEndPoint? endPoint) { ThrowIfDisposed(); - if (datagram == null) + if (datagram is null) { throw new ArgumentNullException(nameof(datagram)); } @@ -327,7 +327,7 @@ private void ValidateDatagram(byte[] datagram, int bytes, IPEndPoint? endPoint) throw new ArgumentOutOfRangeException(nameof(bytes)); } - if (_active && endPoint != null) + if (_active && endPoint is not null) { // Do not allow sending packets to arbitrary host when connected. throw new InvalidOperationException(SR.net_udpconnected); @@ -336,14 +336,14 @@ private void ValidateDatagram(byte[] datagram, int bytes, IPEndPoint? endPoint) private IPEndPoint? GetEndpoint(string? hostname, int port) { - if (_active && ((hostname != null) || (port != 0))) + if (_active && ((hostname is not null) || (port != 0))) { // Do not allow sending packets to arbitrary host when connected. throw new InvalidOperationException(SR.net_udpconnected); } IPEndPoint? ipEndPoint = null; - if (hostname != null && port != 0) + if (hostname is not null && port != 0) { IPAddress[] addresses = Dns.GetHostAddresses(hostname); @@ -420,7 +420,7 @@ public void JoinMulticastGroup(IPAddress multicastAddr) // Validate input parameters. ThrowIfDisposed(); - if (multicastAddr == null) + if (multicastAddr is null) { throw new ArgumentNullException(nameof(multicastAddr)); } @@ -478,7 +478,7 @@ public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr) ThrowIfDisposed(); // Validate input parameters. - if (multicastAddr == null) + if (multicastAddr is null) { throw new ArgumentNullException(nameof(multicastAddr)); } @@ -509,7 +509,7 @@ public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive) ThrowIfDisposed(); // parameter validation; - if (multicastAddr == null) + if (multicastAddr is null) { throw new ArgumentNullException(nameof(multicastAddr)); } @@ -534,7 +534,7 @@ public void DropMulticastGroup(IPAddress multicastAddr) ThrowIfDisposed(); // Validate input parameters. - if (multicastAddr == null) + if (multicastAddr is null) { throw new ArgumentNullException(nameof(multicastAddr)); } @@ -572,7 +572,7 @@ public void DropMulticastGroup(IPAddress multicastAddr, int ifindex) ThrowIfDisposed(); // Validate input parameters. - if (multicastAddr == null) + if (multicastAddr is null) { throw new ArgumentNullException(nameof(multicastAddr)); } @@ -649,7 +649,7 @@ private void CreateClientSocket() public UdpClient(string hostname, int port) { - if (hostname == null) + if (hostname is null) { throw new ArgumentNullException(nameof(hostname)); } @@ -674,7 +674,7 @@ public void Connect(string hostname, int port) { ThrowIfDisposed(); - if (hostname == null) + if (hostname is null) { throw new ArgumentNullException(nameof(hostname)); } @@ -695,7 +695,7 @@ public void Connect(string hostname, int port) try { - if (_clientSocket == null) + if (_clientSocket is null) { if (Socket.OSSupportsIPv4) { @@ -712,25 +712,25 @@ public void Connect(string hostname, int port) { try { - if (_clientSocket == null) + if (_clientSocket is null) { // We came via the constructor. Set the // address family appropriately, create the socket and // try to connect. - if (address.AddressFamily == AddressFamily.InterNetwork && ipv4Socket != null) + if (address.AddressFamily == AddressFamily.InterNetwork && ipv4Socket is not null) { ipv4Socket.Connect(address, port); _clientSocket = ipv4Socket; - if (ipv6Socket != null) + if (ipv6Socket is not null) { ipv6Socket.Close(); } } - else if (ipv6Socket != null) + else if (ipv6Socket is not null) { ipv6Socket.Connect(address, port); _clientSocket = ipv6Socket; - if (ipv4Socket != null) + if (ipv4Socket is not null) { ipv4Socket.Close(); } @@ -776,18 +776,18 @@ public void Connect(string hostname, int port) //did we connect? if (!_active) { - if (ipv6Socket != null) + if (ipv6Socket is not null) { ipv6Socket.Close(); } - if (ipv4Socket != null) + if (ipv4Socket is not null) { ipv4Socket.Close(); } // The connect failed - rethrow the last error we had - if (lastex != null) + if (lastex is not null) { throw lastex; } @@ -803,7 +803,7 @@ public void Connect(IPAddress addr, int port) { ThrowIfDisposed(); - if (addr == null) + if (addr is null) { throw new ArgumentNullException(nameof(addr)); } @@ -821,7 +821,7 @@ public void Connect(IPEndPoint endPoint) { ThrowIfDisposed(); - if (endPoint == null) + if (endPoint is null) { throw new ArgumentNullException(nameof(endPoint)); } @@ -872,17 +872,17 @@ public int Send(byte[] dgram, int bytes, IPEndPoint? endPoint) { ThrowIfDisposed(); - if (dgram == null) + if (dgram is null) { throw new ArgumentNullException(nameof(dgram)); } - if (_active && endPoint != null) + if (_active && endPoint is not null) { // Do not allow sending packets to arbitrary host when connected throw new InvalidOperationException(SR.net_udpconnected); } - if (endPoint == null) + if (endPoint is null) { return Client.Send(dgram, 0, bytes, SocketFlags.None); } @@ -898,17 +898,17 @@ public int Send(byte[] dgram, int bytes, string? hostname, int port) { ThrowIfDisposed(); - if (dgram == null) + if (dgram is null) { throw new ArgumentNullException(nameof(dgram)); } - if (_active && ((hostname != null) || (port != 0))) + if (_active && ((hostname is not null) || (port != 0))) { // Do not allow sending packets to arbitrary host when connected throw new InvalidOperationException(SR.net_udpconnected); } - if (hostname == null || port == 0) + if (hostname is null || port == 0) { return Client.Send(dgram, 0, bytes, SocketFlags.None); } @@ -937,7 +937,7 @@ public int Send(byte[] dgram, int bytes) { ThrowIfDisposed(); - if (dgram == null) + if (dgram is null) { throw new ArgumentNullException(nameof(dgram)); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs index 54e176758caa8c..41d38b7b2187b9 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs @@ -18,12 +18,12 @@ public struct UdpReceiveResult : IEquatable /// The remote endpoint of the UDP packet public UdpReceiveResult(byte[] buffer, IPEndPoint remoteEndPoint) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } - if (remoteEndPoint == null) + if (remoteEndPoint is null) { throw new ArgumentNullException(nameof(remoteEndPoint)); } @@ -60,7 +60,7 @@ public IPEndPoint RemoteEndPoint /// The hash code public override int GetHashCode() { - return (_buffer != null) ? (_buffer.GetHashCode() ^ _remoteEndPoint.GetHashCode()) : 0; + return (_buffer is not null) ? (_buffer.GetHashCode() ^ _remoteEndPoint.GetHashCode()) : 0; } /// diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs index 8ce031120f0499..275174b96b9869 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs @@ -16,7 +16,7 @@ public sealed partial class UnixDomainSocketEndPoint : EndPoint public UnixDomainSocketEndPoint(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -53,7 +53,7 @@ public UnixDomainSocketEndPoint(string path) internal UnixDomainSocketEndPoint(SocketAddress socketAddress) { - if (socketAddress == null) + if (socketAddress is null) { throw new ArgumentNullException(nameof(socketAddress)); } diff --git a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs index c02b1699d66bee..7d1e0909b5ecc8 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -152,7 +152,7 @@ public Encoding Encoding [AllowNull] public string BaseAddress { - get { return _baseAddress != null ? _baseAddress.ToString() : string.Empty; } + get { return _baseAddress is not null ? _baseAddress.ToString() : string.Empty; } set { if (string.IsNullOrEmpty(value)) @@ -223,12 +223,12 @@ protected virtual WebRequest GetWebRequest(Uri address) CopyHeadersTo(request); - if (Credentials != null) + if (Credentials is not null) { request.Credentials = Credentials; } - if (_method != null) + if (_method is not null) { request.Method = _method; } @@ -243,7 +243,7 @@ protected virtual WebRequest GetWebRequest(Uri address) request.Proxy = _proxy; } - if (CachePolicy != null) + if (CachePolicy is not null) { request.CachePolicy = CachePolicy; } @@ -343,7 +343,7 @@ public void DownloadFile(Uri address, string fileName) } finally { - if (fs != null) + if (fs is not null) { fs.Close(); if (!succeeded) @@ -394,7 +394,7 @@ public Stream OpenWrite(string address, string? method) => public Stream OpenWrite(Uri address, string? method) { ThrowIfNull(address, nameof(address)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -435,7 +435,7 @@ public byte[] UploadData(Uri address, string? method, byte[] data) { ThrowIfNull(address, nameof(address)); ThrowIfNull(data, nameof(data)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -484,7 +484,7 @@ private void OpenFileInternal( WebHeaderCollection headers = Headers; string? contentType = headers[HttpKnownHeaderNames.ContentType]; - if (contentType == null) + if (contentType is null) { contentType = DefaultUploadFileContentType; } @@ -556,7 +556,7 @@ public byte[] UploadFile(Uri address, string? method, string fileName) { ThrowIfNull(address, nameof(address)); ThrowIfNull(fileName, nameof(fileName)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -593,7 +593,7 @@ private byte[] GetValuesToUpload(NameValueCollection data) WebHeaderCollection headers = Headers; string? contentType = headers[HttpKnownHeaderNames.ContentType]; - if (contentType != null && !string.Equals(contentType, UploadValuesContentType, StringComparison.OrdinalIgnoreCase)) + if (contentType is not null && !string.Equals(contentType, UploadValuesContentType, StringComparison.OrdinalIgnoreCase)) { throw new WebException(SR.net_webclient_ContentType); } @@ -629,7 +629,7 @@ public byte[] UploadValues(Uri address, string? method, NameValueCollection data { ThrowIfNull(address, nameof(address)); ThrowIfNull(data, nameof(data)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -668,7 +668,7 @@ public string UploadString(Uri address, string? method, string data) { ThrowIfNull(address, nameof(address)); ThrowIfNull(data, nameof(data)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -715,13 +715,13 @@ private static void AbortRequest(WebRequest? request) private void CopyHeadersTo(WebRequest request) { - if (_headers == null) + if (_headers is null) { return; } var hwr = request as HttpWebRequest; - if (hwr == null) + if (hwr is null) { return; } @@ -785,7 +785,7 @@ private Uri GetUri(string address) ThrowIfNull(address, nameof(address)); Uri? uri; - if (_baseAddress != null) + if (_baseAddress is not null) { if (!Uri.TryCreate(_baseAddress, address, out uri)) { @@ -806,12 +806,12 @@ private Uri GetUri(Uri address) Uri? uri = address; - if (!address.IsAbsoluteUri && _baseAddress != null && !Uri.TryCreate(_baseAddress, address, out uri)) + if (!address.IsAbsoluteUri && _baseAddress is not null && !Uri.TryCreate(_baseAddress, address, out uri)) { return address; } - if (string.IsNullOrEmpty(uri.Query) && _requestParameters != null) + if (string.IsNullOrEmpty(uri.Query) && _requestParameters is not null) { var sb = new StringBuilder(); @@ -848,7 +848,7 @@ private Uri GetUri(Uri address) using (Stream readStream = response.GetResponseStream()) { - if (readStream != null) + if (readStream is not null) { int bytesRead; while ((bytesRead = readStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0) @@ -873,8 +873,8 @@ private async void DownloadBitsAsync( WebRequest request, Stream writeStream, AsyncOperation asyncOp, Action completionDelegate) { - Debug.Assert(_progress != null, "ProgressData should have been initialized"); - Debug.Assert(asyncOp != null); + Debug.Assert(_progress is not null, "ProgressData should have been initialized"); + Debug.Assert(asyncOp is not null); Exception? exception = null; try @@ -901,7 +901,7 @@ private async void DownloadBitsAsync( using (writeStream) using (Stream readStream = response.GetResponseStream()) { - if (readStream != null) + if (readStream is not null) { while (true) { @@ -938,7 +938,7 @@ private async void DownloadBitsAsync( } finally { - if (exception != null) + if (exception is not null) { completionDelegate(null, exception, asyncOp); } @@ -958,12 +958,12 @@ private byte[] UploadBits( using (Stream writeStream = request.GetRequestStream()) { - if (header != null) + if (header is not null) { writeStream.Write(header, 0, header.Length); } - if (readStream != null) + if (readStream is not null) { using (readStream) { @@ -990,7 +990,7 @@ private byte[] UploadBits( } } - if (footer != null) + if (footer is not null) { writeStream.Write(footer, 0, footer.Length); } @@ -1011,8 +1011,8 @@ private async void UploadBitsAsync( byte[]? header, byte[]? footer, AsyncOperation asyncOp, Action completionDelegate) { - Debug.Assert(asyncOp != null); - Debug.Assert(_progress != null, "ProgressData should have been initialized"); + Debug.Assert(asyncOp is not null); + Debug.Assert(_progress is not null, "ProgressData should have been initialized"); _progress.HasUploadPhase = true; Exception? exception = null; @@ -1025,14 +1025,14 @@ private async void UploadBitsAsync( using (Stream writeStream = await request.GetRequestStreamAsync().ConfigureAwait(false)) { - if (header != null) + if (header is not null) { await writeStream.WriteAsync(new ReadOnlyMemory(header)).ConfigureAwait(false); _progress.BytesSent += header.Length; PostProgressChanged(asyncOp, _progress); } - if (readStream != null) + if (readStream is not null) { using (readStream) { @@ -1063,7 +1063,7 @@ private async void UploadBitsAsync( } } - if (footer != null) + if (footer is not null) { await writeStream.WriteAsync(new ReadOnlyMemory(footer)).ConfigureAwait(false); _progress.BytesSent += footer.Length; @@ -1080,7 +1080,7 @@ private async void UploadBitsAsync( } finally { - if (exception != null) + if (exception is not null) { completionDelegate(null, exception, asyncOp); } @@ -1089,7 +1089,7 @@ private async void UploadBitsAsync( private static bool ByteArrayHasPrefix(byte[] prefix, byte[] byteArray) { - if (prefix == null || byteArray == null || prefix.Length > byteArray.Length) + if (prefix is null || byteArray is null || prefix.Length > byteArray.Length) { return false; } @@ -1125,7 +1125,7 @@ private string GetStringUsingEncoding(WebRequest request, byte[] data) contentType = null; } - if (contentType != null) + if (contentType is not null) { contentType = contentType.ToLowerInvariant(); string[] parsedList = contentType.Split(s_parseContentTypeSeparators); @@ -1155,7 +1155,7 @@ private string GetStringUsingEncoding(WebRequest request, byte[] data) // If no content encoding listed in the ContentType HTTP header, or no Content-Type header present, then // check for a byte-order-mark (BOM) in the data to figure out encoding. - if (enc == null) + if (enc is null) { // UTF32 must be tested before Unicode because it's BOM is the same but longer. Encoding[] encodings = s_knownEncodings; @@ -1172,7 +1172,7 @@ private string GetStringUsingEncoding(WebRequest request, byte[] data) } // Do we have an encoding guess? If not, use default. - if (enc == null) + if (enc is null) { enc = Encoding; } @@ -1191,7 +1191,7 @@ private string GetStringUsingEncoding(WebRequest request, byte[] data) private string MapToDefaultMethod(Uri address) { - Uri uri = !address.IsAbsoluteUri && _baseAddress != null ? + Uri uri = !address.IsAbsoluteUri && _baseAddress is not null ? new Uri(_baseAddress, address) : address; @@ -1203,7 +1203,7 @@ private string MapToDefaultMethod(Uri address) [return: NotNullIfNotNull("str")] private static string? UrlEncode(string? str) { - if (str == null) + if (str is null) return null; byte[] bytes = Encoding.UTF8.GetBytes(str); return Encoding.ASCII.GetString(UrlEncodeBytesToBytesInternal(bytes, 0, bytes.Length, false)); @@ -1337,7 +1337,7 @@ public void OpenWriteAsync(Uri address, string? method) => public void OpenWriteAsync(Uri address, string? method, object? userToken) { ThrowIfNull(address, nameof(address)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -1377,7 +1377,7 @@ private void DownloadStringAsyncCallback(byte[]? returnBytes, Exception? excepti string? stringData = null; try { - if (returnBytes != null) + if (returnBytes is not null) { stringData = GetStringUsingEncoding(_webRequest!, returnBytes); } @@ -1477,7 +1477,7 @@ public void UploadStringAsync(Uri address, string? method, string data, object? { ThrowIfNull(address, nameof(address)); ThrowIfNull(data, nameof(data)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -1495,7 +1495,7 @@ public void UploadStringAsync(Uri address, string? method, string data, object? (bytesResult, error, uploadAsyncOp) => { string? stringResult = null; - if (error == null && bytesResult != null) + if (error is null && bytesResult is not null) { try { @@ -1528,7 +1528,7 @@ public void UploadDataAsync(Uri address, string? method, byte[] data, object? us { ThrowIfNull(address, nameof(address)); ThrowIfNull(data, nameof(data)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -1541,7 +1541,7 @@ public void UploadDataAsync(Uri address, string? method, byte[] data, object? us WebRequest request = _webRequest = GetWebRequest(GetUri(address)); int chunkSize = 0; - if (UploadProgressChanged != null) + if (UploadProgressChanged is not null) { // If ProgressCallback is requested, we should send the buffer in chunks chunkSize = (int)Math.Min((long)DefaultCopyBufferLength, data.Length); @@ -1569,7 +1569,7 @@ public void UploadFileAsync(Uri address, string? method, string fileName, object { ThrowIfNull(address, nameof(address)); ThrowIfNull(fileName, nameof(fileName)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -1608,7 +1608,7 @@ public void UploadValuesAsync(Uri address, string? method, NameValueCollection d { ThrowIfNull(address, nameof(address)); ThrowIfNull(data, nameof(data)); - if (method == null) + if (method is null) { method = MapToDefaultMethod(address); } @@ -1621,7 +1621,7 @@ public void UploadValuesAsync(Uri address, string? method, NameValueCollection d WebRequest request = _webRequest = GetWebRequest(GetUri(address)); int chunkSize = 0; - if (UploadProgressChanged != null) + if (UploadProgressChanged is not null) { // If ProgressCallback is requested, we should send the buffer in chunks chunkSize = (int)Math.Min((long)DefaultCopyBufferLength, buffer.Length); @@ -1911,7 +1911,7 @@ private void HandleCompletion( try { unregisterHandler(this, handler); } finally { - if (e.Error != null) tcs.TrySetException(e.Error); + if (e.Error is not null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(getResult(e)); } @@ -1920,12 +1920,12 @@ private void HandleCompletion( private void PostProgressChanged(AsyncOperation asyncOp, ProgressData progress) { - if (asyncOp != null && (progress.BytesSent > 0 || progress.BytesReceived > 0)) + if (asyncOp is not null && (progress.BytesSent > 0 || progress.BytesReceived > 0)) { int progressPercentage; if (progress.HasUploadPhase) { - if (UploadProgressChanged != null) + if (UploadProgressChanged is not null) { progressPercentage = progress.TotalBytesToReceive < 0 && progress.BytesReceived == 0 ? progress.TotalBytesToSend < 0 ? 0 : progress.TotalBytesToSend == 0 ? 50 : (int)((50 * progress.BytesSent) / progress.TotalBytesToSend) : @@ -1933,7 +1933,7 @@ private void PostProgressChanged(AsyncOperation asyncOp, ProgressData progress) asyncOp.Post(_reportUploadProgressChanged!, new UploadProgressChangedEventArgs(progressPercentage, asyncOp.UserSuppliedState!, progress.BytesSent, progress.TotalBytesToSend, progress.BytesReceived, progress.TotalBytesToReceive)); } } - else if (DownloadProgressChanged != null) + else if (DownloadProgressChanged is not null) { progressPercentage = progress.TotalBytesToReceive < 0 ? 0 : progress.TotalBytesToReceive == 0 ? 100 : (int)((100 * progress.BytesReceived) / progress.TotalBytesToReceive); asyncOp.Post(_reportDownloadProgressChanged!, new DownloadProgressChangedEventArgs(progressPercentage, asyncOp.UserSuppliedState!, progress.BytesReceived, progress.TotalBytesToReceive)); @@ -1943,7 +1943,7 @@ private void PostProgressChanged(AsyncOperation asyncOp, ProgressData progress) private static void ThrowIfNull(object argument, string parameterName) { - if (argument == null) + if (argument is null) { throw new ArgumentNullException(parameterName); } diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/BrowserWebSocket.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/BrowserWebSocket.cs index c07cd8f01e7936..77276bf29bfbca 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/BrowserWebSocket.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/BrowserWebSocket.cs @@ -78,7 +78,7 @@ public override WebSocketState State { get { - if (_innerWebSocket != null && !_innerWebSocket.IsDisposed) + if (_innerWebSocket is not null && !_innerWebSocket.IsDisposed) { return ReadyStateToDotNetState((int)_innerWebSocket.GetObjectProperty("readyState")); } @@ -102,11 +102,11 @@ private static WebSocketState ReadyStateToDotNetState(int readyState) => _ => WebSocketState.None }; - public override WebSocketCloseStatus? CloseStatus => _innerWebSocket == null ? null : _innerWebSocketCloseStatus; + public override WebSocketCloseStatus? CloseStatus => _innerWebSocket is null ? null : _innerWebSocketCloseStatus; - public override string? CloseStatusDescription => _innerWebSocket == null ? null : _innerWebSocketCloseStatusDescription; + public override string? CloseStatusDescription => _innerWebSocket is null ? null : _innerWebSocketCloseStatusDescription; - public override string? SubProtocol => _innerWebSocket != null && !_innerWebSocket.IsDisposed ? _innerWebSocket!.GetObjectProperty("protocol")?.ToString() : null; + public override string? SubProtocol => _innerWebSocket is not null && !_innerWebSocket.IsDisposed ? _innerWebSocket!.GetObjectProperty("protocol")?.ToString() : null; #endregion Properties @@ -277,22 +277,22 @@ private void NativeCleanup() { // We need to clear the events on websocket as well or stray events // are possible leading to crashes. - if (_onClose != null) + if (_onClose is not null) { _innerWebSocket?.SetObjectProperty("onclose", ""); _onClose = null; } - if (_onError != null) + if (_onError is not null) { _innerWebSocket?.SetObjectProperty("onerror", ""); _onError = null; } - if (_onOpen != null) + if (_onOpen is not null) { _innerWebSocket?.SetObjectProperty("onopen", ""); _onOpen = null; } - if (_onMessage != null) + if (_onMessage is not null) { _innerWebSocket?.SetObjectProperty("onmessage", ""); _onMessage = null; @@ -377,7 +377,7 @@ public override Task SendAsync(ArraySegment buffer, WebSocketMessageType m } break; default: - string strBuffer = buffer.Array == null ? string.Empty : Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count); + string strBuffer = buffer.Array is null ? string.Empty : Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count); _innerWebSocket!.Invoke("send", strBuffer); break; } diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs index 4d71e31863ce03..77568e35bb65dc 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs @@ -32,7 +32,7 @@ public override WebSocketState State get { // state == Connected or Disposed - if (_innerWebSocket != null) + if (_innerWebSocket is not null) { return _innerWebSocket.State; } @@ -52,7 +52,7 @@ public override WebSocketState State public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } @@ -126,8 +126,8 @@ private WebSocket ConnectedWebSocket throw new InvalidOperationException(SR.net_WebSockets_NotConnected); } - Debug.Assert(_innerWebSocket != null); - Debug.Assert(_innerWebSocket.WebSocket != null); + Debug.Assert(_innerWebSocket is not null); + Debug.Assert(_innerWebSocket.WebSocket is not null); return _innerWebSocket.WebSocket; } diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs index 92732ab643aee0..22a8992757020d 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs @@ -66,16 +66,16 @@ public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, Cli // Create the handler for this request and populate it with all of the options. // Try to use a shared handler rather than creating a new one just for this request, if // the options are compatible. - if (options.Credentials == null && + if (options.Credentials is null && !options.UseDefaultCredentials && - options.Proxy == null && - options.Cookies == null && - options.RemoteCertificateValidationCallback == null && + options.Proxy is null && + options.Cookies is null && + options.RemoteCertificateValidationCallback is null && options._clientCertificates?.Count == 0) { disposeHandler = false; handler = s_defaultHandler; - if (handler == null) + if (handler is null) { handler = new SocketsHttpHandler() { @@ -83,7 +83,7 @@ public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, Cli UseProxy = false, UseCookies = false, }; - if (Interlocked.CompareExchange(ref s_defaultHandler, handler, null) != null) + if (Interlocked.CompareExchange(ref s_defaultHandler, handler, null) is not null) { handler.Dispose(); handler = s_defaultHandler; @@ -95,7 +95,7 @@ public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, Cli handler = new SocketsHttpHandler(); handler.PooledConnectionLifetime = TimeSpan.Zero; handler.CookieContainer = options.Cookies; - handler.UseCookies = options.Cookies != null; + handler.UseCookies = options.Cookies is not null; handler.SslOptions.RemoteCertificateValidationCallback = options.RemoteCertificateValidationCallback; if (options.UseDefaultCredentials) @@ -107,7 +107,7 @@ public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, Cli handler.Credentials = options.Credentials; } - if (options.Proxy == null) + if (options.Proxy is null) { handler.UseProxy = false; } @@ -118,7 +118,7 @@ public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, Cli if (options._clientCertificates?.Count > 0) // use field to avoid lazily initializing the collection { - Debug.Assert(handler.SslOptions.ClientCertificates == null); + Debug.Assert(handler.SslOptions.ClientCertificates is null); handler.SslOptions.ClientCertificates = new X509Certificate2Collection(); handler.SslOptions.ClientCertificates.AddRange(options.ClientCertificates); } @@ -166,7 +166,7 @@ public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, Cli if (subprotocolArray.Length > 0 && !string.IsNullOrEmpty(subprotocolArray[0])) { subprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, subprotocolArray[0], StringComparison.OrdinalIgnoreCase)); - if (subprotocol == null) + if (subprotocol is null) { throw new WebSocketException( WebSocketError.UnsupportedProtocol, diff --git a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.netcoreapp.cs b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.netcoreapp.cs index 4b222c541dcb1b..a0f7f50a376159 100644 --- a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.netcoreapp.cs +++ b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.netcoreapp.cs @@ -49,7 +49,7 @@ public override ValueTask ReceiveAsync(Memory private Task ValidateAndReceiveAsync(Task receiveTask, byte[] buffer, CancellationToken cancellationToken) { - if (receiveTask == null || + if (receiveTask is null || (receiveTask.IsCompletedSuccessfully && !(receiveTask is Task wsrr && wsrr.Result.MessageType == WebSocketMessageType.Close) && !(receiveTask is Task vwsrr && vwsrr.Result.MessageType == WebSocketMessageType.Close))) diff --git a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs index 3bd6835a16f1d4..f70016b0fea088 100644 --- a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs +++ b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs @@ -86,7 +86,7 @@ protected static void ThrowOnInvalidState(WebSocketState state, params WebSocket { string validStatesText = string.Empty; - if (validStates != null && validStates.Length > 0) + if (validStates is not null && validStates.Length > 0) { foreach (WebSocketState currentState in validStates) { @@ -135,7 +135,7 @@ public static ArraySegment CreateServerBuffer(int receiveBufferSize) /// The created . public static WebSocket CreateFromStream(Stream stream, bool isServer, string? subProtocol, TimeSpan keepAliveInterval) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -145,7 +145,7 @@ public static WebSocket CreateFromStream(Stream stream, bool isServer, string? s throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(stream)); } - if (subProtocol != null) + if (subProtocol is not null) { WebSocketValidate.ValidateSubprotocol(subProtocol); } @@ -177,7 +177,7 @@ public static WebSocket CreateClientWebSocket(Stream innerStream, string? subProtocol, int receiveBufferSize, int sendBufferSize, TimeSpan keepAliveInterval, bool useZeroMaskingKey, ArraySegment internalBuffer) { - if (innerStream == null) + if (innerStream is null) { throw new ArgumentNullException(nameof(innerStream)); } @@ -187,7 +187,7 @@ public static WebSocket CreateClientWebSocket(Stream innerStream, throw new ArgumentException(!innerStream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(innerStream)); } - if (subProtocol != null) + if (subProtocol is not null) { WebSocketValidate.ValidateSubprotocol(subProtocol); } diff --git a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs index 925512c9956fc5..9e13325f38ba8c 100644 --- a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs +++ b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs @@ -102,7 +102,7 @@ public override void SetValue(int index, T value) protected override void CopyTo(T[] array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } diff --git a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs index bcb3815320dbb6..ce9d390ee86a67 100644 --- a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs +++ b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs @@ -310,7 +310,7 @@ protected Tensor(ReadOnlySpan dimensions, bool reverseStride) /// False (default) to indicate that the first dimension is most major (farthest apart) and the last dimension is most minor (closest together): akin to row-major in a rank-2 tensor. True to indicate that the last dimension is most major (farthest apart) and the first dimension is most minor (closest together): akin to column-major in a rank-2 tensor. protected Tensor(Array fromArray, bool reverseStride) { - if (fromArray == null) + if (fromArray is null) { throw new ArgumentNullException(nameof(fromArray)); } @@ -640,7 +640,7 @@ public virtual T this[params int[] indices] { get { - if (indices == null) + if (indices is null) { throw new ArgumentNullException(nameof(indices)); } @@ -650,7 +650,7 @@ public virtual T this[params int[] indices] set { - if (indices == null) + if (indices is null) { throw new ArgumentNullException(nameof(indices)); } @@ -738,7 +738,7 @@ void ICollection.CopyTo(Array array, int index) } else { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -885,7 +885,7 @@ void ICollection.CopyTo(T[] array, int arrayIndex) /// protected virtual void CopyTo(T[] array, int arrayIndex) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -962,7 +962,7 @@ void IList.RemoveAt(int index) #region IStructuralComparable members int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) + if (other is null) { return 1; } @@ -974,7 +974,7 @@ int IStructuralComparable.CompareTo(object? other, IComparer comparer) var otherArray = other as Array; - if (otherArray != null) + if (otherArray is not null) { return CompareTo(otherArray, comparer); } @@ -1064,7 +1064,7 @@ private int CompareTo(Array other, IComparer comparer) #region IStructuralEquatable members bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null) + if (other is null) { return false; } @@ -1076,7 +1076,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) var otherArray = other as Array; - if (otherArray != null) + if (otherArray is not null) { return Equals(otherArray, comparer); } @@ -1309,7 +1309,7 @@ private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); + return ((value is T) || (value is null && default(T) is null)); } } } diff --git a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs index 3c0c0a4068a755..398c8f1602559a 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs @@ -71,12 +71,12 @@ public TItem this[TKey key] public bool Contains(TKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (dict != null) + if (dict is not null) { return dict.ContainsKey(key); } @@ -94,12 +94,12 @@ public bool Contains(TKey key) public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TItem item) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (dict != null) + if (dict is not null) { return dict.TryGetValue(key, out item!); } @@ -107,7 +107,7 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TItem item) foreach (TItem itemInItems in Items) { TKey keyInItems = GetKeyForItem(itemInItems); - if (keyInItems != null && comparer.Equals(key, keyInItems)) + if (keyInItems is not null && comparer.Equals(key, keyInItems)) { item = itemInItems; return true; @@ -121,7 +121,7 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TItem item) private bool ContainsItem(TItem item) { TKey key; - if ((dict == null) || ((key = GetKeyForItem(item)) == null)) + if ((dict is null) || ((key = GetKeyForItem(item)) is null)) { return Items.Contains(item); } @@ -137,12 +137,12 @@ private bool ContainsItem(TItem item) public bool Remove(TKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } - if (dict != null) + if (dict is not null) { TItem item; return dict.TryGetValue(key, out item!) && Remove(item); @@ -172,11 +172,11 @@ protected void ChangeItemKey(TItem item, TKey newKey) TKey oldKey = GetKeyForItem(item); if (!comparer.Equals(oldKey, newKey)) { - if (newKey != null) + if (newKey is not null) { AddKey(newKey, item); } - if (oldKey != null) + if (oldKey is not null) { RemoveKey(oldKey); } @@ -195,7 +195,7 @@ protected override void ClearItems() protected override void InsertItem(int index, TItem item) { TKey key = GetKeyForItem(item); - if (key != null) + if (key is not null) { AddKey(key, item); } @@ -206,7 +206,7 @@ protected override void InsertItem(int index, TItem item) protected override void RemoveItem(int index) { TKey key = GetKeyForItem(Items[index]); - if (key != null) + if (key is not null) { RemoveKey(key); } @@ -221,19 +221,19 @@ protected override void SetItem(int index, TItem item) if (comparer.Equals(oldKey, newKey)) { - if (newKey != null && dict != null) + if (newKey is not null && dict is not null) { dict[newKey] = item; } } else { - if (newKey != null) + if (newKey is not null) { AddKey(newKey, item); } - if (oldKey != null) + if (oldKey is not null) { RemoveKey(oldKey); } @@ -244,7 +244,7 @@ protected override void SetItem(int index, TItem item) private void AddKey(TKey key, TItem item) { - if (dict != null) + if (dict is not null) { dict.Add(key, item); } @@ -270,7 +270,7 @@ private void CreateDictionary() foreach (TItem item in Items) { TKey key = GetKeyForItem(item); - if (key != null) + if (key is not null) { dict.Add(key, item); } @@ -279,8 +279,8 @@ private void CreateDictionary() private void RemoveKey(TKey key) { - Debug.Assert(key != null, "key shouldn't be null!"); - if (dict != null) + Debug.Assert(key is not null, "key shouldn't be null!"); + if (dict is not null) { dict.Remove(key); } diff --git a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs index b5e6eb8747e3d9..ba531ef8cb5a7b 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs @@ -64,7 +64,7 @@ public ObservableCollection(List list) : base(CreateCopy(list, nameof(list))) private static List CreateCopy(IEnumerable collection, string paramName) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(paramName); } @@ -196,7 +196,7 @@ protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler? handler = CollectionChanged; - if (handler != null) + if (handler is not null) { // Not calling BlockReentrancy() here to avoid the SimpleMonitor allocation. _blockReentrancyCount++; @@ -297,7 +297,7 @@ private void OnSerializing(StreamingContext context) [OnDeserialized] private void OnDeserialized(StreamingContext context) { - if (_monitor != null) + if (_monitor is not null) { _blockReentrancyCount = _monitor._busyCount; _monitor._collection = this; @@ -316,7 +316,7 @@ private sealed class SimpleMonitor : IDisposable public SimpleMonitor(ObservableCollection collection) { - Debug.Assert(collection != null); + Debug.Assert(collection is not null); _collection = collection; } diff --git a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs index 0ef5bfcd67ee35..35a06661f18832 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs @@ -107,7 +107,7 @@ IEnumerator IEnumerable.GetEnumerator() private static bool IsCompatibleKey(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -168,7 +168,7 @@ void IDictionary.Remove(object key) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -205,7 +205,7 @@ void ICollection.CopyTo(Array array, int index) else { object[]? objects = array as object[]; - if (objects == null) + if (objects is null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } @@ -371,7 +371,7 @@ internal static class ReadOnlyDictionaryHelpers // Abstracted away to avoid redundant implementations. internal static void CopyToNonGenericICollectionHelper(ICollection collection, Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -408,7 +408,7 @@ internal static void CopyToNonGenericICollectionHelper(ICollection collect // We can't cast array of value type to object[], so we don't support // widening of primitive types here. object?[]? objects = array as object?[]; - if (objects == null) + if (objects is null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } diff --git a/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs b/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs index 3638daf718ef8e..4a1f041536809d 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs @@ -49,7 +49,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, ob if (action == NotifyCollectionChangedAction.Reset) { - if (changedItem != null) + if (changedItem is not null) { throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); } @@ -78,7 +78,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, ob if (action == NotifyCollectionChangedAction.Reset) { - if (changedItem != null) + if (changedItem is not null) { throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); } @@ -110,7 +110,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL if (action == NotifyCollectionChangedAction.Reset) { - if (changedItems != null) + if (changedItems is not null) { throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); } @@ -119,7 +119,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL } else { - if (changedItems == null) + if (changedItems is null) { throw new ArgumentNullException(nameof(changedItems)); } @@ -144,7 +144,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL if (action == NotifyCollectionChangedAction.Reset) { - if (changedItems != null) + if (changedItems is not null) { throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); } @@ -157,7 +157,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL } else { - if (changedItems == null) + if (changedItems is null) { throw new ArgumentNullException(nameof(changedItems)); } @@ -215,11 +215,11 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); } - if (newItems == null) + if (newItems is null) { throw new ArgumentNullException(nameof(newItems)); } - if (oldItems == null) + if (oldItems is null) { throw new ArgumentNullException(nameof(oldItems)); } @@ -240,11 +240,11 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); } - if (newItems == null) + if (newItems is null) { throw new ArgumentNullException(nameof(newItems)); } - if (oldItems == null) + if (oldItems is null) { throw new ArgumentNullException(nameof(oldItems)); } @@ -301,8 +301,8 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL internal NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList? newItems, IList? oldItems, int newIndex, int oldIndex) { _action = action; - _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); - _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); + _newItems = (newItems is null) ? null : new ReadOnlyList(newItems); + _oldItems = (oldItems is null) ? null : new ReadOnlyList(oldItems); _newStartingIndex = newIndex; _oldStartingIndex = oldIndex; } @@ -323,14 +323,14 @@ private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList? private void InitializeAdd(NotifyCollectionChangedAction action, IList? newItems, int newStartingIndex) { _action = action; - _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); + _newItems = (newItems is null) ? null : new ReadOnlyList(newItems); _newStartingIndex = newStartingIndex; } private void InitializeRemove(NotifyCollectionChangedAction action, IList? oldItems, int oldStartingIndex) { _action = action; - _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); + _oldItems = (oldItems is null) ? null : new ReadOnlyList(oldItems); _oldStartingIndex = oldStartingIndex; } @@ -377,7 +377,7 @@ internal sealed class ReadOnlyList : IList internal ReadOnlyList(IList list) { - Debug.Assert(list != null); + Debug.Assert(list is not null); _list = list; } diff --git a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs index df6569a283a73a..8b61d13904c30a 100644 --- a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs @@ -34,7 +34,7 @@ public TypeConverterAttribute() /// public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -49,7 +49,7 @@ public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMem /// public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName) { - if (typeName == null) + if (typeName is null) { throw new ArgumentNullException(nameof(typeName)); } diff --git a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs index 5f42f291038524..99a780e4f0dff3 100644 --- a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs @@ -13,7 +13,7 @@ public sealed class TypeDescriptionProviderAttribute : Attribute /// public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string typeName) { - if (typeName == null) + if (typeName is null) { throw new ArgumentNullException(nameof(typeName)); } @@ -26,7 +26,7 @@ public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyA /// public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } diff --git a/src/libraries/System.ObjectModel/src/System/Windows/Markup/ValueSerializerAttribute.cs b/src/libraries/System.ObjectModel/src/System/Windows/Markup/ValueSerializerAttribute.cs index f7e9897596259f..d2655c0fc7ba1d 100644 --- a/src/libraries/System.ObjectModel/src/System/Windows/Markup/ValueSerializerAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/Windows/Markup/ValueSerializerAttribute.cs @@ -43,7 +43,7 @@ public Type ValueSerializerType { get { - if (_valueSerializerType == null && _valueSerializerTypeName != null) + if (_valueSerializerType is null && _valueSerializerTypeName is not null) { _valueSerializerType = Type.GetType(_valueSerializerTypeName); } @@ -59,7 +59,7 @@ public string ValueSerializerTypeName { get { - if (_valueSerializerType != null) + if (_valueSerializerType is not null) { return _valueSerializerType.AssemblyQualifiedName!; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs b/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs index 09d3bdf608c218..951c12ed2f793f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs @@ -115,7 +115,7 @@ public static partial class Activator { Type? type = null; Assembly? assembly = null; - if (assemblyString == null) + if (assemblyString is null) { assembly = Assembly.GetExecutingAssembly(ref stackMark); } @@ -135,14 +135,14 @@ public static partial class Activator } } - if (type == null) + if (type is null) { type = assembly!.GetType(typeName, throwOnError: true, ignoreCase); } object? o = CreateInstance(type!, bindingAttr, binder, args, culture, activationAttributes); - return o != null ? new ObjectHandle(o) : null; + return o is not null ? new ObjectHandle(o) : null; } [System.Runtime.CompilerServices.Intrinsic] diff --git a/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs b/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs index 14bc2f56436fe5..fa67d6f96349f9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs @@ -54,7 +54,7 @@ public AggregateException(string? message) public AggregateException(string? message, Exception innerException) : base(message, innerException) { - if (innerException == null) + if (innerException is null) { throw new ArgumentNullException(nameof(innerException)); } @@ -103,7 +103,7 @@ public AggregateException(params Exception[] innerExceptions) : public AggregateException(string? message, IEnumerable innerExceptions) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. - : this(message, innerExceptions as IList ?? (innerExceptions == null ? (List)null! : new List(innerExceptions))) + : this(message, innerExceptions as IList ?? (innerExceptions is null ? (List)null! : new List(innerExceptions))) { } @@ -132,9 +132,9 @@ public AggregateException(string? message, params Exception[] innerExceptions) : /// An element of is /// null. private AggregateException(string? message, IList innerExceptions) - : base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null) + : base(message, innerExceptions is not null && innerExceptions.Count > 0 ? innerExceptions[0] : null) { - if (innerExceptions == null) + if (innerExceptions is null) { throw new ArgumentNullException(nameof(innerExceptions)); } @@ -148,7 +148,7 @@ private AggregateException(string? message, IList innerExceptions) { exceptionsCopy[i] = innerExceptions[i]; - if (exceptionsCopy[i] == null) + if (exceptionsCopy[i] is null) { throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } @@ -190,7 +190,7 @@ internal AggregateException(string message, IEnumerable i // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptionInfos as IList ?? - (innerExceptionInfos == null ? + (innerExceptionInfos is null ? (List)null! : new List(innerExceptionInfos))) { @@ -209,10 +209,10 @@ internal AggregateException(string message, IEnumerable i /// An element of is /// null. private AggregateException(string message, IList innerExceptionInfos) - : base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ? + : base(message, innerExceptionInfos is not null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] is not null ? innerExceptionInfos[0].SourceException : null) { - if (innerExceptionInfos == null) + if (innerExceptionInfos is null) { throw new ArgumentNullException(nameof(innerExceptionInfos)); } @@ -225,9 +225,9 @@ private AggregateException(string message, IList innerExc for (int i = 0; i < exceptionsCopy.Length; i++) { ExceptionDispatchInfo edi = innerExceptionInfos[i]; - if (edi != null) exceptionsCopy[i] = edi.SourceException; + if (edi is not null) exceptionsCopy[i] = edi.SourceException; - if (exceptionsCopy[i] == null) + if (exceptionsCopy[i] is null) { throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } @@ -248,7 +248,7 @@ private AggregateException(string message, IList innerExc protected AggregateException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -290,7 +290,7 @@ public override Exception GetBaseException() // Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception Exception? back = this; AggregateException? backAsAggregate = this; - while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1) + while (backAsAggregate is not null && backAsAggregate.InnerExceptions.Count == 1) { back = back!.InnerException; backAsAggregate = back as AggregateException; @@ -326,7 +326,7 @@ public override Exception GetBaseException() /// null. public void Handle(Func predicate) { - if (predicate == null) + if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } @@ -344,7 +344,7 @@ public void Handle(Func predicate) } // If there are unhandled exceptions remaining, throw them. - if (unhandledExceptions != null) + if (unhandledExceptions is not null) { throw new AggregateException(Message, unhandledExceptions); } @@ -382,7 +382,7 @@ public AggregateException Flatten() { Exception currentInnerException = currentInnerExceptions[i]; - if (currentInnerException == null) + if (currentInnerException is null) { continue; } diff --git a/src/libraries/System.Private.CoreLib/src/System/AppContext.AnyOS.cs b/src/libraries/System.Private.CoreLib/src/System/AppContext.AnyOS.cs index e497fdf6d395b9..3f2729b2dfdc39 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppContext.AnyOS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppContext.AnyOS.cs @@ -19,7 +19,7 @@ private static string GetBaseDirectoryCore() string? directory = Path.GetDirectoryName(path); - if (directory == null) + if (directory is null) return string.Empty; if (!Path.EndsInDirectorySeparator(directory)) diff --git a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs index 8c187fa53e6290..004b145df10941 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs @@ -31,10 +31,10 @@ public static partial class AppContext public static object? GetData(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (s_dataStore == null) + if (s_dataStore is null) return null; object? data; @@ -47,10 +47,10 @@ public static partial class AppContext public static void SetData(string name, object? data) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (s_dataStore == null) + if (s_dataStore is null) { Interlocked.CompareExchange(ref s_dataStore, new Dictionary(), null); } @@ -84,12 +84,12 @@ internal static void OnProcessExit() /// A return value of true represents that the switch was set and contains the value of the switch public static bool TryGetSwitch(string switchName, out bool isEnabled) { - if (switchName == null) + if (switchName is null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(switchName)); - if (s_switches != null) + if (s_switches is not null) { lock (s_switches) { @@ -114,12 +114,12 @@ public static bool TryGetSwitch(string switchName, out bool isEnabled) /// The value to assign public static void SetSwitch(string switchName, bool isEnabled) { - if (switchName == null) + if (switchName is null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(switchName)); - if (s_switches == null) + if (s_switches is null) { // Compatibility switches are rarely used. Initialize the Dictionary lazily Interlocked.CompareExchange(ref s_switches, new Dictionary(), null); @@ -134,7 +134,7 @@ public static void SetSwitch(string switchName, bool isEnabled) #if !CORERT internal static unsafe void Setup(char** pNames, char** pValues, int count) { - Debug.Assert(s_dataStore == null, "s_dataStore is not expected to be inited before Setup is called"); + Debug.Assert(s_dataStore is null, "s_dataStore is not expected to be inited before Setup is called"); s_dataStore = new Dictionary(count); for (int i = 0; i < count; i++) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Array.Enumerators.cs b/src/libraries/System.Private.CoreLib/src/System/Array.Enumerators.cs index 9d886312c8e7c7..4349ed69b41e30 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Array.Enumerators.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Array.Enumerators.cs @@ -166,7 +166,7 @@ internal sealed class SZGenericArrayEnumerator : IEnumerator internal SZGenericArrayEnumerator(T[] array) { - Debug.Assert(array != null); + Debug.Assert(array is not null); _array = array; _index = -1; diff --git a/src/libraries/System.Private.CoreLib/src/System/Array.cs b/src/libraries/System.Private.CoreLib/src/System/Array.cs index 1e0fca689b40c3..52fc2f8c20be36 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Array.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Array.cs @@ -36,7 +36,7 @@ private protected Array() { } public static ReadOnlyCollection AsReadOnly(T[] array) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -51,7 +51,7 @@ public static void Resize([NotNull] ref T[]? array, int newSize) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); T[]? larray = array; // local copy - if (larray == null) + if (larray is null) { array = new T[newSize]; return; @@ -73,12 +73,12 @@ ref MemoryMarshal.GetArrayDataReference(larray), array = newArray; } - Debug.Assert(array != null); + Debug.Assert(array is not null); } public static Array CreateInstance(Type elementType, params long[] lengths) { - if (lengths == null) + if (lengths is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } @@ -164,7 +164,7 @@ public static void Copy(Array sourceArray, long sourceIndex, Array destinationAr public object? GetValue(params long[] indices) { - if (indices == null) + if (indices is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); @@ -224,7 +224,7 @@ public void SetValue(object? value, long index1, long index2, long index3) public void SetValue(object? value, params long[] indices) { - if (indices == null) + if (indices is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); @@ -326,14 +326,14 @@ public object Clone() int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) + if (other is null) { return 1; } Array? o = other as Array; - if (o == null || this.Length != o.Length) + if (o is null || this.Length != o.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength, ExceptionArgument.other); } @@ -355,7 +355,7 @@ int IStructuralComparable.CompareTo(object? other, IComparer comparer) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null) + if (other is null) { return false; } @@ -388,7 +388,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { - if (comparer == null) + if (comparer is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); HashCode hashCode = default; @@ -416,7 +416,7 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) // public static int BinarySearch(Array array, object? value) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return BinarySearch(array, array.GetLowerBound(0), array.Length, value, null); } @@ -455,7 +455,7 @@ public static int BinarySearch(Array array, int index, int length, object? value // public static int BinarySearch(Array array, object? value, IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer); } @@ -477,7 +477,7 @@ public static int BinarySearch(Array array, object? value, IComparer? comparer) // public static int BinarySearch(Array array, int index, int length, object? value, IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); if (index < lb) @@ -528,7 +528,7 @@ public static int BinarySearch(Array array, int index, int length, object? value CorElementType et = array.GetCorElementTypeOfElementType(); if (et.IsPrimitiveType()) { - if (value == null) + if (value is null) return ~index; if (array.IsValueOfElementType(value)) @@ -623,14 +623,14 @@ static int GenericBinarySearch(Array array, int adjustedIndex, int length, ob public static int BinarySearch(T[] array, T value) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return BinarySearch(array, 0, array.Length, value, null); } public static int BinarySearch(T[] array, T value, System.Collections.Generic.IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return BinarySearch(array, 0, array.Length, value, comparer); } @@ -642,7 +642,7 @@ public static int BinarySearch(T[] array, int index, int length, T value) public static int BinarySearch(T[] array, int index, int length, T value, System.Collections.Generic.IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -657,12 +657,12 @@ public static int BinarySearch(T[] array, int index, int length, T value, Sys public static TOutput[] ConvertAll(TInput[] array, Converter converter) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (converter == null) + if (converter is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } @@ -684,7 +684,7 @@ public static TOutput[] ConvertAll(TInput[] array, Converter(T[] array, Predicate match) public static void Fill(T[] array, T value) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -731,7 +731,7 @@ public static void Fill(T[] array, T value) public static void Fill(T[] array, T value, int startIndex, int count) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -754,12 +754,12 @@ public static void Fill(T[] array, T value, int startIndex, int count) public static T? Find(T[] array, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -776,12 +776,12 @@ public static void Fill(T[] array, T value, int startIndex, int count) public static T[] FindAll(T[] array, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -799,7 +799,7 @@ public static T[] FindAll(T[] array, Predicate match) public static int FindIndex(T[] array, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -809,7 +809,7 @@ public static int FindIndex(T[] array, Predicate match) public static int FindIndex(T[] array, int startIndex, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -819,7 +819,7 @@ public static int FindIndex(T[] array, int startIndex, Predicate match) public static int FindIndex(T[] array, int startIndex, int count, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -834,7 +834,7 @@ public static int FindIndex(T[] array, int startIndex, int count, Predicate(T[] array, int startIndex, int count, Predicate(T[] array, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -872,7 +872,7 @@ public static int FindIndex(T[] array, int startIndex, int count, Predicate(T[] array, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -882,7 +882,7 @@ public static int FindLastIndex(T[] array, Predicate match) public static int FindLastIndex(T[] array, int startIndex, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -892,12 +892,12 @@ public static int FindLastIndex(T[] array, int startIndex, Predicate match public static int FindLastIndex(T[] array, int startIndex, int count, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -938,12 +938,12 @@ public static int FindLastIndex(T[] array, int startIndex, int count, Predica public static void ForEach(T[] array, Action action) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (action == null) + if (action is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } @@ -960,7 +960,7 @@ public static void ForEach(T[] array, Action action) // public static int IndexOf(Array array, object? value) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return IndexOf(array, value, array.GetLowerBound(0), array.Length); } @@ -973,7 +973,7 @@ public static int IndexOf(Array array, object? value) // public static int IndexOf(Array array, object? value, int startIndex) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return IndexOf(array, value, startIndex, array.Length - startIndex + lb); @@ -987,7 +987,7 @@ public static int IndexOf(Array array, object? value, int startIndex) // public static int IndexOf(Array array, object? value, int startIndex, int count) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); @@ -1001,11 +1001,11 @@ public static int IndexOf(Array array, object? value, int startIndex, int count) int endIndex = startIndex + count; if (array is object[] objArray) { - if (value == null) + if (value is null) { for (int i = startIndex; i < endIndex; i++) { - if (objArray[i] == null) + if (objArray[i] is null) return i; } } @@ -1014,7 +1014,7 @@ public static int IndexOf(Array array, object? value, int startIndex, int count) for (int i = startIndex; i < endIndex; i++) { object obj = objArray[i]; - if (obj != null && obj.Equals(value)) + if (obj is not null && obj.Equals(value)) return i; } } @@ -1024,7 +1024,7 @@ public static int IndexOf(Array array, object? value, int startIndex, int count) CorElementType et = array.GetCorElementTypeOfElementType(); if (et.IsPrimitiveType()) { - if (value == null) + if (value is null) return lb - 1; if (array.IsValueOfElementType(value)) @@ -1080,9 +1080,9 @@ static int GenericIndexOf(Array array, object value, int adjustedIndex, int l for (int i = startIndex; i < endIndex; i++) { object? obj = array.GetValue(i); - if (obj == null) + if (obj is null) { - if (value == null) + if (value is null) return i; } else @@ -1100,7 +1100,7 @@ static int GenericIndexOf(Array array, object value, int adjustedIndex, int l public static int IndexOf(T[] array, T value) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1110,7 +1110,7 @@ public static int IndexOf(T[] array, T value) public static int IndexOf(T[] array, T value, int startIndex) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1120,7 +1120,7 @@ public static int IndexOf(T[] array, T value, int startIndex) public static int IndexOf(T[] array, T value, int startIndex, int count) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1184,7 +1184,7 @@ ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)) // public static int LastIndexOf(Array array, object? value) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, array.Length - 1 + lb, array.Length); @@ -1197,7 +1197,7 @@ public static int LastIndexOf(Array array, object? value) // public static int LastIndexOf(Array array, object? value, int startIndex) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, startIndex, startIndex + 1 - lb); @@ -1211,7 +1211,7 @@ public static int LastIndexOf(Array array, object? value, int startIndex) // public static int LastIndexOf(Array array, object? value, int startIndex, int count) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); if (array.Length == 0) @@ -1231,11 +1231,11 @@ public static int LastIndexOf(Array array, object? value, int startIndex, int co int endIndex = startIndex - count + 1; if (array is object[] objArray) { - if (value == null) + if (value is null) { for (int i = startIndex; i >= endIndex; i--) { - if (objArray[i] == null) + if (objArray[i] is null) return i; } } @@ -1244,7 +1244,7 @@ public static int LastIndexOf(Array array, object? value, int startIndex, int co for (int i = startIndex; i >= endIndex; i--) { object obj = objArray[i]; - if (obj != null && obj.Equals(value)) + if (obj is not null && obj.Equals(value)) return i; } } @@ -1254,7 +1254,7 @@ public static int LastIndexOf(Array array, object? value, int startIndex, int co CorElementType et = array.GetCorElementTypeOfElementType(); if (et.IsPrimitiveType()) { - if (value == null) + if (value is null) return lb - 1; if (array.IsValueOfElementType(value)) @@ -1310,9 +1310,9 @@ static int GenericLastIndexOf(Array array, object value, int adjustedIndex, i for (int i = startIndex; i >= endIndex; i--) { object? obj = array.GetValue(i); - if (obj == null) + if (obj is null) { - if (value == null) + if (value is null) return i; } else @@ -1326,7 +1326,7 @@ static int GenericLastIndexOf(Array array, object value, int adjustedIndex, i public static int LastIndexOf(T[] array, T value) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1336,7 +1336,7 @@ public static int LastIndexOf(T[] array, T value) public static int LastIndexOf(T[] array, T value, int startIndex) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1346,7 +1346,7 @@ public static int LastIndexOf(T[] array, T value, int startIndex) public static int LastIndexOf(T[] array, T value, int startIndex, int count) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1440,7 +1440,7 @@ ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)) // public static void Reverse(Array array) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Reverse(array, array.GetLowerBound(0), array.Length); } @@ -1453,7 +1453,7 @@ public static void Reverse(Array array) // public static void Reverse(Array array, int index, int length) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lowerBound = array.GetLowerBound(0); if (index < lowerBound) @@ -1521,14 +1521,14 @@ public static void Reverse(Array array, int index, int length) public static void Reverse(T[] array) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Reverse(array, 0, array.Length); } public static void Reverse(T[] array, int index, int length) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -1558,7 +1558,7 @@ public static void Reverse(T[] array, int index, int length) // public static void Sort(Array array) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort(array, null, array.GetLowerBound(0), array.Length, null); } @@ -1571,7 +1571,7 @@ public static void Sort(Array array) // public static void Sort(Array keys, Array? items) { - if (keys == null) + if (keys is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort(keys, items, keys.GetLowerBound(0), keys.Length, null); } @@ -1604,7 +1604,7 @@ public static void Sort(Array keys, Array? items, int index, int length) // public static void Sort(Array array, IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort(array, null, array.GetLowerBound(0), array.Length, comparer); } @@ -1619,7 +1619,7 @@ public static void Sort(Array array, IComparer? comparer) // public static void Sort(Array keys, Array? items, IComparer? comparer) { - if (keys == null) + if (keys is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); } @@ -1645,19 +1645,19 @@ public static void Sort(Array array, int index, int length, IComparer? comparer) // public static void Sort(Array keys, Array? items, int index, int length, IComparer? comparer) { - if (keys == null) + if (keys is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - if (keys.Rank != 1 || (items != null && items.Rank != 1)) + if (keys.Rank != 1 || (items is not null && items.Rank != 1)) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int keysLowerBound = keys.GetLowerBound(0); - if (items != null && keysLowerBound != items.GetLowerBound(0)) + if (items is not null && keysLowerBound != items.GetLowerBound(0)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_LowerBoundsMustMatch); if (index < keysLowerBound) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length)) + if (keys.Length - (index - keysLowerBound) < length || (items is not null && (index - keysLowerBound) > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length <= 1) @@ -1668,7 +1668,7 @@ public static void Sort(Array keys, Array? items, int index, int length, ICompar if (keys is object[] objKeys) { object[]? objItems = items as object[]; - if (items == null || objItems != null) + if (items is null || objItems is not null) { new SorterObjectArray(objKeys, objItems, comparer).Sort(index, length); return; @@ -1678,7 +1678,7 @@ public static void Sort(Array keys, Array? items, int index, int length, ICompar if (comparer == Comparer.Default) { CorElementType et = keys.GetCorElementTypeOfElementType(); - if (items == null || items.GetCorElementTypeOfElementType() == et) + if (items is null || items.GetCorElementTypeOfElementType() == et) { int adjustedIndex = index - keysLowerBound; switch (et) @@ -1732,7 +1732,7 @@ public static void Sort(Array keys, Array? items, int index, int length, ICompar static void GenericSort(Array keys, Array? items, int adjustedIndex, int length) where T: struct { Span keysSpan = UnsafeArrayAsSpan(keys, adjustedIndex, length); - if (items != null) + if (items is not null) { keysSpan.Sort(UnsafeArrayAsSpan(items, adjustedIndex, length)); } @@ -1749,7 +1749,7 @@ static void GenericSort(Array keys, Array? items, int adjustedIndex, int leng public static void Sort(T[] array) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Length > 1) @@ -1761,7 +1761,7 @@ public static void Sort(T[] array) public static void Sort(TKey[] keys, TValue[]? items) { - if (keys == null) + if (keys is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort(keys, items, 0, keys.Length, null); } @@ -1778,21 +1778,21 @@ public static void Sort(TKey[] keys, TValue[]? items, int index, i public static void Sort(T[] array, System.Collections.Generic.IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort(array, 0, array.Length, comparer); } public static void Sort(TKey[] keys, TValue[]? items, System.Collections.Generic.IComparer? comparer) { - if (keys == null) + if (keys is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort(keys, items, 0, keys.Length, comparer); } public static void Sort(T[] array, int index, int length, System.Collections.Generic.IComparer? comparer) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -1810,18 +1810,18 @@ public static void Sort(T[] array, int index, int length, System.Collections. public static void Sort(TKey[] keys, TValue[]? items, int index, int length, System.Collections.Generic.IComparer? comparer) { - if (keys == null) + if (keys is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (keys.Length - index < length || (items != null && index > items.Length - length)) + if (keys.Length - index < length || (items is not null && index > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) { - if (items == null) + if (items is null) { Sort(keys, index, length, comparer); return; @@ -1835,12 +1835,12 @@ public static void Sort(TKey[] keys, TValue[]? items, int index, i public static void Sort(T[] array, Comparison comparison) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (comparison == null) + if (comparison is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } @@ -1851,12 +1851,12 @@ public static void Sort(T[] array, Comparison comparison) public static bool TrueForAll(T[] array, Predicate match) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -1894,7 +1894,7 @@ internal void SwapIfGreater(int a, int b) object temp = keys[a]; keys[a] = keys[b]; keys[b] = temp; - if (items != null) + if (items is not null) { object? item = items[a]; items[a] = items[b]; @@ -1910,7 +1910,7 @@ private void Swap(int i, int j) keys[i] = keys[j]; keys[j] = t; - if (items != null) + if (items is not null) { object? item = items[i]; items[i] = items[j]; @@ -2050,12 +2050,12 @@ private void DownHeap(int i, int n, int lo) if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; - if (items != null) + if (items is not null) items[lo + i - 1] = items[lo + child - 1]; i = child; } keys[lo + i - 1] = d; - if (items != null) + if (items is not null) items[lo + i - 1] = dt; } @@ -2072,12 +2072,12 @@ private void InsertionSort(int lo, int hi) while (j >= lo && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; - if (items != null) + if (items is not null) items[j + 1] = items[j]; j--; } keys[j + 1] = t; - if (items != null) + if (items is not null) items[j + 1] = ti; } } @@ -2108,7 +2108,7 @@ internal void SwapIfGreater(int a, int b) object? key = keys.GetValue(a); keys.SetValue(keys.GetValue(b), a); keys.SetValue(key, b); - if (items != null) + if (items is not null) { object? item = items.GetValue(a); items.SetValue(items.GetValue(b), a); @@ -2124,7 +2124,7 @@ private void Swap(int i, int j) keys.SetValue(keys.GetValue(j), i); keys.SetValue(t1, j); - if (items != null) + if (items is not null) { object? t2 = items.GetValue(i); items.SetValue(items.GetValue(j), i); @@ -2265,12 +2265,12 @@ private void DownHeap(int i, int n, int lo) break; keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1); - if (items != null) + if (items is not null) items.SetValue(items.GetValue(lo + child - 1), lo + i - 1); i = child; } keys.SetValue(d, lo + i - 1); - if (items != null) + if (items is not null) items.SetValue(dt, lo + i - 1); } @@ -2288,13 +2288,13 @@ private void InsertionSort(int lo, int hi) while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0) { keys.SetValue(keys.GetValue(j), j + 1); - if (items != null) + if (items is not null) items.SetValue(items.GetValue(j), j + 1); j--; } keys.SetValue(t, j + 1); - if (items != null) + if (items is not null) items.SetValue(dt, j + 1); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs b/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs index 6355847a87f49e..7f34de7f2e81e0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs @@ -39,7 +39,7 @@ namespace System public ArraySegment(T[] array) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _array = array; @@ -52,7 +52,7 @@ public ArraySegment(T[] array, int offset, int count) // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path // Negative values discovered though conversion to high values when converted to unsigned // Failure should be rare and location determination and message is delegated to failure functions - if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) + if (array is null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count); _array = array; @@ -166,7 +166,7 @@ public T[] ToArray() public static bool operator !=(ArraySegment a, ArraySegment b) => !(a == b); - public static implicit operator ArraySegment(T[] array) => array != null ? new ArraySegment(array) : default; + public static implicit operator ArraySegment(T[] array) => array is not null ? new ArraySegment(array) : default; #region IList T IList.this[int index] @@ -262,7 +262,7 @@ bool ICollection.Remove(T item) private void ThrowInvalidOperationIfDefault() { - if (_array == null) + if (_array is null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); } @@ -277,7 +277,7 @@ public struct Enumerator : IEnumerator internal Enumerator(ArraySegment arraySegment) { - Debug.Assert(arraySegment.Array != null); + Debug.Assert(arraySegment.Array is not null); Debug.Assert(arraySegment.Offset >= 0); Debug.Assert(arraySegment.Count >= 0); Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); diff --git a/src/libraries/System.Private.CoreLib/src/System/Buffer.cs b/src/libraries/System.Private.CoreLib/src/System/Buffer.cs index 46c80da913d0fd..545dd56938a645 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffer.cs @@ -21,9 +21,9 @@ public static partial class Buffer // array element indices and counts, use Array.Copy. public static unsafe void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count) { - if (src == null) + if (src is null) throw new ArgumentNullException(nameof(src)); - if (dst == null) + if (dst is null) throw new ArgumentNullException(nameof(dst)); nuint uSrcLen = (nuint)src.LongLength; @@ -66,7 +66,7 @@ public static unsafe void BlockCopy(Array src, int srcOffset, Array dst, int dst public static int ByteLength(Array array) { // Is the array present? - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? diff --git a/src/libraries/System.Private.CoreLib/src/System/Byte.cs b/src/libraries/System.Private.CoreLib/src/System/Byte.cs index 1fdebb7e84e807..9552f8447014cd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Byte.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Byte.cs @@ -31,7 +31,7 @@ namespace System // public int CompareTo(object? value) { - if (value == null) + if (value is null) { return 1; } @@ -72,20 +72,20 @@ public override int GetHashCode() public static byte Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } @@ -95,7 +95,7 @@ public static byte Parse(string s, IFormatProvider? provider) public static byte Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider)); } @@ -119,7 +119,7 @@ private static byte Parse(ReadOnlySpan s, NumberStyles style, NumberFormat public static bool TryParse([NotNullWhen(true)] string? s, out byte result) { - if (s == null) + if (s is null) { result = 0; return false; @@ -137,7 +137,7 @@ public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, I { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) + if (s is null) { result = 0; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/CharEnumerator.cs b/src/libraries/System.Private.CoreLib/src/System/CharEnumerator.cs index b7af82179fafca..2195b43ed8b64e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/CharEnumerator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/CharEnumerator.cs @@ -48,7 +48,7 @@ public bool MoveNext() public void Dispose() { - if (_str != null) + if (_str is not null) _index = _str.Length; _str = null; } diff --git a/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs b/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs index 659fc0fbf43cce..5eb9dc7f846a87 100644 --- a/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs @@ -21,7 +21,7 @@ public IndentedTextWriter(TextWriter writer) : this(writer, DefaultTabString) { public IndentedTextWriter(TextWriter writer, string tabString) : base(CultureInfo.InvariantCulture) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs index c23b06ade9fca8..fc0f7da945c663 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs @@ -61,7 +61,7 @@ public ArrayList(int capacity) // public ArrayList(ICollection c) { - if (c == null) + if (c is null) throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); int count = c.Count; @@ -153,7 +153,7 @@ public virtual object? this[int index] // public static ArrayList Adapter(IList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new IListWrapper(list); } @@ -252,17 +252,17 @@ public virtual object Clone() // public virtual bool Contains(object? item) { - if (item == null) + if (item is null) { for (int i = 0; i < _size; i++) - if (_items[i] == null) + if (_items[i] is null) return true; return false; } else { for (int i = 0; i < _size; i++) - if ((_items[i] != null) && (_items[i]!.Equals(item))) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) + if ((_items[i] is not null) && (_items[i]!.Equals(item))) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return true; return false; } @@ -281,7 +281,7 @@ public virtual void CopyTo(Array array) // public virtual void CopyTo(Array array, int arrayIndex) { - if ((array != null) && (array.Rank != 1)) + if ((array is not null) && (array.Rank != 1)) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // Delegate rest of error checking to Array.Copy. @@ -296,7 +296,7 @@ public virtual void CopyTo(int index, Array array, int arrayIndex, int count) { if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - if ((array != null) && (array.Rank != 1)) + if ((array is not null) && (array.Rank != 1)) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // Delegate rest of error checking to Array.Copy. @@ -325,7 +325,7 @@ private void EnsureCapacity(int min) // public static IList FixedSize(IList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new FixedSizeList(list); } @@ -335,7 +335,7 @@ public static IList FixedSize(IList list) // public static ArrayList FixedSize(ArrayList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new FixedSizeArrayList(list); } @@ -438,7 +438,7 @@ public virtual void Insert(int index, object? value) // public virtual void InsertRange(int index, ICollection c) { - if (c == null) + if (c is null) throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -516,7 +516,7 @@ public virtual int LastIndexOf(object? value, int startIndex, int count) // public static IList ReadOnly(IList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new ReadOnlyList(list); } @@ -525,7 +525,7 @@ public static IList ReadOnly(IList list) // public static ArrayList ReadOnly(ArrayList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new ReadOnlyArrayList(list); } @@ -625,7 +625,7 @@ public virtual void Reverse(int index, int count) // public virtual void SetRange(int index, ICollection c) { - if (c == null) throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); + if (c is null) throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); int count = c.Count; if (index < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -685,7 +685,7 @@ public virtual void Sort(int index, int count, IComparer? comparer) // public static IList Synchronized(IList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new SyncIList(list); } @@ -694,7 +694,7 @@ public static IList Synchronized(IList list) // public static ArrayList Synchronized(ArrayList list) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); return new SyncArrayList(list); } @@ -718,7 +718,7 @@ public static ArrayList Synchronized(ArrayList list) // public virtual Array ToArray(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); Array array = Array.CreateInstance(type, _size); @@ -856,7 +856,7 @@ public override void CopyTo(Array array, int index) public override void CopyTo(int index, Array array, int arrayIndex, int count) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0 || arrayIndex < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -906,17 +906,17 @@ public override int IndexOf(object? value, int startIndex, int count) if (count < 0 || startIndex > Count - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); int endIndex = startIndex + count; - if (value == null) + if (value is null) { for (int i = startIndex; i < endIndex; i++) - if (_list[i] == null) + if (_list[i] is null) return i; return -1; } else { for (int i = startIndex; i < endIndex; i++) - if (_list[i] != null && _list[i]!.Equals(value)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) + if (_list[i] is not null && _list[i]!.Equals(value)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return i; return -1; } @@ -930,7 +930,7 @@ public override void Insert(int index, object? obj) public override void InsertRange(int index, ICollection c) { - if (c == null) + if (c is null) throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); if (index < 0 || index > Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -974,17 +974,17 @@ public override int LastIndexOf(object? value, int startIndex, int count) if (count < 0 || count > startIndex + 1) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); int endIndex = startIndex - count + 1; - if (value == null) + if (value is null) { for (int i = startIndex; i >= endIndex; i--) - if (_list[i] == null) + if (_list[i] is null) return i; return -1; } else { for (int i = startIndex; i >= endIndex; i--) - if (_list[i] != null && _list[i]!.Equals(value)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) + if (_list[i] is not null && _list[i]!.Equals(value)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return i; return -1; } @@ -1042,7 +1042,7 @@ public override void Reverse(int index, int count) public override void SetRange(int index, ICollection c) { - if (c == null) + if (c is null) { throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); } @@ -1101,7 +1101,7 @@ public override void Sort(int index, int count, IComparer? comparer) public override Array ToArray(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); Array array = Array.CreateInstance(type, _list.Count); @@ -2239,7 +2239,7 @@ public override int Add(object? value) public override void AddRange(ICollection c) { - if (c == null) + if (c is null) { throw new ArgumentNullException(nameof(c)); } @@ -2301,17 +2301,17 @@ public override object Clone() public override bool Contains(object? item) { InternalUpdateRange(); - if (item == null) + if (item is null) { for (int i = 0; i < _baseSize; i++) - if (_baseList[_baseIndex + i] == null) + if (_baseList[_baseIndex + i] is null) return true; return false; } else { for (int i = 0; i < _baseSize; i++) - if (_baseList[_baseIndex + i] != null && _baseList[_baseIndex + i]!.Equals(item)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) + if (_baseList[_baseIndex + i] is not null && _baseList[_baseIndex + i]!.Equals(item)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return true; return false; } @@ -2319,7 +2319,7 @@ public override bool Contains(object? item) public override void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -2334,7 +2334,7 @@ public override void CopyTo(Array array, int index) public override void CopyTo(int index, Array array, int arrayIndex, int count) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -2442,7 +2442,7 @@ public override void Insert(int index, object? value) public override void InsertRange(int index, ICollection c) { if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - if (c == null) + if (c is null) { throw new ArgumentNullException(nameof(c)); } @@ -2580,7 +2580,7 @@ public override object? this[int index] public override Array ToArray(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); InternalUpdateRange(); @@ -2692,7 +2692,7 @@ internal class ArrayListDebugView public ArrayListDebugView(ArrayList arrayList) { - if (arrayList == null) + if (arrayList is null) throw new ArgumentNullException(nameof(arrayList)); _arrayList = arrayList; diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs index 26997e6e240c5d..e49fe857cd67b7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs @@ -23,7 +23,7 @@ public sealed class Comparer : IComparer, ISerializable public Comparer(CultureInfo culture) { - if (culture == null) + if (culture is null) throw new ArgumentNullException(nameof(culture)); _compareInfo = culture.CompareInfo; @@ -31,7 +31,7 @@ public Comparer(CultureInfo culture) private Comparer(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) throw new ArgumentNullException(nameof(info)); _compareInfo = (CompareInfo)info.GetValue("CompareInfo", typeof(CompareInfo))!; @@ -39,7 +39,7 @@ private Comparer(SerializationInfo info, StreamingContext context) public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) throw new ArgumentNullException(nameof(info)); info.AddValue("CompareInfo", _compareInfo); @@ -54,8 +54,8 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) public int Compare(object? a, object? b) { if (a == b) return 0; - if (a == null) return -1; - if (b == null) return 1; + if (a is null) return -1; + if (b is null) return 1; if (a is string sa && b is string sb) return _compareInfo.Compare(sa, sb); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs index d9e679c438aa1e..4ec755e23a08aa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs @@ -27,12 +27,12 @@ public int Compare(object? a, object? b) { if (a == b) return 0; - if (a == null) + if (a is null) return -1; - if (b == null) + if (b is null) return 1; - if (_comparer != null) + if (_comparer is not null) { return _comparer.Compare(a, b); } @@ -47,12 +47,12 @@ public int Compare(object? a, object? b) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } - return _hcp != null ? + return _hcp is not null ? _hcp.GetHashCode(obj) : obj.GetHashCode(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentQueue.cs index d46f4501d354f0..c3f7e93bdfd706 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentQueue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentQueue.cs @@ -76,7 +76,7 @@ public ConcurrentQueue() /// The argument is null. public ConcurrentQueue(IEnumerable collection) { - if (collection == null) + if (collection is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } @@ -139,7 +139,7 @@ void ICollection.CopyTo(Array array, int index) } // Validate arguments. - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -437,7 +437,7 @@ private static long GetCount(ConcurrentQueueSegment head, int headHead, Concu /// public void CopyTo(T[] array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -495,9 +495,9 @@ private void SnapForObservation(out ConcurrentQueueSegment head, out int head // Snap the head and tail head = _head; tail = _tail; - Debug.Assert(head != null); - Debug.Assert(tail != null); - Debug.Assert(tail._nextSegment == null); + Debug.Assert(head is not null); + Debug.Assert(tail is not null); + Debug.Assert(tail._nextSegment is null); // Mark them and all segments in between as preserving, and ensure no additional items // can be added to the tail. @@ -687,13 +687,13 @@ private bool TryDequeueSlow([MaybeNullWhen(false)] out T item) // Check to see whether this segment is the last. If it is, we can consider // this to be a moment-in-time empty condition (even though between the TryDequeue // check and this check, another item could have arrived). - if (head._nextSegment == null) + if (head._nextSegment is null) { item = default; return false; } - // At this point we know that head.Next != null, which means + // At this point we know that head.Next is not null, which means // this segment has been frozen for additional enqueues. But between // the time that we ran TryDequeue and checked for a next segment, // another item could have been added. Try to dequeue one more time @@ -756,7 +756,7 @@ private bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed) // The current segment was empty at the moment we checked. - if (next != null) + if (next is not null) { // If prior to the peek there was already a next segment, then // during the peek no additional items could have been enqueued @@ -764,7 +764,7 @@ private bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed) Debug.Assert(next == s._nextSegment); s = next; } - else if (Volatile.Read(ref s._nextSegment) == null) + else if (Volatile.Read(ref s._nextSegment) is null) { // The next segment is null. Nothing more to peek at. break; diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs index 85cbe02ad8de9d..a66de41b595212 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs @@ -52,7 +52,7 @@ public int BinarySearch(T[] array, int index, int length, T value, IComparer? internal static void Sort(Span keys, Comparison comparer) { - Debug.Assert(comparer != null, "Check the arguments in the caller!"); + Debug.Assert(comparer is not null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try @@ -71,7 +71,7 @@ internal static void Sort(Span keys, Comparison comparer) internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer comparer) { - Debug.Assert(array != null, "Check the arguments in the caller!"); + Debug.Assert(array is not null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; @@ -119,7 +119,7 @@ private static void Swap(Span a, int i, int j) internal static void IntrospectiveSort(Span keys, Comparison comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); if (keys.Length > 1) { @@ -131,7 +131,7 @@ private static void IntroSort(Span keys, int depthLimit, Comparison compar { Debug.Assert(!keys.IsEmpty); Debug.Assert(depthLimit >= 0); - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); int partitionSize = keys.Length; while (partitionSize > 1) @@ -175,7 +175,7 @@ private static void IntroSort(Span keys, int depthLimit, Comparison compar private static int PickPivotAndPartition(Span keys, Comparison comparer) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); int hi = keys.Length - 1; @@ -212,7 +212,7 @@ private static int PickPivotAndPartition(Span keys, Comparison comparer) private static void HeapSort(Span keys, Comparison comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); Debug.Assert(!keys.IsEmpty); int n = keys.Length; @@ -230,7 +230,7 @@ private static void HeapSort(Span keys, Comparison comparer) private static void DownHeap(Span keys, int i, int n, int lo, Comparison comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); @@ -282,7 +282,7 @@ public void Sort(Span keys, IComparer? comparer) { try { - if (comparer == null || comparer == Comparer.Default) + if (comparer is null || comparer == Comparer.Default) { if (keys.Length > 1) { @@ -321,12 +321,12 @@ public void Sort(Span keys, IComparer? comparer) public int BinarySearch(T[] array, int index, int length, T value, IComparer? comparer) { - Debug.Assert(array != null, "Check the arguments in the caller!"); + Debug.Assert(array is not null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { - if (comparer == null || comparer == Comparer.Default) + if (comparer is null || comparer == Comparer.Default) { return BinarySearch(array, index, length, value); } @@ -355,9 +355,9 @@ private static int BinarySearch(T[] array, int index, int length, T value) { int i = lo + ((hi - lo) >> 1); int order; - if (array[i] == null) + if (array[i] is null) { - order = (value == null) ? 0 : -1; + order = (value is null) ? 0 : -1; } else { @@ -386,7 +386,7 @@ private static int BinarySearch(T[] array, int index, int length, T value) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { - if (i != null && GreaterThan(ref i, ref j)) + if (i is not null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } @@ -471,7 +471,7 @@ private static int PickPivotAndPartition(Span keys) ref T leftRef = ref zeroRef, rightRef = ref nextToLastRef; while (Unsafe.IsAddressLessThan(ref leftRef, ref rightRef)) { - if (pivot == null) + if (pivot is null) { while (Unsafe.IsAddressLessThan(ref leftRef, ref nextToLastRef) && (leftRef = ref Unsafe.Add(ref leftRef, 1)) == null) ; while (Unsafe.IsAddressGreaterThan(ref rightRef, ref zeroRef) && (rightRef = ref Unsafe.Add(ref rightRef, -1)) != null) ; @@ -524,12 +524,12 @@ private static void DownHeap(Span keys, int i, int n, int lo) while (i <= n >> 1) { int child = 2 * i; - if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) + if (child < n && (keys[lo + child - 1] is null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } - if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) + if (keys[lo + child - 1] is null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; @@ -546,7 +546,7 @@ private static void InsertionSort(Span keys) T t = Unsafe.Add(ref MemoryMarshal.GetReference(keys), i + 1); int j = i; - while (j >= 0 && (t == null || LessThan(ref t, ref Unsafe.Add(ref MemoryMarshal.GetReference(keys), j)))) + while (j >= 0 && (t is null || LessThan(ref t, ref Unsafe.Add(ref MemoryMarshal.GetReference(keys), j)))) { Unsafe.Add(ref MemoryMarshal.GetReference(keys), j + 1) = Unsafe.Add(ref MemoryMarshal.GetReference(keys), j); j--; @@ -630,7 +630,7 @@ public void Sort(Span keys, Span values, IComparer? comparer private static void SwapIfGreaterWithValues(Span keys, Span values, IComparer comparer, int i, int j) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); @@ -663,7 +663,7 @@ private static void Swap(Span keys, Span values, int i, int j) internal static void IntrospectiveSort(Span keys, Span values, IComparer comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) @@ -677,7 +677,7 @@ private static void IntroSort(Span keys, Span values, int depthLim Debug.Assert(!keys.IsEmpty); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); int partitionSize = keys.Length; while (partitionSize > 1) @@ -721,7 +721,7 @@ private static void IntroSort(Span keys, Span values, int depthLim private static int PickPivotAndPartition(Span keys, Span values, IComparer comparer) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); int hi = keys.Length - 1; @@ -758,7 +758,7 @@ private static int PickPivotAndPartition(Span keys, Span values, I private static void HeapSort(Span keys, Span values, IComparer comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); Debug.Assert(!keys.IsEmpty); int n = keys.Length; @@ -776,7 +776,7 @@ private static void HeapSort(Span keys, Span values, IComparer keys, Span values, int i, int n, int lo, IComparer comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); @@ -805,7 +805,7 @@ private static void DownHeap(Span keys, Span values, int i, int n, private static void InsertionSort(Span keys, Span values, IComparer comparer) { - Debug.Assert(comparer != null); + Debug.Assert(comparer is not null); for (int i = 0; i < keys.Length - 1; i++) { @@ -835,7 +835,7 @@ public void Sort(Span keys, Span values, IComparer? comparer // underlying IComparables, etc) that are bogus. try { - if (comparer == null || comparer == Comparer.Default) + if (comparer is null || comparer == Comparer.Default) { if (keys.Length > 1) { @@ -878,7 +878,7 @@ private static void SwapIfGreaterWithValues(Span keys, Span values Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; - if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) + if (keyRef is not null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; @@ -969,10 +969,10 @@ private static int PickPivotAndPartition(Span keys, Span values) while (left < right) { - if (pivot == null) + if (pivot is null) { - while (left < (hi - 1) && keys[++left] == null) ; - while (right > 0 && keys[--right] != null) ; + while (left < (hi - 1) && keys[++left] is null) ; + while (right > 0 && keys[--right] is not null) ; } else { @@ -1022,12 +1022,12 @@ private static void DownHeap(Span keys, Span values, int i, int n, while (i <= n >> 1) { int child = 2 * i; - if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) + if (child < n && (keys[lo + child - 1] is null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } - if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) + if (keys[lo + child - 1] is null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; @@ -1047,7 +1047,7 @@ private static void InsertionSort(Span keys, Span values) TValue tValue = values[i + 1]; int j = i; - while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) + while (j >= 0 && (t is null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs index 2ee414aa62791f..a7e9d74a8342fe 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs @@ -15,7 +15,7 @@ public abstract partial class Comparer : IComparer, IComparer public static Comparer Create(Comparison comparison) { - if (comparison == null) + if (comparison is null) throw new ArgumentNullException(nameof(comparison)); return new ComparisonComparer(comparison); @@ -25,8 +25,8 @@ public static Comparer Create(Comparison comparison) int IComparer.Compare(object? x, object? y) { - if (x == null) return y == null ? 0 : -1; - if (y == null) return 1; + if (x is null) return y is null ? 0 : -1; + if (y is null) return 1; if (x is T && y is T) return Compare((T)x, (T)y); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; @@ -57,18 +57,18 @@ public sealed partial class GenericComparer : Comparer where T : IComparab { public override int Compare(T? x, T? y) { - if (x != null) + if (x is not null) { - if (y != null) return x.CompareTo(y); + if (y is not null) return x.CompareTo(y); return 1; } - if (y != null) return -1; + if (y is not null) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); @@ -92,7 +92,7 @@ public override int Compare(T? x, T? y) // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); @@ -110,7 +110,7 @@ public override int Compare(T? x, T? y) // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); @@ -128,7 +128,7 @@ private EnumComparer(SerializationInfo info, StreamingContext context) { } // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs index 83d0d3a5c060ec..1ea9bee85aa8d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs @@ -54,7 +54,7 @@ public Dictionary(int capacity, IEqualityComparer? comparer) Initialize(capacity); } - if (comparer != null && comparer != EqualityComparer.Default) // first check for null to avoid forcing default comparer instantiation unnecessarily + if (comparer is not null && comparer != EqualityComparer.Default) // first check for null to avoid forcing default comparer instantiation unnecessarily { _comparer = comparer; } @@ -83,9 +83,9 @@ public Dictionary(int capacity, IEqualityComparer? comparer) public Dictionary(IDictionary dictionary) : this(dictionary, null) { } public Dictionary(IDictionary dictionary, IEqualityComparer? comparer) : - this(dictionary != null ? dictionary.Count : 0, comparer) + this(dictionary is not null ? dictionary.Count : 0, comparer) { - if (dictionary == null) + if (dictionary is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } @@ -251,8 +251,8 @@ public void Clear() int count = _count; if (count > 0) { - Debug.Assert(_buckets != null, "_buckets should be non-null"); - Debug.Assert(_entries != null, "_entries should be non-null"); + Debug.Assert(_buckets is not null, "_buckets should be non-null"); + Debug.Assert(_entries is not null, "_entries should be non-null"); Array.Clear(_buckets, 0, _buckets.Length); @@ -269,11 +269,11 @@ public bool ContainsKey(TKey key) => public bool ContainsValue(TValue value) { Entry[]? entries = _entries; - if (value == null) + if (value is null) { for (int i = 0; i < _count; i++) { - if (entries![i].next >= -1 && entries[i].value == null) + if (entries![i].next >= -1 && entries[i].value is null) { return true; } @@ -310,7 +310,7 @@ public bool ContainsValue(TValue value) private void CopyTo(KeyValuePair[] array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -343,16 +343,16 @@ IEnumerator> IEnumerable>. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, _version); info.AddValue(ComparerName, Comparer, typeof(IEqualityComparer)); - info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array + info.AddValue(HashSizeName, _buckets is null ? 0 : _buckets.Length); // This is the length of the bucket array - if (_buckets != null) + if (_buckets is not null) { var array = new KeyValuePair[Count]; CopyTo(array, 0); @@ -362,17 +362,17 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte private ref TValue FindValue(TKey key) { - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ref Entry entry = ref Unsafe.NullRef(); - if (_buckets != null) + if (_buckets is not null) { - Debug.Assert(_entries != null, "expected entries to be != null"); + Debug.Assert(_entries is not null, "expected entries to be is not null"); IEqualityComparer? comparer = _comparer; - if (comparer == null) + if (comparer is null) { uint hashCode = (uint)key.GetHashCode(); int i = GetBucket(hashCode); @@ -505,28 +505,28 @@ private int Initialize(int capacity) private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) { - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (_buckets == null) + if (_buckets is null) { Initialize(0); } - Debug.Assert(_buckets != null); + Debug.Assert(_buckets is not null); Entry[]? entries = _entries; - Debug.Assert(entries != null, "expected entries to be non-null"); + Debug.Assert(entries is not null, "expected entries to be non-null"); IEqualityComparer? comparer = _comparer; - uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key)); + uint hashCode = (uint)((comparer is null) ? key.GetHashCode() : comparer.GetHashCode(key)); uint collisionCount = 0; ref int bucket = ref GetBucket(hashCode); int i = bucket - 1; // Value in _buckets is 1-based - if (comparer == null) + if (comparer is null) { if (typeof(TKey).IsValueType) { @@ -693,7 +693,7 @@ public virtual void OnDeserialization(object? sender) { HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo); - if (siInfo == null) + if (siInfo is null) { // We can return immediately if this function is called twice. // Note we remove the serialization info from the table at the end of this method. @@ -711,14 +711,14 @@ public virtual void OnDeserialization(object? sender) KeyValuePair[]? array = (KeyValuePair[]?) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair[])); - if (array == null) + if (array is null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i = 0; i < array.Length; i++) { - if (array[i].Key == null) + if (array[i].Key is null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } @@ -741,7 +741,7 @@ private void Resize(int newSize, bool forceNewHashCodes) { // Value types never rehash Debug.Assert(!forceNewHashCodes || !typeof(TKey).IsValueType); - Debug.Assert(_entries != null, "_entries should be non-null"); + Debug.Assert(_entries is not null, "_entries should be non-null"); Debug.Assert(newSize >= _entries.Length); Entry[] entries = new Entry[newSize]; @@ -792,14 +792,14 @@ public bool Remove(TKey key) // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (_buckets != null) + if (_buckets is not null) { - Debug.Assert(_entries != null, "entries should be non-null"); + Debug.Assert(_entries is not null, "entries should be non-null"); uint collisionCount = 0; uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); ref int bucket = ref GetBucket(hashCode); @@ -860,14 +860,14 @@ public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (_buckets != null) + if (_buckets is not null) { - Debug.Assert(_entries != null, "entries should be non-null"); + Debug.Assert(_entries is not null, "entries should be non-null"); uint collisionCount = 0; uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); ref int bucket = ref GetBucket(hashCode); @@ -949,7 +949,7 @@ void ICollection>.CopyTo(KeyValuePair[] void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -992,7 +992,7 @@ void ICollection.CopyTo(Array array, int index) else { object[]? objects = array as object[]; - if (objects == null) + if (objects is null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } @@ -1028,7 +1028,7 @@ public int EnsureCapacity(int capacity) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); } - int currentCapacity = _entries == null ? 0 : _entries.Length; + int currentCapacity = _entries is null ? 0 : _entries.Length; if (currentCapacity >= capacity) { return currentCapacity; @@ -1036,7 +1036,7 @@ public int EnsureCapacity(int capacity) _version++; - if (_buckets == null) + if (_buckets is null) { return Initialize(capacity); } @@ -1076,7 +1076,7 @@ public void TrimExcess(int capacity) int newSize = HashHelpers.GetPrime(capacity); Entry[]? oldEntries = _entries; - int currentCapacity = oldEntries == null ? 0 : oldEntries.Length; + int currentCapacity = oldEntries is null ? 0 : oldEntries.Length; if (newSize >= currentCapacity) { return; @@ -1144,7 +1144,7 @@ private void CopyEntries(Entry[] entries, int count) } set { - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } @@ -1171,7 +1171,7 @@ private void CopyEntries(Entry[] entries, int count) private static bool IsCompatibleKey(object key) { - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } @@ -1180,7 +1180,7 @@ private static bool IsCompatibleKey(object key) void IDictionary.Add(object key, object? value) { - if (key == null) + if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } @@ -1375,7 +1375,7 @@ public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCol public KeyCollection(Dictionary dictionary) { - if (dictionary == null) + if (dictionary is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } @@ -1387,7 +1387,7 @@ public KeyCollection(Dictionary dictionary) public void CopyTo(TKey[] array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1435,7 +1435,7 @@ bool ICollection.Remove(TKey item) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1467,7 +1467,7 @@ void ICollection.CopyTo(Array array, int index) else { object[]? objects = array as object[]; - if (objects == null) + if (objects is null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } @@ -1568,7 +1568,7 @@ public sealed class ValueCollection : ICollection, ICollection, IReadOnl public ValueCollection(Dictionary dictionary) { - if (dictionary == null) + if (dictionary is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } @@ -1580,7 +1580,7 @@ public ValueCollection(Dictionary dictionary) public void CopyTo(TValue[] array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1627,7 +1627,7 @@ void ICollection.Clear() => void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -1659,7 +1659,7 @@ void ICollection.CopyTo(Array array, int index) else { object[]? objects = array as object[]; - if (objects == null) + if (objects is null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs index 180bea6ddf9ddb..422070e169011e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs @@ -18,7 +18,7 @@ public abstract partial class EqualityComparer : IEqualityComparer, IEquality int IEqualityComparer.GetHashCode(object? obj) { - if (obj == null) return 0; + if (obj is null) return 0; if (obj is T) return GetHashCode((T)obj); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; @@ -27,7 +27,7 @@ int IEqualityComparer.GetHashCode(object? obj) bool IEqualityComparer.Equals(object? x, object? y) { if (x == y) return true; - if (x == null || y == null) return false; + if (x is null || y is null) return false; if ((x is T) && (y is T)) return Equals((T)x, (T)y); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return false; @@ -44,12 +44,12 @@ public sealed partial class GenericEqualityComparer : EqualityComparer whe [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(T? x, T? y) { - if (x != null) + if (x is not null) { - if (y != null) return x.Equals(y); + if (y is not null) return x.Equals(y); return false; } - if (y != null) return false; + if (y is not null) return false; return true; } @@ -57,7 +57,7 @@ public override bool Equals(T? x, T? y) public override int GetHashCode([DisallowNull] T obj) => obj?.GetHashCode() ?? 0; // Equals method for the comparer itself. - // If in the future this type is made sealed, change the is check to obj != null && GetType() == obj.GetType(). + // If in the future this type is made sealed, change the is check to obj is not null && GetType() == obj.GetType(). public override bool Equals(object? obj) => obj is GenericEqualityComparer; @@ -88,7 +88,7 @@ public override bool Equals(T? x, T? y) // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); @@ -102,12 +102,12 @@ public sealed partial class ObjectEqualityComparer : EqualityComparer [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(T? x, T? y) { - if (x != null) + if (x is not null) { - if (y != null) return x.Equals(y); + if (y is not null) return x.Equals(y); return false; } - if (y != null) return false; + if (y is not null) return false; return true; } @@ -116,7 +116,7 @@ public override bool Equals(T? x, T? y) // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); @@ -141,7 +141,7 @@ public override int GetHashCode(byte b) // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); @@ -176,7 +176,7 @@ public override int GetHashCode(T obj) // Equals method for the comparer itself. public override bool Equals(object? obj) => - obj != null && GetType() == obj.GetType(); + obj is not null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs index 394b0ff6fa625b..11754b32382d4b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs @@ -55,7 +55,7 @@ public HashSet() : this((IEqualityComparer?)null) { } public HashSet(IEqualityComparer? comparer) { - if (comparer != null && comparer != EqualityComparer.Default) // first check for null to avoid forcing default comparer instantiation unnecessarily + if (comparer is not null && comparer != EqualityComparer.Default) // first check for null to avoid forcing default comparer instantiation unnecessarily { _comparer = comparer; } @@ -87,7 +87,7 @@ public HashSet(IEnumerable collection) : this(collection, null) { } public HashSet(IEnumerable collection, IEqualityComparer? comparer) : this(comparer) { - if (collection == null) + if (collection is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } @@ -195,8 +195,8 @@ public void Clear() int count = _count; if (count > 0) { - Debug.Assert(_buckets != null, "_buckets should be non-null"); - Debug.Assert(_entries != null, "_entries should be non-null"); + Debug.Assert(_buckets is not null, "_buckets should be non-null"); + Debug.Assert(_entries is not null, "_entries should be non-null"); Array.Clear(_buckets, 0, _buckets.Length); _count = 0; @@ -215,17 +215,17 @@ public void Clear() private int FindItemIndex(T item) { int[]? buckets = _buckets; - if (buckets != null) + if (buckets is not null) { Entry[]? entries = _entries; - Debug.Assert(entries != null, "Expected _entries to be initialized"); + Debug.Assert(entries is not null, "Expected _entries to be initialized"); uint collisionCount = 0; IEqualityComparer? comparer = _comparer; - if (comparer == null) + if (comparer is null) { - int hashCode = item != null ? item.GetHashCode() : 0; + int hashCode = item is not null ? item.GetHashCode() : 0; if (typeof(T).IsValueType) { // ValueType: Devirtualize with EqualityComparer.Default intrinsic @@ -273,7 +273,7 @@ private int FindItemIndex(T item) } else { - int hashCode = item != null ? comparer.GetHashCode(item) : 0; + int hashCode = item is not null ? comparer.GetHashCode(item) : 0; int i = GetBucketRef(hashCode) - 1; // Value in _buckets is 1-based while (i >= 0) { @@ -311,14 +311,14 @@ private ref int GetBucketRef(int hashCode) public bool Remove(T item) { - if (_buckets != null) + if (_buckets is not null) { Entry[]? entries = _entries; - Debug.Assert(entries != null, "entries should be non-null"); + Debug.Assert(entries is not null, "entries should be non-null"); uint collisionCount = 0; int last = -1; - int hashCode = item != null ? (_comparer?.GetHashCode(item) ?? item.GetHashCode()) : 0; + int hashCode = item is not null ? (_comparer?.GetHashCode(item) ?? item.GetHashCode()) : 0; ref int bucket = ref GetBucketRef(hashCode); int i = bucket - 1; // Value in buckets is 1-based @@ -388,16 +388,16 @@ public bool Remove(T item) public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, _version); // need to serialize version to avoid problems with serializing while enumerating info.AddValue(ComparerName, Comparer, typeof(IEqualityComparer)); - info.AddValue(CapacityName, _buckets == null ? 0 : _buckets.Length); + info.AddValue(CapacityName, _buckets is null ? 0 : _buckets.Length); - if (_buckets != null) + if (_buckets is not null) { var array = new T[Count]; CopyTo(array); @@ -411,7 +411,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte public virtual void OnDeserialization(object? sender) { - if (_siInfo == null) + if (_siInfo is null) { // It might be necessary to call OnDeserialization from a container if the // container object also implements OnDeserialization. We can return immediately @@ -433,7 +433,7 @@ public virtual void OnDeserialization(object? sender) #endif T[]? array = (T[]?)_siInfo.GetValue(ElementsName, typeof(T[])); - if (array == null) + if (array is null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } @@ -474,7 +474,7 @@ public virtual void OnDeserialization(object? sender) /// public bool TryGetValue(T equalValue, [MaybeNullWhen(false)] out T actualValue) { - if (_buckets != null) + if (_buckets is not null) { int index = FindItemIndex(equalValue); if (index >= 0) @@ -492,7 +492,7 @@ public bool TryGetValue(T equalValue, [MaybeNullWhen(false)] out T actualValue) /// The collection to compare to the current object. public void UnionWith(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -507,7 +507,7 @@ public void UnionWith(IEnumerable other) /// The collection to compare to the current object. public void IntersectWith(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -544,7 +544,7 @@ public void IntersectWith(IEnumerable other) /// The collection to compare to the current object. public void ExceptWith(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -573,7 +573,7 @@ public void ExceptWith(IEnumerable other) /// The collection to compare to the current object. public void SymmetricExceptWith(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -612,7 +612,7 @@ public void SymmetricExceptWith(IEnumerable other) /// true if the object is a subset of ; otherwise, false. public bool IsSubsetOf(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -648,7 +648,7 @@ public bool IsSubsetOf(IEnumerable other) /// true if the object is a proper subset of ; otherwise, false. public bool IsProperSubsetOf(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -696,7 +696,7 @@ public bool IsProperSubsetOf(IEnumerable other) /// true if the object is a superset of ; otherwise, false. public bool IsSupersetOf(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -733,7 +733,7 @@ public bool IsSupersetOf(IEnumerable other) /// true if the object is a proper superset of ; otherwise, false. public bool IsProperSupersetOf(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -776,7 +776,7 @@ public bool IsProperSupersetOf(IEnumerable other) /// true if the object and share at least one common element; otherwise, false. public bool Overlaps(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -808,7 +808,7 @@ public bool Overlaps(IEnumerable other) /// true if the object is equal to ; otherwise, false. public bool SetEquals(IEnumerable other) { - if (other == null) + if (other is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); } @@ -857,7 +857,7 @@ other is ICollection otherAsCollection && public void CopyTo(T[] array, int arrayIndex, int count) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -897,7 +897,7 @@ public void CopyTo(T[] array, int arrayIndex, int count) /// Removes all elements that match the conditions defined by the specified predicate from a collection. public int RemoveWhere(Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -949,13 +949,13 @@ public int EnsureCapacity(int capacity) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); } - int currentCapacity = _entries == null ? 0 : _entries.Length; + int currentCapacity = _entries is null ? 0 : _entries.Length; if (currentCapacity >= capacity) { return currentCapacity; } - if (_buckets == null) + if (_buckets is null) { return Initialize(capacity); } @@ -971,7 +971,7 @@ private void Resize(int newSize, bool forceNewHashCodes) { // Value types never rehash Debug.Assert(!forceNewHashCodes || !typeof(T).IsValueType); - Debug.Assert(_entries != null, "_entries should be non-null"); + Debug.Assert(_entries is not null, "_entries should be non-null"); Debug.Assert(newSize >= _entries.Length); var entries = new Entry[newSize]; @@ -989,7 +989,7 @@ private void Resize(int newSize, bool forceNewHashCodes) ref Entry entry = ref entries[i]; if (entry.Next >= -1) { - entry.HashCode = entry.Value != null ? _comparer!.GetHashCode(entry.Value) : 0; + entry.HashCode = entry.Value is not null ? _comparer!.GetHashCode(entry.Value) : 0; } } @@ -1028,7 +1028,7 @@ public void TrimExcess() int newSize = HashHelpers.GetPrime(capacity); Entry[]? oldEntries = _entries; - int currentCapacity = oldEntries == null ? 0 : oldEntries.Length; + int currentCapacity = oldEntries is null ? 0 : oldEntries.Length; if (newSize >= currentCapacity) { return; @@ -1091,14 +1091,14 @@ private int Initialize(int capacity) /// true if the element is added to the object; false if the element is already present. private bool AddIfNotPresent(T value, out int location) { - if (_buckets == null) + if (_buckets is null) { Initialize(0); } - Debug.Assert(_buckets != null); + Debug.Assert(_buckets is not null); Entry[]? entries = _entries; - Debug.Assert(entries != null, "expected entries to be non-null"); + Debug.Assert(entries is not null, "expected entries to be non-null"); IEqualityComparer? comparer = _comparer; int hashCode; @@ -1106,9 +1106,9 @@ private bool AddIfNotPresent(T value, out int location) uint collisionCount = 0; ref int bucket = ref Unsafe.NullRef(); - if (comparer == null) + if (comparer is null) { - hashCode = value != null ? value.GetHashCode() : 0; + hashCode = value is not null ? value.GetHashCode() : 0; bucket = ref GetBucketRef(hashCode); int i = bucket - 1; // Value in _buckets is 1-based if (typeof(T).IsValueType) @@ -1158,7 +1158,7 @@ private bool AddIfNotPresent(T value, out int location) } else { - hashCode = value != null ? comparer.GetHashCode(value) : 0; + hashCode = value is not null ? comparer.GetHashCode(value) : 0; bucket = ref GetBucketRef(hashCode); int i = bucket - 1; // Value in _buckets is 1-based while (i >= 0) @@ -1294,7 +1294,7 @@ private void IntersectWithHashSetWithSameComparer(HashSet other) /// private unsafe void IntersectWithEnumerable(IEnumerable other) { - Debug.Assert(_buckets != null, "_buckets shouldn't be null; callers should check first"); + Debug.Assert(_buckets is not null, "_buckets shouldn't be null; callers should check first"); // Keep track of current last index; don't want to move past the end of our bit array // (could happen if another thread is modifying the collection). @@ -1452,7 +1452,7 @@ private unsafe (int UniqueCount, int UnfoundCount) CheckUniqueAndUnfoundElements return (UniqueCount: 0, UnfoundCount: numElementsInOther); } - Debug.Assert((_buckets != null) && (_count > 0), "_buckets was null but count greater than 0"); + Debug.Assert((_buckets is not null) && (_count > 0), "_buckets was null but count greater than 0"); int originalCount = _count; int intArrayLength = BitHelper.ToIntArrayLength(originalCount); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSetEqualityComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSetEqualityComparer.cs index 37466e5fb4c0c0..913331f5d7c5fd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSetEqualityComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSetEqualityComparer.cs @@ -15,7 +15,7 @@ public bool Equals(HashSet? x, HashSet? y) } // They're not both null, so if either is null, they're not equal. - if (x == null || y == null) + if (x is null || y is null) { return false; } @@ -55,11 +55,11 @@ public int GetHashCode(HashSet? obj) { int hashCode = 0; // default to 0 for null/empty set - if (obj != null) + if (obj is not null) { foreach (T t in obj) { - if (t != null) + if (t is not null) { hashCode ^= t.GetHashCode(); // same hashcode as as default comparer } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs index ef35460a01327f..708057db5d7a61 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs @@ -11,7 +11,7 @@ internal sealed class ICollectionDebugView public ICollectionDebugView(ICollection collection) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs index c7e58780a2f751..488e2a092c8e75 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs @@ -11,7 +11,7 @@ internal sealed class IDictionaryDebugView where K : notnull public IDictionaryDebugView(IDictionary dictionary) { - if (dictionary == null) + if (dictionary is null) throw new ArgumentNullException(nameof(dictionary)); _dict = dictionary; @@ -35,7 +35,7 @@ internal sealed class DictionaryKeyCollectionDebugView public DictionaryKeyCollectionDebugView(ICollection collection) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); _collection = collection; @@ -59,7 +59,7 @@ internal sealed class DictionaryValueCollectionDebugView public DictionaryValueCollectionDebugView(ICollection collection) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); _collection = collection; diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs index 83f4fda598eb2b..86ead8a92b7908 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs @@ -25,14 +25,14 @@ internal static string PairToString(object? key, object? value) s.Append('['); - if (key != null) + if (key is not null) { s.Append(key.ToString()); } s.Append(", "); - if (value != null) + if (value is not null) { s.Append(value.ToString()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs index 6da36e0f57bf4f..5c82c90953eb8d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs @@ -60,7 +60,7 @@ public List(int capacity) // public List(IEnumerable collection) { - if (collection == null) + if (collection is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); if (collection is ICollection c) @@ -167,7 +167,7 @@ private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return (value is T) || (value == null && default(T) == null); + return (value is T) || (value is null && default(T) is null); } object? IList.this[int index] @@ -331,7 +331,7 @@ bool IList.Contains(object? item) public List ConvertAll(Converter converter) { - if (converter == null) + if (converter is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } @@ -354,7 +354,7 @@ public void CopyTo(T[] array) // compatible array type. void ICollection.CopyTo(Array array, int arrayIndex) { - if ((array != null) && (array.Rank != 1)) + if ((array is not null) && (array.Rank != 1)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } @@ -414,7 +414,7 @@ public bool Exists(Predicate match) public T? Find(Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -431,7 +431,7 @@ public bool Exists(Predicate match) public List FindAll(Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -465,7 +465,7 @@ public int FindIndex(int startIndex, int count, Predicate match) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -480,7 +480,7 @@ public int FindIndex(int startIndex, int count, Predicate match) public T? FindLast(Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -503,7 +503,7 @@ public int FindLastIndex(int startIndex, Predicate match) public int FindLastIndex(int startIndex, int count, Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -544,7 +544,7 @@ public int FindLastIndex(int startIndex, int count, Predicate match) public void ForEach(Action action) { - if (action == null) + if (action is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } @@ -699,7 +699,7 @@ void IList.Insert(int index, object? item) // public void InsertRange(int index, IEnumerable collection) { - if (collection == null) + if (collection is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } @@ -849,7 +849,7 @@ void IList.Remove(object? item) // The complexity is O(n). public int RemoveAll(Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } @@ -1009,7 +1009,7 @@ public void Sort(int index, int count, IComparer? comparer) public void Sort(Comparison comparison) { - if (comparison == null) + if (comparison is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } @@ -1055,7 +1055,7 @@ public void TrimExcess() public bool TrueForAll(Predicate match) { - if (match == null) + if (match is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs index 0ec1a501d56f75..b90a44cee89b8b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs @@ -28,7 +28,7 @@ public class NonRandomizedStringEqualityComparer : IEqualityComparer, I private NonRandomizedStringEqualityComparer(IEqualityComparer underlyingComparer) { - Debug.Assert(underlyingComparer != null); + Debug.Assert(underlyingComparer is not null); _underlyingComparer = underlyingComparer; } @@ -83,7 +83,7 @@ internal OrdinalComparer(IEqualityComparer wrappedComparer) public override int GetHashCode(string? obj) { - Debug.Assert(obj != null, "This implementation is only called from first-party collection types that guarantee non-null parameters."); + Debug.Assert(obj is not null, "This implementation is only called from first-party collection types that guarantee non-null parameters."); return obj.GetNonRandomizedHashCode(); } @@ -100,7 +100,7 @@ internal OrdinalIgnoreCaseComparer(IEqualityComparer wrappedComparer) public override int GetHashCode(string? obj) { - Debug.Assert(obj != null, "This implementation is only called from first-party collection types that guarantee non-null parameters."); + Debug.Assert(obj is not null, "This implementation is only called from first-party collection types that guarantee non-null parameters."); return obj.GetNonRandomizedHashCodeOrdinalIgnoreCase(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ValueListBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ValueListBuilder.cs index 21c8f77a732fd0..ad638a42a7589e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ValueListBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ValueListBuilder.cs @@ -60,7 +60,7 @@ public ReadOnlySpan AsSpan() [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { - if (_arrayFromPool != null) + if (_arrayFromPool is not null) { ArrayPool.Shared.Return(_arrayFromPool); _arrayFromPool = null; @@ -76,7 +76,7 @@ private void Grow() T[]? toReturn = _arrayFromPool; _span = _arrayFromPool = array; - if (toReturn != null) + if (toReturn is not null) { ArrayPool.Shared.Return(toReturn); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.SerializationInfoTable.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.SerializationInfoTable.cs index 25a47ec67bd5e5..ba2460bdff461d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.SerializationInfoTable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.SerializationInfoTable.cs @@ -18,7 +18,7 @@ public static ConditionalWeakTable SerializationInfoT { get { - if (s_serializationInfoTable == null) + if (s_serializationInfoTable is null) Interlocked.CompareExchange(ref s_serializationInfoTable, new ConditionalWeakTable(), null); return s_serializationInfoTable; diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs index 373304cd1d4e6b..08821d15cb1206 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs @@ -158,7 +158,7 @@ protected IHashCodeProvider? hcp { return ((CompatibleComparer)_keycomparer).HashCodeProvider; } - else if (_keycomparer == null) + else if (_keycomparer is null) { return null; } @@ -173,7 +173,7 @@ protected IHashCodeProvider? hcp { _keycomparer = new CompatibleComparer(value, keyComparer.Comparer); } - else if (_keycomparer == null) + else if (_keycomparer is null) { _keycomparer = new CompatibleComparer(value, (IComparer?)null); } @@ -193,7 +193,7 @@ protected IComparer? comparer { return ((CompatibleComparer)_keycomparer).Comparer; } - else if (_keycomparer == null) + else if (_keycomparer is null) { return null; } @@ -208,7 +208,7 @@ protected IComparer? comparer { _keycomparer = new CompatibleComparer(keyComparer.HashCodeProvider, value); } - else if (_keycomparer == null) + else if (_keycomparer is null) { _keycomparer = new CompatibleComparer((IHashCodeProvider?)null, value); } @@ -335,7 +335,7 @@ public Hashtable(IDictionary d, IEqualityComparer? equalityComparer) public Hashtable(int capacity, float loadFactor, IHashCodeProvider? hcp, IComparer? comparer) : this(capacity, loadFactor) { - if (hcp != null || comparer != null) + if (hcp is not null || comparer is not null) { _keycomparer = new CompatibleComparer(hcp, comparer); } @@ -343,9 +343,9 @@ public Hashtable(int capacity, float loadFactor, IHashCodeProvider? hcp, ICompar [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")] public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider? hcp, IComparer? comparer) - : this(d != null ? d.Count : 0, loadFactor, hcp, comparer) + : this(d is not null ? d.Count : 0, loadFactor, hcp, comparer) { - if (d == null) + if (d is null) throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); IDictionaryEnumerator e = d.GetEnumerator(); @@ -354,9 +354,9 @@ public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider? hcp, ICompa } public Hashtable(IDictionary d, float loadFactor, IEqualityComparer? equalityComparer) - : this(d != null ? d.Count : 0, loadFactor, equalityComparer) + : this(d is not null ? d.Count : 0, loadFactor, equalityComparer) { - if (d == null) + if (d is null) throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); IDictionaryEnumerator e = d.GetEnumerator(); @@ -454,7 +454,7 @@ public virtual object Clone() { bucket--; object? keyv = lbuckets[bucket].key; - if ((keyv != null) && (keyv != lbuckets)) + if ((keyv is not null) && (keyv != lbuckets)) { ht[keyv] = lbuckets[bucket].val; } @@ -474,7 +474,7 @@ public virtual bool Contains(object key) // public virtual bool ContainsKey(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -489,7 +489,7 @@ public virtual bool ContainsKey(object key) do { b = lbuckets[bucketNumber]; - if (b.key == null) + if (b.key is null) { return false; } @@ -509,11 +509,11 @@ public virtual bool ContainsKey(object key) // public virtual bool ContainsValue(object? value) { - if (value == null) + if (value is null) { for (int i = _buckets.Length; --i >= 0;) { - if (_buckets[i].key != null && _buckets[i].key != _buckets && _buckets[i].val == null) + if (_buckets[i].key is not null && _buckets[i].key != _buckets && _buckets[i].val is null) return true; } } @@ -522,7 +522,7 @@ public virtual bool ContainsValue(object? value) for (int i = _buckets.Length; --i >= 0;) { object? val = _buckets[i].val; - if (val != null && val.Equals(value)) + if (val is not null && val.Equals(value)) return true; } } @@ -534,14 +534,14 @@ public virtual bool ContainsValue(object? value) // the KeyCollection class. private void CopyKeys(Array array, int arrayIndex) { - Debug.Assert(array != null); + Debug.Assert(array is not null); Debug.Assert(array.Rank == 1); bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { object? keyv = lbuckets[i].key; - if ((keyv != null) && (keyv != _buckets)) + if ((keyv is not null) && (keyv != _buckets)) { array.SetValue(keyv, arrayIndex++); } @@ -553,14 +553,14 @@ private void CopyKeys(Array array, int arrayIndex) // the KeyCollection class. private void CopyEntries(Array array, int arrayIndex) { - Debug.Assert(array != null); + Debug.Assert(array is not null); Debug.Assert(array.Rank == 1); bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { object? keyv = lbuckets[i].key; - if ((keyv != null) && (keyv != _buckets)) + if ((keyv is not null) && (keyv != _buckets)) { DictionaryEntry entry = new DictionaryEntry(keyv, lbuckets[i].val); array.SetValue(entry, arrayIndex++); @@ -572,7 +572,7 @@ private void CopyEntries(Array array, int arrayIndex) // a given index. Note that this only copies values, and not keys. public virtual void CopyTo(Array array, int arrayIndex) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -596,7 +596,7 @@ internal virtual KeyValuePairs[] ToKeyValuePairsArray() for (int i = lbuckets.Length; --i >= 0;) { object? keyv = lbuckets[i].key; - if ((keyv != null) && (keyv != _buckets)) + if ((keyv is not null) && (keyv != _buckets)) { array[index++] = new KeyValuePairs(keyv, lbuckets[i].val); } @@ -610,14 +610,14 @@ internal virtual KeyValuePairs[] ToKeyValuePairsArray() // the ValueCollection class. private void CopyValues(Array array, int arrayIndex) { - Debug.Assert(array != null); + Debug.Assert(array is not null); Debug.Assert(array.Rank == 1); bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { object? keyv = lbuckets[i].key; - if ((keyv != null) && (keyv != _buckets)) + if ((keyv is not null) && (keyv != _buckets)) { array.SetValue(lbuckets[i].val, arrayIndex++); } @@ -631,7 +631,7 @@ public virtual object? this[object key] { get { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -677,7 +677,7 @@ public virtual object? this[object key] spin.SpinOnce(); } - if (b.key == null) + if (b.key is null) { return null; } @@ -736,7 +736,7 @@ private void rehash(int newsize) for (nb = 0; nb < _buckets.Length; nb++) { bucket oldb = _buckets[nb]; - if ((oldb.key != null) && (oldb.key != _buckets)) + if ((oldb.key is not null) && (oldb.key != _buckets)) { int hashcode = oldb.hash_coll & 0x7FFFFFFF; putEntry(newBuckets, oldb.key, oldb.val, hashcode); @@ -778,7 +778,7 @@ public virtual IDictionaryEnumerator GetEnumerator() // instance. Otherwise, it calls hcp.GetHashCode(obj). protected virtual int GetHash(object key) { - if (_keycomparer != null) + if (_keycomparer is not null) return _keycomparer.GetHashCode(key); return key.GetHashCode(); } @@ -797,7 +797,7 @@ protected virtual int GetHash(object key) // protected virtual bool KeyEquals(object? item, object key) { - Debug.Assert(key != null, "key can't be null here!"); + Debug.Assert(key is not null, "key can't be null here!"); if (object.ReferenceEquals(_buckets, item)) { return false; @@ -806,9 +806,9 @@ protected virtual bool KeyEquals(object? item, object key) if (object.ReferenceEquals(item, key)) return true; - if (_keycomparer != null) + if (_keycomparer is not null) return _keycomparer.Equals(item, key); - return item == null ? false : item.Equals(key); + return item is null ? false : item.Equals(key); } // Returns a collection representing the keys of this hashtable. The order @@ -839,7 +839,7 @@ protected virtual bool KeyEquals(object? item, object key) // exists in the hashtable, an exception is thrown. private void Insert(object key, object? nvalue, bool add) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -872,7 +872,7 @@ private void Insert(object key, object? nvalue, bool add) // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry // OR // This bucket once contained an entry but there has never been a collision - if ((_buckets[bucketNumber].key == null) || + if ((_buckets[bucketNumber].key is null) || (_buckets[bucketNumber].key == _buckets && ((_buckets[bucketNumber].hash_coll & unchecked(0x80000000)) == 0))) { // If we have found an available bucket that has never had a collision, but we've seen an available @@ -957,7 +957,7 @@ private void putEntry(bucket[] newBuckets, object key, object? nvalue, int hashc int bucketNumber = (int)(seed % (uint)newBuckets.Length); while (true) { - if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == _buckets)) + if ((newBuckets[bucketNumber].key is null) || (newBuckets[bucketNumber].key == _buckets)) { newBuckets[bucketNumber].val = nvalue; newBuckets[bucketNumber].key = key; @@ -980,7 +980,7 @@ private void putEntry(bucket[] newBuckets, object key, object? nvalue, int hashc // public virtual void Remove(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -1031,14 +1031,14 @@ public virtual void Remove(object key) // public static Hashtable Synchronized(Hashtable table) { - if (table == null) + if (table is null) throw new ArgumentNullException(nameof(table)); return new SyncHashtable(table); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -1062,7 +1062,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte #pragma warning disable 618 IEqualityComparer? keyComparerForSerilization = _keycomparer; - if (keyComparerForSerilization == null) + if (keyComparerForSerilization is null) { info.AddValue(ComparerName, null, typeof(IComparer)); info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider)); @@ -1101,7 +1101,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte // public virtual void OnDeserialization(object? sender) { - if (_buckets != null) + if (_buckets is not null) { // Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it. return; @@ -1109,7 +1109,7 @@ public virtual void OnDeserialization(object? sender) HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo); - if (siInfo == null) + if (siInfo is null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } @@ -1159,18 +1159,18 @@ public virtual void OnDeserialization(object? sender) _loadsize = (int)(_loadFactor * hashsize); // V1 object doesn't has _keycomparer field. - if ((_keycomparer == null) && ((c != null) || (hcp != null))) + if ((_keycomparer is null) && ((c is not null) || (hcp is not null))) { _keycomparer = new CompatibleComparer(hcp, c); } _buckets = new bucket[hashsize]; - if (serKeys == null) + if (serKeys is null) { throw new SerializationException(SR.Serialization_MissingKeys); } - if (serValues == null) + if (serValues is null) { throw new SerializationException(SR.Serialization_MissingValues); } @@ -1180,7 +1180,7 @@ public virtual void OnDeserialization(object? sender) } for (int i = 0; i < serKeys.Length; i++) { - if (serKeys[i] == null) + if (serKeys[i] is null) { throw new SerializationException(SR.Serialization_NullKey); } @@ -1205,7 +1205,7 @@ internal KeyCollection(Hashtable hashtable) public virtual void CopyTo(Array array, int arrayIndex) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -1241,7 +1241,7 @@ internal ValueCollection(Hashtable hashtable) public virtual void CopyTo(Array array, int arrayIndex) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -1329,7 +1329,7 @@ public override bool Contains(object key) public override bool ContainsKey(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -1459,7 +1459,7 @@ public virtual bool MoveNext() { _bucket--; object? keyv = _hashtable._buckets[_bucket].key; - if ((keyv != null) && (keyv != _hashtable._buckets)) + if ((keyv is not null) && (keyv != _hashtable._buckets)) { _currentKey = keyv; _currentValue = _hashtable._buckets[_bucket].val; @@ -1525,7 +1525,7 @@ internal class HashtableDebugView public HashtableDebugView(Hashtable hashtable) { - if (hashtable == null) + if (hashtable is null) { throw new ArgumentNullException(nameof(hashtable)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs index 32ecd3ad7ba9da..956b85f2a730ae 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs @@ -33,13 +33,13 @@ public object? this[object key] { get { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } DictionaryNode? node = head; - while (node != null) + while (node is not null) { if (node.key.Equals(key)) { @@ -51,7 +51,7 @@ public object? this[object key] } set { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -59,7 +59,7 @@ public object? this[object key] version++; DictionaryNode? last = null; DictionaryNode? node; - for (node = head; node != null; node = node.next) + for (node = head; node is not null; node = node.next) { if (node.key.Equals(key)) { @@ -67,7 +67,7 @@ public object? this[object key] } last = node; } - if (node != null) + if (node is not null) { // Found it node.value = value; @@ -77,7 +77,7 @@ public object? this[object key] DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; - if (last != null) + if (last is not null) { last.next = newNode; } @@ -105,7 +105,7 @@ public object? this[object key] public void Add(object key, object? value) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } @@ -113,7 +113,7 @@ public void Add(object key, object? value) version++; DictionaryNode? last = null; DictionaryNode? node; - for (node = head; node != null; node = node.next) + for (node = head; node is not null; node = node.next) { if (node.key.Equals(key)) { @@ -121,7 +121,7 @@ public void Add(object key, object? value) } last = node; } - if (node != null) + if (node is not null) { // Found it node.value = value; @@ -131,7 +131,7 @@ public void Add(object key, object? value) DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; - if (last != null) + if (last is not null) { last.next = newNode; } @@ -151,11 +151,11 @@ public void Clear() public bool Contains(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - for (DictionaryNode? node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node is not null; node = node.next) { if (node.key.Equals(key)) { @@ -167,7 +167,7 @@ public bool Contains(object key) public void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) @@ -179,7 +179,7 @@ public void CopyTo(Array array, int index) if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); - for (DictionaryNode? node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node is not null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; @@ -198,14 +198,14 @@ IEnumerator IEnumerable.GetEnumerator() public void Remove(object key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } version++; DictionaryNode? last = null; DictionaryNode? node; - for (node = head; node != null; node = node.next) + for (node = head; node is not null; node = node.next) { if (node.key.Equals(key)) { @@ -213,7 +213,7 @@ public void Remove(object key) } last = node; } - if (node == null) + if (node is null) { return; } @@ -249,7 +249,7 @@ public DictionaryEntry Entry { get { - if (current == null) + if (current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -261,7 +261,7 @@ public object Key { get { - if (current == null) + if (current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -273,7 +273,7 @@ public object? Value { get { - if (current == null) + if (current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -294,12 +294,12 @@ public bool MoveNext() } else { - if (current != null) + if (current is not null) { current = current.next; } } - return current != null; + return current is not null; } public void Reset() @@ -326,7 +326,7 @@ public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -334,7 +334,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < list.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); - for (DictionaryNode? node = list.head; node != null; node = node.next) + for (DictionaryNode? node = list.head; node is not null; node = node.next) { array.SetValue(isKeys ? node.key : node.value, index); index++; @@ -346,7 +346,7 @@ int ICollection.Count get { int count = 0; - for (DictionaryNode? node = list.head; node != null; node = node.next) + for (DictionaryNode? node = list.head; node is not null; node = node.next) { count++; } @@ -384,7 +384,7 @@ public object? Current { get { - if (current == null) + if (current is null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } @@ -405,12 +405,12 @@ public bool MoveNext() } else { - if (current != null) + if (current is not null) { current = current.next; } } - return current != null; + return current is not null; } public void Reset() diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/Collection.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/Collection.cs index fcafafed633f6d..d7b34895c93528 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/Collection.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/Collection.cs @@ -21,7 +21,7 @@ public Collection() public Collection(IList list) { - if (list == null) + if (list is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } @@ -168,7 +168,7 @@ IEnumerator IEnumerable.GetEnumerator() void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -217,7 +217,7 @@ void ICollection.CopyTo(Array array, int index) // widening of primitive types here. // object?[]? objects = array as object[]; - if (objects == null) + if (objects is null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } @@ -358,7 +358,7 @@ private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return (value is T) || (value == null && default(T) == null); + return (value is T) || (value is null && default(T) is null); } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs index 09f2bc622990fd..0923884c42b72e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs @@ -16,7 +16,7 @@ public class ReadOnlyCollection : IList, IList, IReadOnlyList public ReadOnlyCollection(IList list) { - if (list == null) + if (list is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } @@ -94,7 +94,7 @@ IEnumerator IEnumerable.GetEnumerator() void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } @@ -143,7 +143,7 @@ void ICollection.CopyTo(Array array, int index) // widening of primitive types here. // object?[]? objects = array as object[]; - if (objects == null) + if (objects is null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } @@ -188,7 +188,7 @@ private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return (value is T) || (value == null && default(T) == null); + return (value is T) || (value is null && default(T) is null); } bool IList.Contains(object? value) diff --git a/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs index 1d96a8bb75ecea..731190776b6a73 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs @@ -34,7 +34,7 @@ public DefaultValueAttribute(Type type, string? value) // The null check and try/catch here are because attributes should never throw exceptions. // We would fail to load an otherwise normal class. - if (type == null) + if (type is null) { return; } @@ -45,11 +45,11 @@ public DefaultValueAttribute(Type type, string? value) { _value = convertedValue; } - else if (type.IsSubclassOf(typeof(Enum)) && value != null) + else if (type.IsSubclassOf(typeof(Enum)) && value is not null) { _value = Enum.Parse(type, value, true); } - else if (type == typeof(TimeSpan) && value != null) + else if (type == typeof(TimeSpan) && value is not null) { _value = TimeSpan.Parse(value); } @@ -64,11 +64,11 @@ static bool TryConvertFromInvariantString(Type? typeToConvert, string? stringVal conversionResult = null; // lazy init reflection objects - if (s_convertFromInvariantString == null) + if (s_convertFromInvariantString is null) { Type? typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); MethodInfo? mi = typeDescriptorType?.GetMethod("ConvertFromInvariantString", BindingFlags.NonPublic | BindingFlags.Static); - Volatile.Write(ref s_convertFromInvariantString, mi == null ? new object() : mi.CreateDelegate(typeof(Func))); + Volatile.Write(ref s_convertFromInvariantString, mi is null ? new object() : mi.CreateDelegate(typeof(Func))); } if (!(s_convertFromInvariantString is Func convertFromInvariantString)) @@ -237,9 +237,9 @@ public override bool Equals(object? obj) return false; } - if (Value == null) + if (Value is null) { - return other.Value == null; + return other.Value is null; } return Value.Equals(other.Value); diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index f45333cbad1cf2..fdf0d8d3a46243 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -227,7 +227,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, // public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar) { - if (calendar == null) + if (calendar is null) throw new ArgumentNullException(nameof(calendar)); int originalSecond = second; @@ -307,7 +307,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, // public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar) { - if (calendar == null) + if (calendar is null) throw new ArgumentNullException(nameof(calendar)); if (millisecond < 0 || millisecond >= MillisPerSecond) { @@ -339,7 +339,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) { - if (calendar == null) + if (calendar is null) throw new ArgumentNullException(nameof(calendar)); if (millisecond < 0 || millisecond >= MillisPerSecond) { @@ -375,7 +375,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, private DateTime(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) throw new ArgumentNullException(nameof(info)); bool foundTicks = false; @@ -605,7 +605,7 @@ public static int Compare(DateTime t1, DateTime t2) // Returns a value less than zero if this object public int CompareTo(object? value) { - if (value == null) return 1; + if (value is null) return 1; if (!(value is DateTime)) { throw new ArgumentException(SR.Arg_MustBeDateTime); @@ -817,7 +817,7 @@ public static DateTime FromOADate(double d) void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -1139,7 +1139,7 @@ public static bool IsLeapYear(int year) // public static DateTime Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None); } @@ -1149,14 +1149,14 @@ public static DateTime Parse(string s) // public static DateTime Parse(string s, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None); } public static DateTime Parse(string s, IFormatProvider? provider, DateTimeStyles styles) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles); } @@ -1172,8 +1172,8 @@ public static DateTime Parse(ReadOnlySpan s, IFormatProvider? provider = n // public static DateTime ParseExact(string s, string format, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (format is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None); } @@ -1184,8 +1184,8 @@ public static DateTime ParseExact(string s, string format, IFormatProvider? prov public static DateTime ParseExact(string s, string format, IFormatProvider? provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (format is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style); } @@ -1198,7 +1198,7 @@ public static DateTime ParseExact(ReadOnlySpan s, ReadOnlySpan forma public static DateTime ParseExact(string s, string[] formats, IFormatProvider? provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style); } @@ -1358,7 +1358,7 @@ public DateTime ToUniversalTime() public static bool TryParse([NotNullWhen(true)] string? s, out DateTime result) { - if (s == null) + if (s is null) { result = default; return false; @@ -1375,7 +1375,7 @@ public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? prov { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); - if (s == null) + if (s is null) { result = default; return false; @@ -1394,7 +1394,7 @@ public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(tru { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); - if (s == null || format == null) + if (s is null || format is null) { result = default; return false; @@ -1413,7 +1413,7 @@ public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(tru { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); - if (s == null) + if (s is null) { result = default; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs index df06b7f0caf668..15dcf37b57a14a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs @@ -347,7 +347,7 @@ public static int Compare(DateTimeOffset first, DateTimeOffset second) => // int IComparable.CompareTo(object? obj) { - if (obj == null) return 1; + if (obj is null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); @@ -447,7 +447,7 @@ void IDeserializationCallback.OnDeserialization(object? sender) void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -458,7 +458,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex private DateTimeOffset(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -477,7 +477,7 @@ private DateTimeOffset(SerializationInfo info, StreamingContext context) // public static DateTimeOffset Parse(string input) { - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, @@ -492,14 +492,14 @@ public static DateTimeOffset Parse(string input) // public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider) { - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), @@ -521,8 +521,8 @@ public static DateTimeOffset Parse(ReadOnlySpan input, IFormatProvider? fo // public static DateTimeOffset ParseExact(string input, string format, IFormatProvider? formatProvider) { - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (format is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return ParseExact(input, format, formatProvider, DateTimeStyles.None); } @@ -533,8 +533,8 @@ public static DateTimeOffset ParseExact(string input, string format, IFormatProv public static DateTimeOffset ParseExact(string input, string format, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (format is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); DateTime dateResult = DateTimeParse.ParseExact(input, format, @@ -554,7 +554,7 @@ public static DateTimeOffset ParseExact(ReadOnlySpan input, ReadOnlySpan input, out DateTimeOffset result) public static bool TryParse([NotNullWhen(true)] string? input, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); - if (input == null) + if (input is null) { result = default; return false; @@ -696,7 +696,7 @@ public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); - if (input == null || format == null) + if (input is null || format is null) { result = default; return false; @@ -725,7 +725,7 @@ public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); - if (input == null) + if (input is null) { result = default; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractFailedEventArgs.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractFailedEventArgs.cs index 15e7ba06d773c4..cc57687119cfc0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractFailedEventArgs.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractFailedEventArgs.cs @@ -16,7 +16,7 @@ public sealed class ContractFailedEventArgs : EventArgs public ContractFailedEventArgs(ContractFailureKind failureKind, string? message, string? condition, Exception? originalException) { - Debug.Assert(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); + Debug.Assert(originalException is null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs index 49445f16b2d071..10d391567eb080 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs @@ -517,7 +517,7 @@ public static bool ForAll(int fromInclusive, int toExclusive, Predicate pre { if (fromInclusive > toExclusive) throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = fromInclusive; i < toExclusive; i++) @@ -538,9 +538,9 @@ public static bool ForAll(int fromInclusive, int toExclusive, Predicate pre [Pure] public static bool ForAll(IEnumerable collection, Predicate predicate) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); foreach (T t in collection) @@ -567,7 +567,7 @@ public static bool Exists(int fromInclusive, int toExclusive, Predicate pre { if (fromInclusive > toExclusive) throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = fromInclusive; i < toExclusive; i++) @@ -587,9 +587,9 @@ public static bool Exists(int fromInclusive, int toExclusive, Predicate pre [Pure] public static bool Exists(IEnumerable collection, Predicate predicate) { - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); foreach (T t in collection) @@ -629,7 +629,7 @@ private static void AssertMustUseRewriter(ContractFailureKind kind, string contr for (int i = 0; i < stack.FrameCount; i++) { Assembly? caller = stack.GetFrame(i)!.GetMethod()?.DeclaringType?.Assembly; - if (caller != null && caller != thisAssembly) + if (caller is not null && caller != thisAssembly) { probablyNotRewritten = caller; break; @@ -656,9 +656,9 @@ private static void ReportFailure(ContractFailureKind failureKind, string? userM if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); - // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message + // displayMessage is null means: yes we handled it. Otherwise it is the localized failure message string? displayMessage = ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); - if (displayMessage == null) + if (displayMessage is null) return; ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs index da744f6d7bee01..c25c61e3a6bbd6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs @@ -19,7 +19,7 @@ public static partial class Debug public static DebugProvider SetProvider(DebugProvider provider) { - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); return Interlocked.Exchange(ref s_provider, provider); @@ -146,7 +146,7 @@ public static void WriteLine(string format, params object?[] args) => [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string? message, string? category) { - if (category == null) + if (category is null) { WriteLine(message); } @@ -163,7 +163,7 @@ public static void Write(object? value) => [System.Diagnostics.Conditional("DEBUG")] public static void Write(string? message, string? category) { - if (category == null) + if (category is null) { Write(message); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Unix.cs index 468d1d55282472..61b0efa165b795 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Unix.cs @@ -9,7 +9,7 @@ public partial class DebugProvider public static void FailCore(string stackTrace, string? message, string? detailMessage, string errorSource) { - if (s_FailCore != null) + if (s_FailCore is not null) { s_FailCore(stackTrace, message, detailMessage, errorSource); return; @@ -31,7 +31,7 @@ public static void FailCore(string stackTrace, string? message, string? detailMe public static void WriteCore(string message) { - if (s_WriteCore != null) + if (s_WriteCore is not null) { s_WriteCore(message); return; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Windows.cs index 47bf9d2cfe2900..b26108017f7ff3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.Windows.cs @@ -7,7 +7,7 @@ public partial class DebugProvider { public static void FailCore(string stackTrace, string? message, string? detailMessage, string errorSource) { - if (s_FailCore != null) + if (s_FailCore is not null) { s_FailCore(stackTrace, message, detailMessage, errorSource); return; @@ -31,7 +31,7 @@ public static void FailCore(string stackTrace, string? message, string? detailMe public static void WriteCore(string message) { - if (s_WriteCore != null) + if (s_WriteCore is not null) { s_WriteCore(message); return; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs index 4bc93b781bf670..e2820e1da968f9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs @@ -45,7 +45,7 @@ public virtual void Write(string? message) { lock (s_lock) { - if (message == null) + if (message is null) { WriteCore(string.Empty); return; @@ -83,7 +83,7 @@ internal DebugAssertException(string? message, string? detailMessage, string? st private static string? Terminate(string? s) { - if (s == null) + if (s is null) return s; s = s.Trim(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs index ea67b9c043afd1..984069a089ba90 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs @@ -35,7 +35,7 @@ public Type? Target get => _target; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs index 1f99516869be62..911d469c7367d5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs @@ -13,7 +13,7 @@ public sealed class DebuggerTypeProxyAttribute : Attribute public DebuggerTypeProxyAttribute( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -37,7 +37,7 @@ public Type? Target get => _target; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs index 0ad6bd8ed43bfb..4efdee85e40856 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs @@ -25,7 +25,7 @@ public DebuggerVisualizerAttribute(string visualizerTypeName, string? visualizer public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource) { - if (visualizerObjectSource == null) + if (visualizerObjectSource is null) { throw new ArgumentNullException(nameof(visualizerObjectSource)); } @@ -36,7 +36,7 @@ public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObj public DebuggerVisualizerAttribute(Type visualizer) { - if (visualizer == null) + if (visualizer is null) { throw new ArgumentNullException(nameof(visualizer)); } @@ -46,11 +46,11 @@ public DebuggerVisualizerAttribute(Type visualizer) public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource) { - if (visualizer == null) + if (visualizer is null) { throw new ArgumentNullException(nameof(visualizer)); } - if (visualizerObjectSource == null) + if (visualizerObjectSource is null) { throw new ArgumentNullException(nameof(visualizerObjectSource)); } @@ -61,7 +61,7 @@ public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource) public DebuggerVisualizerAttribute(Type visualizer, string? visualizerObjectSourceTypeName) { - if (visualizer == null) + if (visualizer is null) { throw new ArgumentNullException(nameof(visualizer)); } @@ -81,7 +81,7 @@ public Type? Target get => _target; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs index cc2d1d16a10997..64452e105f97d7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs @@ -188,7 +188,7 @@ public override string ToString() StringBuilder sb = new StringBuilder(255); bool includeFileInfoIfAvailable; - if (_method != null) + if (_method is not null) { sb.Append(_method.Name); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrameExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrameExtensions.cs index df4dcf166fd2f0..6e8d835f5c5cba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrameExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrameExtensions.cs @@ -14,7 +14,7 @@ public static bool HasNativeImage(this StackFrame stackFrame) public static bool HasMethod(this StackFrame stackFrame) { - return stackFrame.GetMethod() != null; + return stackFrame.GetMethod() is not null; } public static bool HasILOffset(this StackFrame stackFrame) @@ -24,7 +24,7 @@ public static bool HasILOffset(this StackFrame stackFrame) public static bool HasSource(this StackFrame stackFrame) { - return stackFrame.GetFileName() != null; + return stackFrame.GetFileName() is not null; } public static IntPtr GetNativeIP(this StackFrame stackFrame) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs index 84cd6745f306ab..f7cde302dc3a3b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs @@ -73,7 +73,7 @@ public StackTrace(int skipFrames, bool fNeedFileInfo) /// public StackTrace(Exception e) { - if (e == null) + if (e is null) throw new ArgumentNullException(nameof(e)); InitializeForException(e, METHODS_TO_SKIP, false); @@ -84,7 +84,7 @@ public StackTrace(Exception e) /// public StackTrace(Exception e, bool fNeedFileInfo) { - if (e == null) + if (e is null) throw new ArgumentNullException(nameof(e)); InitializeForException(e, METHODS_TO_SKIP, fNeedFileInfo); @@ -96,7 +96,7 @@ public StackTrace(Exception e, bool fNeedFileInfo) /// public StackTrace(Exception e, int skipFrames) { - if (e == null) + if (e is null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) @@ -112,7 +112,7 @@ public StackTrace(Exception e, int skipFrames) /// public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { - if (e == null) + if (e is null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) @@ -143,7 +143,7 @@ public StackTrace(StackFrame frame) /// public virtual StackFrame? GetFrame(int index) { - if (_stackFrames != null && index < _numOfFrames && index >= 0) + if (_stackFrames is not null && index < _numOfFrames && index >= 0) return _stackFrames[index + _methodsToSkip]; return null; @@ -157,7 +157,7 @@ public StackTrace(StackFrame frame) /// public virtual StackFrame[] GetFrames() { - if (_stackFrames == null || _numOfFrames <= 0) + if (_stackFrames is null || _numOfFrames <= 0) return Array.Empty(); // We have to return a subset of the array. Unfortunately this @@ -210,7 +210,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) { StackFrame? sf = GetFrame(iFrameIndex); MethodBase? mb = sf?.GetMethod(); - if (mb != null && (ShowInStackTrace(mb) || + if (mb is not null && (ShowInStackTrace(mb) || (iFrameIndex == _numOfFrames - 1))) // Don't filter last frame { // We want a newline at the end of every line except for the last @@ -225,7 +225,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) Type? declaringType = mb.DeclaringType; string methodName = mb.Name; bool methodChanged = false; - if (declaringType != null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)) + if (declaringType is not null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)) { isAsync = declaringType.IsAssignableTo(typeof(IAsyncStateMachine)); if (isAsync || declaringType.IsAssignableTo(typeof(IEnumerator))) @@ -236,7 +236,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) // if there is a type (non global method) print it // ResolveStateMachineMethod may have set declaringType to null - if (declaringType != null) + if (declaringType is not null) { // Append t.FullName, replacing '+' with '.' string fullName = declaringType.FullName!; @@ -279,7 +279,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) // The parameter info cannot be loaded, so we don't // append the parameter list. } - if (pi != null) + if (pi is not null) { // arguments printing sb.Append('('); @@ -292,7 +292,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) fFirstParam = false; string typeName = ""; - if (pi[j].ParameterType != null) + if (pi[j].ParameterType is not null) typeName = pi[j].ParameterType.Name; sb.Append(typeName); sb.Append(' '); @@ -316,7 +316,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) // then the file name will be null. string? fileName = sf.GetFileName(); - if (fileName != null) + if (fileName is not null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append(' '); @@ -342,7 +342,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb) private static bool ShowInStackTrace(MethodBase mb) { - Debug.Assert(mb != null); + Debug.Assert(mb is not null); if ((mb.MethodImplementationFlags & MethodImplAttributes.AggressiveInlining) != 0) { @@ -361,7 +361,7 @@ private static bool ShowInStackTrace(MethodBase mb) Type? declaringType = mb.DeclaringType; // Methods don't always have containing types, for example dynamic RefEmit generated methods. - if (declaringType != null && + if (declaringType is not null && declaringType.IsDefined(typeof(StackTraceHiddenAttribute), inherit: false)) { // Don't show where StackTraceHidden is applied to the containing Type of the method. @@ -373,19 +373,19 @@ private static bool ShowInStackTrace(MethodBase mb) private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type declaringType) { - Debug.Assert(method != null); - Debug.Assert(method.DeclaringType != null); + Debug.Assert(method is not null); + Debug.Assert(method.DeclaringType is not null); declaringType = method.DeclaringType; Type? parentType = declaringType.DeclaringType; - if (parentType == null) + if (parentType is null) { return false; } MethodInfo[]? methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); - if (methods == null) + if (methods is null) { return false; } @@ -393,7 +393,7 @@ private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type foreach (MethodInfo candidateMethod in methods) { IEnumerable? attributes = candidateMethod.GetCustomAttributes(inherit: false); - if (attributes == null) + if (attributes is null) { continue; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs index e3f6632f59fb45..eb1356864e7622 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs @@ -53,7 +53,7 @@ internal class ActivityTracker /// public void OnStart(string providerName, string activityName, int task, ref Guid activityId, ref Guid relatedActivityId, EventActivityOptions options, bool useTplSource = true) { - if (m_current == null) // We are not enabled + if (m_current is null) // We are not enabled { // We used to rely on the TPL provider turning us on, but that has the disadvantage that you don't get Start-Stop tracking // until you use Tasks for the first time (which you may never do). Thus we change it to pull rather tan push for whether @@ -63,7 +63,7 @@ public void OnStart(string providerName, string activityName, int task, ref Guid m_checkedForEnable = true; if (useTplSource && TplEventSource.Log.IsEnabled(EventLevel.Informational, TplEventSource.Keywords.TasksFlowActivityIds)) Enable(); - if (m_current == null) + if (m_current is null) return; } @@ -73,14 +73,14 @@ public void OnStart(string providerName, string activityName, int task, ref Guid string fullActivityName = NormalizeActivityName(providerName, activityName, task); TplEventSource? log = useTplSource ? TplEventSource.Log : null; - bool tplDebug = log != null && log.Debug; + bool tplDebug = log is not null && log.Debug; if (tplDebug) { log!.DebugFacilityMessage("OnStartEnter", fullActivityName); log!.DebugFacilityMessage("OnStartEnterActivityState", ActivityInfo.LiveActivities(currentActivity)); } - if (currentActivity != null) + if (currentActivity is not null) { // Stop activity tracking if we reached the maximum allowed depth if (currentActivity.m_level >= MAX_ACTIVITY_DEPTH) @@ -95,7 +95,7 @@ public void OnStart(string providerName, string activityName, int task, ref Guid if ((options & EventActivityOptions.Recursive) == 0) { ActivityInfo? existingActivity = FindActiveActivity(fullActivityName, currentActivity); - if (existingActivity != null) + if (existingActivity is not null) { OnStop(providerName, activityName, task, ref activityId); currentActivity = m_current.Value; @@ -105,7 +105,7 @@ public void OnStart(string providerName, string activityName, int task, ref Guid // Get a unique ID for this activity. long id; - if (currentActivity == null) + if (currentActivity is null) id = Interlocked.Increment(ref m_nextId); else id = Interlocked.Increment(ref currentActivity.m_lastChildID); @@ -135,13 +135,13 @@ public void OnStart(string providerName, string activityName, int task, ref Guid /// public void OnStop(string providerName, string activityName, int task, ref Guid activityId, bool useTplSource = true) { - if (m_current == null) // We are not enabled + if (m_current is null) // We are not enabled return; string fullActivityName = NormalizeActivityName(providerName, activityName, task); TplEventSource? log = useTplSource ? TplEventSource.Log : null; - bool tplDebug = log != null && log.Debug; + bool tplDebug = log is not null && log.Debug; if (tplDebug) { log!.DebugFacilityMessage("OnStopEnter", fullActivityName); @@ -159,7 +159,7 @@ public void OnStop(string providerName, string activityName, int task, ref Guid ActivityInfo? activityToStop = FindActiveActivity(fullActivityName, currentActivity); // ignore stops where we can't find a start because we may have popped them previously. - if (activityToStop == null) + if (activityToStop is null) { activityId = Guid.Empty; // TODO add some logging about this. Basically could not find matching start. @@ -172,7 +172,7 @@ public void OnStop(string providerName, string activityName, int task, ref Guid // See if there are any orphans that need to be stopped. ActivityInfo? orphan = currentActivity; - while (orphan != activityToStop && orphan != null) + while (orphan != activityToStop && orphan is not null) { if (orphan.m_stopped != 0) // Skip dead activities. { @@ -218,7 +218,7 @@ public void OnStop(string providerName, string activityName, int task, ref Guid /// public void Enable() { - if (m_current == null) + if (m_current is null) { // Catch the not Implemented try @@ -246,7 +246,7 @@ public void Enable() private static ActivityInfo? FindActiveActivity(string name, ActivityInfo? startLocation) { ActivityInfo? activity = startLocation; - while (activity != null) + while (activity is not null) { if (name == activity.m_name && activity.m_stopped == 0) return activity; @@ -308,7 +308,7 @@ public ActivityInfo(string name, long uniqueId, ActivityInfo? creator, Guid acti m_eventOptions = options; m_creator = creator; m_uniqueId = uniqueId; - m_level = creator != null ? creator.m_level + 1 : 0; + m_level = creator is not null ? creator.m_level + 1 : 0; m_activityIdToRestore = activityIDToRestore; // Create a nice GUID that encodes the chain of activities that started this one. @@ -319,7 +319,7 @@ public ActivityInfo(string name, long uniqueId, ActivityInfo? creator, Guid acti public static string Path(ActivityInfo? activityInfo) { - if (activityInfo == null) + if (activityInfo is null) return ""; return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId.ToString(); } @@ -331,7 +331,7 @@ public override string ToString() public static string LiveActivities(ActivityInfo? list) { - if (list == null) + if (list is null) return ""; return list.ToString() + ";" + LiveActivities(list.m_creator); } @@ -369,7 +369,7 @@ private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathG fixed (Guid* outPtr = &idRet) { int activityPathGuidOffsetStart = 0; - if (m_creator != null) + if (m_creator is not null) { activityPathGuidOffsetStart = m_creator.m_activityPathGuidOffset; idRet = m_creator.m_guid; @@ -402,7 +402,7 @@ private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathG private unsafe void CreateOverflowGuid(Guid* outPtr) { // Search backwards for an ancestor that has sufficient space to put the ID. - for (ActivityInfo? ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator) + for (ActivityInfo? ancestor = m_creator; ancestor is not null; ancestor = ancestor.m_creator) { if (ancestor.m_activityPathGuidOffset <= 10) // we need at least 2 bytes. { @@ -557,12 +557,12 @@ private void ActivityChanging(AsyncLocalValueChangedArgs args) // Are we popping off a value? (we have a prev, and it creator is cur) // Then check if we should use the GUID at the time of the start event - if (prev != null && prev.m_creator == cur) + if (prev is not null && prev.m_creator == cur) { // If the saved activity ID is not the same as the creator activity // that takes precedence (it means someone explicitly did a SetActivityID) // Set it to that and get out - if (cur == null || prev.m_activityIdToRestore != cur.ActivityId) + if (cur is null || prev.m_activityIdToRestore != cur.ActivityId) { EventSource.SetCurrentThreadActivityId(prev.m_activityIdToRestore); return; @@ -573,7 +573,7 @@ private void ActivityChanging(AsyncLocalValueChangedArgs args) // setting the activity to current ActivityInfo. However that activity // might be dead, in which case we should skip it, so we never set // the ID to dead things. - while (cur != null) + while (cur is not null) { // We found a live activity (typically the first time), set it to that. if (cur.m_stopped == 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs index effc21fd61ad57..d02eca75837b3f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs @@ -50,7 +50,7 @@ private void OnEventSourceCommand(object? sender, EventCommandEventArgs e) { if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update) { - Debug.Assert(e.Arguments != null); + Debug.Assert(e.Arguments is not null); if (e.Arguments.TryGetValue("EventCounterIntervalSec", out string? valueStr) && float.TryParse(valueStr, out float value)) { @@ -81,7 +81,7 @@ private void OnEventSourceCommand(object? sender, EventCommandEventArgs e) private static void EnsureEventSourceIndexAvailable(int eventSourceIndex) { Debug.Assert(Monitor.IsEntered(s_counterGroupLock)); - if (CounterGroup.s_counterGroups == null) + if (CounterGroup.s_counterGroups is null) { CounterGroup.s_counterGroups = new WeakReference[eventSourceIndex + 1]; } @@ -99,9 +99,9 @@ internal static CounterGroup GetCounterGroup(EventSource eventSource) { int eventSourceIndex = EventListener.EventSourceIndex(eventSource); EnsureEventSourceIndexAvailable(eventSourceIndex); - Debug.Assert(s_counterGroups != null); + Debug.Assert(s_counterGroups is not null); WeakReference weakRef = CounterGroup.s_counterGroups[eventSourceIndex]; - if (weakRef == null || !weakRef.TryGetTarget(out CounterGroup? ret)) + if (weakRef is null || !weakRef.TryGetTarget(out CounterGroup? ret)) { ret = new CounterGroup(eventSource); CounterGroup.s_counterGroups[eventSourceIndex] = new WeakReference(ret); @@ -144,7 +144,7 @@ private void EnableTimer(float pollingIntervalInSeconds) _nextPollingTimeStamp = DateTime.UtcNow + new TimeSpan(0, 0, (int)pollingIntervalInSeconds); // Create the polling thread and init all the shared state if needed - if (s_pollingThread == null) + if (s_pollingThread is null) { s_pollingThreadSleepEvent = new AutoResetEvent(false); s_counterGroupEnabledList = new List(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs index c2c7e20b347f43..2470432cf950eb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs @@ -29,12 +29,12 @@ public abstract class DiagnosticCounter : IDisposable /// The event source. internal DiagnosticCounter(string name, EventSource eventSource) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(Name)); } - if (eventSource == null) + if (eventSource is null) { throw new ArgumentNullException(nameof(EventSource)); } @@ -51,8 +51,8 @@ internal DiagnosticCounter(string name, EventSource eventSource) private protected void Publish() { Debug.Assert(_group is null); - Debug.Assert(Name != null); - Debug.Assert(EventSource != null); + Debug.Assert(Name is not null); + Debug.Assert(EventSource is not null); _group = CounterGroup.GetCounterGroup(EventSource); _group.Add(this); @@ -66,7 +66,7 @@ private protected void Publish() /// public void Dispose() { - if (_group != null) + if (_group is not null) { _group.Remove(this); _group = null; @@ -91,7 +91,7 @@ public string DisplayName get => _displayName; set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(DisplayName)); _displayName = value; } @@ -103,7 +103,7 @@ public string DisplayUnits get => _displayUnits; set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(DisplayUnits)); _displayUnits = value; } @@ -129,7 +129,7 @@ internal string GetMetadataString() { Debug.Assert(Monitor.IsEntered(this)); - if (_metadata == null) + if (_metadata is null) { return ""; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.cs index 4ea1fb87ffba7b..8aa1d990672f1f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.cs @@ -180,12 +180,12 @@ internal static class EventPipe internal static void Enable(EventPipeConfiguration configuration) { - if (configuration == null) + if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } - if (configuration.Providers == null) + if (configuration.Providers is null) { throw new ArgumentNullException(nameof(configuration.Providers)); } @@ -224,11 +224,11 @@ internal static void MarshalToNative(EventPipeProviderConfiguration managed, ref internal void Release() { - if (m_pProviderName != null) + if (m_pProviderName is not null) { Marshal.FreeCoTaskMem((IntPtr)m_pProviderName); } - if (m_pFilterData != null) + if (m_pFilterData is not null) { Marshal.FreeCoTaskMem((IntPtr)m_pFilterData); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeEventDispatcher.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeEventDispatcher.cs index 49a14e2b4c2238..845c2945808bff 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeEventDispatcher.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeEventDispatcher.cs @@ -139,7 +139,7 @@ private void StartDispatchTask() { Debug.Assert(Monitor.IsEntered(m_dispatchControlLock)); - if (m_dispatchTask == null) + if (m_dispatchTask is null) { m_stopDispatchTask = false; // Create a SafeWaitHandle that won't release the handle when done @@ -153,7 +153,7 @@ private void StopDispatchTask() { Debug.Assert(Monitor.IsEntered(m_dispatchControlLock)); - if (m_dispatchTask != null) + if (m_dispatchTask is not null) { m_stopDispatchTask = true; Debug.Assert(!m_dispatchTaskWaitHandle.SafeWaitHandle.IsInvalid); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeMetadataGenerator.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeMetadataGenerator.cs index 65ac1d7aeecd33..f565097475a929 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeMetadataGenerator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipeMetadataGenerator.cs @@ -53,7 +53,7 @@ private EventPipeMetadataGenerator() { } for (int i = 0; i < typeInfos.Length; i++) { string paramName = string.Empty; - if (paramNames != null) + if (paramNames is not null) { paramName = paramNames[i]; } @@ -271,7 +271,7 @@ internal unsafe bool GenerateMetadata(byte* pMetadataBlob, ref uint offset, uint // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; - if (properties != null) + if (properties is not null) { // Write the count of serializable properties. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)properties.Length); @@ -309,8 +309,8 @@ internal unsafe bool GenerateMetadata(byte* pMetadataBlob, ref uint offset, uint private static unsafe bool GenerateMetadataForProperty(PropertyAnalysis property, byte* pMetadataBlob, ref uint offset, uint blobSize) { - Debug.Assert(property != null); - Debug.Assert(pMetadataBlob != null); + Debug.Assert(property is not null); + Debug.Assert(pMetadataBlob is not null); // Check if this property is a nested struct. if (property.typeInfo is InvokeTypeInfo invokeTypeInfo) @@ -324,7 +324,7 @@ private static unsafe bool GenerateMetadataForProperty(PropertyAnalysis property // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; - if (properties != null) + if (properties is not null) { // Write the count of serializable properties. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)properties.Length); @@ -376,14 +376,14 @@ private static unsafe bool GenerateMetadataForProperty(PropertyAnalysis property internal unsafe bool GenerateMetadataV2(byte* pMetadataBlob, ref uint offset, uint blobSize) { - if (TypeInfo == null) + if (TypeInfo is null) return false; return GenerateMetadataForNamedTypeV2(ParameterName, TypeInfo, pMetadataBlob, ref offset, blobSize); } private static unsafe bool GenerateMetadataForNamedTypeV2(string name, TraceLoggingTypeInfo typeInfo, byte* pMetadataBlob, ref uint offset, uint blobSize) { - Debug.Assert(pMetadataBlob != null); + Debug.Assert(pMetadataBlob is not null); if (!GetMetadataLengthForNamedTypeV2(name, typeInfo, out uint length)) { @@ -403,8 +403,8 @@ private static unsafe bool GenerateMetadataForNamedTypeV2(string name, TraceLogg private static unsafe bool GenerateMetadataForTypeV2(TraceLoggingTypeInfo? typeInfo, byte* pMetadataBlob, ref uint offset, uint blobSize) { - Debug.Assert(typeInfo != null); - Debug.Assert(pMetadataBlob != null); + Debug.Assert(typeInfo is not null); + Debug.Assert(pMetadataBlob is not null); // Check if this type is a nested struct. if (typeInfo is InvokeTypeInfo invokeTypeInfo) @@ -417,7 +417,7 @@ private static unsafe bool GenerateMetadataForTypeV2(TraceLoggingTypeInfo? typeI // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; - if (properties != null) + if (properties is not null) { // Write the count of serializable properties. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)properties.Length); @@ -587,7 +587,7 @@ internal bool GetMetadataLength(out uint size) // Get the set of properties to be serialized. PropertyAnalysis[]? properties = typeInfo.properties; - if (properties != null) + if (properties is not null) { foreach (PropertyAnalysis prop in properties) { @@ -610,7 +610,7 @@ internal bool GetMetadataLength(out uint size) private static uint GetMetadataLengthForProperty(PropertyAnalysis property) { - Debug.Assert(property != null); + Debug.Assert(property is not null); uint ret = 0; @@ -627,7 +627,7 @@ private static uint GetMetadataLengthForProperty(PropertyAnalysis property) // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; - if (properties != null) + if (properties is not null) { foreach (PropertyAnalysis prop in properties) { @@ -676,7 +676,7 @@ internal bool GetMetadataLengthV2(out uint size) private static bool GetMetadataLengthForTypeV2(TraceLoggingTypeInfo? typeInfo, out uint size) { size = 0; - if (typeInfo == null) + if (typeInfo is null) { return false; } @@ -692,7 +692,7 @@ private static bool GetMetadataLengthForTypeV2(TraceLoggingTypeInfo? typeInfo, o // Get the set of properties to be serialized. PropertyAnalysis[]? properties = invokeTypeInfo.properties; - if (properties != null) + if (properties is not null) { foreach (PropertyAnalysis prop in properties) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs index 6ed62d08290a8f..7256bd402fee11 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs @@ -290,7 +290,7 @@ private unsafe void EtwEnableCallBack( { args = new Dictionary(4); // data can be null if the filterArgs had a very large size which failed our sanity check - if (data != null) + if (data is not null) { while (keyIndex < data.Length) { @@ -387,7 +387,7 @@ private List> GetSessions() // first look for sessions that have gone away (or have changed) // (present in the m_liveSessions but not in the new liveSessionList) - if (m_liveSessions != null) + if (m_liveSessions is not null) { foreach (SessionInfo s in m_liveSessions) { @@ -399,7 +399,7 @@ private List> GetSessions() } // next look for sessions that were created since the last callback (or have changed) // (present in the new liveSessionList but not in m_liveSessions) - if (liveSessionList != null) + if (liveSessionList is not null) { foreach (SessionInfo s in liveSessionList) { @@ -513,7 +513,7 @@ private unsafe void GetSessionInfo(SessionInfoCallback action, ref List private static int IndexOfSessionInList(List? sessions, int etwSessionId) { - if (sessions == null) + if (sessions is null) return -1; // for non-coreclr code we could use List.FindIndex(Predicate), but we need this to compile // on coreclr as well @@ -605,7 +605,7 @@ private unsafe bool GetDataFromController(int etwSessionId, { data = null; dataStart = 0; - if (filterData == null) + if (filterData is null) { #if TARGET_WINDOWS string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; @@ -623,7 +623,7 @@ private unsafe bool GetDataFromController(int etwSessionId, using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(regKey)) { data = key?.GetValue(valueName, null) as byte[]; - if (data != null) + if (data is not null) { // We only used the persisted data from the registry for updates. command = ControllerCommand.Update; @@ -758,11 +758,11 @@ to fill the passed in ETW data descriptor. string? sRet = data as string; byte[]? blobRet = null; - if (sRet != null) + if (sRet is not null) { dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } - else if ((blobRet = data as byte[]) != null) + else if ((blobRet = data as byte[]) is not null) { // first store array length *(int*)dataBuffer = blobRet.Length; @@ -920,7 +920,7 @@ to fill the passed in ETW data descriptor. } // To our eyes, everything else is a just a string - if (data == null) + if (data is null) sRet = ""; else sRet = data.ToString()!; @@ -1006,11 +1006,11 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even bool hasNonStringRefArgs = false; for (index = 0; index < eventPayload.Length; index++) { - if (eventPayload[index] != null) + if (eventPayload[index] is not null) { object? supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); - if (supportedRefObj != null) + if (supportedRefObj is not null) { // EncodeObject advanced userDataPtr to the next empty slot int idx = (int)(userDataPtr - userData - 1); @@ -1064,35 +1064,35 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even v4 = (string?)dataRefObj[4], v5 = (string?)dataRefObj[5], v6 = (string?)dataRefObj[6], v7 = (string?)dataRefObj[7]) { userDataPtr = (EventData*)userData; - if (dataRefObj[0] != null) + if (dataRefObj[0] is not null) { userDataPtr[refObjPosition[0]].Ptr = (ulong)v0; } - if (dataRefObj[1] != null) + if (dataRefObj[1] is not null) { userDataPtr[refObjPosition[1]].Ptr = (ulong)v1; } - if (dataRefObj[2] != null) + if (dataRefObj[2] is not null) { userDataPtr[refObjPosition[2]].Ptr = (ulong)v2; } - if (dataRefObj[3] != null) + if (dataRefObj[3] is not null) { userDataPtr[refObjPosition[3]].Ptr = (ulong)v3; } - if (dataRefObj[4] != null) + if (dataRefObj[4] is not null) { userDataPtr[refObjPosition[4]].Ptr = (ulong)v4; } - if (dataRefObj[5] != null) + if (dataRefObj[5] is not null) { userDataPtr[refObjPosition[5]].Ptr = (ulong)v5; } - if (dataRefObj[6] != null) + if (dataRefObj[6] is not null) { userDataPtr[refObjPosition[6]].Ptr = (ulong)v6; } - if (dataRefObj[7] != null) + if (dataRefObj[7] is not null) { userDataPtr[refObjPosition[7]].Ptr = (ulong)v7; } @@ -1168,7 +1168,7 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even // protected internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { - if (childActivityID != null) + if (childActivityID is not null) { // activity transfers are supported only for events that specify the Send or Receive opcode Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index d5bc0a6c1c203b..59fed4a2be3676 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -300,24 +300,24 @@ public bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel cha /// public static Guid GetGuid(Type eventSourceType) { - if (eventSourceType == null) + if (eventSourceType is null) throw new ArgumentNullException(nameof(eventSourceType)); EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute)); string name = eventSourceType.Name; - if (attrib != null) + if (attrib is not null) { - if (attrib.Guid != null) + if (attrib.Guid is not null) { if (Guid.TryParse(attrib.Guid, out Guid g)) return g; } - if (attrib.Name != null) + if (attrib.Name is not null) name = attrib.Name; } - if (name == null) + if (name is null) { throw new ArgumentException(SR.Argument_InvalidTypeName, nameof(eventSourceType)); } @@ -382,11 +382,11 @@ public static string GetName(Type eventSourceType) return null; } - if (eventSourceType == null) + if (eventSourceType is null) throw new ArgumentNullException(nameof(eventSourceType)); byte[]? manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags); - return (manifestBytes == null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length); + return (manifestBytes is null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length); } // EventListener support @@ -404,7 +404,7 @@ public static IEnumerable GetSources() var ret = new List(); lock (EventListener.EventListenersLock) { - Debug.Assert(EventListener.s_EventSources != null); + Debug.Assert(EventListener.s_EventSources is not null); foreach (WeakReference eventSourceRef in EventListener.s_EventSources) { @@ -431,7 +431,7 @@ public static void SendCommand(EventSource eventSource, EventCommand command, ID return; } - if (eventSource == null) + if (eventSource is null) throw new ArgumentNullException(nameof(eventSource)); // User-defined EventCommands should not conflict with the reserved commands. @@ -465,7 +465,7 @@ public static void SendCommand(EventSource eventSource, EventCommand command, ID /// The value string associated with key. Will return null if there is no such key. public string? GetTrait(string key) { - if (m_traits != null) + if (m_traits is not null) { for (int i = 0; i < m_traits.Length - 1; i += 2) { @@ -492,7 +492,7 @@ public event EventHandler? EventCommandExecuted { add { - if (value == null) + if (value is null) return; m_eventCommandExecuted += value; @@ -500,7 +500,7 @@ public event EventHandler? EventCommandExecuted // If we have an EventHandler attached to the EventSource before the first command arrives // It should get a chance to handle the deferred commands. EventCommandEventArgs? deferredCommands = m_deferredCommands; - while (deferredCommands != null) + while (deferredCommands is not null) { value(this, deferredCommands); deferredCommands = deferredCommands.nextCommand; @@ -538,7 +538,7 @@ public static void SetCurrentThreadActivityId(Guid activityId) return; } - if (TplEventSource.Log != null) + if (TplEventSource.Log is not null) TplEventSource.Log.SetActivityId(activityId); // We ignore errors to keep with the convention that EventSources do not throw errors. @@ -640,7 +640,7 @@ public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActiv // We don't call the activityDying callback here because the caller has declared that // it is not dying. - if (TplEventSource.Log != null) + if (TplEventSource.Log is not null) TplEventSource.Log.SetActivityId(activityId); } #endregion @@ -717,8 +717,8 @@ private unsafe void DefineEventPipeEvents() return; } - Debug.Assert(m_eventData != null); - Debug.Assert(m_eventPipeProvider != null); + Debug.Assert(m_eventData is not null); + Debug.Assert(m_eventPipeProvider is not null); int cnt = m_eventData.Length; for (int i = 0; i < cnt; i++) { @@ -727,7 +727,7 @@ private unsafe void DefineEventPipeEvents() continue; byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateEventMetadata(m_eventData[i]); - uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; + uint metadataLength = (metadata is not null) ? (uint)metadata.Length : 0; string eventName = m_eventData[i].Name; long keywords = m_eventData[i].Descriptor.Keywords; @@ -1027,7 +1027,7 @@ protected unsafe void WriteEvent(int eventId, byte[]? arg1) if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; - if (arg1 == null || arg1.Length == 0) + if (arg1 is null || arg1.Length == 0) { int blobSize = 0; descrs[0].DataPointer = (IntPtr)(&blobSize); @@ -1063,7 +1063,7 @@ protected unsafe void WriteEvent(int eventId, long arg1, byte[]? arg2) descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; - if (arg2 == null || arg2.Length == 0) + if (arg2 is null || arg2.Length == 0) { int blobSize = 0; descrs[1].DataPointer = (IntPtr)(&blobSize); @@ -1214,7 +1214,7 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel { if (IsEnabled()) { - Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. + Debug.Assert(m_eventData is not null); // You must have initialized this if you enabled the source. try { EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode; @@ -1223,7 +1223,7 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel Guid activityId = Guid.Empty; Guid relActivityId = Guid.Empty; - if (opcode != EventOpcode.Info && relatedActivityId == null && + if (opcode != EventOpcode.Info && relatedActivityId is null && ((activityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) @@ -1260,7 +1260,7 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel else { TraceLoggingEventTypes? tlet = m_eventData[eventId].TraceLoggingEventTypes; - if (tlet == null) + if (tlet is null) { tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name, m_eventData[eventId].Tags, @@ -1279,7 +1279,7 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel } #endif // FEATURE_MANAGED_ETW - if (m_Dispatchers != null && m_eventData[eventId].EnabledForAnyListener) + if (m_Dispatchers is not null && m_eventData[eventId].EnabledForAnyListener) WriteToAllListeners(eventId, pActivityId, relatedActivityId, eventDataCount, data); } catch (Exception ex) @@ -1360,14 +1360,14 @@ protected virtual void Dispose(bool disposing) catch { } // If it fails, simply give up. m_eventSourceEnabled = false; } - if (m_etwProvider != null) + if (m_etwProvider is not null) { m_etwProvider.Dispose(); m_etwProvider = null!; } #endif #if FEATURE_PERFTRACING - if (m_eventPipeProvider != null) + if (m_eventPipeProvider is not null) { m_eventPipeProvider.Dispose(); m_eventPipeProvider = null!; @@ -1400,16 +1400,16 @@ private unsafe void WriteEventRaw( #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING bool allAreNull = true; #if FEATURE_MANAGED_ETW - allAreNull &= (m_etwProvider == null); - if (m_etwProvider != null + allAreNull &= (m_etwProvider is null); + if (m_etwProvider is not null && !m_etwProvider.WriteEventRaw(ref eventDescriptor, eventHandle, activityID, relatedActivityID, dataCount, data)) { ThrowEventSourceException(eventName); } #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING - allAreNull &= (m_eventPipeProvider == null); - if (m_eventPipeProvider != null + allAreNull &= (m_eventPipeProvider is null); + if (m_eventPipeProvider is not null && !m_eventPipeProvider.WriteEventRaw(ref eventDescriptor, eventHandle, activityID, relatedActivityID, dataCount, data)) { ThrowEventSourceException(eventName); @@ -1453,7 +1453,7 @@ private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, str try { m_traits = traits; - if (m_traits != null && m_traits.Length % 2 != 0) + if (m_traits is not null && m_traits.Length % 2 != 0) { throw new ArgumentException(SR.EventSource_TraitEven, nameof(traits)); } @@ -1463,7 +1463,7 @@ private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, str throw new ArgumentException(SR.EventSource_NeedGuid); } - if (eventSourceName == null) + if (eventSourceName is null) { throw new ArgumentException(SR.EventSource_NeedName); } @@ -1544,7 +1544,7 @@ private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, str // Note that we are NOT resetting m_deferredCommands to NULL here, // We are giving for EventHandler that will be attached later EventCommandEventArgs? deferredCommands = m_deferredCommands; - while (deferredCommands != null) + while (deferredCommands is not null) { DoCommand(deferredCommands); // This can never throw, it catches them and reports the errors. deferredCommands = deferredCommands.nextCommand; @@ -1554,11 +1554,11 @@ private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, str private static string GetName(Type eventSourceType, EventManifestOptions flags) { - if (eventSourceType == null) + if (eventSourceType is null) throw new ArgumentNullException(nameof(eventSourceType)); EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); - if (attrib != null && attrib.Name != null) + if (attrib is not null && attrib.Name is not null) return attrib.Name; return eventSourceType.Name; @@ -1728,7 +1728,7 @@ private void Drain() private static Guid GenerateGuidFromName(string name) { #if ES_BUILD_STANDALONE - if (namespaceBytes == null) + if (namespaceBytes is null) { namespaceBytes = new byte[] { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, @@ -1764,7 +1764,7 @@ private static Guid GenerateGuidFromName(string name) // advance to next EventData in array ++data; - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); Type dataType = GetDataType(m_eventData[eventId], parameterId); Again: @@ -1893,7 +1893,7 @@ private static Guid GenerateGuidFromName(string name) private EventDispatcher? GetDispatcher(EventListener? listener) { EventDispatcher? dispatcher = m_Dispatchers; - while (dispatcher != null) + while (dispatcher is not null) { if (dispatcher.m_Listener == listener) return dispatcher; @@ -1906,10 +1906,10 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object { if (IsEnabled()) { - Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. + Debug.Assert(m_eventData is not null); // You must have initialized this if you enabled the source. try { - if (childActivityID != null) + if (childActivityID is not null) { // If you use WriteEventWithRelatedActivityID you MUST declare the first argument to be a GUID // with the name 'relatedActivityID, and NOT pass this argument to the WriteEvent method. @@ -1933,7 +1933,7 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode; EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions; - if (childActivityID == null && + if (childActivityID is null && ((activityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) @@ -1970,7 +1970,7 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object else { TraceLoggingEventTypes? tlet = m_eventData[eventId].TraceLoggingEventTypes; - if (tlet == null) + if (tlet is null) { tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name, EventTags.None, @@ -1989,7 +1989,7 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object } } #endif // FEATURE_MANAGED_ETW - if (m_Dispatchers != null && m_eventData[eventId].EnabledForAnyListener) + if (m_Dispatchers is not null && m_eventData[eventId].EnabledForAnyListener) { #if !ES_BUILD_STANDALONE // Maintain old behavior - object identity is preserved @@ -2029,9 +2029,9 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object private unsafe object?[] SerializeEventArgs(int eventId, object?[] args) { - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); TraceLoggingEventTypes? eventTypes = m_eventData[eventId].TraceLoggingEventTypes; - if (eventTypes == null) + if (eventTypes is null) { eventTypes = new TraceLoggingEventTypes(m_eventData[eventId].Name, EventTags.None, @@ -2055,7 +2055,7 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object /// private void LogEventArgsMismatches(int eventId, object?[] args) { - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); ParameterInfo[] infos = m_eventData[eventId].Parameters; if (args.Length != infos.Length) @@ -2073,8 +2073,8 @@ private void LogEventArgsMismatches(int eventId, object?[] args) // Checking to see if the Parameter types (from the Event method) match the supplied argument types. // Fail if one of two things hold : either the argument type is not equal or assignable to the parameter type, or the // argument is null and the parameter type is a non-Nullable value type. - if ((arg != null && !pType.IsAssignableFrom(arg.GetType())) - || (arg == null && (pType.IsValueType && !(pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable<>)))) + if ((arg is not null && !pType.IsAssignableFrom(arg.GetType())) + || (arg is null && (pType.IsValueType && !(pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable<>)))) ) { ReportOutOfBandMessage(SR.Format(SR.EventSource_VarArgsParameterMismatch, eventId, infos[i].Name)); @@ -2087,7 +2087,7 @@ private void LogEventArgsMismatches(int eventId, object?[] args) private unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* childActivityID, int eventDataCount, EventSource.EventData* data) { - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); // We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious // warning because eventDataCount is off by one for the byte[] case since a byte[] has 2 items associated it. So we want to check // that the number of parameters is correct against the byte[] case, but also we the args array would be one too long if @@ -2131,16 +2131,16 @@ internal unsafe void WriteToAllListeners(int eventId, uint* osThreadId, DateTime { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventId = eventId; - if (osThreadId != null) + if (osThreadId is not null) eventCallbackArgs.OSThreadId = (int)*osThreadId; - if (timeStamp != null) + if (timeStamp is not null) eventCallbackArgs.TimeStamp = *timeStamp; - if (activityID != null) + if (activityID is not null) eventCallbackArgs.ActivityId = *activityID; - if (childActivityID != null) + if (childActivityID is not null) eventCallbackArgs.RelatedActivityId = *childActivityID; - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); eventCallbackArgs.EventName = m_eventData[eventId].Name; eventCallbackArgs.Message = m_eventData[eventId].Message; eventCallbackArgs.Payload = new ReadOnlyCollection(args); @@ -2151,9 +2151,9 @@ internal unsafe void WriteToAllListeners(int eventId, uint* osThreadId, DateTime private unsafe void DispatchToAllListeners(int eventId, EventWrittenEventArgs eventCallbackArgs) { Exception? lastThrownException = null; - for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) + for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher is not null; dispatcher = dispatcher.m_Next) { - Debug.Assert(dispatcher.m_EventEnabled != null); + Debug.Assert(dispatcher.m_EventEnabled is not null); if (eventId == -1 || dispatcher.m_EventEnabled[eventId]) { { @@ -2171,7 +2171,7 @@ private unsafe void DispatchToAllListeners(int eventId, EventWrittenEventArgs ev } } - if (lastThrownException != null) + if (lastThrownException is not null) { throw new EventSourceException(lastThrownException); } @@ -2186,10 +2186,10 @@ private unsafe void WriteEventString(string msgString) #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING bool allAreNull = true; #if FEATURE_MANAGED_ETW - allAreNull &= (m_etwProvider == null); + allAreNull &= (m_etwProvider is null); #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING - allAreNull &= (m_eventPipeProvider == null); + allAreNull &= (m_eventPipeProvider is null); #endif // FEATURE_PERFTRACING if (allAreNull) { @@ -2213,7 +2213,7 @@ private unsafe void WriteEventString(string msgString) { // We want the name of the provider to show up so if we don't have a manifest we create // on that at least has the provider name (I don't define any events). - if (m_rawManifest == null && m_outOfBandMessageCount == 1) + if (m_rawManifest is null && m_outOfBandMessageCount == 1) { ManifestBuilder manifestBuilder = new ManifestBuilder(Name, Guid, Name, null, EventManifestOptions.None); manifestBuilder.StartEvent(EventName, new EventAttribute(0) { Level = level, Task = (EventTask)0xFFFE }); @@ -2231,13 +2231,13 @@ private unsafe void WriteEventString(string msgString) data.Size = (uint)(2 * (msgString.Length + 1)); data.Reserved = 0; #if FEATURE_MANAGED_ETW - if (m_etwProvider != null) + if (m_etwProvider is not null) { m_etwProvider.WriteEvent(ref descr, IntPtr.Zero, null, null, 1, (IntPtr)((void*)&data)); } #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING - if (m_eventPipeProvider != null) + if (m_eventPipeProvider is not null) { if (m_writeEventStringEventHandle == IntPtr.Zero) { @@ -2249,7 +2249,7 @@ private unsafe void WriteEventString(string msgString) EventParameterInfo paramInfo = default(EventParameterInfo); paramInfo.SetInfo("message", typeof(string)); byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateMetadata(0, eventName, keywords, (uint)level, 0, EventOpcode.Info, new EventParameterInfo[] { paramInfo }); - uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; + uint metadataLength = (metadata is not null) ? (uint)metadata.Length : 0; fixed (byte* pMetadata = metadata) { @@ -2281,10 +2281,10 @@ private void WriteStringToAllListeners(string eventName, string msg) eventCallbackArgs.PayloadNames = new ReadOnlyCollection(new List { "message" }); eventCallbackArgs.EventName = eventName; - for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) + for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher is not null; dispatcher = dispatcher.m_Next) { bool dispatcherEnabled = false; - if (dispatcher.m_EventEnabled == null) + if (dispatcher.m_EventEnabled is null) { // if the listeners that weren't correctly initialized, we will send to it // since this is an error message and we want to see it go out. @@ -2324,7 +2324,7 @@ private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLev if (!enable) return false; - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); EventLevel eventLevel = (EventLevel)m_eventData[eventNum].Descriptor.Level; EventKeywords eventKeywords = unchecked((EventKeywords)((ulong)m_eventData[eventNum].Descriptor.Keywords & (~(SessionMask.All.ToEventKeywords())))); @@ -2352,7 +2352,7 @@ private bool IsEnabledCommon(bool enabled, EventLevel currentLevel, EventKeyword { #if FEATURE_MANAGED_ETW_CHANNELS // is there a channel with keywords that match currentMatchAnyKeyword? - if (eventChannel != EventChannel.None && this.m_channelData != null && this.m_channelData.Length > (int)eventChannel) + if (eventChannel != EventChannel.None && this.m_channelData is not null && this.m_channelData.Length > (int)eventChannel) { EventKeywords channel_keywords = unchecked((EventKeywords)(m_channelData[(int)eventChannel] | (ulong)eventKeywords)); if (channel_keywords != 0 && (channel_keywords & currentMatchAnyKeyword) == 0) @@ -2380,7 +2380,7 @@ private void ThrowEventSourceException(string? eventName, Exception? innerEx = n m_EventSourceExceptionRecurenceCount++; string errorPrefix = "EventSourceException"; - if (eventName != null) + if (eventName is not null) { errorPrefix += " while processing event \"" + eventName + "\""; } @@ -2405,7 +2405,7 @@ private void ThrowEventSourceException(string? eventName, Exception? innerEx = n if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_TooManyArgs, innerEx); break; default: - if (innerEx != null) + if (innerEx is not null) { innerEx = innerEx.GetBaseException(); ReportOutOfBandMessage(errorPrefix + ": " + innerEx.GetType() + ":" + innerEx.Message); @@ -2424,7 +2424,7 @@ private void ThrowEventSourceException(string? eventName, Exception? innerEx = n internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string? eventName) { - if (opcode == EventOpcode.Info && eventName != null) + if (opcode == EventOpcode.Info && eventName is not null) { if (eventName.EndsWith(s_ActivityStartSuffix, StringComparison.Ordinal)) { @@ -2510,7 +2510,7 @@ private static Type GetDataType(EventMetadata eventData, int parameterId) // // * if Command == Update // * perEventSourceSessionId specifies the per-provider ETW session ID that the command applies - // to (if listener != null) + // to (if listener is not null) // perEventSourceSessionId = 0 - reserved for EventListeners // perEventSourceSessionId = 1..SessionMask.MAX - reserved for activity tracing aware ETW sessions // perEventSourceSessionId-1 represents the bit in the reserved field (bits 44..47) in @@ -2530,7 +2530,7 @@ private static Type GetDataType(EventMetadata eventData, int parameterId) // * Simply call OnEventCommand. The expectation is that filtering is NOT changed. // * The 'enabled' 'level', matchAnyKeyword' arguments are ignored (must be true, 0, 0). // - // dispatcher == null has special meaning. It is the 'ETW' dispatcher. + // dispatcher is null has special meaning. It is the 'ETW' dispatcher. internal void SendCommand(EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeyword, @@ -2554,7 +2554,7 @@ internal void SendCommand(EventListener? listener, EventProviderType eventProvid else { // We can't do the command, simply remember it and we do it when we are fully constructed. - if (m_deferredCommands == null) + if (m_deferredCommands is null) { m_deferredCommands = commandArgs; // create the first entry } @@ -2562,7 +2562,7 @@ internal void SendCommand(EventListener? listener, EventProviderType eventProvid { // We have one or more entries, find the last one and add it to that. EventCommandEventArgs lastCommand = m_deferredCommands; - while (lastCommand.nextCommand != null) + while (lastCommand.nextCommand is not null) lastCommand = lastCommand.nextCommand; lastCommand.nextCommand = commandArgs; } @@ -2588,11 +2588,11 @@ internal void DoCommand(EventCommandEventArgs commandArgs) Debug.Assert(m_completelyInited); #if FEATURE_MANAGED_ETW - if (m_etwProvider == null) // If we failed to construct + if (m_etwProvider is null) // If we failed to construct return; #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING - if (m_eventPipeProvider == null) + if (m_eventPipeProvider is null) return; #endif @@ -2600,11 +2600,11 @@ internal void DoCommand(EventCommandEventArgs commandArgs) try { EnsureDescriptorsInitialized(); - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); // Find the per-EventSource dispatcher corresponding to registered dispatcher commandArgs.dispatcher = GetDispatcher(commandArgs.listener); - if (commandArgs.dispatcher == null && commandArgs.listener != null) // dispatcher == null means ETW dispatcher + if (commandArgs.dispatcher is null && commandArgs.listener is not null) // dispatcher is null means ETW dispatcher { throw new ArgumentException(SR.EventSource_ListenerNotFound); } @@ -2643,11 +2643,11 @@ internal void DoCommand(EventCommandEventArgs commandArgs) if (commandArgs.perEventSourceSessionId == 0 && !commandArgs.enable) bSessionEnable = false; - if (commandArgs.listener == null) + if (commandArgs.listener is null) { if (!bSessionEnable) commandArgs.perEventSourceSessionId = -commandArgs.perEventSourceSessionId; - // for "global" enable/disable (passed in with listener == null and + // for "global" enable/disable (passed in with listener is null and // perEventSourceSessionId == 0) perEventSourceSessionId becomes -1 --commandArgs.perEventSourceSessionId; } @@ -2661,9 +2661,9 @@ internal void DoCommand(EventCommandEventArgs commandArgs) Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); // Send the manifest if we are enabling an ETW session - if (bSessionEnable && commandArgs.dispatcher == null) + if (bSessionEnable && commandArgs.dispatcher is null) { - // eventSourceDispatcher == null means this is the ETW manifest + // eventSourceDispatcher is null means this is the ETW manifest // Note that we unconditionally send the manifest whenever we are enabled, even if // we were already enabled. This is because there may be multiple sessions active @@ -2676,7 +2676,7 @@ internal void DoCommand(EventCommandEventArgs commandArgs) // things like log messages, or test if keywords are enabled in the callback. if (commandArgs.enable) { - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); m_eventSourceEnabled = true; } @@ -2693,9 +2693,9 @@ internal void DoCommand(EventCommandEventArgs commandArgs) for (int i = 0; i < m_eventData.Length; i++) { bool isEnabledForAnyListener = false; - for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) + for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher is not null; dispatcher = dispatcher.m_Next) { - Debug.Assert(dispatcher.m_EventEnabled != null); + Debug.Assert(dispatcher.m_EventEnabled is not null); if (dispatcher.m_EventEnabled[i]) { @@ -2720,7 +2720,7 @@ internal void DoCommand(EventCommandEventArgs commandArgs) if (commandArgs.Command == EventCommand.SendManifest) { // TODO: should we generate the manifest here if we hadn't already? - if (m_rawManifest != null) + if (m_rawManifest is not null) SendManifest(m_rawManifest); } @@ -2752,24 +2752,24 @@ internal bool EnableEventForDispatcher(EventDispatcher? dispatcher, EventProvide if (!IsSupported) return false; - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); - if (dispatcher == null) + if (dispatcher is null) { if (eventId >= m_eventData.Length) return false; #if FEATURE_MANAGED_ETW - if (m_etwProvider != null && eventProviderType == EventProviderType.ETW) + if (m_etwProvider is not null && eventProviderType == EventProviderType.ETW) m_eventData[eventId].EnabledForETW = value; #endif #if FEATURE_PERFTRACING - if (m_eventPipeProvider != null && eventProviderType == EventProviderType.EventPipe) + if (m_eventPipeProvider is not null && eventProviderType == EventProviderType.EventPipe) m_eventData[eventId].EnabledForEventPipe = value; #endif } else { - Debug.Assert(dispatcher.m_EventEnabled != null); + Debug.Assert(dispatcher.m_EventEnabled is not null); if (eventId >= dispatcher.m_EventEnabled.Length) return false; dispatcher.m_EventEnabled[eventId] = value; @@ -2784,7 +2784,7 @@ internal bool EnableEventForDispatcher(EventDispatcher? dispatcher, EventProvide /// private bool AnyEventEnabled() { - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); for (int i = 0; i < m_eventData.Length; i++) if (m_eventData[i].EnabledForETW || m_eventData[i].EnabledForAnyListener @@ -2803,15 +2803,15 @@ private void EnsureDescriptorsInitialized() #if !ES_BUILD_STANDALONE Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif - if (m_eventData == null) + if (m_eventData is null) { // get the metadata via reflection. - Debug.Assert(m_rawManifest == null); + Debug.Assert(m_rawManifest is null); m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this); - Debug.Assert(m_eventData != null); + Debug.Assert(m_eventData is not null); // TODO Enforce singleton pattern - Debug.Assert(EventListener.s_EventSources != null, "should be called within lock on EventListener.EventListenersLock which ensures s_EventSources to be initialized"); + Debug.Assert(EventListener.s_EventSources is not null, "should be called within lock on EventListener.EventListenersLock which ensures s_EventSources to be initialized"); foreach (WeakReference eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource) && eventSource.Guid == m_guid && !eventSource.IsDisposed) @@ -2825,7 +2825,7 @@ private void EnsureDescriptorsInitialized() // Make certain all dispatchers also have their arrays initialized EventDispatcher? dispatcher = m_Dispatchers; - while (dispatcher != null) + while (dispatcher is not null) { dispatcher.m_EventEnabled ??= new bool[m_eventData.Length]; dispatcher = dispatcher.m_Next; @@ -2841,7 +2841,7 @@ private void EnsureDescriptorsInitialized() // Today, we only send the manifest to ETW, custom listeners don't get it. private unsafe void SendManifest(byte[]? rawManifest) { - if (rawManifest == null) + if (rawManifest is null) return; Debug.Assert(!SelfDescribingEvents); @@ -2876,7 +2876,7 @@ private unsafe void SendManifest(byte[]? rawManifest) while (dataLeft > 0) { dataDescrs[1].Size = (uint)Math.Min(dataLeft, chunkSize); - if (m_etwProvider != null) + if (m_etwProvider is not null) { if (!m_etwProvider.WriteEvent(ref manifestDescr, IntPtr.Zero, null, null, 2, (IntPtr)dataDescrs)) { @@ -2953,7 +2953,7 @@ private unsafe void SendManifest(byte[]? rawManifest) attr = (Attribute?)Activator.CreateInstance(attributeType); } - if (attr != null) + if (attr is not null) { foreach (CustomAttributeNamedArgument namedArgument in data.NamedArguments) { @@ -3009,7 +3009,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt Type? ret = eventSourceType; // return false for "object" and interfaces - if (ret.BaseType == null) + if (ret.BaseType is null) return null; // now go up the inheritance chain until hitting a concrete type ("object" at worse) @@ -3017,9 +3017,9 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt { ret = ret.BaseType; } - while (ret != null && ret.IsAbstract); + while (ret is not null && ret.IsAbstract); - if (ret != null) + if (ret is not null) { if (!allowEventSourceOverride) { @@ -3050,7 +3050,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt EventManifestOptions flags = EventManifestOptions.None) { ManifestBuilder? manifest = null; - bool bNeedsManifest = source != null ? !source.SelfDescribingEvents : true; + bool bNeedsManifest = source is not null ? !source.SelfDescribingEvents : true; Exception? exception = null; // exception that might get raised during validation b/c we couldn't/didn't recover from a previous error byte[]? res = null; @@ -3064,7 +3064,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt int eventId = 1; // The number given to an event that does not have a explicitly given ID. EventMetadata[]? eventData = null; Dictionary? eventsByName = null; - if (source != null || (flags & EventManifestOptions.Strict) != 0) + if (source is not null || (flags & EventManifestOptions.Strict) != 0) { eventData = new EventMetadata[methods.Length + 1]; eventData[0].Name = ""; // Event 0 is the 'write messages string' event, and has an empty name. @@ -3073,7 +3073,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt // See if we have localization information. ResourceManager? resources = null; EventSourceAttribute? eventSourceAttrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); - if (eventSourceAttrib != null && eventSourceAttrib.LocalizationResources != null) + if (eventSourceAttrib is not null && eventSourceAttrib.LocalizationResources is not null) resources = new ResourceManager(eventSourceAttrib.LocalizationResources, eventSourceType.Assembly); manifest = new ManifestBuilder(GetName(eventSourceType, flags), GetGuid(eventSourceType), eventSourceDllName, @@ -3087,7 +3087,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt // eventSourceType must be sealed and must derive from this EventSource if ((flags & EventManifestOptions.Strict) != 0) { - bool typeMatch = GetEventSourceBaseType(eventSourceType, (flags & EventManifestOptions.AllowEventSourceOverride) != 0, eventSourceType.Assembly.ReflectionOnly) != null; + bool typeMatch = GetEventSourceBaseType(eventSourceType, (flags & EventManifestOptions.AllowEventSourceOverride) != 0, eventSourceType.Assembly.ReflectionOnly) is not null; if (!typeMatch) { @@ -3107,7 +3107,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt #endif { Type? nestedType = eventSourceType.GetNestedType(providerEnumKind); - if (nestedType != null) + if (nestedType is not null) { if (eventSourceType.IsAbstract) { @@ -3152,13 +3152,13 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt if (eventSourceType.IsAbstract) { - if (eventAttribute != null) + if (eventAttribute is not null) { manifest.ManifestError(SR.Format(SR.EventSource_AbstractMustNotDeclareEventMethods, method.Name, eventAttribute.EventId)); } continue; } - else if (eventAttribute == null) + else if (eventAttribute is null) { // Methods that don't return void can't be events, if they're NOT marked with [Event]. // (see Compat comment above) @@ -3175,7 +3175,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt } // If we explicitly mark the method as not being an event, then honor that. - if (GetCustomAttributeHelper(method, typeof(NonEventAttribute), flags) != null) + if (GetCustomAttributeHelper(method, typeof(NonEventAttribute), flags) is not null) continue; defaultEventAttribute = new EventAttribute(eventId); @@ -3224,7 +3224,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt { // Find the start associated with this stop event. We require start to be immediately before the stop int startEventId = eventAttribute.EventId - 1; - if (eventData != null && startEventId < eventData.Length) + if (eventData is not null && startEventId < eventData.Length) { Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 EventMetadata startEventMetadata = eventData[startEventId]; @@ -3250,7 +3250,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt } bool hasRelatedActivityID = RemoveFirstArgIfRelatedActivityId(ref args); - if (!(source != null && source.SelfDescribingEvents)) + if (!(source is not null && source.SelfDescribingEvents)) { manifest.StartEvent(eventName, eventAttribute); for (int fieldIdx = 0; fieldIdx < args.Length; fieldIdx++) @@ -3260,9 +3260,9 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt manifest.EndEvent(); } - if (source != null || (flags & EventManifestOptions.Strict) != 0) + if (source is not null || (flags & EventManifestOptions.Strict) != 0) { - Debug.Assert(eventData != null); + Debug.Assert(eventData is not null); // Do checking for user errors (optional, but not a big deal so we do it). DebugCheckEvent(ref eventsByName, eventData, method, eventAttribute, manifest, flags); @@ -3280,7 +3280,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt string eventKey = "event_" + eventName; string? msg = manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false); // overwrite inline message with the localized message - if (msg != null) eventAttribute.Message = msg; + if (msg is not null) eventAttribute.Message = msg; AddEventDescriptor(ref eventData, eventName, eventAttribute, args, hasRelatedActivityID); } @@ -3290,9 +3290,9 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt // Tell the TraceLogging stuff where to start allocating its own IDs. NameInfo.ReserveEventIDsBelow(eventId); - if (source != null) + if (source is not null) { - Debug.Assert(eventData != null); + Debug.Assert(eventData is not null); TrimEventDescriptors(ref eventData); source.m_eventData = eventData; // officially initialize it. We do this at most once (it is racy otherwise). #if FEATURE_MANAGED_ETW_CHANNELS @@ -3301,7 +3301,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt } // if this is an abstract event source we've already performed all the validation we can - if (!eventSourceType.IsAbstract && (source == null || !source.SelfDescribingEvents)) + if (!eventSourceType.IsAbstract && (source is null || !source.SelfDescribingEvents)) { bNeedsManifest = (flags & EventManifestOptions.OnlyIfNeededForRegistration) == 0 #if FEATURE_MANAGED_ETW_CHANNELS @@ -3325,7 +3325,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt exception = e; } - if ((flags & EventManifestOptions.Strict) != 0 && (manifest?.Errors.Count > 0 || exception != null)) + if ((flags & EventManifestOptions.Strict) != 0 && (manifest?.Errors.Count > 0 || exception is not null)) { string msg = string.Empty; @@ -3467,7 +3467,7 @@ internal void AddListener(EventListener listener) lock (EventListener.EventListenersLock) { bool[]? enabledArray = null; - if (m_eventData != null) + if (m_eventData is not null) enabledArray = new bool[m_eventData.Length]; m_Dispatchers = new EventDispatcher(m_Dispatchers, enabledArray, listener); listener.OnEventSourceCreated(this); @@ -3499,7 +3499,7 @@ private static void DebugCheckEvent(ref Dictionary? eventsByName for (int idx = 0; idx < eventData.Length; ++idx) { // skip unused Event IDs. - if (eventData[idx].Name == null) + if (eventData[idx].Name is null) continue; if (eventData[idx].Descriptor.Task == (int)eventAttribute.Task && eventData[idx].Descriptor.Opcode == (int)eventAttribute.Opcode) @@ -3936,7 +3936,7 @@ public virtual void Dispose() { lock (EventListenersLock) { - if (s_Listeners != null) + if (s_Listeners is not null) { if (this == s_Listeners) { @@ -3951,7 +3951,7 @@ public virtual void Dispose() while (true) { EventListener? cur = prev.m_Next; - if (cur == null) + if (cur is null) break; if (cur == this) { @@ -4013,7 +4013,7 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword /// public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary? arguments) { - if (eventSource == null) + if (eventSource is null) { throw new ArgumentNullException(nameof(eventSource)); } @@ -4034,7 +4034,7 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword /// public void DisableEvents(EventSource eventSource) { - if (eventSource == null) + if (eventSource is null) { throw new ArgumentNullException(nameof(eventSource)); } @@ -4074,7 +4074,7 @@ public void DisableEvents(EventSource eventSource) protected internal virtual void OnEventSourceCreated(EventSource eventSource) { EventHandler? callBack = this._EventSourceCreated; - if (callBack != null) + if (callBack is not null) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; @@ -4156,7 +4156,7 @@ internal static void AddEventSource(EventSource newEventSource) { #endif // Add every existing dispatcher to the new EventSource - for (EventListener? listener = s_Listeners; listener != null; listener = listener.m_Next) + for (EventListener? listener = s_Listeners; listener is not null; listener = listener.m_Next) newEventSource.AddListener(listener); #if DEBUG } @@ -4181,7 +4181,7 @@ private static void DisposeOnShutdown(object? sender, EventArgs e) { lock (EventListenersLock) { - Debug.Assert(s_EventSources != null); + Debug.Assert(s_EventSources is not null); foreach (WeakReference esRef in s_EventSources) { if (esRef.TryGetTarget(out EventSource? es)) @@ -4202,12 +4202,12 @@ private static void RemoveReferencesToListenerInEventSources(EventListener liste Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // Foreach existing EventSource in the appdomain - Debug.Assert(s_EventSources != null); + Debug.Assert(s_EventSources is not null); foreach (WeakReference eventSourceRef in s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource)) { - Debug.Assert(eventSource.m_Dispatchers != null); + Debug.Assert(eventSource.m_Dispatchers is not null); // Is the first output dispatcher the dispatcher we are removing? if (eventSource.m_Dispatchers.m_Listener == listenerToRemove) eventSource.m_Dispatchers = eventSource.m_Dispatchers.m_Next; @@ -4218,7 +4218,7 @@ private static void RemoveReferencesToListenerInEventSources(EventListener liste while (true) { EventDispatcher? cur = prev.m_Next; - if (cur == null) + if (cur is null) { Debug.Fail("EventSource did not have a registered EventListener!"); break; @@ -4256,11 +4256,11 @@ internal static void Validate() lock (EventListenersLock) { - Debug.Assert(s_EventSources != null); + Debug.Assert(s_EventSources is not null); // Get all listeners Dictionary allListeners = new Dictionary(); EventListener? cur = s_Listeners; - while (cur != null) + while (cur is not null) { allListeners.Add(cur, true); cur = cur.m_Next; @@ -4277,7 +4277,7 @@ internal static void Validate() // None listeners on eventSources exist in the dispatcher list. EventDispatcher? dispatcher = eventSource.m_Dispatchers; - while (dispatcher != null) + while (dispatcher is not null) { Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); dispatcher = dispatcher.m_Next; @@ -4289,7 +4289,7 @@ internal static void Validate() dispatcher = eventSource.m_Dispatchers; while (true) { - Debug.Assert(dispatcher != null, "Listener is not on all eventSources."); + Debug.Assert(dispatcher is not null, "Listener is not on all eventSources."); if (dispatcher.m_Listener == listener) break; dispatcher = dispatcher.m_Next; @@ -4307,7 +4307,7 @@ internal static object EventListenersLock { get { - if (s_EventSources == null) + if (s_EventSources is null) Interlocked.CompareExchange(ref s_EventSources, new List>(2), null); return s_EventSources; } @@ -4317,7 +4317,7 @@ private void CallBackForExistingEventSources(bool addToListenersList, EventHandl { lock (EventListenersLock) { - Debug.Assert(s_EventSources != null); + Debug.Assert(s_EventSources is not null); // Disallow creating EventListener reentrancy. if (s_CreatingListener) @@ -4337,7 +4337,7 @@ private void CallBackForExistingEventSources(bool addToListenersList, EventHandl s_Listeners = this; } - if (callback != null) + if (callback is not null) { // Find all existing eventSources call OnEventSourceCreated to 'catchup' // Note that we DO have reentrancy here because 'AddListener' calls out to user code (via OnEventSourceCreated callback) @@ -4520,13 +4520,13 @@ public string? EventName { get { - if (m_eventName != null || EventId < 0) // TraceLogging convention EventID == -1 + if (m_eventName is not null || EventId < 0) // TraceLogging convention EventID == -1 { return m_eventName; } else { - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return m_eventSource.m_eventData[EventId].Name; } } @@ -4580,10 +4580,10 @@ public ReadOnlyCollection? PayloadNames // For contract based events we create the list lazily. // You can have m_payloadNames be null in the TraceLogging case (EventID < 0) so only // do the lazy init if you know it is contract based (EventID >= 0) - if (EventId >= 0 && m_payloadNames == null) + if (EventId >= 0 && m_payloadNames is null) { var names = new List(); - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); foreach (ParameterInfo parameter in m_eventSource.m_eventData[EventId].Parameters) { names.Add(parameter.Name!); @@ -4613,7 +4613,7 @@ public EventKeywords Keywords if (EventId <= 0) // TraceLogging convention EventID == -1 return m_keywords; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return (EventKeywords)m_eventSource.m_eventData[EventId].Descriptor.Keywords; } } @@ -4628,7 +4628,7 @@ public EventOpcode Opcode if (EventId <= 0) // TraceLogging convention EventID == -1 return m_opcode; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return (EventOpcode)m_eventSource.m_eventData[EventId].Descriptor.Opcode; } } @@ -4643,7 +4643,7 @@ public EventTask Task if (EventId <= 0) // TraceLogging convention EventID == -1 return EventTask.None; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return (EventTask)m_eventSource.m_eventData[EventId].Descriptor.Task; } } @@ -4658,7 +4658,7 @@ public EventTags Tags if (EventId <= 0) // TraceLogging convention EventID == -1 return m_tags; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return m_eventSource.m_eventData[EventId].Tags; } } @@ -4676,7 +4676,7 @@ public string? Message } else { - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return m_eventSource.m_eventData[EventId].Message; } } @@ -4694,7 +4694,7 @@ public EventChannel Channel if (EventId <= 0) // TraceLogging convention EventID == -1 return EventChannel.None; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return (EventChannel)m_eventSource.m_eventData[EventId].Descriptor.Channel; } } @@ -4710,7 +4710,7 @@ public byte Version if (EventId <= 0) // TraceLogging convention EventID == -1 return 0; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return m_eventSource.m_eventData[EventId].Descriptor.Version; } } @@ -4725,7 +4725,7 @@ public EventLevel Level if (EventId <= 0) // TraceLogging convention EventID == -1 return m_level; - Debug.Assert(m_eventSource.m_eventData != null); + Debug.Assert(m_eventSource.m_eventData is not null); return (EventLevel)m_eventSource.m_eventData[EventId].Descriptor.Level; } } @@ -5202,7 +5202,7 @@ public ManifestBuilder(string providerName, Guid providerGuid, string? dllName, sb.AppendLine(" "); sb.Append(" 255) ManifestError(SR.Format(SR.EventSource_EventChannelOutOfRange, name, value)); else if (chValue >= EventChannel.Admin && chValue <= EventChannel.Debug && - channelAttribute != null && EventChannelToChannelType(chValue) != channelAttribute.EventChannelType) + channelAttribute is not null && EventChannelToChannelType(chValue) != channelAttribute.EventChannelType) { // we want to ensure developers do not define EventChannels that conflict with the builtin ones, // but we want to allow them to override the default ones... @@ -5315,7 +5315,7 @@ private static EventChannelAttribute GetDefaultChannelAttribute(EventChannel cha public ulong[] GetChannelData() { - if (this.channelTab == null) + if (this.channelTab is null) { return Array.Empty(); } @@ -5344,7 +5344,7 @@ public ulong[] GetChannelData() public void StartEvent(string eventName, EventAttribute eventAttribute) { Debug.Assert(numParams == 0); - Debug.Assert(this.eventName == null); + Debug.Assert(this.eventName is null); this.eventName = eventName; numParams = 0; byteArrArgIndices = null; @@ -5411,7 +5411,7 @@ public void AddEventParameter(Type type, string name) } public void EndEvent() { - Debug.Assert(eventName != null); + Debug.Assert(eventName is not null); if (numParams > 0) { @@ -5420,7 +5420,7 @@ public void EndEvent() } events.AppendLine("/>"); - if (byteArrArgIndices != null) + if (byteArrArgIndices is not null) perEventByteArrayArgIndices[eventName] = byteArrArgIndices; // at this point we have all the information we need to translate the C# Message @@ -5501,7 +5501,7 @@ private string CreateManifestString() { #if FEATURE_MANAGED_ETW_CHANNELS // Write out the channels - if (channelTab != null) + if (channelTab is not null) { sb.AppendLine(" "); var sortedChannels = new List>(); @@ -5520,14 +5520,14 @@ private string CreateManifestString() string? isolation = null; string? access = null; #endif - if (channelInfo.Attribs != null) + if (channelInfo.Attribs is not null) { EventChannelAttribute attribs = channelInfo.Attribs; if (Enum.IsDefined(typeof(EventChannelType), attribs.EventChannelType)) channelType = attribs.EventChannelType.ToString(); enabled = attribs.Enabled; #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS - if (attribs.ImportChannel != null) + if (attribs.ImportChannel is not null) { fullName = attribs.ImportChannel; elementName = "importChannel"; @@ -5545,16 +5545,16 @@ private string CreateManifestString() sb.Append(" name=\"").Append(fullName).Append('"'); if (ElementName == "channel") // not applicable to importChannels. { - Debug.Assert(channelInfo.Name != null); + Debug.Assert(channelInfo.Name is not null); WriteMessageAttrib(sb, "channel", channelInfo.Name, null); sb.Append(" value=\"").Append(channel).Append('"'); - if (channelType != null) + if (channelType is not null) sb.Append(" type=\"").Append(channelType).Append('"'); sb.Append(" enabled=\"").Append(enabled ? "true" : "false").Append('"'); #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS - if (access != null) + if (access is not null) sb.Append(" access=\"").Append(access).Append("\""); - if (isolation != null) + if (isolation is not null) sb.Append(" isolation=\"").Append(isolation).Append("\""); #endif } @@ -5565,7 +5565,7 @@ private string CreateManifestString() #endif // Write out the tasks - if (taskTab != null) + if (taskTab is not null) { sb.AppendLine(" "); var sortedTasks = new List(taskTab.Keys); @@ -5580,12 +5580,12 @@ private string CreateManifestString() } // Write out the maps - if (mapsTab != null) + if (mapsTab is not null) { sb.AppendLine(" "); foreach (Type enumType in mapsTab.Values) { - bool isbitmap = EventSource.GetCustomAttributeHelper(enumType, typeof(FlagsAttribute), flags) != null; + bool isbitmap = EventSource.GetCustomAttributeHelper(enumType, typeof(FlagsAttribute), flags) is not null; string mapKind = isbitmap ? "bitMap" : "valueMap"; sb.Append(" <").Append(mapKind).Append(" name=\"").Append(enumType.Name).AppendLine("\">"); @@ -5596,7 +5596,7 @@ private string CreateManifestString() { object? constantValObj = staticField.GetRawConstantValue(); - if (constantValObj != null) + if (constantValObj is not null) { ulong hexValue; if (constantValObj is ulong) @@ -5641,7 +5641,7 @@ private string CreateManifestString() sb.AppendLine(" "); // Write out the keywords - if (keywordTab != null) + if (keywordTab is not null) { sb.AppendLine(" "); var sortedKeywords = new List(keywordTab.Keys); @@ -5679,7 +5679,7 @@ private string CreateManifestString() // Output the localization information. sb.AppendLine(""); - List cultures = (resources != null && (flags & EventManifestOptions.AllCultures) != 0) ? + List cultures = (resources is not null && (flags & EventManifestOptions.AllCultures) != 0) ? GetSupportedCultures() : new List() { CultureInfo.CurrentUICulture }; @@ -5715,14 +5715,14 @@ private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, { string key = elementName + "_" + name; // See if the user wants things localized. - if (resources != null) + if (resources is not null) { // resource fallback: strings in the neutral culture will take precedence over inline strings string? localizedString = resources.GetString(key, CultureInfo.InvariantCulture); - if (localizedString != null) + if (localizedString is not null) value = localizedString; } - if (value == null) + if (value is null) return; stringBuilder.Append(" message=\"$(string.").Append(key).Append(")\""); @@ -5738,10 +5738,10 @@ private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, internal string? GetLocalizedMessage(string key, CultureInfo ci, bool etwFormat) { string? value = null; - if (resources != null) + if (resources is not null) { string? localizedString = resources.GetString(key, ci); - if (localizedString != null) + if (localizedString is not null) { value = localizedString; if (etwFormat && key.StartsWith("event_", StringComparison.Ordinal)) @@ -5751,7 +5751,7 @@ private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, } } } - if (etwFormat && value == null) + if (etwFormat && value is null) stringTab.TryGetValue(key, out value); return value; @@ -5780,7 +5780,7 @@ private static string GetLevelName(EventLevel level) #if FEATURE_MANAGED_ETW_CHANNELS private string? GetChannelName(EventChannel channel, string eventName, string? eventMessage) { - if (channelTab == null || !channelTab.TryGetValue((int)channel, out ChannelInfo? info)) + if (channelTab is null || !channelTab.TryGetValue((int)channel, out ChannelInfo? info)) { if (channel < EventChannel.Admin) // || channel > EventChannel.Debug) ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName)); @@ -5798,11 +5798,11 @@ private static string GetLevelName(EventLevel level) ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName)); } // events that specify admin channels *must* have non-null "Message" attributes - if (resources != null) + if (resources is not null) eventMessage ??= resources.GetString("event_" + eventName, CultureInfo.InvariantCulture); - Debug.Assert(info!.Attribs != null); - if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage == null) + Debug.Assert(info!.Attribs is not null); + if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage is null) ManifestError(SR.Format(SR.EventSource_EventWithAdminChannelMustHaveMessage, eventName, info.Name)); return info.Name; } @@ -5846,7 +5846,7 @@ private string GetTaskName(EventTask task, string eventName) return "win:Receive"; } - if (opcodeTab == null || !opcodeTab.TryGetValue((int)opcode, out string? ret)) + if (opcodeTab is null || !opcodeTab.TryGetValue((int)opcode, out string? ret)) { ManifestError(SR.Format(SR.EventSource_UndefinedOpcode, opcode, eventName), true); ret = null; @@ -5869,14 +5869,14 @@ private string GetKeywords(ulong keywords, string eventName) if ((keywords & bit) != 0) { string? keyword = null; - if ((keywordTab == null || !keywordTab.TryGetValue(bit, out keyword)) && + if ((keywordTab is null || !keywordTab.TryGetValue(bit, out keyword)) && (bit >= (ulong)0x1000000000000)) { // do not report Windows reserved keywords in the manifest (this allows the code // to be resilient to potential renaming of these keywords) keyword = string.Empty; } - if (keyword == null) + if (keyword is null) { ManifestError(SR.Format(SR.EventSource_UndefinedKeyword, "0x" + bit.ToString("x", CultureInfo.CurrentCulture), eventName), true); keyword = string.Empty; @@ -5957,7 +5957,7 @@ private string TranslateToManifestConvention(string eventMessage, string evtName { if (i >= eventMessage.Length) { - if (stringBuilder == null) + if (stringBuilder is null) return eventMessage; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); return stringBuilder.ToString(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs index 3854d1c93cce6e..29ea6fcf05c2bd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs @@ -31,7 +31,7 @@ public partial class IncrementingPollingCounter : DiagnosticCounter /// The delegate to invoke to get the total value for this counter. public IncrementingPollingCounter(string name, EventSource eventSource, Func totalValueProvider) : base(name, eventSource) { - if (totalValueProvider == null) + if (totalValueProvider is null) throw new ArgumentNullException(nameof(totalValueProvider)); _totalValueProvider = totalValueProvider; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs index 12f0349067f0a6..a6b805ccc3e395 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs @@ -29,7 +29,7 @@ public partial class PollingCounter : DiagnosticCounter /// The delegate to invoke to get the current metric value. public PollingCounter(string name, EventSource eventSource, Func metricProvider) : base(name, eventSource) { - if (metricProvider == null) + if (metricProvider is null) throw new ArgumentNullException(nameof(metricProvider)); _metricProvider = metricProvider; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs index f009d70474e364..00cf10b68df82d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs @@ -38,7 +38,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu int count = 0; Array? array = (Array?)value.ReferenceValue; - if (array != null) + if (array is not null) { count = array.Length; for (int i = 0; i < array.Length; i++) @@ -52,7 +52,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu public override object? GetData(object? value) { - Debug.Assert(value != null, "null accepted only for some overrides"); + Debug.Assert(value is not null, "null accepted only for some overrides"); var array = (Array)value; var serializedArray = new object?[array.Length]; for (int i = 0; i < array.Length; i++) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs index a7fd4fabbd7852..695d20821431dd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs @@ -34,7 +34,7 @@ internal struct ConcurrentSet ItemType? item; ItemType[]? oldItems = this.items; - if (oldItems != null) + if (oldItems is not null) { int lo = 0; int hi = oldItems.Length; @@ -75,7 +75,7 @@ public ItemType GetOrAdd(ItemType newItem) Retry: - if (oldItems == null) + if (oldItems is null) { newItems = new ItemType[] { newItem }; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs index 19bf2e01fdc03f..1aa6594092c056 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs @@ -99,7 +99,7 @@ internal void AddScalar(void* value, int size) int oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); for (int i = 0; i != size; i++, oldPos++) { @@ -134,7 +134,7 @@ internal void AddBinary(string? value, int size) int oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); fixed (void* p = value) { @@ -147,7 +147,7 @@ internal void AddBinary(string? value, int size) internal void AddNullTerminatedString(string? value) { // Treat null strings as empty strings. - if (value == null) + if (value is null) { value = string.Empty; } @@ -176,7 +176,7 @@ internal void AddNullTerminatedString(string? value) int oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); fixed (void* p = value) { @@ -217,7 +217,7 @@ internal void AddArray(Array? value, int length, int itemSize) int oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); - Debug.Assert(value != null && buffer != null); + Debug.Assert(value is not null && buffer is not null); Buffer.BlockCopy(value, 0, this.buffer, oldPos, size); } } @@ -242,7 +242,7 @@ internal int BeginBufferedArray() internal void EndBufferedArray(int bookmark, int count) { this.EnsureBuffer(); - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); this.buffer[bookmark - 2] = unchecked((byte)count); this.buffer[bookmark - 1] = unchecked((byte)(count >> 8)); this.EndBuffered(); @@ -275,7 +275,7 @@ more efficient to buffer the array instead of pinning it. */ this.EnsureBuffer(); - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); this.PinArray(this.buffer, this.bufferPos); this.buffer = null; this.bufferPos = 0; @@ -285,7 +285,7 @@ more efficient to buffer the array instead of pinning it. private void EnsureBuffer() { int required = this.bufferPos; - if (this.buffer == null || this.buffer.Length < required) + if (this.buffer is null || this.buffer.Length < required) { this.GrowBuffer(required); } @@ -294,7 +294,7 @@ private void EnsureBuffer() private void EnsureBuffer(int additionalSize) { int required = this.bufferPos + additionalSize; - if (this.buffer == null || this.buffer.Length < required) + if (this.buffer is null || this.buffer.Length < required) { this.GrowBuffer(required); } @@ -302,7 +302,7 @@ private void EnsureBuffer(int additionalSize) private void GrowBuffer(int required) { - int newSize = this.buffer == null ? 64 : this.buffer.Length; + int newSize = this.buffer is null ? 64 : this.buffer.Length; do { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs index 605675116820fa..bd3e4ddc5c04f3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs @@ -42,7 +42,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu int count = 0; IEnumerable? enumerable = (IEnumerable?)value.ReferenceValue; - if (enumerable != null) + if (enumerable is not null) { foreach (object? element in enumerable) { @@ -56,7 +56,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu public override object? GetData(object? value) { - Debug.Assert(value != null, "null accepted only for some overrides"); + Debug.Assert(value is not null, "null accepted only for some overrides"); var iterType = (IEnumerable)value; List serializedEnumerable = new List(); foreach (object? element in iterType) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs index 615fdef28362dc..65b85b11d2e586 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs @@ -38,7 +38,7 @@ public class EventDataAttribute /// /// The name of the event will be determined as follows: /// - /// if (T has an EventData attribute and attribute.Name != null) + /// if (T has an EventData attribute and attribute.Name is not null) /// eventName = attribute.Name; /// else /// eventName = typeof(T).Name; @@ -49,7 +49,7 @@ public class EventDataAttribute /// /// The name of the field will be determined as follows: /// - /// if (T has an EventData attribute and attribute.Name != null) + /// if (T has an EventData attribute and attribute.Name is not null) /// fieldName = attribute.Name; /// else /// fieldName = typeof(T).Name; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs index 005ffb19f25dfa..b4cec07c4e8669 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs @@ -37,7 +37,7 @@ public object? this[string key] { get { - if (key == null) + if (key is null) throw new System.ArgumentNullException(nameof(key)); int position = 0; @@ -77,7 +77,7 @@ public bool Contains(KeyValuePair entry) public bool ContainsKey(string key) { - if (key == null) + if (key is null) throw new System.ArgumentNullException(nameof(key)); foreach (string item in m_names) @@ -123,7 +123,7 @@ public bool Remove(KeyValuePair entry) public bool TryGetValue(string key, [MaybeNullWhen(false)] out object? value) { - if (key == null) + if (key is null) throw new System.ArgumentNullException(nameof(key)); int position = 0; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs index bfd8d0ff989dda..5a4cab8f3da786 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs @@ -30,7 +30,7 @@ internal sealed class EventSourceActivity /// public EventSourceActivity(EventSource eventSource) { - if (eventSource == null) + if (eventSource is null) throw new ArgumentNullException(nameof(eventSource)); this.eventSource = eventSource; @@ -260,7 +260,7 @@ private void Write(EventSource eventSource, string? eventName, ref EventSourc { if (this.state != State.Started) throw new InvalidOperationException(); // Write after stop. - if (eventName == null) + if (eventName is null) throw new ArgumentNullException(); eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data); @@ -275,10 +275,10 @@ private void Stop(string? eventName, ref T data) if (!StartEventWasFired) return; - Debug.Assert(this.eventName != null); + Debug.Assert(this.eventName is not null); this.state = State.Stopped; - if (eventName == null) + if (eventName is null) { eventName = this.eventName; if (eventName.EndsWith("Start", StringComparison.Ordinal)) @@ -298,7 +298,7 @@ private enum State /// /// If eventName is non-null then we logged a start event /// - private bool StartEventWasFired => eventName != null; + private bool StartEventWasFired => eventName is not null; private readonly EventSource eventSource; private EventSourceOptions startStopOptions; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs index cd5db860c31a90..442d2ad1d1a6b7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs @@ -88,7 +88,7 @@ public FieldMetadata( type, tags, Statics.InTypeCustomCountFlag, - checked((ushort)(custom == null ? 0 : custom.Length)), + checked((ushort)(custom is null ? 0 : custom.Length)), custom) { } @@ -101,7 +101,7 @@ private FieldMetadata( ushort fixedCount = 0, byte[]? custom = null) { - if (name == null) + if (name is null) { throw new ArgumentNullException( nameof(name), @@ -170,14 +170,14 @@ public void IncrementStructFieldCount() public void Encode(ref int pos, byte[]? metadata) { // Write out the null terminated UTF8 encoded name - if (metadata != null) + if (metadata is not null) { Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos); } pos += this.nameSize; // Write 1 byte for inType - if (metadata != null) + if (metadata is not null) { metadata[pos] = this.inType; } @@ -186,7 +186,7 @@ public void Encode(ref int pos, byte[]? metadata) // If InTypeChainFlag set, then write out the outType if (0 != (this.inType & Statics.InTypeChainFlag)) { - if (metadata != null) + if (metadata is not null) { metadata[pos] = this.outType; } @@ -202,7 +202,7 @@ public void Encode(ref int pos, byte[]? metadata) // If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian) if (0 != (this.inType & Statics.InTypeFixedCountFlag)) { - if (metadata != null) + if (metadata is not null) { metadata[pos + 0] = unchecked((byte)this.fixedCount); metadata[pos + 1] = (byte)(this.fixedCount >> 8); @@ -213,9 +213,9 @@ public void Encode(ref int pos, byte[]? metadata) if (Statics.InTypeCustomCountFlag == (this.inType & Statics.InTypeCountMask) && this.fixedCount != 0) { - if (metadata != null) + if (metadata is not null) { - Debug.Assert(custom != null); + Debug.Assert(custom is not null); Buffer.BlockCopy(custom, 0, metadata, pos, this.fixedCount); } pos += this.fixedCount; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs index 23076a43710256..5e0c9a9f666f33 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs @@ -42,13 +42,13 @@ public override void WriteMetadata( EventFieldFormat format) { TraceLoggingMetadataCollector groupCollector = collector.AddGroup(name); - if (this.properties != null) + if (this.properties is not null) { foreach (PropertyAnalysis property in this.properties) { EventFieldFormat propertyFormat = EventFieldFormat.Default; EventFieldAttribute? propertyAttribute = property.fieldAttribute; - if (propertyAttribute != null) + if (propertyAttribute is not null) { groupCollector.Tags = propertyAttribute.Tags; propertyFormat = propertyAttribute.Format; @@ -64,7 +64,7 @@ public override void WriteMetadata( public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { - if (this.properties != null) + if (this.properties is not null) { foreach (PropertyAnalysis property in this.properties) { @@ -75,7 +75,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu public override object? GetData(object? value) { - if (this.properties != null) + if (this.properties is not null) { var membersNames = new List(); var membersValues = new List(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs index 201e878f68b0be..7249f6fd8cf7fc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs @@ -95,7 +95,7 @@ public IntPtr GetOrCreateEventHandle(EventProvider provider, TraceLoggingEventHa descriptor.Version, (EventOpcode)descriptor.Opcode, eventTypes); - uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; + uint metadataLength = (metadata is not null) ? (uint)metadata.Length : 0; unsafe { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs index 4218aaec8f50db..13b5e3fa130f8a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs @@ -32,7 +32,7 @@ private static TraceLoggingEventTypes InitInstance() var info = TraceLoggingTypeInfo.GetInstance(typeof(T), null); var newInstance = new TraceLoggingEventTypes(info.Name, info.Tags, new TraceLoggingTypeInfo[] { info }); Interlocked.CompareExchange(ref instance, newInstance, null); - Debug.Assert(instance != null); + Debug.Assert(instance is not null); return instance; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index 4b232538944dfa..d979cce34c48a7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -160,7 +160,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu public override object GetData(object? value) { - if (value == null) + if (value is null) { return ""; } @@ -293,7 +293,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu { // It's not currently possible to get the HasValue property of a nullable type through reflection when the // value is null. Instead, we simply check that the nullable is not null. - bool hasValue = value.ReferenceValue != null; + bool hasValue = value.ReferenceValue is not null; collector.AddScalar(hasValue); PropertyValue val = hasValue ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType)); this.valueInfo.WriteData(collector, val); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs index b7ad6be87d6bfa..d42cd2ab576a6d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -119,7 +119,7 @@ public static void EncodeTags(int tags, ref int pos, byte[]? metadata) current |= (byte)(more ? 0x80 : 0x00); tagsLeft <<= 7; - if (metadata != null) + if (metadata is not null) { metadata[pos] = current; } @@ -169,7 +169,7 @@ public static int Combine( public static void CheckName(string? name) { - if (name != null && 0 <= name.IndexOf('\0')) + if (name is not null && 0 <= name.IndexOf('\0')) { throw new ArgumentOutOfRangeException(nameof(name)); } @@ -362,7 +362,7 @@ public static bool HasCustomAttribute( foreach (Type ifaceType in ifaceTypes) { - if (elementType != null) + if (elementType is not null) { // ambiguous match. report no match at all. elementType = null; @@ -395,8 +395,8 @@ public static TraceLoggingTypeInfo CreateDefaultTypeInfo( recursionCheck.Add(dataType); EventDataAttribute? eventAttrib = Statics.GetCustomAttribute(dataType); - if (eventAttrib != null || - Statics.GetCustomAttribute(dataType) != null || + if (eventAttrib is not null || + Statics.GetCustomAttribute(dataType) is not null || IsGenericMatch(dataType, typeof(KeyValuePair<,>))) { var analysis = new TypeAnalysis(dataType, eventAttrib, recursionCheck); @@ -566,7 +566,7 @@ public static TraceLoggingTypeInfo CreateDefaultTypeInfo( else { Type? elementType = FindEnumerableElementType(dataType); - if (elementType != null) + if (elementType is not null) { result = new EnumerableTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs index cc9552970b1a1c..aca8b8f5ca2ceb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs @@ -112,13 +112,13 @@ public void AddNullTerminatedString(string? value) /// public void AddBinary(string? value) { - DataCollector.ThreadInstance.AddBinary(value, value == null ? 0 : value.Length * 2); + DataCollector.ThreadInstance.AddBinary(value, value is null ? 0 : value.Length * 2); } public void AddArray(PropertyValue value, int elementSize) { Array? array = (Array?)value.ReferenceValue; - DataCollector.ThreadInstance.AddArray(array, array == null ? 0 : array.Length, elementSize); + DataCollector.ThreadInstance.AddArray(array, array is null ? 0 : array.Length, elementSize); } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs index c6127beeb4cd08..e316db70e3ebac 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs @@ -80,11 +80,11 @@ public EventSource( EventSourceSettings config, params string[]? traits) : this( - eventSourceName == null ? default : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), + eventSourceName is null ? default : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName!, config, traits) { - if (eventSourceName == null) + if (eventSourceName is null) { throw new ArgumentNullException(nameof(eventSourceName)); } @@ -403,7 +403,7 @@ private unsafe void WriteMultiMergeInner( : eventTypes.keywords; NameInfo nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags); - if (nameInfo == null) + if (nameInfo is null) { return; } @@ -519,7 +519,7 @@ internal unsafe void WriteMultiMerge( fixed (EventSourceOptions* pOptions = &options) { NameInfo? nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out EventDescriptor descriptor); - if (nameInfo == null) + if (nameInfo is null) { return; } @@ -587,7 +587,7 @@ private unsafe void WriteImpl( { options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); NameInfo? nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out EventDescriptor descriptor); - if (nameInfo == null) + if (nameInfo is null) { return; } @@ -627,17 +627,17 @@ private unsafe void WriteImpl( Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; - if (pActivityId == null && pRelatedActivityId == null && + if (pActivityId is null && pRelatedActivityId is null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { - Debug.Assert(eventName != null, "GetOpcodeWithDefault should not returned Start when eventName is null"); + Debug.Assert(eventName is not null, "GetOpcodeWithDefault should not returned Start when eventName is null"); m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { - Debug.Assert(eventName != null, "GetOpcodeWithDefault should not returned Stop when eventName is null"); + Debug.Assert(eventName is not null, "GetOpcodeWithDefault should not returned Stop when eventName is null"); m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) @@ -671,7 +671,7 @@ private unsafe void WriteImpl( #endif // FEATURE_MANAGED_ETW // TODO enable filtering for listeners. - if (m_Dispatchers != null) + if (m_Dispatchers is not null) { var eventData = (EventPayload?)(eventTypes.typeInfos[0].GetData(data)); WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, pRelatedActivityId, eventData); @@ -713,12 +713,12 @@ private unsafe void WriteToAllListeners(string? eventName, ref EventDescriptor e // Self described events do not have an id attached. We mark it internally with -1. eventCallbackArgs.EventId = -1; - if (pActivityId != null) + if (pActivityId is not null) eventCallbackArgs.ActivityId = *pActivityId; - if (pChildActivityId != null) + if (pChildActivityId is not null) eventCallbackArgs.RelatedActivityId = *pChildActivityId; - if (payload != null) + if (payload is not null) { eventCallbackArgs.Payload = new ReadOnlyCollection((IList)payload.Values); eventCallbackArgs.PayloadNames = new ReadOnlyCollection((IList)payload.Keys); @@ -749,7 +749,7 @@ private static unsafe void WriteCleanup(GCHandle* pPins, int cPins) private void InitializeProviderMetadata() { #if FEATURE_MANAGED_ETW - if (m_traits != null) + if (m_traits is not null) { List traitMetaData = new List(100); for (int i = 0; i < m_traits.Length - 1; i += 2) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs index 3791d6001943fd..1a8d67a489f16c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs @@ -87,7 +87,7 @@ internal TraceLoggingEventTypes( EventTags tags, System.Reflection.ParameterInfo[] paramInfos) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -126,7 +126,7 @@ private TraceLoggingEventTypes( string defaultName, TraceLoggingTypeInfo[] typeInfos) { - if (defaultName == null) + if (defaultName is null) { throw new ArgumentNullException(nameof(defaultName)); } @@ -182,7 +182,7 @@ internal NameInfo GetNameInfo(string name, EventTags tags) => private TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] paramInfos) { - if (paramInfos == null) + if (paramInfos is null) { throw new ArgumentNullException(nameof(paramInfos)); } @@ -199,7 +199,7 @@ private TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] param private static TraceLoggingTypeInfo[] MakeArray(Type[] types) { - if (types == null) + if (types is null) { throw new ArgumentNullException(nameof(types)); } @@ -217,7 +217,7 @@ private static TraceLoggingTypeInfo[] MakeArray(Type[] types) private static TraceLoggingTypeInfo[] MakeArray( TraceLoggingTypeInfo[] typeInfos) { - if (typeInfos == null) + if (typeInfos is null) { throw new ArgumentNullException(nameof(typeInfos)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs index e0f2943cbce757..748d16e5f6c8d4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs @@ -83,7 +83,7 @@ public TraceLoggingMetadataCollector AddGroup(string? name) { TraceLoggingMetadataCollector result = this; - if (name != null || // Normal. + if (name is not null || // Normal. this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception. { var newGroup = new FieldMetadata( @@ -307,7 +307,7 @@ private void AddField(FieldMetadata fieldMetadata) this.bufferedArrayFieldCount++; this.impl.fields.Add(fieldMetadata); - if (this.currentGroup != null) + if (this.currentGroup is not null) { this.currentGroup.IncrementStructFieldCount(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs index 8d65c00e88de43..2615579cb88aeb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs @@ -29,7 +29,7 @@ internal abstract class TraceLoggingTypeInfo internal TraceLoggingTypeInfo(Type dataType) { - if (dataType == null) + if (dataType is null) { throw new ArgumentNullException(nameof(dataType)); } @@ -47,12 +47,12 @@ internal TraceLoggingTypeInfo( EventKeywords keywords, EventTags tags) { - if (dataType == null) + if (dataType is null) { throw new ArgumentNullException(nameof(dataType)); } - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs index 0324f31563bba9..8d00a065dc19a2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs @@ -46,7 +46,7 @@ public TypeAnalysis( } MethodInfo? getterInfo = propertyInfo.GetGetMethod(); - if (getterInfo == null) + if (getterInfo is null) { continue; } @@ -61,7 +61,7 @@ public TypeAnalysis( EventFieldAttribute? fieldAttribute = Statics.GetCustomAttribute(propertyInfo); string propertyName = - fieldAttribute != null && fieldAttribute.Name != null + fieldAttribute is not null && fieldAttribute.Name is not null ? fieldAttribute.Name : Statics.ShouldOverrideFieldName(propertyInfo.Name) ? propertyTypeInfo.Name @@ -84,7 +84,7 @@ public TypeAnalysis( this.tags |= typeInfo.Tags; } - if (eventAttrib != null) + if (eventAttrib is not null) { this.level = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode); @@ -93,7 +93,7 @@ public TypeAnalysis( this.name = eventAttrib.Name; } - if (this.name == null) + if (this.name is null) { this.name = dataType.Name; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/XplatEventLogger.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/XplatEventLogger.cs index abe2362a0b18a1..e10651d44a26aa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/XplatEventLogger.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/XplatEventLogger.cs @@ -74,7 +74,7 @@ private static void minimalJsonserializer(string payload, StringBuilder sb) private static string Serialize(ReadOnlyCollection? payloadName, ReadOnlyCollection? payload, string? eventMessage) { - if (payloadName == null || payload == null) + if (payloadName is null || payload is null) return string.Empty; if (payloadName.Count == 0 || payload.Count == 0) @@ -131,7 +131,7 @@ private static string Serialize(ReadOnlyCollection? payloadName, ReadOnl } default: { - if (payload[i] != null) + if (payload[i] is not null) { sb.Append(payload[i]!.ToString()); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } @@ -145,8 +145,8 @@ private static string Serialize(ReadOnlyCollection? payloadName, ReadOnl private static void AppendByteArrayAsHexString(StringBuilder builder, byte[] byteArray) { - Debug.Assert(builder != null); - Debug.Assert(byteArray != null); + Debug.Assert(builder is not null); + Debug.Assert(byteArray is not null); ReadOnlySpan hexFormat = "X2"; Span hex = stackalloc char[2]; @@ -185,7 +185,7 @@ protected internal override void OnEventWritten(EventWrittenEventArgs eventData) private static void LogOnEventWritten(EventWrittenEventArgs eventData) { string payload = ""; - if (eventData.Payload != null) + if (eventData.Payload is not null) { try { diff --git a/src/libraries/System.Private.CoreLib/src/System/Double.cs b/src/libraries/System.Private.CoreLib/src/System/Double.cs index 2aba7894f4e846..50d40c407f4424 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Double.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Double.cs @@ -161,7 +161,7 @@ internal static ulong ExtractSignificandFromBits(ulong bits) // public int CompareTo(object? value) { - if (value == null) + if (value is null) { return 1; } @@ -283,27 +283,27 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan public static double Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static double Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, style, NumberFormatInfo.CurrentInfo); } public static double Parse(string s, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static double Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider)); } @@ -323,7 +323,7 @@ public static double Parse(ReadOnlySpan s, NumberStyles style = NumberStyl public static bool TryParse([NotNullWhen(true)] string? s, out double result) { - if (s == null) + if (s is null) { result = 0; return false; @@ -341,7 +341,7 @@ public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, I { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); - if (s == null) + if (s is null) { result = 0; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Enum.cs index 38ed61a36610cb..939aa3b9371013 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Enum.cs @@ -140,7 +140,7 @@ private static string ValueToHexString(object value) private static string? InternalFlagsFormat(RuntimeType enumType, EnumInfo enumInfo, ulong resultValue) { - Debug.Assert(enumType != null); + Debug.Assert(enumType is not null); string[] names = enumInfo.Names; ulong[] values = enumInfo.Values; @@ -291,7 +291,7 @@ internal static string[] InternalGetNames(RuntimeType enumType) public static Type GetUnderlyingType(Type enumType) { - if (enumType == null) + if (enumType is null) throw new ArgumentNullException(nameof(enumType)); return enumType.GetEnumUnderlyingType(); @@ -379,7 +379,7 @@ private static bool TryParse(Type enumType, string? value, bool ignoreCase, bool { if (throwOnFailure) { - throw value == null ? + throw value is null ? new ArgumentNullException(nameof(value)) : new ArgumentException(SR.Arg_MustContainEnumInfo, nameof(value)); } @@ -458,7 +458,7 @@ private static bool TryParse(string? value, bool ignoreCase, bool throwOn { if (throwOnFailure) { - throw value == null ? + throw value is null ? new ArgumentNullException(nameof(value)) : new ArgumentException(SR.Arg_MustContainEnumInfo, nameof(value)); } @@ -805,7 +805,7 @@ private static bool TryParseByName(RuntimeType enumType, string? originalValueSt public static object ToObject(Type enumType, object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // Delegate rest of error checking to the other functions @@ -831,10 +831,10 @@ public static string Format(Type enumType, object value, string format) { RuntimeType rtType = ValidateRuntimeType(enumType); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (format == null) + if (format is null) throw new ArgumentNullException(nameof(format)); // If the value is an Enum then we need to extract the underlying value from it @@ -991,7 +991,7 @@ public int CompareTo(object? target) if (target == this) return 0; - if (target == null) + if (target is null) return 1; // all values are greater than null if (GetType() != target.GetType()) @@ -1225,7 +1225,7 @@ private static object ToObject(Type enumType, bool value) => private static RuntimeType ValidateRuntimeType(Type enumType) { - if (enumType == null) + if (enumType is null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.OSVersion.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.OSVersion.Unix.cs index ecbf02022a3a27..3be82e4435bc9d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.OSVersion.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.OSVersion.Unix.cs @@ -15,7 +15,7 @@ private static OperatingSystem GetOperatingSystem(string release) // Parse the uname's utsname.release for the first four numbers found. // This isn't perfect, but Version already doesn't map exactly to all possible release // formats, e.g. 2.6.19-1.2895.fc6 - if (release != null) + if (release is not null) { int i = 0; major = FindAndParseNextNumber(release, ref i); diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.UnixOrBrowser.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.UnixOrBrowser.cs index 588e1dbf57d180..0865d11ae3c741 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.UnixOrBrowser.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.UnixOrBrowser.cs @@ -31,7 +31,7 @@ private static string ExpandEnvironmentVariablesCore(string name) { string key = name.Substring(lastPos + 1, pos - lastPos - 1); string? value = GetEnvironmentVariable(key); - if (value != null) + if (value is not null) { result.Append(value); lastPos = pos + 1; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Variables.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Variables.Windows.cs index 15f027c202e65e..fd2ae25b38ff9a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Variables.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Variables.Windows.cs @@ -59,7 +59,7 @@ private static void SetEnvironmentVariableCore(string variable, string? value) public static unsafe IDictionary GetEnvironmentVariables() { char* pStrings = Interop.Kernel32.GetEnvironmentStrings(); - if (pStrings == null) + if (pStrings is null) { throw new OutOfMemoryException(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs index ca769085b173f1..cb9f5610d231dc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs @@ -17,7 +17,7 @@ public static partial class Environment private static string? GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) { - Debug.Assert(variable != null); + Debug.Assert(variable is not null); using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) { @@ -27,7 +27,7 @@ public static partial class Environment private static void SetEnvironmentVariableFromRegistry(string variable, string? value, bool fromMachine) { - Debug.Assert(variable != null); + Debug.Assert(variable is not null); const int MaxUserEnvVariableLength = 255; // User-wide env vars stored in the registry have names limited to 255 chars if (!fromMachine && variable.Length >= MaxUserEnvVariableLength) @@ -37,9 +37,9 @@ private static void SetEnvironmentVariableFromRegistry(string variable, string? using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: true)) { - if (environmentKey != null) + if (environmentKey is not null) { - if (value == null) + if (value is null) { environmentKey.DeleteValue(variable, throwOnMissingValue: false); } @@ -67,7 +67,7 @@ private static IDictionary GetEnvironmentVariablesFromRegistry(bool fromMachine) using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) { - if (environmentKey != null) + if (environmentKey is not null) { foreach (string name in environmentKey.GetValueNames()) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.cs index 15e19465cae31d..5910e994ffb374 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.cs @@ -22,7 +22,7 @@ public static partial class Environment public static string? GetEnvironmentVariable(string variable) { - if (variable == null) + if (variable is null) throw new ArgumentNullException(nameof(variable)); return GetEnvironmentVariableCore(variable); @@ -33,7 +33,7 @@ public static partial class Environment if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariable(variable); - if (variable == null) + if (variable is null) throw new ArgumentNullException(nameof(variable)); bool fromMachine = ValidateAndConvertRegistryTarget(target); @@ -76,7 +76,7 @@ public static string CurrentDirectory get => CurrentDirectoryCore; set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) @@ -88,7 +88,7 @@ public static string CurrentDirectory public static string ExpandEnvironmentVariables(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) @@ -150,13 +150,13 @@ public static string? ProcessPath get { string? processPath = s_processPath; - if (processPath == null) + if (processPath is null) { // The value is cached both as a performance optimization and to ensure that the API always returns // the same path in a given process. Interlocked.CompareExchange(ref s_processPath, GetProcessPath() ?? "", null); processPath = s_processPath; - Debug.Assert(processPath != null); + Debug.Assert(processPath is not null); } return (processPath.Length != 0) ? processPath : null; } @@ -175,11 +175,11 @@ public static OperatingSystem OSVersion get { OperatingSystem? osVersion = s_osVersion; - if (osVersion == null) + if (osVersion is null) { Interlocked.CompareExchange(ref s_osVersion, GetOSVersion(), null); osVersion = s_osVersion; - Debug.Assert(osVersion != null); + Debug.Assert(osVersion is not null); } return osVersion; } @@ -218,7 +218,7 @@ private static bool ValidateAndConvertRegistryTarget(EnvironmentVariableTarget t private static void ValidateVariableAndValue(string variable, ref string? value) { - if (variable == null) + if (variable is null) throw new ArgumentNullException(nameof(variable)); if (variable.Length == 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Gen2GcCallback.cs b/src/libraries/System.Private.CoreLib/src/System/Gen2GcCallback.cs index 949c5334d48e19..ff4557ee9281c8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Gen2GcCallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Gen2GcCallback.cs @@ -57,7 +57,7 @@ public static void Register(Func callback, object targetObj) { // Check to see if the target object is still alive. object? targetObj = _weakTargetObj.Target; - if (targetObj == null) + if (targetObj is null) { // The target object is dead, so this callback object is no longer needed. _weakTargetObj.Free(); @@ -67,7 +67,7 @@ public static void Register(Func callback, object targetObj) // Execute the callback method. try { - Debug.Assert(_callback1 != null); + Debug.Assert(_callback1 is not null); if (!_callback1(targetObj)) { // If the callback returns false, this callback object is no longer needed. @@ -88,7 +88,7 @@ public static void Register(Func callback, object targetObj) // Execute the callback method. try { - Debug.Assert(_callback0 != null); + Debug.Assert(_callback0 is not null); if (!_callback0()) { // If the callback returns false, this callback object is no longer needed. diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs index beb0d3fa7cad6e..4307dbd8dd3bc6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs @@ -84,7 +84,7 @@ public virtual object Clone() public static Calendar ReadOnly(Calendar calendar) { - if (calendar == null) + if (calendar is null) { throw new ArgumentNullException(nameof(calendar)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs index af5db2379c4dbc..5cc8badadf7263 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs @@ -41,7 +41,7 @@ private bool IcuLoadCalendarDataFromSystem(string localeName, CalendarId calenda result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName!); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay!); - if (this.sMonthDay != null) + if (this.sMonthDay is not null) { this.sMonthDay = NormalizeDatePattern(this.sMonthDay); } @@ -55,9 +55,9 @@ private bool IcuLoadCalendarDataFromSystem(string localeName, CalendarId calenda string? leapHebrewMonthName = null; result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames!, ref leapHebrewMonthName); - if (leapHebrewMonthName != null) + if (leapHebrewMonthName is not null) { - Debug.Assert(this.saMonthNames != null); + Debug.Assert(this.saMonthNames is not null); // In Hebrew calendar, get the leap month name Adar II and override the non-leap month 7 Debug.Assert(calendarId == CalendarId.HEBREW && saMonthNames.Length == 13); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Nls.cs index ea0bcbb8026955..bb0f59f0b2b7c4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Nls.cs @@ -81,7 +81,7 @@ private static unsafe Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfo // If we had a user override, check to make sure this differs if (context.userOverride != calendarInfo) { - Debug.Assert(context.strings != null); + Debug.Assert(context.strings is not null); context.strings.Add(calendarInfo); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs index 8f89619276ffa5..def8b0f3c07711 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs @@ -66,7 +66,7 @@ private bool LoadCalendarDataFromSystemCore(string localeName, CalendarId calend private void InsertOrSwapOverride(string? value, ref string[] destination) { - if (value == null) + if (value is null) return; for (int i = 0; i < destination.Length; i++) @@ -254,7 +254,7 @@ private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId ca string? res = CultureData.GetLocaleInfoEx(localeName, lcType); // if it succeeded remember the override for the later callers - if (res != null) + if (res is not null) { // Remember this was the override (so we can look for duplicates later in the enum function) context.userOverride = res; @@ -269,7 +269,7 @@ private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId ca Interop.Kernel32.EnumCalendarInfoExEx(&EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref context)); // Now we have a list of data, fail if we didn't find anything. - Debug.Assert(context.strings != null); + Debug.Assert(context.strings is not null); if (context.strings.Count == 0) { data = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.cs index e1c1b71252012a..6c9cd198e08807 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.cs @@ -147,11 +147,11 @@ internal CalendarData(string localeName, CalendarId calendarId, bool bUseUserOve } // Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc) - if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saMonthGenitiveNames[0])) + if (this.saMonthGenitiveNames is null || this.saMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saMonthGenitiveNames[0])) this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant) - if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) + if (this.saAbbrevMonthGenitiveNames is null || this.saAbbrevMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) - if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || string.IsNullOrEmpty(this.saLeapYearMonthNames[0])) + if (this.saLeapYearMonthNames is null || this.saLeapYearMonthNames.Length == 0 || string.IsNullOrEmpty(this.saLeapYearMonthNames[0])) this.saLeapYearMonthNames = this.saMonthNames; InitializeEraNames(localeName, calendarId); @@ -182,7 +182,7 @@ private void InitializeEraNames(string localeName, CalendarId calendarId) // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing - if (this.saEraNames == null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) + if (this.saEraNames is null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new string[] { "A.D." }; } @@ -244,7 +244,7 @@ private void InitializeEraNames(string localeName, CalendarId calendarId) break; case CalendarId.PERSIAN: - if (this.saEraNames == null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) + if (this.saEraNames is null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new string[] { "\x0647\x002e\x0634" }; } @@ -265,7 +265,7 @@ private void InitializeAbbreviatedEraNames(string localeName, CalendarId calenda // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing - if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) + if (this.saAbbrevEraNames is null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = new string[] { "AD" }; } @@ -306,7 +306,7 @@ private void InitializeAbbreviatedEraNames(string localeName, CalendarId calenda break; case CalendarId.PERSIAN: - if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) + if (this.saAbbrevEraNames is null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = this.saEraNames; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CharUnicodeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CharUnicodeInfo.cs index ad0056c4ec3e55..3c5bec1920060c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CharUnicodeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CharUnicodeInfo.cs @@ -54,7 +54,7 @@ internal static StrongBidiCategory GetBidiCategory(string s, int index) internal static StrongBidiCategory GetBidiCategory(StringBuilder s, int index) { - Debug.Assert(s != null, "s != null"); + Debug.Assert(s is not null, "s is not null"); Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); // The logic below follows Table 3-5 in the Unicode Standard, Sec. 3.9. @@ -293,7 +293,7 @@ public static UnicodeCategory GetUnicodeCategory(string s, int index) /// internal static UnicodeCategory GetUnicodeCategoryInternal(string value, int index) { - Debug.Assert(value != null, "value can not be null"); + Debug.Assert(value is not null, "value can not be null"); Debug.Assert(index < value.Length, "index < value.Length"); return GetUnicodeCategoryNoBoundsChecks((uint)GetCodePointFromString(value, index)); @@ -305,7 +305,7 @@ internal static UnicodeCategory GetUnicodeCategoryInternal(string value, int ind /// internal static UnicodeCategory GetUnicodeCategoryInternal(string str, int index, out int charLength) { - Debug.Assert(str != null, "str can not be null"); + Debug.Assert(str is not null, "str can not be null"); Debug.Assert(str.Length > 0, "str.Length > 0"); Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); @@ -339,7 +339,7 @@ private static UnicodeCategory GetUnicodeCategoryNoBoundsChecks(uint codePoint) /// private static int GetCodePointFromString(string s, int index) { - Debug.Assert(s != null, "s != null"); + Debug.Assert(s is not null, "s is not null"); Debug.Assert((uint)index < (uint)s.Length, "index < s.Length"); int codePoint = 0; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs index 4d27d9e881e493..c252d0be80a64d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs @@ -172,7 +172,7 @@ private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, Rea // The match may be affected by special character. Verify that the following character is regular ASCII. if (sourceIndex < source.Length && *(a + sourceIndex) >= 0x80) goto InteropCall; - if (matchLengthPtr != null) + if (matchLengthPtr is not null) *matchLengthPtr = target.Length; return i; @@ -265,7 +265,7 @@ private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan< // The match may be affected by special character. Verify that the following character is regular ASCII. if (sourceIndex < source.Length && *(a + sourceIndex) >= 0x80) goto InteropCall; - if (matchLengthPtr != null) + if (matchLengthPtr is not null) *matchLengthPtr = target.Length; return i; @@ -372,7 +372,7 @@ private unsafe bool StartsWithOrdinalIgnoreCaseHelper(ReadOnlySpan source, goto InteropCall; } - if (matchLengthPtr != null) + if (matchLengthPtr is not null) { *matchLengthPtr = prefix.Length; // non-linguistic match doesn't change UTF-16 length } @@ -436,7 +436,7 @@ private unsafe bool StartsWithOrdinalHelper(ReadOnlySpan source, ReadOnlyS goto InteropCall; } - if (matchLengthPtr != null) + if (matchLengthPtr is not null) { *matchLengthPtr = prefix.Length; // non-linguistic match doesn't change UTF-16 length } @@ -537,7 +537,7 @@ private unsafe bool EndsWithOrdinalIgnoreCaseHelper(ReadOnlySpan source, R goto InteropCall; } - if (matchLengthPtr != null) + if (matchLengthPtr is not null) { *matchLengthPtr = suffix.Length; // non-linguistic match doesn't change UTF-16 length } @@ -601,7 +601,7 @@ private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan source, ReadOnlySpa goto InteropCall; } - if (matchLengthPtr != null) + if (matchLengthPtr is not null) { *matchLengthPtr = suffix.Length; // non-linguistic match doesn't change UTF-16 length } @@ -739,7 +739,7 @@ private unsafe int IcuGetHashCodeOfString(ReadOnlySpan source, CompareOpti if (sortKeyLength > sortKey.Length) // slow path for big strings { - if (borrowedArray != null) + if (borrowedArray is not null) { ArrayPool.Shared.Return(borrowedArray); } @@ -760,7 +760,7 @@ private unsafe int IcuGetHashCodeOfString(ReadOnlySpan source, CompareOpti int hash = Marvin.ComputeHash32(sortKey.Slice(0, sortKeyLength), Marvin.DefaultSeed); - if (borrowedArray != null) + if (borrowedArray is not null) { ArrayPool.Shared.Return(borrowedArray); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs index b1033b5f2b4e5d..d413b9ebb0bf72 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs @@ -11,8 +11,8 @@ public partial class CompareInfo { internal static unsafe int InvariantIndexOf(string source, string value, int startIndex, int count, bool ignoreCase) { - Debug.Assert(source != null); - Debug.Assert(value != null); + Debug.Assert(source is not null); + Debug.Assert(value is not null); Debug.Assert(startIndex >= 0 && startIndex < source.Length); fixed (char* pSource = source) fixed (char* pValue = value) @@ -42,7 +42,7 @@ internal static unsafe int InvariantIndexOf(ReadOnlySpan source, ReadOnlyS internal static unsafe int InvariantLastIndexOf(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!string.IsNullOrEmpty(source)); - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(startIndex >= 0 && startIndex < source.Length); fixed (char* pSource = source) fixed (char* pValue = value) @@ -65,8 +65,8 @@ private static unsafe int InvariantFindString(char* source, int sourceCount, cha char valueChar; // Character for case lookup in value int lastSourceStart; - Debug.Assert(source != null); - Debug.Assert(value != null); + Debug.Assert(source is not null); + Debug.Assert(value is not null); Debug.Assert(sourceCount >= 0); Debug.Assert(valueCount >= 0); @@ -215,7 +215,7 @@ private static char InvariantCaseFold(char c) private SortKey InvariantCreateSortKey(string source, CompareOptions options) { - if (source == null) { throw new ArgumentNullException(nameof(source)); } + if (source is null) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidCompareMaskOffFlags) != 0) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs index 396b3b0c699a59..7a7fe7d41a94d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs @@ -54,8 +54,8 @@ private static unsafe int FindStringOrdinal( fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) { - Debug.Assert(pSource != null); - Debug.Assert(pValue != null); + Debug.Assert(pSource is not null); + Debug.Assert(pValue is not null); int ret = Interop.Kernel32.FindStringOrdinal( dwFindStringOrdinalFlags, @@ -91,8 +91,8 @@ internal static int NlsLastIndexOfOrdinalCore(string source, string value, int s Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(source != null); - Debug.Assert(value != null); + Debug.Assert(source is not null); + Debug.Assert(value is not null); int offset = startIndex - count + 1; int result = FindStringOrdinal(FIND_FROMEND, source.AsSpan(offset, count), value, ignoreCase); @@ -172,7 +172,7 @@ private unsafe int NlsGetHashCodeOfString(ReadOnlySpan source, CompareOpti int hash = Marvin.ComputeHash32(span.Slice(0, sortKeyLength), Marvin.DefaultSeed); // Return the borrowed array if necessary. - if (borrowedArr != null) + if (borrowedArr is not null) { ArrayPool.Shared.Return(borrowedArr); } @@ -192,8 +192,8 @@ internal static unsafe int NlsCompareStringOrdinalIgnoreCase(ref char string1, i fixed (char* char1 = &string1) fixed (char* char2 = &string2) { - Debug.Assert(char1 != null); - Debug.Assert(char2 != null); + Debug.Assert(char1 is not null); + Debug.Assert(char2 is not null); // Use the OS to compare and then convert the result to expected value by subtracting 2 int result = Interop.Kernel32.CompareStringOrdinal(char1, count1, char2, count2, bIgnoreCase: true); @@ -283,7 +283,7 @@ private unsafe int FindString( fixed (char* pSource = &MemoryMarshal.GetReference(lpStringSource)) fixed (char* pValue = &MemoryMarshal.GetReference(lpStringValue)) { - Debug.Assert(pSource != null && pValue != null); + Debug.Assert(pSource is not null && pValue is not null); int result = Interop.Kernel32.FindNLSStringEx( pLocaleName, @@ -328,7 +328,7 @@ private unsafe bool NlsStartsWith(ReadOnlySpan source, ReadOnlySpan int idx = FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, prefix, matchLengthPtr); if (idx >= 0) { - if (matchLengthPtr != null) + if (matchLengthPtr is not null) { *matchLengthPtr += idx; // account for chars we skipped at the front of the string } @@ -349,7 +349,7 @@ private unsafe bool NlsEndsWith(ReadOnlySpan source, ReadOnlySpan su int idx = FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, suffix, pcchFound: null); if (idx >= 0) { - if (matchLengthPtr != null) + if (matchLengthPtr is not null) { *matchLengthPtr = source.Length - idx; // all chars from idx to the end of the string are consumed } @@ -371,7 +371,7 @@ private unsafe SortKey NlsCreateSortKey(string source, CompareOptions options) Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - if (source == null) { throw new ArgumentNullException(nameof(source)); } + if (source is null) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidCompareMaskOffFlags) != 0) { @@ -464,8 +464,8 @@ private unsafe int NlsGetSortKey(ReadOnlySpan source, Span destinati fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (byte* pSortKey = &MemoryMarshal.GetReference(destination)) { - Debug.Assert(pSource != null); - Debug.Assert(pSortKey != null); + Debug.Assert(pSource is not null); + Debug.Assert(pSortKey is not null); #if TARGET_WINDOWS if (!Environment.IsWindows8OrAbove) @@ -542,7 +542,7 @@ private unsafe int NlsGetSortKeyLength(ReadOnlySpan source, CompareOptions fixed (char* pSource = &MemoryMarshal.GetReference(source)) { - Debug.Assert(pSource != null); + Debug.Assert(pSource is not null); sortKeyLength = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, flags, pSource, sourceLength, diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs index 148daeb0aed624..59de5d263e4b01 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs @@ -65,7 +65,7 @@ internal CompareInfo(CultureInfo culture) public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { // Parameter checking. - if (assembly == null) + if (assembly is null) { throw new ArgumentNullException(nameof(assembly)); } @@ -84,11 +84,11 @@ public static CompareInfo GetCompareInfo(int culture, Assembly assembly) /// public static CompareInfo GetCompareInfo(string name, Assembly assembly) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } - if (assembly == null) + if (assembly is null) { throw new ArgumentNullException(nameof(assembly)); } @@ -119,7 +119,7 @@ public static CompareInfo GetCompareInfo(int culture) /// public static CompareInfo GetCompareInfo(string name) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -134,7 +134,7 @@ public static bool IsSortable(char ch) public static bool IsSortable(string text) { - if (text == null) + if (text is null) { throw new ArgumentNullException(nameof(text)); } @@ -217,7 +217,7 @@ private void OnDeserialized(StreamingContext ctx) private void OnDeserialized() { // If we didn't have a name, use the LCID - if (m_name == null) + if (m_name is null) { // From whidbey, didn't have a name m_name = CultureInfo.GetCultureInfo(culture)._name; @@ -233,7 +233,7 @@ private void OnSerializing(StreamingContext ctx) { // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more. culture = CultureInfo.GetCultureInfo(Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort) - Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); + Debug.Assert(m_name is not null, "CompareInfo.OnSerializing - expected m_name to be set already"); } /// @@ -250,7 +250,7 @@ public string Name { get { - Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set"); + Debug.Assert(m_name is not null, "CompareInfo.Name Expected _name to be set"); if (m_name == "zh-CHT" || m_name == "zh-CHS") { return m_name; @@ -278,12 +278,12 @@ public int Compare(string? string1, string? string2, CompareOptions options) // Our paradigm is that null sorts less than any other string and // that two nulls sort as equal. - if (string1 == null) + if (string1 is null) { - retVal = (string2 == null) ? 0 : -1; + retVal = (string2 is null) ? 0 : -1; goto CheckOptionsAndReturn; } - if (string2 == null) + if (string2 is null) { retVal = 1; goto CheckOptionsAndReturn; @@ -321,8 +321,8 @@ public int Compare(string? string1, int offset1, int length1, string? string2, i public int Compare(string? string1, int offset1, string? string2, int offset2, CompareOptions options) { - return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1, - string2, offset2, string2 == null ? 0 : string2.Length - offset2, options); + return Compare(string1, offset1, string1 is null ? 0 : string1.Length - offset1, + string2, offset2, string2 is null ? 0 : string2.Length - offset2, options); } public int Compare(string? string1, int offset1, string? string2, int offset2) @@ -335,7 +335,7 @@ public int Compare(string? string1, int offset1, int length1, string? string2, i ReadOnlySpan span1 = default; ReadOnlySpan span2 = default; - if (string1 == null) + if (string1 is null) { if (offset1 != 0 || length1 != 0) { @@ -347,7 +347,7 @@ public int Compare(string? string1, int offset1, int length1, string? string2, i goto BoundsCheckError; } - if (string2 == null) + if (string2 is null) { if (offset2 != 0 || length2 != 0) { @@ -366,12 +366,12 @@ public int Compare(string? string1, int offset1, int length1, string? string2, i // Our paradigm is that null sorts less than any other string and // that two nulls sort as equal. - if (string1 == null) + if (string1 is null) { - retVal = (string2 == null) ? 0 : -1; + retVal = (string2 is null) ? 0 : -1; goto CheckOptionsAndReturn; } - if (string2 == null) + if (string2 is null) { retVal = 1; goto CheckOptionsAndReturn; @@ -408,12 +408,12 @@ public int Compare(string? string1, int offset1, int length1, string? string2, i throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum); } - if (offset1 > (string1 == null ? 0 : string1.Length) - length1) + if (offset1 > (string1 is null ? 0 : string1.Length) - length1) { throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength); } - Debug.Assert(offset2 > (string2 == null ? 0 : string2.Length) - length2); + Debug.Assert(offset2 > (string2 is null ? 0 : string2.Length) - length2); throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength); } @@ -516,11 +516,11 @@ private unsafe int CompareStringCore(ReadOnlySpan string1, ReadOnlySpan public bool IsPrefix(string source, string prefix, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (prefix == null) + if (prefix is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.prefix); } @@ -654,11 +654,11 @@ public bool IsPrefix(string source, string prefix) /// public bool IsSuffix(string source, string suffix, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (suffix == null) + if (suffix is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.suffix); } @@ -806,7 +806,7 @@ public int IndexOf(string source, string value) public int IndexOf(string source, char value, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -816,11 +816,11 @@ public int IndexOf(string source, char value, CompareOptions options) public int IndexOf(string source, string value, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } @@ -840,7 +840,7 @@ public int IndexOf(string source, string value, int startIndex) public int IndexOf(string source, char value, int startIndex, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -851,7 +851,7 @@ public int IndexOf(string source, char value, int startIndex, CompareOptions opt public int IndexOf(string source, string value, int startIndex, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -871,7 +871,7 @@ public int IndexOf(string source, string value, int startIndex, int count) public unsafe int IndexOf(string source, char value, int startIndex, int count, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -901,11 +901,11 @@ public unsafe int IndexOf(string source, char value, int startIndex, int count, public unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } @@ -1051,7 +1051,7 @@ public int IndexOf(ReadOnlySpan source, Rune value, CompareOptions options /// private unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, int* matchLengthPtr, CompareOptions options, bool fromBeginning) { - Debug.Assert(matchLengthPtr != null); + Debug.Assert(matchLengthPtr is not null); *matchLengthPtr = 0; int retVal = 0; @@ -1139,7 +1139,7 @@ public int LastIndexOf(string source, string value) public int LastIndexOf(string source, char value, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -1149,11 +1149,11 @@ public int LastIndexOf(string source, char value, CompareOptions options) public int LastIndexOf(string source, string value, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } @@ -1193,7 +1193,7 @@ public int LastIndexOf(string source, string value, int startIndex, int count) public int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -1249,11 +1249,11 @@ public int LastIndexOf(string source, char value, int startIndex, int count, Com public int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } @@ -1535,7 +1535,7 @@ public override bool Equals(object? value) /// public int GetHashCode(string source, CompareOptions options) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -1595,7 +1595,7 @@ public SortVersion Version { get { - if (m_SortVersion == null) + if (m_SortVersion is null) { if (GlobalizationMode.Invariant) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Icu.cs index faa339fcc3000a..a197dface6fc88 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Icu.cs @@ -48,7 +48,7 @@ private string IcuGetLocaleInfo(LocaleStringData type) Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.IcuGetLocaleInfo] Expected _sWindowsName to be populated already"); return IcuGetLocaleInfo(_sWindowsName, type); } @@ -57,7 +57,7 @@ private string IcuGetLocaleInfo(LocaleStringData type) private unsafe string IcuGetLocaleInfo(string localeName, LocaleStringData type) { Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(localeName != null, "[CultureData.IcuGetLocaleInfo] Expected localeName to be not be null"); + Debug.Assert(localeName is not null, "[CultureData.IcuGetLocaleInfo] Expected localeName to be not be null"); switch (type) { @@ -83,7 +83,7 @@ private int IcuGetLocaleInfo(LocaleNumberData type) { Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.IcuGetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); switch (type) { @@ -107,7 +107,7 @@ private int IcuGetLocaleInfo(LocaleNumberData type) private int[] IcuGetLocaleInfo(LocaleGroupingData type) { Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.IcuGetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); int primaryGroupingSize = 0; int secondaryGroupingSize = 0; @@ -130,7 +130,7 @@ private int[] IcuGetLocaleInfo(LocaleGroupingData type) private unsafe string IcuGetTimeFormatString(bool shortFormat) { Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY]; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Nls.cs index 9738d5a289464d..eb55c2154bf6a2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Nls.cs @@ -47,7 +47,7 @@ internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, cha private string NlsGetLocaleInfo(LocaleStringData type) { Debug.Assert(ShouldUseUserOverrideNlsData); - Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already"); return NlsGetLocaleInfo(_sWindowsName, type); } @@ -74,28 +74,28 @@ private int NlsGetLocaleInfo(LocaleNumberData type) // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. - Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); return GetLocaleInfoExInt(_sWindowsName, lctype); } private int[] NlsGetLocaleInfo(LocaleGroupingData type) { Debug.Assert(ShouldUseUserOverrideNlsData); - Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, _bUseOverrides)); } private string? NlsGetTimeFormatString() { Debug.Assert(ShouldUseUserOverrideNlsData); - Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, Interop.Kernel32.LOCALE_STIMEFORMAT, _bUseOverrides)); } private int NlsGetFirstDayOfWeek() { Debug.Assert(ShouldUseUserOverrideNlsData); - Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); int result = GetLocaleInfoExInt(_sWindowsName, Interop.Kernel32.LOCALE_IFIRSTDAYOFWEEK | (!_bUseOverrides ? Interop.Kernel32.LOCALE_NOUSEROVERRIDE : 0)); @@ -109,7 +109,7 @@ private int NlsGetFirstDayOfWeek() { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(regionName != null); + Debug.Assert(regionName is not null); EnumLocaleData context; context.cultureName = null; @@ -120,7 +120,7 @@ private int NlsGetFirstDayOfWeek() Interop.Kernel32.EnumSystemLocalesEx(&EnumSystemLocalesProc, Interop.Kernel32.LOCALE_SPECIFICDATA | Interop.Kernel32.LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero); } - if (context.cultureName != null) + if (context.cultureName is not null) { // we got a matched culture return GetCultureData(context.cultureName, true); @@ -137,8 +137,8 @@ private string NlsGetLanguageDisplayName(string cultureName) // if DefaultThreadCurrentUICulture was set CultureInfo? ci; - if (CultureInfo.DefaultThreadCurrentUICulture != null && - ((ci = CultureInfo.GetUserDefaultCulture()) != null) && + if (CultureInfo.DefaultThreadCurrentUICulture is not null && + ((ci = CultureInfo.GetUserDefaultCulture()) is not null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { return NativeName; @@ -167,7 +167,7 @@ private string NlsGetRegionDisplayName() private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOverride) { - Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); + Debug.Assert(localeName is not null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); // Fix lctype if we don't want overrides if (!useUserOverride) @@ -197,7 +197,7 @@ private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bo internal static string? ReescapeWin32String(string? str) { // If we don't have data, then don't try anything - if (str == null) + if (str is null) { return null; } @@ -252,7 +252,7 @@ private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bo } // Unchanged string? , just return input string - if (result == null) + if (result is null) return str; // String changed, need to use the builder @@ -262,7 +262,7 @@ private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bo [return: NotNullIfNotNull("array")] internal static string[]? ReescapeWin32Strings(string[]? array) { - if (array != null) + if (array is not null) { for (int i = 0; i < array.Length; i++) { @@ -346,7 +346,7 @@ private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, u { string cultureName = new string(lpLocaleString); string? regionName = GetLocaleInfoEx(cultureName, Interop.Kernel32.LOCALE_SISO3166CTRYNAME); - if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase)) + if (regionName is not null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase)) { context.cultureName = cultureName; return Interop.BOOL.FALSE; // we found a match, then stop the enumeration diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Unix.cs index 5d35cfc90af79c..43f93f4d360470 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Unix.cs @@ -15,7 +15,7 @@ internal partial class CultureData /// private bool InitCultureDataCore() { - Debug.Assert(_sRealName != null); + Debug.Assert(_sRealName is not null); Debug.Assert(!GlobalizationMode.Invariant); string realNameBuffer = _sRealName; @@ -47,7 +47,7 @@ private bool InitCultureDataCore() } // Replace the ICU collation keyword with an _ - Debug.Assert(_sWindowsName != null); + Debug.Assert(_sWindowsName is not null); index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal); if (index >= 0) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs index 2c77cf6381a006..897a4bb8ddf732 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs @@ -144,7 +144,7 @@ private unsafe bool InitCultureDataCore() private void InitUserOverride(bool useUserOverride) { - Debug.Assert(_sWindowsName != null, "[CultureData.InitUserOverride] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.InitUserOverride] Expected _sWindowsName to be populated by already"); _bUseOverrides = useUserOverride && _sWindowsName == CultureInfo.UserDefaultLocaleName; } @@ -167,7 +167,7 @@ internal static unsafe CultureData GetCurrentRegionData() { geoIsoIdLength -= geoIso2Letters[geoIsoIdLength - 1] == 0 ? 1 : 0; // handle null termination and exclude it. CultureData? cd = GetCultureDataForRegion(geoIso2Letters.Slice(0, geoIsoIdLength).ToString(), true); - if (cd != null) + if (cd is not null) { return cd; } @@ -195,7 +195,7 @@ internal static unsafe CultureData GetCurrentRegionData() private string[]? GetTimeFormatsCore(bool shortFormat) { - Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatsCore] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.GetTimeFormatsCore] Expected _sWindowsName to be populated by already"); if (GlobalizationMode.UseNls) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs index 939c16e4d8d9a6..d8209fad3d9a19 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs @@ -425,7 +425,7 @@ internal partial class CultureData // First check if GetCultureData() can find it (ie: its a real culture) CultureData? retVal = GetCultureData(cultureName, useUserOverride); - if (retVal != null && !retVal.IsNeutralCulture) + if (retVal is not null && !retVal.IsNeutralCulture) { return retVal; } @@ -440,7 +440,7 @@ internal partial class CultureData string hashName = AnsiToLower(useUserOverride ? cultureName : cultureName + '*'); Dictionary? tempHashTable = s_cachedRegions; - if (tempHashTable == null) + if (tempHashTable is null) { // No table yet, make a new one tempHashTable = new Dictionary(); @@ -452,7 +452,7 @@ internal partial class CultureData { tempHashTable.TryGetValue(hashName, out retVal); } - if (retVal != null) + if (retVal is not null) { return retVal; } @@ -461,7 +461,7 @@ internal partial class CultureData // Not found in the hash table, look it up the hard way // If not a valid mapping from the registry we'll have to try the hard coded table - if (retVal == null || retVal.IsNeutralCulture) + if (retVal is null || retVal.IsNeutralCulture) { // Not a valid mapping, try the hard coded table if (RegionNames.TryGetValue(cultureName, out string? name)) @@ -472,13 +472,13 @@ internal partial class CultureData } // If not found in the hard coded table we'll have to find a culture that works for us - if (!GlobalizationMode.Invariant && (retVal == null || retVal.IsNeutralCulture)) + if (!GlobalizationMode.Invariant && (retVal is null || retVal.IsNeutralCulture)) { retVal = GlobalizationMode.UseNls ? NlsGetCultureDataFromRegionName(cultureName) : IcuGetCultureDataFromRegionName(cultureName); } // If we found one we can use, then cache it for next time - if (retVal != null && !retVal.IsNeutralCulture) + if (retVal is not null && !retVal.IsNeutralCulture) { // first add it to the cache lock (s_lock) @@ -679,7 +679,7 @@ private static CultureData CreateCultureWithInvariantData() // Try the hash table first string hashName = AnsiToLower(useUserOverride ? cultureName : cultureName + '*'); Dictionary? tempHashTable = s_cachedCultures; - if (tempHashTable == null) + if (tempHashTable is null) { // No table yet, make a new one tempHashTable = new Dictionary(); @@ -693,7 +693,7 @@ private static CultureData CreateCultureWithInvariantData() { ret = tempHashTable.TryGetValue(hashName, out retVal); } - if (ret && retVal != null) + if (ret && retVal is not null) { return retVal; } @@ -701,7 +701,7 @@ private static CultureData CreateCultureWithInvariantData() // Not found in the hash table, need to see if we can build one that works for us CultureData? culture = CreateCultureData(cultureName, useUserOverride); - if (culture == null) + if (culture is null) { return null; } @@ -879,7 +879,7 @@ internal static CultureData GetCultureData(int culture, bool bUseUserOverride) } // If not successful, throw - if (retVal == null) + if (retVal is null) { throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); } @@ -895,7 +895,7 @@ internal string CultureName { get { - Debug.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName is not null, "[CultureData.CultureName] Expected _sRealName to be populated by already"); // since windows doesn't know about zh-CHS and zh-CHT, // we leave sRealName == zh-Hanx but we still need to // pretend that it was zh-CHX. @@ -929,7 +929,7 @@ internal string DisplayName get { string? localizedDisplayName = _sLocalizedDisplayName; - if (localizedDisplayName == null && !GlobalizationMode.Invariant) + if (localizedDisplayName is null && !GlobalizationMode.Invariant) { if (IsSupplementalCustomCulture) { @@ -982,8 +982,8 @@ internal string DisplayName // if DefaultThreadCurrentUICulture was set CultureInfo ci; - if (CultureInfo.DefaultThreadCurrentUICulture != null && - ((ci = CultureInfo.GetUserDefaultCulture()) != null) && + if (CultureInfo.DefaultThreadCurrentUICulture is not null && + ((ci = CultureInfo.GetUserDefaultCulture()) is not null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { localizedDisplayName = NativeName; @@ -1014,7 +1014,7 @@ internal string EnglishName get { string? englishDisplayName = _sEnglishDisplayName; - if (englishDisplayName == null && !GlobalizationMode.Invariant) + if (englishDisplayName is null && !GlobalizationMode.Invariant) { // If its neutral use the language name if (IsNeutralCulture) @@ -1071,7 +1071,7 @@ internal string NativeName get { string? nativeDisplayName = _sNativeDisplayName; - if (nativeDisplayName == null && !GlobalizationMode.Invariant) + if (nativeDisplayName is null && !GlobalizationMode.Invariant) { // If its neutral use the language name if (IsNeutralCulture) @@ -1115,7 +1115,7 @@ internal string SpecificCultureName get { // This got populated during the culture initialization - Debug.Assert(_sSpecificCulture != null, "[CultureData.SpecificCultureName] Expected this.sSpecificCulture to be populated by culture data initialization already"); + Debug.Assert(_sSpecificCulture is not null, "[CultureData.SpecificCultureName] Expected this.sSpecificCulture to be populated by culture data initialization already"); return _sSpecificCulture; } } @@ -1145,14 +1145,14 @@ private string LocalizedLanguageName { get { - if (_sLocalizedLanguage == null && !GlobalizationMode.Invariant) + if (_sLocalizedLanguage is null && !GlobalizationMode.Invariant) { // Usually the UI culture shouldn't be different than what we got from WinRT except // if DefaultThreadCurrentUICulture was set CultureInfo ci; - if (CultureInfo.DefaultThreadCurrentUICulture != null && - ((ci = CultureInfo.GetUserDefaultCulture()) != null) && + if (CultureInfo.DefaultThreadCurrentUICulture is not null && + ((ci = CultureInfo.GetUserDefaultCulture()) is not null) && !CultureInfo.DefaultThreadCurrentUICulture!.Name.Equals(ci.Name)) { _sLocalizedLanguage = NativeLanguageName; @@ -1202,7 +1202,7 @@ internal string LocalizedCountryName get { string? localizedCountry = _sLocalizedCountry; - if (localizedCountry == null && !GlobalizationMode.Invariant) + if (localizedCountry is null && !GlobalizationMode.Invariant) { try { @@ -1400,12 +1400,12 @@ internal string[] LongTimes { get { - if (_saLongTimes == null && !GlobalizationMode.Invariant) + if (_saLongTimes is null && !GlobalizationMode.Invariant) { Debug.Assert(!GlobalizationMode.Invariant); string[]? longTimes = GetTimeFormatsCore(shortFormat: false); - if (longTimes == null || longTimes.Length == 0) + if (longTimes is null || longTimes.Length == 0) { _saLongTimes = Invariant._saLongTimes!; } @@ -1426,14 +1426,14 @@ internal string[] ShortTimes { get { - if (_saShortTimes == null && !GlobalizationMode.Invariant) + if (_saShortTimes is null && !GlobalizationMode.Invariant) { Debug.Assert(!GlobalizationMode.Invariant); // Try to get the short times from the OS/culture.dll string[]? shortTimes = GetTimeFormatsCore(shortFormat: true); - if (shortTimes == null || shortTimes.Length == 0) + if (shortTimes is null || shortTimes.Length == 0) { // // If we couldn't find short times, then compute them from long times @@ -1689,13 +1689,13 @@ internal CalendarId[] CalendarIds { get { - if (_waCalendars == null && !GlobalizationMode.Invariant) + if (_waCalendars is null && !GlobalizationMode.Invariant) { // We pass in an array of ints, and native side fills it up with count calendars. // We then have to copy that list to a new array of the right size. // Default calendar should be first CalendarId[] calendars = new CalendarId[23]; - Debug.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already"); int count = CalendarData.GetCalendarsCore(_sWindowsName, _bUseOverrides, calendars); @@ -1777,9 +1777,9 @@ internal CalendarData GetCalendar(CalendarId calendarId) // right after we insert the newly created CalendarData (below) CalendarData? calendarData = _calendars[calendarIndex]; // Make sure that calendar has data - if (calendarData == null) + if (calendarData is null) { - Debug.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already"); calendarData = new CalendarData(_sWindowsName, calendarId, _bUseOverrides); _calendars[calendarIndex] = calendarData; } @@ -1808,7 +1808,7 @@ private int ReadingLayout { if (_iReadingLayout == undef && !GlobalizationMode.Invariant) { - Debug.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName is not null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already"); _iReadingLayout = GetLocaleInfoCore(LocaleNumberData.ReadingLayout); } @@ -1832,7 +1832,7 @@ internal string TextInfoName { // Note: Custom cultures might point at another culture's textinfo, however windows knows how // to redirect it to the desired textinfo culture, so this is OK. - Debug.Assert(_sRealName != null, "[CultureData.TextInfoName] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName is not null, "[CultureData.TextInfoName] Expected _sRealName to be populated by already"); return _sRealName; } } @@ -1844,7 +1844,7 @@ internal string SortName { get { - Debug.Assert(_sRealName != null, "[CultureData.SortName] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName is not null, "[CultureData.SortName] Expected _sRealName to be populated by already"); return _sRealName; } } @@ -1917,7 +1917,7 @@ internal int LCID { if (_iLanguage == 0 && !GlobalizationMode.Invariant) { - Debug.Assert(_sRealName != null, "[CultureData.LCID] Expected this.sRealName to be populated already"); + Debug.Assert(_sRealName is not null, "[CultureData.LCID] Expected this.sRealName to be populated already"); _iLanguage = GlobalizationMode.UseNls ? NlsLocaleNameToLCID(_sRealName) : IcuLocaleNameToLCID(_sRealName); } return _iLanguage; @@ -1983,7 +1983,7 @@ internal string TimeSeparator { get { - if (_sTimeSeparator == null && !GlobalizationMode.Invariant) + if (_sTimeSeparator is null && !GlobalizationMode.Invariant) { string? longTimeFormat = ShouldUseUserOverrideNlsData ? NlsGetTimeFormatString() : IcuGetTimeFormatString(); if (string.IsNullOrEmpty(longTimeFormat)) @@ -2041,7 +2041,7 @@ internal string DateSeparator(CalendarId calendarId) /// private static string UnescapeNlsString(string str, int start, int end) { - Debug.Assert(str != null); + Debug.Assert(str is not null); Debug.Assert(start >= 0); Debug.Assert(end >= 0); StringBuilder? result = null; @@ -2067,7 +2067,7 @@ private static string UnescapeNlsString(string str, int start, int end) } } - if (result == null) + if (result is null) { return str.Substring(start, end - start + 1); } @@ -2190,7 +2190,7 @@ internal void GetNFIValues(NumberFormatInfo nfi) } else { - Debug.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName is not null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already"); // String values nfi._positiveSign = GetLocaleInfoCoreUserOverride(LocaleStringData.PositiveSign); nfi._negativeSign = GetLocaleInfoCoreUserOverride(LocaleStringData.NegativeSign); @@ -2216,7 +2216,7 @@ internal void GetNFIValues(NumberFormatInfo nfi) nfi._nativeDigits[i] = char.ToString(digits[i]); } - Debug.Assert(_sRealName != null); + Debug.Assert(_sRealName is not null); nfi._digitSubstitution = ShouldUseUserOverrideNlsData ? NlsGetLocaleInfo(LocaleNumberData.DigitSubstitution) : IcuGetDigitSubstitution(_sRealName); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Unix.cs index a35b88c220609f..8aa5fd65739e21 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Unix.cs @@ -15,7 +15,7 @@ internal static CultureInfo GetUserDefaultCulture() CultureInfo cultureInfo; if (CultureData.GetDefaultLocaleName(out string? localeName)) { - Debug.Assert(localeName != null); + Debug.Assert(localeName is not null); cultureInfo = GetCultureByName(localeName); } else diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs index e2ab1851141c7b..62159bbaedac67 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs @@ -12,7 +12,7 @@ internal static CultureInfo GetUserDefaultCulture() string? strDefault = UserDefaultLocaleName; - return strDefault != null ? + return strDefault is not null ? GetCultureByName(strDefault) : CultureInfo.InvariantCulture; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs index 6cf5e4ca2fdf85..37f88e27300c63 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -163,7 +163,7 @@ public CultureInfo(string name) : this(name, true) public CultureInfo(string name, bool useUserOverride) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -171,7 +171,7 @@ public CultureInfo(string name, bool useUserOverride) // Get our data providing record CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); - if (cultureData == null) + if (cultureData is null) { throw new CultureNotFoundException(nameof(name), name, SR.Argument_CultureNotSupported); } @@ -183,7 +183,7 @@ public CultureInfo(string name, bool useUserOverride) private CultureInfo(CultureData cultureData, bool isReadOnly = false) { - Debug.Assert(cultureData != null); + Debug.Assert(cultureData is not null); _cultureData = cultureData; _name = cultureData.CultureName; _isReadOnly = isReadOnly; @@ -191,9 +191,9 @@ private CultureInfo(CultureData cultureData, bool isReadOnly = false) private static CultureInfo? CreateCultureInfoNoThrow(string name, bool useUserOverride) { - Debug.Assert(name != null); + Debug.Assert(name is not null); CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); - if (cultureData == null) + if (cultureData is null) { return null; } @@ -242,7 +242,7 @@ public CultureInfo(int culture, bool useUserOverride) /// internal CultureInfo(string cultureName, string textAndCompareCultureName) { - if (cultureName == null) + if (cultureName is null) { throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); } @@ -318,7 +318,7 @@ public static CultureInfo CreateSpecificCulture(string name) } } - if (culture == null) + if (culture is null) { // nothing to save here; throw the original exception throw; @@ -394,12 +394,12 @@ public static CultureInfo CurrentCulture } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } - if (s_asyncLocalCurrentCulture == null) + if (s_asyncLocalCurrentCulture is null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal(AsyncLocalSetCurrentCulture), null); } @@ -417,14 +417,14 @@ public static CultureInfo CurrentUICulture } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } CultureInfo.VerifyCultureName(value, true); - if (s_asyncLocalCurrentUICulture == null) + if (s_asyncLocalCurrentUICulture is null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal(AsyncLocalSetCurrentUICulture), null); } @@ -458,7 +458,7 @@ public static CultureInfo? DefaultThreadCurrentUICulture // If you add more pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentUICulture.set. - if (value != null) + if (value is not null) { CultureInfo.VerifyCultureName(value, true); } @@ -479,7 +479,7 @@ public static CultureInfo InvariantCulture { get { - Debug.Assert(s_InvariantCultureInfo != null); + Debug.Assert(s_InvariantCultureInfo is not null); return s_InvariantCultureInfo; } } @@ -491,7 +491,7 @@ public virtual CultureInfo Parent { get { - if (_parent == null) + if (_parent is null) { CultureInfo culture; string parentName = _cultureData.ParentName; @@ -559,7 +559,7 @@ public virtual string DisplayName { get { - Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set"); + Debug.Assert(_name is not null, "[CultureInfo.DisplayName] Always expect _name to be set"); return _cultureData.DisplayName; } } @@ -609,7 +609,7 @@ public virtual TextInfo TextInfo { get { - if (_textInfo == null) + if (_textInfo is null) { // Make a new textInfo TextInfo tempTextInfo = new TextInfo(_cultureData); @@ -695,7 +695,7 @@ public virtual NumberFormatInfo NumberFormat { get { - if (_numInfo == null) + if (_numInfo is null) { NumberFormatInfo temp = new NumberFormatInfo(_cultureData); temp._isReadOnly = _isReadOnly; @@ -705,7 +705,7 @@ public virtual NumberFormatInfo NumberFormat } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -723,7 +723,7 @@ public virtual DateTimeFormatInfo DateTimeFormat { get { - if (_dateTimeInfo == null) + if (_dateTimeInfo is null) { // Change the calendar of DTFI to the specified calendar of this CultureInfo. DateTimeFormatInfo temp = new DateTimeFormatInfo(_cultureData, this.Calendar); @@ -735,7 +735,7 @@ public virtual DateTimeFormatInfo DateTimeFormat set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -830,7 +830,7 @@ public virtual Calendar Calendar { get { - if (_calendar == null) + if (_calendar is null) { // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. @@ -872,7 +872,7 @@ public virtual Calendar[] OptionalCalendars public CultureInfo GetConsoleFallbackUICulture() { CultureInfo? temp = _consoleFallbackCulture; - if (temp == null) + if (temp is null) { temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); temp._isReadOnly = true; @@ -890,11 +890,11 @@ public virtual object Clone() // they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!_isInherited) { - if (_dateTimeInfo != null) + if (_dateTimeInfo is not null) { ci._dateTimeInfo = (DateTimeFormatInfo)_dateTimeInfo.Clone(); } - if (_numInfo != null) + if (_numInfo is not null) { ci._numInfo = (NumberFormatInfo)_numInfo.Clone(); } @@ -905,12 +905,12 @@ public virtual object Clone() ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone(); } - if (_textInfo != null) + if (_textInfo is not null) { ci._textInfo = (TextInfo)_textInfo.Clone(); } - if (_dateTimeInfo != null && _dateTimeInfo.Calendar == _calendar) + if (_dateTimeInfo is not null && _dateTimeInfo.Calendar == _calendar) { // Usually when we access CultureInfo.DateTimeFormat first time, we create the DateTimeFormatInfo object // using CultureInfo.Calendar. i.e. CultureInfo.DateTimeInfo.Calendar == CultureInfo.calendar. @@ -918,7 +918,7 @@ public virtual object Clone() // then we can keep the same behavior for the cloned object and no need to create another calendar object. ci._calendar = ci.DateTimeFormat.Calendar; } - else if (_calendar != null) + else if (_calendar is not null) { ci._calendar = (Calendar)_calendar.Clone(); } @@ -928,7 +928,7 @@ public virtual object Clone() public static CultureInfo ReadOnly(CultureInfo ci) { - if (ci == null) + if (ci is null) { throw new ArgumentNullException(nameof(ci)); } @@ -945,11 +945,11 @@ public static CultureInfo ReadOnly(CultureInfo ci) // they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!ci._isInherited) { - if (ci._dateTimeInfo != null) + if (ci._dateTimeInfo is not null) { newInfo._dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci._dateTimeInfo); } - if (ci._numInfo != null) + if (ci._numInfo is not null) { newInfo._numInfo = NumberFormatInfo.ReadOnly(ci._numInfo); } @@ -961,12 +961,12 @@ public static CultureInfo ReadOnly(CultureInfo ci) } } - if (ci._textInfo != null) + if (ci._textInfo is not null) { newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo); } - if (ci._calendar != null) + if (ci._calendar is not null) { newInfo._calendar = Calendar.ReadOnly(ci._calendar); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureNotFoundException.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureNotFoundException.cs index bc274c3c907907..f03b13ab438130 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureNotFoundException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureNotFoundException.cs @@ -77,7 +77,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont private static string DefaultMessage => SR.Argument_CultureNotSupported; private string? FormattedInvalidCultureId => - InvalidCultureId != null ? + InvalidCultureId is not null ? string.Format(CultureInfo.InvariantCulture, "{0} (0x{0:x4})", (int)InvalidCultureId) : InvalidCultureName; @@ -86,10 +86,10 @@ public override string Message get { string s = base.Message; - if (_invalidCultureId != null || _invalidCultureName != null) + if (_invalidCultureId is not null || _invalidCultureName is not null) { string valueMessage = SR.Format(SR.Argument_CultureInvalidIdentifier, FormattedInvalidCultureId); - if (s == null) + if (s is null) { return valueMessage; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs index b1023765037a7f..d54ccc7f979609 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs @@ -449,7 +449,7 @@ private static StringBuilder FormatCustomized( Calendar cal = dtfi.Calendar; bool resultBuilderIsPooled = false; - if (result == null) + if (result is null) { resultBuilderIsPooled = true; result = StringBuilderCache.Acquire(); @@ -988,7 +988,7 @@ internal static string Format(DateTime dateTime, string? format, IFormatProvider internal static string Format(DateTime dateTime, string? format, IFormatProvider? provider, TimeSpan offset) { - if (format != null && format.Length == 1) + if (format is not null && format.Length == 1) { // Optimize for these standard formats that are not affected by culture. switch (format[0]) @@ -1059,7 +1059,7 @@ internal static bool TryFormat(DateTime dateTime, Span destination, out in private static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan format, DateTimeFormatInfo dtfi, TimeSpan offset) { - Debug.Assert(dtfi != null); + Debug.Assert(dtfi is not null); if (format.Length == 0) { bool timeOnlySpecialCase = false; @@ -1316,7 +1316,7 @@ private static void WriteDigits(ulong value, Span buffer) internal static string[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { - Debug.Assert(dtfi != null); + Debug.Assert(dtfi is not null); string[] allFormats; string[] results; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs index a6c20e7c22dccf..f43b9752eac74a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs @@ -237,8 +237,8 @@ public DateTimeFormatInfo() internal DateTimeFormatInfo(CultureData cultureData, Calendar cal) { - Debug.Assert(cultureData != null); - Debug.Assert(cal != null); + Debug.Assert(cultureData is not null); + Debug.Assert(cal is not null); // Remember our culture _cultureData = cultureData; @@ -248,7 +248,7 @@ internal DateTimeFormatInfo(CultureData cultureData, Calendar cal) private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarId) { - Debug.Assert(cultureData != null); + Debug.Assert(cultureData is not null); Debug.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId"); if (firstDayOfWeek == -1) @@ -260,19 +260,19 @@ private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarWeekRule = cultureData.CalendarWeekRule; } - if (amDesignator == null) + if (amDesignator is null) { amDesignator = cultureData.AMDesignator; } - if (pmDesignator == null) + if (pmDesignator is null) { pmDesignator = cultureData.PMDesignator; } - if (timeSeparator == null) + if (timeSeparator is null) { timeSeparator = cultureData.TimeSeparator; } - if (dateSeparator == null) + if (dateSeparator is null) { dateSeparator = cultureData.DateSeparator(calendarId); } @@ -301,7 +301,7 @@ public static DateTimeFormatInfo InvariantInfo { get { - if (s_invariantInfo == null) + if (s_invariantInfo is null) { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.Calendar.SetReadOnlyState(true); @@ -323,7 +323,7 @@ public static DateTimeFormatInfo CurrentInfo if (!culture._isInherited) { DateTimeFormatInfo? info = culture._dateTimeInfo; - if (info != null) + if (info is not null) { return info; } @@ -333,7 +333,7 @@ public static DateTimeFormatInfo CurrentInfo } public static DateTimeFormatInfo GetInstance(IFormatProvider? provider) => - provider == null ? CurrentInfo : + provider is null ? CurrentInfo : provider is CultureInfo cultureProvider && !cultureProvider._isInherited ? cultureProvider.DateTimeFormat : provider is DateTimeFormatInfo info ? info : provider.GetFormat(typeof(DateTimeFormatInfo)) is DateTimeFormatInfo info2 ? info2 : @@ -358,12 +358,12 @@ public string AMDesignator { get { - if (amDesignator == null) + if (amDesignator is null) { amDesignator = _cultureData.AMDesignator; } - Debug.Assert(amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); + Debug.Assert(amDesignator is not null, "DateTimeFormatInfo.AMDesignator, amDesignator is not null"); return amDesignator; } set @@ -372,7 +372,7 @@ public string AMDesignator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -386,7 +386,7 @@ public Calendar Calendar { get { - Debug.Assert(calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); + Debug.Assert(calendar is not null, "DateTimeFormatInfo.Calendar: calendar is not null"); return calendar; } [MemberNotNull(nameof(calendar))] @@ -396,7 +396,7 @@ public Calendar Calendar { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -412,7 +412,7 @@ public Calendar Calendar { // We can use this one, so do so. // Clean related properties if we already had a calendar set - if (calendar != null) + if (calendar is not null) { // clean related properties which are affected by the calendar setting, // so that they will be refreshed when they are accessed next time. @@ -484,7 +484,7 @@ public Calendar Calendar /// public int GetEra(string eraName) { - if (eraName == null) + if (eraName is null) { throw new ArgumentNullException(nameof(eraName)); } @@ -591,7 +591,7 @@ internal string[] AbbreviatedEnglishEraNames { get { - if (m_abbrevEnglishEraNames == null) + if (m_abbrevEnglishEraNames is null) { Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); m_abbrevEnglishEraNames = _cultureData.AbbreviatedEnglishEraNames(Calendar.ID); @@ -608,11 +608,11 @@ public string DateSeparator { get { - if (dateSeparator == null) + if (dateSeparator is null) { dateSeparator = _cultureData.DateSeparator(Calendar.ID); } - Debug.Assert(dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); + Debug.Assert(dateSeparator is not null, "DateTimeFormatInfo.DateSeparator, dateSeparator is not null"); return dateSeparator; } set @@ -621,7 +621,7 @@ public string DateSeparator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -701,7 +701,7 @@ public string FullDateTimePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -725,7 +725,7 @@ public string LongDatePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -762,7 +762,7 @@ public string LongTimePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -792,13 +792,13 @@ public string MonthDayPattern { get { - if (monthDayPattern == null) + if (monthDayPattern is null) { Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); monthDayPattern = _cultureData.MonthDay(Calendar.ID); } - Debug.Assert(monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); + Debug.Assert(monthDayPattern is not null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern is not null"); return monthDayPattern; } set @@ -807,7 +807,7 @@ public string MonthDayPattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -820,12 +820,12 @@ public string PMDesignator { get { - if (pmDesignator == null) + if (pmDesignator is null) { pmDesignator = _cultureData.PMDesignator; } - Debug.Assert(pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); + Debug.Assert(pmDesignator is not null, "DateTimeFormatInfo.PMDesignator, pmDesignator is not null"); return pmDesignator; } set @@ -834,7 +834,7 @@ public string PMDesignator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -865,7 +865,7 @@ public string ShortDatePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -904,7 +904,7 @@ public string ShortTimePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -950,7 +950,7 @@ internal string DateTimeOffsetPattern { get { - if (dateTimeOffsetPattern == null) + if (dateTimeOffsetPattern is null) { /* LongTimePattern might contain a "z" as part of the format string in which case we don't want to append a time zone offset */ @@ -1008,11 +1008,11 @@ public string TimeSeparator { get { - if (timeSeparator == null) + if (timeSeparator is null) { timeSeparator = _cultureData.TimeSeparator; } - Debug.Assert(timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); + Debug.Assert(timeSeparator is not null, "DateTimeFormatInfo.TimeSeparator, timeSeparator is not null"); return timeSeparator; } set @@ -1021,7 +1021,7 @@ public string TimeSeparator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1049,7 +1049,7 @@ public string YearMonthPattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1072,11 +1072,11 @@ private void OnYearMonthPatternChanged() /// private static void CheckNullValue(string[] values, int length) { - Debug.Assert(values != null, "value != null"); + Debug.Assert(values is not null, "value is not null"); Debug.Assert(values.Length >= length); for (int i = 0; i < length; i++) { - if (values[i] == null) + if (values[i] is null) { throw new ArgumentNullException("value", SR.ArgumentNull_ArrayValue); } @@ -1092,7 +1092,7 @@ public string[] AbbreviatedDayNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1120,7 +1120,7 @@ public string[] ShortestDayNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1143,7 +1143,7 @@ public string[] DayNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1168,7 +1168,7 @@ public string[] AbbreviatedMonthNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1192,7 +1192,7 @@ public string[] MonthNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1245,7 +1245,7 @@ private string[] InternalGetGenitiveMonthNames(bool abbreviated) { if (abbreviated) { - if (m_genitiveAbbreviatedMonthNames == null) + if (m_genitiveAbbreviatedMonthNames is null) { m_genitiveAbbreviatedMonthNames = _cultureData.AbbreviatedGenitiveMonthNames(Calendar.ID); Debug.Assert(m_genitiveAbbreviatedMonthNames.Length == 13, @@ -1255,7 +1255,7 @@ private string[] InternalGetGenitiveMonthNames(bool abbreviated) return m_genitiveAbbreviatedMonthNames; } - if (genitiveMonthNames == null) + if (genitiveMonthNames is null) { genitiveMonthNames = _cultureData.GenitiveMonthNames(Calendar.ID); Debug.Assert(genitiveMonthNames.Length == 13, @@ -1272,7 +1272,7 @@ private string[] InternalGetGenitiveMonthNames(bool abbreviated) /// internal string[] InternalGetLeapYearMonthNames() { - if (leapYearMonthNames == null) + if (leapYearMonthNames is null) { Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.InternalGetLeapYearMonthNames] Expected Calendar.ID > 0"); leapYearMonthNames = _cultureData.LeapYearMonthNames(Calendar.ID); @@ -1321,8 +1321,8 @@ public string GetShortestDayName(DayOfWeek dayOfWeek) /// private static string[] GetCombinedPatterns(string[] patterns1, string[] patterns2, string connectString) { - Debug.Assert(patterns1 != null); - Debug.Assert(patterns2 != null); + Debug.Assert(patterns1 is not null); + Debug.Assert(patterns2 is not null); // Get array size string[] result = new string[patterns1.Length * patterns2.Length]; @@ -1469,9 +1469,9 @@ public string GetMonthName(int month) /// private static string[] GetMergedPatterns(string[] patterns, string defaultPattern) { - Debug.Assert(patterns != null && patterns.Length > 0, + Debug.Assert(patterns is not null && patterns.Length > 0, "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern"); - Debug.Assert(defaultPattern != null, + Debug.Assert(defaultPattern is not null, "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string"); // If the default happens to be the first in the list just return (a cloned) copy @@ -1545,7 +1545,7 @@ private string[] UnclonedYearMonthPatterns { get { - if (allYearMonthPatterns == null) + if (allYearMonthPatterns is null) { Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); allYearMonthPatterns = _cultureData.YearMonths(Calendar.ID); @@ -1566,7 +1566,7 @@ private string[] UnclonedShortDatePatterns { get { - if (allShortDatePatterns == null) + if (allShortDatePatterns is null) { Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); allShortDatePatterns = _cultureData.ShortDates(Calendar.ID); @@ -1587,7 +1587,7 @@ private string[] UnclonedLongDatePatterns { get { - if (allLongDatePatterns == null) + if (allLongDatePatterns is null) { Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); allLongDatePatterns = _cultureData.LongDates(Calendar.ID); @@ -1608,7 +1608,7 @@ private string[] UnclonedShortTimePatterns { get { - if (allShortTimePatterns == null) + if (allShortTimePatterns is null) { allShortTimePatterns = _cultureData.ShortTimes; Debug.Assert(allShortTimePatterns.Length > 0, @@ -1628,7 +1628,7 @@ private string[] UnclonedLongTimePatterns { get { - if (allLongTimePatterns == null) + if (allLongTimePatterns is null) { allLongTimePatterns = _cultureData.LongTimes; Debug.Assert(allLongTimePatterns.Length > 0, @@ -1641,7 +1641,7 @@ private string[] UnclonedLongTimePatterns public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) { - if (dtfi == null) + if (dtfi is null) { throw new ArgumentNullException(nameof(dtfi)); } @@ -1694,7 +1694,7 @@ public void SetAllDateTimePatterns(string[] patterns, char format) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (patterns == null) + if (patterns is null) { throw new ArgumentNullException(nameof(patterns)); } @@ -1706,7 +1706,7 @@ public void SetAllDateTimePatterns(string[] patterns, char format) for (int i = 0; i < patterns.Length; i++) { - if (patterns[i] == null) + if (patterns[i] is null) { throw new ArgumentNullException(nameof(patterns) + "[" + i + "]", SR.ArgumentNull_ArrayValue); } @@ -1760,7 +1760,7 @@ public string[] AbbreviatedMonthGenitiveNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1784,7 +1784,7 @@ public string[] MonthGenitiveNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1993,7 +1993,7 @@ internal bool YearMonthAdjustment(ref int year, ref int month, bool parsedMonthN internal static DateTimeFormatInfo GetJapaneseCalendarDTFI() { DateTimeFormatInfo? temp = s_jajpDTFI; - if (temp == null) + if (temp is null) { temp = new CultureInfo("ja-JP", false).DateTimeFormat; temp.Calendar = JapaneseCalendar.GetDefaultInstance(); @@ -2011,7 +2011,7 @@ internal static DateTimeFormatInfo GetJapaneseCalendarDTFI() internal static DateTimeFormatInfo GetTaiwanCalendarDTFI() { DateTimeFormatInfo? temp = s_zhtwDTFI; - if (temp == null) + if (temp is null) { temp = new CultureInfo("zh-TW", false).DateTimeFormat; temp.Calendar = TaiwanCalendar.GetDefaultInstance(); @@ -2032,7 +2032,7 @@ private void ClearTokenHashTable() internal TokenHashValue[] CreateTokenHashTable() { TokenHashValue[]? temp = _dtfiTokenHash; - if (temp == null) + if (temp is null) { temp = new TokenHashValue[TOKEN_HASH_SIZE]; @@ -2114,7 +2114,7 @@ internal TokenHashValue[] CreateTokenHashTable() // This is determined in DateTimeFormatInfoScanner. Use this flag to determine if we should treat date separator as ignorable symbol. bool useDateSepAsIgnorableSymbol = false; - if (dateWords != null) + if (dateWords is not null) { // There are DateWords. It could be a real date word (such as "de"), or a monthPostfix. // The monthPostfix starts with '\xfffe' (MonthPostfixChar), followed by the real monthPostfix. @@ -2432,7 +2432,7 @@ internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tok do { value = hashTable[hashcode]; - if (value == null) + if (value is null) { // Not found. break; @@ -2504,13 +2504,13 @@ private void InsertAtCurrentHashNode(TokenHashValue[] hashTable, string str, cha // Remember this slot TokenHashValue temp = hashTable[hashcode]; - if (temp != null && Culture.TextInfo.ToLower(temp.tokenString[0]) != ch) + if (temp is not null && Culture.TextInfo.ToLower(temp.tokenString[0]) != ch) { continue; } // Put the previous slot into this slot. hashTable[hashcode] = previousNode; - if (temp == null) + if (temp is null) { // Done return; @@ -2548,7 +2548,7 @@ private void InsertHash(TokenHashValue[] hashTable, string str, TokenType tokenT do { value = hashTable[hashcode]; - if (value == null) + if (value is null) { hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue); return; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs index bae033c675ffd0..e1ffcef7ff7754 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs @@ -259,7 +259,7 @@ internal int AddDateWords(string pattern, int index, string? formatPostfix) { // Skip any whitespaces so we will start from a letter. int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index); - if (newIndex != index && formatPostfix != null) + if (newIndex != index && formatPostfix is not null) { // There are whitespaces. This will not be a postfix. formatPostfix = null; @@ -301,7 +301,7 @@ internal int AddDateWords(string pattern, int index, string? formatPostfix) { // Found a whitespace. We have to add the current date word/postfix. AddDateWordOrPostfix(formatPostfix, dateWord.ToString()); - if (formatPostfix != null) + if (formatPostfix is not null) { // Done with postfix. The rest will be regular date word. formatPostfix = null; @@ -352,7 +352,7 @@ internal static int ScanRepeatChar(string pattern, char ch, int index, out int c internal void AddIgnorableSymbols(string? text) { - if (m_dateWords == null) + if (m_dateWords is null) { // Create the date word array. m_dateWords = new List(); @@ -521,7 +521,7 @@ internal void ScanDateWord(string pattern) } string[]? result = null; - if (m_dateWords != null && m_dateWords.Count > 0) + if (m_dateWords is not null && m_dateWords.Count > 0) { result = new string[m_dateWords.Count]; for (i = 0; i < m_dateWords.Count; i++) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs index 7db6ace267572c..d8b5c00f9540e7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs @@ -93,7 +93,7 @@ internal static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan form return false; } - Debug.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi is not null, "dtfi is null"); return DoStrictParse(s, format, style, dtfi, ref result); } @@ -168,7 +168,7 @@ internal static bool TryParseExactMultiple(ReadOnlySpan s, string?[]? form internal static bool TryParseExactMultiple(ReadOnlySpan s, string?[]? formats, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) { - if (formats == null) + if (formats is null) { result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(formats)); return false; @@ -186,7 +186,7 @@ internal static bool TryParseExactMultiple(ReadOnlySpan s, string?[]? form return false; } - Debug.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi is not null, "dtfi is null"); // // Do a loop through the provided formats and see if we can parse successfully in @@ -194,7 +194,7 @@ internal static bool TryParseExactMultiple(ReadOnlySpan s, string?[]? form // for (int i = 0; i < formats.Length; i++) { - if (formats[i] == null || formats[i]!.Length == 0) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) + if (formats[i] is null || formats[i]!.Length == 0) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) { result.SetBadFormatSpecifierFailure(); return false; @@ -1971,7 +1971,7 @@ private static void AdjustTimeMark(DateTimeFormatInfo dtfi, ref DateTimeRawInfo if (raw.timeMark == TM.NotSet) { - if (dtfi.AMDesignator != null && dtfi.PMDesignator != null) + if (dtfi.AMDesignator is not null && dtfi.PMDesignator is not null) { if (dtfi.AMDesignator.Length == 0 && dtfi.PMDesignator.Length != 0) { @@ -2482,7 +2482,7 @@ internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, Dat return false; } - Debug.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi is not null, "dtfi is null"); #if _LOGGING DTFITrace(dtfi); @@ -3511,7 +3511,7 @@ private static bool MatchEraName(ref __DTString str, DateTimeFormatInfo dtfi, re { int[] eras = dtfi.Calendar.Eras; - if (eras != null) + if (eras is not null) { for (int i = 0; i < eras.Length; i++) { @@ -5138,7 +5138,7 @@ private static void DTFITrace(DateTimeFormatInfo dtfi) // return a string in the form: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" private static string Hex(string[] strs) { - if (strs == null || strs.Length == 0) + if (strs is null || strs.Length == 0) return string.Empty; if (strs.Length == 1) return Hex(strs[0]); @@ -5256,7 +5256,7 @@ internal __DTString(ReadOnlySpan str, DateTimeFormatInfo dtfi, bool checkD internal __DTString(ReadOnlySpan str, DateTimeFormatInfo dtfi) { - Debug.Assert(dtfi != null, "Expected non-null DateTimeFormatInfo"); + Debug.Assert(dtfi is not null, "Expected non-null DateTimeFormatInfo"); Index = -1; Value = str; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs index 4d7cba3f7abfc3..576c38a2cccbdf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs @@ -78,7 +78,7 @@ public int GetTerrestrialBranch(int sexagenaryYear) internal int MinEraCalendarYear(int era) { EraInfo[]? eraInfo = CalEraInfo; - if (eraInfo == null) + if (eraInfo is null) { return MinCalendarYear; } @@ -108,7 +108,7 @@ internal int MinEraCalendarYear(int era) internal int MaxEraCalendarYear(int era) { EraInfo[]? eraInfo = CalEraInfo; - if (eraInfo == null) + if (eraInfo is null) { return MaxCalendarYear; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs index 8e2ee3d3af8acd..d71234665fd413 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs @@ -7,7 +7,7 @@ public static class GlobalizationExtensions { public static StringComparer GetStringComparer(this CompareInfo compareInfo, CompareOptions options) { - if (compareInfo == null) + if (compareInfo is null) { throw new ArgumentNullException(nameof(compareInfo)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs index 281b7269354199..d8cfcac9fe3284 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs @@ -19,7 +19,7 @@ private static bool GetSwitchValue(string switchName, string envVariable) if (!AppContext.TryGetSwitch(switchName, out bool ret)) { string? switchValue = Environment.GetEnvironmentVariable(envVariable); - if (switchValue != null) + if (switchValue is not null) { ret = bool.IsTrueStringIgnoreCase(switchValue) || switchValue.Equals("1"); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs index 6e8df3e0244a67..d1168e29e14543 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs @@ -480,7 +480,7 @@ public int[] Eras { get { - if (m_eras == null) + if (m_eras is null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewNumber.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewNumber.cs index 9b3c928eb15eea..3e10cc41a5d76d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewNumber.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewNumber.cs @@ -82,7 +82,7 @@ internal static class HebrewNumber internal static void Append(StringBuilder outputBuffer, int Number) { - Debug.Assert(outputBuffer != null); + Debug.Assert(outputBuffer is not null); int outputBufferStartingLength = outputBuffer.Length; char cTens = '\x0'; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.Win32.cs index 86145ca0fd89b4..c8b9b252cecc91 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.Win32.cs @@ -41,13 +41,13 @@ private static int GetAdvanceHijriDate() using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(InternationalRegKey)) { // Abort if we didn't find anything - if (key == null) + if (key is null) { return 0; } object? value = key.GetValue(HijriAdvanceRegKeyEntry); - if (value == null) + if (value is null) { return 0; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Icu.cs index bfaeb2c721e6f3..bac17da18e4e75 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Icu.cs @@ -11,7 +11,7 @@ private unsafe string IcuGetAsciiCore(string unicodeString, char* unicode, int c { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(unicodeString != null && unicodeString.Length >= count); + Debug.Assert(unicodeString is not null && unicodeString.Length >= count); uint flags = IcuFlags; CheckInvalidIdnCharacters(unicode, count, flags, nameof(unicode)); @@ -55,7 +55,7 @@ private unsafe string IcuGetUnicodeCore(string asciiString, char* ascii, int cou { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(asciiString != null && asciiString.Length >= count); + Debug.Assert(asciiString is not null && asciiString.Length >= count); uint flags = IcuFlags; CheckInvalidIdnCharacters(ascii, count, flags, nameof(ascii)); @@ -80,7 +80,7 @@ private unsafe string IcuGetUnicodeCore(string asciiString, char* ascii, int cou { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); - Debug.Assert(asciiString != null && asciiString.Length >= count); + Debug.Assert(asciiString is not null && asciiString.Length >= count); int realLen = Interop.Globalization.ToUnicode(flags, ascii, count, output, outputLength); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Nls.cs index 2e0e664520c042..cd8d119142986f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.Nls.cs @@ -13,7 +13,7 @@ private unsafe string NlsGetAsciiCore(string unicodeString, char* unicode, int c { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(unicodeString != null && unicodeString.Length >= count); + Debug.Assert(unicodeString is not null && unicodeString.Length >= count); uint flags = NlsFlags; @@ -45,7 +45,7 @@ private static unsafe string NlsGetAsciiCore(string unicodeString, char* unicode { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(unicodeString != null && unicodeString.Length >= count); + Debug.Assert(unicodeString is not null && unicodeString.Length >= count); int length = Interop.Normaliz.IdnToAscii(flags, unicode, count, output, outputLength); if (length == 0) @@ -60,7 +60,7 @@ private unsafe string NlsGetUnicodeCore(string asciiString, char* ascii, int cou { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(asciiString != null && asciiString.Length >= count); + Debug.Assert(asciiString is not null && asciiString.Length >= count); uint flags = NlsFlags; @@ -92,7 +92,7 @@ private static unsafe string NlsGetUnicodeCore(string asciiString, char* ascii, { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(asciiString != null && asciiString.Length >= count); + Debug.Assert(asciiString is not null && asciiString.Length >= count); int length = Interop.Normaliz.IdnToUnicode(flags, ascii, count, output, outputLength); if (length == 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs index e0b9e8251f6026..c21b024e701534 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs @@ -57,14 +57,14 @@ public string GetAscii(string unicode) => public string GetAscii(string unicode, int index) { - if (unicode == null) + if (unicode is null) throw new ArgumentNullException(nameof(unicode)); return GetAscii(unicode, index, unicode.Length - index); } public string GetAscii(string unicode, int index, int count) { - if (unicode == null) + if (unicode is null) throw new ArgumentNullException(nameof(unicode)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -104,14 +104,14 @@ public string GetUnicode(string ascii) => public string GetUnicode(string ascii, int index) { - if (ascii == null) + if (ascii is null) throw new ArgumentNullException(nameof(ascii)); return GetUnicode(ascii, index, ascii.Length - index); } public string GetUnicode(string ascii, int index, int count) { - if (ascii == null) + if (ascii is null) throw new ArgumentNullException(nameof(ascii)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.Nls.cs index 90365e2d2decae..dea4bbbfc4f8b0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.Nls.cs @@ -43,11 +43,11 @@ public partial class JapaneseCalendar : Calendar using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(JapaneseErasHive)) { // Abort if we didn't find anything - if (key == null) return null; + if (key is null) return null; // Look up the values in our reg key string[] valueNames = key.GetValueNames(); - if (valueNames != null && valueNames.Length > 0) + if (valueNames is not null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; @@ -58,7 +58,7 @@ public partial class JapaneseCalendar : Calendar EraInfo? era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i])?.ToString()); // continue if not valid - if (era == null) continue; + if (era is null) continue; // Remember we found one. registryEraRanges[iFoundEras] = era; @@ -161,7 +161,7 @@ private static int CompareEraRanges(EraInfo a, EraInfo b) private static EraInfo? GetEraFromValue(string? value, string? data) { // Need inputs - if (value == null || data == null) return null; + if (value is null || data is null) return null; // // Get Date diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Icu.cs index cfe698fabcd980..d5581979f4fe68 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Icu.cs @@ -73,7 +73,7 @@ private static unsafe string IcuNormalize(string strInput, NormalizationForm nor if (attempt == 0) { - if (toReturn != null) + if (toReturn is not null) { // Clear toReturn first to ensure we don't return the same buffer twice char[] temp = toReturn; @@ -89,7 +89,7 @@ private static unsafe string IcuNormalize(string strInput, NormalizationForm nor } finally { - if (toReturn != null) + if (toReturn is not null) { ArrayPool.Shared.Return(toReturn); } @@ -98,7 +98,7 @@ private static unsafe string IcuNormalize(string strInput, NormalizationForm nor private static void ValidateArguments(string strInput, NormalizationForm normalizationForm) { - Debug.Assert(strInput != null); + Debug.Assert(strInput is not null); if (OperatingSystem.IsBrowser() && (normalizationForm == NormalizationForm.FormKC || normalizationForm == NormalizationForm.FormKD)) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Nls.cs index 76b0983c8f2337..c0b9a9c1bcd4a9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.Nls.cs @@ -14,7 +14,7 @@ private static unsafe bool NlsIsNormalized(string strInput, NormalizationForm no { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(strInput != null); + Debug.Assert(strInput is not null); // The only way to know if IsNormalizedString failed is through checking the Win32 last error // IsNormalizedString pinvoke has SetLastError attribute property which will set the last error @@ -57,7 +57,7 @@ private static unsafe string NlsNormalize(string strInput, NormalizationForm nor { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(strInput != null); + Debug.Assert(strInput is not null); if (strInput.Length == 0) { @@ -98,7 +98,7 @@ private static unsafe string NlsNormalize(string strInput, NormalizationForm nor case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: realLength = Math.Abs(realLength); Debug.Assert(realLength > buffer.Length, "Buffer overflow should have iLength > cBuffer.Length"); - if (toReturn != null) + if (toReturn is not null) { // Clear toReturn first to ensure we don't return the same buffer twice char[] temp = toReturn; @@ -133,7 +133,7 @@ private static unsafe string NlsNormalize(string strInput, NormalizationForm nor } finally { - if (toReturn != null) + if (toReturn is not null) { ArrayPool.Shared.Return(toReturn); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs index 6371361bf4ae1f..2cbff88cdb258f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs @@ -77,7 +77,7 @@ public NumberFormatInfo() private static void VerifyDecimalSeparator(string decSep, string propertyName) { - if (decSep == null) + if (decSep is null) { throw new ArgumentNullException(propertyName); } @@ -90,7 +90,7 @@ private static void VerifyDecimalSeparator(string decSep, string propertyName) private static void VerifyGroupSeparator(string groupSep, string propertyName) { - if (groupSep == null) + if (groupSep is null) { throw new ArgumentNullException(propertyName); } @@ -98,7 +98,7 @@ private static void VerifyGroupSeparator(string groupSep, string propertyName) private static void VerifyNativeDigits(string[] nativeDig, string propertyName) { - if (nativeDig == null) + if (nativeDig is null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array); } @@ -110,7 +110,7 @@ private static void VerifyNativeDigits(string[] nativeDig, string propertyName) for (int i = 0; i < nativeDig.Length; i++) { - if (nativeDig[i] == null) + if (nativeDig[i] is null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue); } @@ -163,7 +163,7 @@ private void UpdateHasInvariantNumberSigns() internal NumberFormatInfo(CultureData? cultureData) { - if (cultureData != null) + if (cultureData is not null) { // We directly use fields here since these data is coming from data table or Win32, so we // don't need to verify their values (except for invalid parsing situations). @@ -193,7 +193,7 @@ private void VerifyWritable() public static NumberFormatInfo GetInstance(IFormatProvider? formatProvider) { - return formatProvider == null ? + return formatProvider is null ? CurrentInfo : // Fast path for a null provider GetProviderNonNull(formatProvider); @@ -280,7 +280,7 @@ public int[] CurrencyGroupSizes get => (int[])_currencyGroupSizes.Clone(); set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -298,7 +298,7 @@ public int[] NumberGroupSizes get => (int[])_numberGroupSizes.Clone(); set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -316,7 +316,7 @@ public int[] PercentGroupSizes get => (int[])_percentGroupSizes.Clone(); set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -344,7 +344,7 @@ public string CurrencySymbol get => _currencySymbol; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -366,7 +366,7 @@ public static NumberFormatInfo CurrentInfo if (!culture._isInherited) { NumberFormatInfo? info = culture._numInfo; - if (info != null) + if (info is not null) { return info; } @@ -381,7 +381,7 @@ public string NaNSymbol get => _nanSymbol; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -471,7 +471,7 @@ public string NegativeInfinitySymbol get => _negativeInfinitySymbol; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -486,7 +486,7 @@ public string NegativeSign get => _negativeSign; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -560,7 +560,7 @@ public string PositiveInfinitySymbol get => _positiveInfinitySymbol; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -575,7 +575,7 @@ public string PositiveSign get => _positiveSign; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -631,7 +631,7 @@ public string PercentSymbol get => _percentSymbol; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -646,7 +646,7 @@ public string PerMilleSymbol get => _perMilleSymbol; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -685,7 +685,7 @@ public DigitShapes DigitSubstitution public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { - if (nfi == null) + if (nfi is null) { throw new ArgumentNullException(nameof(nfi)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/Ordinal.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/Ordinal.cs index 50bff4353e188f..f5908f80793fc2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Ordinal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Ordinal.cs @@ -218,12 +218,12 @@ internal static int CompareIgnoreCaseInvariantMode(ref char strA, int lengthA, r internal static unsafe int IndexOf(string source, string value, int startIndex, int count, bool ignoreCase) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } @@ -279,12 +279,12 @@ internal static int IndexOfOrdinalIgnoreCase(ReadOnlySpan source, ReadOnly internal static unsafe int LastIndexOf(string source, string value, int startIndex, int count, bool ignoreCase) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs index a10c39d02ed75e..786cbcf72e7f15 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs @@ -92,7 +92,7 @@ internal static char ToUpper(char c) return c; } - if (casingTable == null) + if (casingTable is null) { casingTable = InitOrdinalCasingPage(pageNumber); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs index 26375f2f698259..57f8c9d62132f9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs @@ -24,7 +24,7 @@ public class RegionInfo public RegionInfo(string name) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -93,7 +93,7 @@ public static RegionInfo CurrentRegion get { RegionInfo? temp = s_currentRegionInfo; - if (temp == null) + if (temp is null) { temp = new RegionInfo(CultureData.GetCurrentRegionData()); @@ -112,7 +112,7 @@ public virtual string Name { get { - Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); + Debug.Assert(_name is not null, "Expected RegionInfo._name to be populated already"); return _name; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs index 78e5117131e5dc..ada9354ce0173c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs @@ -46,11 +46,11 @@ internal SortKey(CompareInfo compareInfo, string str, CompareOptions options, by /// public static int Compare(SortKey sortkey1, SortKey sortkey2) { - if (sortkey1 == null) + if (sortkey1 is null) { throw new ArgumentNullException(nameof(sortkey1)); } - if (sortkey2 == null) + if (sortkey2 is null) { throw new ArgumentNullException(nameof(sortkey2)); } @@ -58,8 +58,8 @@ public static int Compare(SortKey sortkey1, SortKey sortkey2) byte[] key1Data = sortkey1._keyData; byte[] key2Data = sortkey2._keyData; - Debug.Assert(key1Data != null, "key1Data != null"); - Debug.Assert(key2Data != null, "key2Data != null"); + Debug.Assert(key1Data is not null, "key1Data is not null"); + Debug.Assert(key2Data is not null, "key2Data is not null"); // SortKey comparisons are done as an ordinal comparison by the raw sort key bytes. diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortVersion.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortVersion.cs index c146480e589ac1..b8e495fb39a3c0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortVersion.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortVersion.cs @@ -45,7 +45,7 @@ public override bool Equals(object? obj) public bool Equals(SortVersion? other) { - if (other == null) + if (other is null) { return false; } @@ -62,7 +62,7 @@ public override int GetHashCode() [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(SortVersion? left, SortVersion? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/StringInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/StringInfo.cs index c395e92d247a07..1bb466daaaa0b8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/StringInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/StringInfo.cs @@ -44,7 +44,7 @@ private int[]? Indexes { get { - if (_indexes == null && String.Length > 0) + if (_indexes is null && String.Length > 0) { _indexes = StringInfo.ParseCombiningCharacters(String); } @@ -176,7 +176,7 @@ public static int[] ParseCombiningCharacters(string str) private static int[] ParseCombiningCharactersForLargeString(string str) { - Debug.Assert(str != null); + Debug.Assert(str is not null); // If we have a large string, we may as well take the hit of using a List // instead of trying the stackalloc optimizations we have for smaller strings. diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextElementEnumerator.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextElementEnumerator.cs index e891d22a937080..7494658453e9ed 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextElementEnumerator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextElementEnumerator.cs @@ -18,7 +18,7 @@ public class TextElementEnumerator : IEnumerator internal TextElementEnumerator(string str, int startIndex) { - Debug.Assert(str != null, "TextElementEnumerator(): str != null"); + Debug.Assert(str is not null, "TextElementEnumerator(): str is not null"); Debug.Assert(startIndex >= 0 && startIndex <= str.Length, "TextElementEnumerator(): startIndex >= 0 && startIndex <= str.Length"); _str = str; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Icu.cs index 762bb9f3bec77e..34db4ac63a69ad 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Icu.cs @@ -11,7 +11,7 @@ public partial class TextInfo private static bool NeedsTurkishCasing(string localeName) { - Debug.Assert(localeName != null); + Debug.Assert(localeName is not null); return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("\u0131", "I", CompareOptions.IgnoreCase) == 0; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Nls.cs index ca6689f4cef534..e83b7827637792 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.Nls.cs @@ -11,8 +11,8 @@ private unsafe void NlsChangeCase(char* pSource, int pSourceLen, char* pResult, { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - Debug.Assert(pSource != null); - Debug.Assert(pResult != null); + Debug.Assert(pSource is not null); + Debug.Assert(pResult is not null); Debug.Assert(pSourceLen >= 0); Debug.Assert(pResultLen >= 0); Debug.Assert(pSourceLen <= pResultLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs index 06d9ac7e041882..17a911c0410f79 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -91,7 +91,7 @@ public object Clone() /// public static TextInfo ReadOnly(TextInfo textInfo) { - if (textInfo == null) + if (textInfo is null) { throw new ArgumentNullException(nameof(textInfo)); } @@ -127,7 +127,7 @@ public string ListSeparator get => _listSeparator ??= _cultureData.ListSeparator; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -163,7 +163,7 @@ internal static char ToLowerInvariant(char c) public string ToLower(string str) { - if (str == null) + if (str is null) { throw new ArgumentNullException(nameof(str)); } @@ -319,7 +319,7 @@ private unsafe string ChangeCaseCommon(string source) where TConver bool toUpper = typeof(TConversion) == typeof(ToUpperConversion); // JIT will treat this as a constant in release builds Debug.Assert(!GlobalizationMode.Invariant); - Debug.Assert(source != null); + Debug.Assert(source is not null); // If the string is empty, we're done. if (source.Length == 0) @@ -567,7 +567,7 @@ internal static char ToUpperInvariant(char c) public string ToUpper(string str) { - if (str == null) + if (str is null) { throw new ArgumentNullException(nameof(str)); } @@ -645,7 +645,7 @@ public override string ToString() /// public unsafe string ToTitleCase(string str) { - if (str == null) + if (str is null) { throw new ArgumentNullException(nameof(str)); } @@ -703,7 +703,7 @@ public unsafe string ToTitleCase(string str) i++; if (hasLowerCase) { - if (lowercaseData == null) + if (lowercaseData is null) { lowercaseData = ToLower(str); } @@ -735,7 +735,7 @@ public unsafe string ToTitleCase(string str) { if (hasLowerCase) { - if (lowercaseData == null) + if (lowercaseData is null) { lowercaseData = ToLower(str); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanFormat.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanFormat.cs index c82a2c3c950fca..021bec2c4da781 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanFormat.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanFormat.cs @@ -257,7 +257,7 @@ private static bool TryFormatStandard(TimeSpan value, StandardFormat format, str // Write fraction and separator, if necessary if (fractionDigits != 0) { - Debug.Assert(format == StandardFormat.C || decimalSeparator != null); + Debug.Assert(format == StandardFormat.C || decimalSeparator is not null); if (format == StandardFormat.C) { destination[idx++] = '.'; @@ -309,10 +309,10 @@ private static void WriteDigits(uint value, Span buffer) /// Format the TimeSpan instance using the specified format. private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan format, DateTimeFormatInfo dtfi, StringBuilder? result = null) { - Debug.Assert(dtfi != null); + Debug.Assert(dtfi is not null); bool resultBuilderIsPooled = false; - if (result == null) + if (result is null) { result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); resultBuilderIsPooled = true; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanParse.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanParse.cs index 2e7df616e238f8..b8ac57034287a1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanParse.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TimeSpanParse.cs @@ -391,7 +391,7 @@ internal bool FullHMSFMatch(TimeSpanFormat.FormatLiterals pattern) => internal void Init(DateTimeFormatInfo dtfi) { - Debug.Assert(dtfi != null); + Debug.Assert(dtfi is not null); _lastSeenTTT = TTT.None; _tokenCount = 0; @@ -527,7 +527,7 @@ internal bool SetArgumentNullFailure(string argumentName) return false; } - Debug.Assert(argumentName != null); + Debug.Assert(argumentName is not null); throw new ArgumentNullException(argumentName, SR.ArgumentNull_String); } @@ -1658,7 +1658,7 @@ internal void SkipBlanks() /// Common private ParseExactMultiple method called by both ParseExactMultiple and TryParseExactMultiple. private static bool TryParseExactMultipleTimeSpan(ReadOnlySpan input, string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) { - if (formats == null) + if (formats is null) { return result.SetArgumentNullFailure(nameof(formats)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Int16.cs b/src/libraries/System.Private.CoreLib/src/System/Int16.cs index c1375df6658d40..2ae4a0a708e735 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Int16.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Int16.cs @@ -27,7 +27,7 @@ namespace System // public int CompareTo(object? value) { - if (value == null) + if (value is null) { return 1; } @@ -94,27 +94,27 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan public static short Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider)); } @@ -143,7 +143,7 @@ private static short Parse(ReadOnlySpan s, NumberStyles style, NumberForma public static bool TryParse([NotNullWhen(true)] string? s, out short result) { - if (s == null) + if (s is null) { result = 0; return false; @@ -161,7 +161,7 @@ public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, I { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) + if (s is null) { result = 0; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/Int32.cs b/src/libraries/System.Private.CoreLib/src/System/Int32.cs index de18cd3b84a737..3697769ace7145 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Int32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Int32.cs @@ -30,7 +30,7 @@ namespace System // public int CompareTo(object? value) { - if (value == null) + if (value is null) { return 1; } @@ -104,14 +104,14 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan public static int Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static int Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo); } @@ -121,7 +121,7 @@ public static int Parse(string s, NumberStyles style) // public static int Parse(string s, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } @@ -132,7 +132,7 @@ public static int Parse(string s, IFormatProvider? provider) public static int Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } @@ -147,7 +147,7 @@ public static int Parse(ReadOnlySpan s, NumberStyles style = NumberStyles. // public static bool TryParse([NotNullWhen(true)] string? s, out int result) { - if (s == null) + if (s is null) { result = 0; return false; @@ -168,7 +168,7 @@ public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, I { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) + if (s is null) { result = 0; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs b/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs index c1a9fb84dce430..c97e0f48a0a7da 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs @@ -66,7 +66,7 @@ private unsafe IntPtr(SerializationInfo info, StreamingContext context) unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) throw new ArgumentNullException(nameof(info)); info.AddValue("value", ToInt64()); diff --git a/src/libraries/System.Private.CoreLib/src/System/Lazy.cs b/src/libraries/System.Private.CoreLib/src/System/Lazy.cs index b0778f5b71c215..25c3b640c5a92e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Lazy.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Lazy.cs @@ -90,7 +90,7 @@ internal LazyHelper(LazyThreadSafetyMode mode, Exception exception) [DoesNotReturn] internal void ThrowException() { - Debug.Assert(_exceptionDispatch != null, "execution path is invalid"); + Debug.Assert(_exceptionDispatch is not null, "execution path is invalid"); _exceptionDispatch.Throw(); } @@ -123,12 +123,12 @@ private LazyThreadSafetyMode GetMode() internal static LazyThreadSafetyMode? GetMode(LazyHelper? state) { - if (state == null) + if (state is null) return null; // we don't know the mode anymore return state.GetMode(); } - internal static bool GetIsValueFaulted(LazyHelper? state) => state?._exceptionDispatch != null; + internal static bool GetIsValueFaulted(LazyHelper? state) => state?._exceptionDispatch is not null; internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor) { @@ -296,7 +296,7 @@ public Lazy(Func valueFactory, LazyThreadSafetyMode mode) private Lazy(Func? valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor) { - if (valueFactory == null && !useDefaultConstructor) + if (valueFactory is null && !useDefaultConstructor) throw new ArgumentNullException(nameof(valueFactory)); _factory = valueFactory; @@ -314,7 +314,7 @@ private void ViaFactory(LazyThreadSafetyMode mode) try { Func? factory = _factory; - if (factory == null) + if (factory is null) throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue); _factory = null; @@ -367,7 +367,7 @@ private void PublicationOnlyViaConstructor(LazyHelper initializer) private void PublicationOnlyViaFactory(LazyHelper initializer) { Func? factory = _factory; - if (factory == null) + if (factory is null) { PublicationOnlyWaitForOtherThreadToPublish(); } @@ -393,7 +393,7 @@ private T CreateValue() // we have to create a copy of state here, and use the copy exclusively from here on in // so as to ensure thread safety. LazyHelper? state = _state; - if (state != null) + if (state is not null) { switch (state.State) { @@ -478,7 +478,7 @@ internal T? ValueForDebugDisplay /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization, /// will return false. /// - public bool IsValueCreated => _state == null; + public bool IsValueCreated => _state is null; /// Gets the lazily initialized value of the current . @@ -502,7 +502,7 @@ internal T? ValueForDebugDisplay /// from initialization delegate. /// [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public T Value => _state == null ? _value! : CreateValue(); + public T Value => _state is null ? _value! : CreateValue(); } /// A debugger view of the Lazy<T> to surface additional debugging properties and diff --git a/src/libraries/System.Private.CoreLib/src/System/Memory.cs b/src/libraries/System.Private.CoreLib/src/System/Memory.cs index c93dfc4baed177..7634e0abefd6dd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Memory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Memory.cs @@ -40,7 +40,7 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array) { - if (array == null) + if (array is null) { this = default; return; // returns default @@ -56,7 +56,7 @@ public Memory(T[]? array) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[]? array, int start) { - if (array == null) + if (array is null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -88,7 +88,7 @@ internal Memory(T[]? array, int start) [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array, int start, int length) { - if (array == null) + if (array is null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -124,7 +124,7 @@ public Memory(T[]? array, int start, int length) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager manager, int length) { - Debug.Assert(manager != null); + Debug.Assert(manager is not null); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -148,7 +148,7 @@ internal Memory(MemoryManager manager, int length) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager manager, int start, int length) { - Debug.Assert(manager != null); + Debug.Assert(manager is not null); if (length < 0 || start < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -164,7 +164,7 @@ internal Memory(object? obj, int start, int length) // No validation performed in release builds; caller must provide any necessary validation. // 'obj is T[]' below also handles things like int[] <-> uint[] being convertible - Debug.Assert((obj == null) + Debug.Assert((obj is null) || (typeof(T) == typeof(char) && obj is string) #if FEATURE_UTF8STRING || ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String) @@ -293,7 +293,7 @@ public unsafe Span Span // Copy this field into a local so that it can't change out from under us mid-operation. object? tmpObject = _object; - if (tmpObject != null) + if (tmpObject is not null) { if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string)) { @@ -415,7 +415,7 @@ public unsafe MemoryHandle Pin() // and we're not required to keep this as safe as the other Span-based APIs. object? tmpObject = _object; - if (tmpObject != null) + if (tmpObject is not null) { if (typeof(T) == typeof(char) && tmpObject is string s) { @@ -507,7 +507,7 @@ public override int GetHashCode() { // We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash // code is based on object identity and referential equality, not deep equality (as common with string). - return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; + return (_object is not null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs index 86038795cef8d7..8be62a598fea22 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs @@ -20,7 +20,7 @@ public static partial class MemoryExtensions [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, int start) { - if (array == null) + if (array is null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -40,7 +40,7 @@ public static Span AsSpan(this T[]? array, int start) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, Index startIndex) { - if (array == null) + if (array is null) { if (!startIndex.Equals(Index.Start)) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); @@ -64,7 +64,7 @@ public static Span AsSpan(this T[]? array, Index startIndex) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, Range range) { - if (array == null) + if (array is null) { Index startIndex = range.Start; Index endIndex = range.End; @@ -90,7 +90,7 @@ public static Span AsSpan(this T[]? array, Range range) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string? text) { - if (text == null) + if (text is null) return default; return new ReadOnlySpan(ref text.GetRawStringData(), text.Length); @@ -108,7 +108,7 @@ public static ReadOnlySpan AsSpan(this string? text) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string? text, int start) { - if (text == null) + if (text is null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); @@ -134,7 +134,7 @@ public static ReadOnlySpan AsSpan(this string? text, int start) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string? text, int start, int length) { - if (text == null) + if (text is null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); @@ -158,7 +158,7 @@ public static ReadOnlySpan AsSpan(this string? text, int start, int length /// Returns default when is null. public static ReadOnlyMemory AsMemory(this string? text) { - if (text == null) + if (text is null) return default; return new ReadOnlyMemory(text, 0, text.Length); @@ -173,7 +173,7 @@ public static ReadOnlyMemory AsMemory(this string? text) /// public static ReadOnlyMemory AsMemory(this string? text, int start) { - if (text == null) + if (text is null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); @@ -191,7 +191,7 @@ public static ReadOnlyMemory AsMemory(this string? text, int start) /// The index at which to begin this slice. public static ReadOnlyMemory AsMemory(this string? text, Index startIndex) { - if (text == null) + if (text is null) { if (!startIndex.Equals(Index.Start)) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); @@ -216,7 +216,7 @@ public static ReadOnlyMemory AsMemory(this string? text, Index startIndex) /// public static ReadOnlyMemory AsMemory(this string? text, int start, int length) { - if (text == null) + if (text is null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); @@ -240,7 +240,7 @@ public static ReadOnlyMemory AsMemory(this string? text, int start, int le /// The range used to indicate the start and length of the sliced string. public static ReadOnlyMemory AsMemory(this string? text, Range range) { - if (text == null) + if (text is null) { Index startIndex = range.Start; Index endIndex = range.End; @@ -1275,7 +1275,7 @@ public static Span AsSpan(this ArraySegment segment, Range range) /// public static Memory AsMemory(this T[]? array, Index startIndex) { - if (array == null) + if (array is null) { if (!startIndex.Equals(Index.Start)) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); @@ -1307,7 +1307,7 @@ public static Memory AsMemory(this T[]? array, Index startIndex) /// public static Memory AsMemory(this T[]? array, Range range) { - if (array == null) + if (array is null) { Index startIndex = range.Start; Index endIndex = range.End; @@ -1769,7 +1769,7 @@ public static int BinarySearch( this ReadOnlySpan span, T value, TComparer comparer) where TComparer : IComparer { - if (comparer == null) + if (comparer is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); var comparable = new SpanHelpers.ComparerComparable( @@ -1824,7 +1824,7 @@ public static void Sort(this Span span, TComparer comparer) /// is null. public static void Sort(this Span span, Comparison comparison) { - if (comparison == null) + if (comparison is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); if (span.Length > 1) @@ -1898,7 +1898,7 @@ public static void Sort(this Span keys, Span public static void Sort(this Span keys, Span items, Comparison comparison) { - if (comparison == null) + if (comparison is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); if (keys.Length != items.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_SpansMustHaveSameLength); diff --git a/src/libraries/System.Private.CoreLib/src/System/MissingFieldException.cs b/src/libraries/System.Private.CoreLib/src/System/MissingFieldException.cs index d87f7023b7b548..3aa480ada95288 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MissingFieldException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MissingFieldException.cs @@ -42,14 +42,14 @@ public override string Message { get { - if (ClassName == null) + if (ClassName is null) { return base.Message; } else { // do any desired fixups to classname here. - return SR.Format(SR.MissingField_Name, (Signature != null ? FormatSignature(Signature) + " " : "") + ClassName + "." + MemberName); + return SR.Format(SR.MissingField_Name, (Signature is not null ? FormatSignature(Signature) + " " : "") + ClassName + "." + MemberName); } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/MissingMethodException.cs b/src/libraries/System.Private.CoreLib/src/System/MissingMethodException.cs index 715e122072d3a1..047957cc3684ef 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MissingMethodException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MissingMethodException.cs @@ -48,9 +48,9 @@ protected MissingMethodException(SerializationInfo info, StreamingContext contex } public override string Message => - ClassName == null ? + ClassName is null ? base.Message : SR.Format(SR.MissingMethod_Name, ClassName + "." + MemberName + - (Signature != null ? " " + FormatSignature(Signature) : string.Empty)); + (Signature is not null ? " " + FormatSignature(Signature) : string.Empty)); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Nullable.cs b/src/libraries/System.Private.CoreLib/src/System/Nullable.cs index 0fa9141483ee24..107197cd196e55 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Nullable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Nullable.cs @@ -52,8 +52,8 @@ public readonly T GetValueOrDefault(T defaultValue) => public override bool Equals(object? other) { - if (!hasValue) return other == null; - if (other == null) return false; + if (!hasValue) return other is null; + if (other is null) return false; return value.Equals(other); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs b/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs index d8a842251bc3f5..f637fbed04206e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs @@ -30,7 +30,7 @@ internal unsafe ref struct NumberBuffer public NumberBuffer(NumberBufferKind kind, byte* digits, int digitsLength) { - Debug.Assert(digits != null); + Debug.Assert(digits is not null); Debug.Assert(digitsLength > 0); DigitsCount = 0; diff --git a/src/libraries/System.Private.CoreLib/src/System/Object.cs b/src/libraries/System.Private.CoreLib/src/System/Object.cs index fd217954014082..f3dc7a7a6431cd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Object.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Object.cs @@ -56,7 +56,7 @@ public static bool Equals(object? objA, object? objB) { return true; } - if (objA == null || objB == null) + if (objA is null || objB is null) { return false; } diff --git a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs index 6b3a5b5682f48b..dca7d24150ab53 100644 --- a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs +++ b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs @@ -28,7 +28,7 @@ internal OperatingSystem(PlatformID platform, Version version, string? servicePa throw new ArgumentOutOfRangeException(nameof(platform), platform, SR.Format(SR.Arg_EnumIllegalVal, platform)); } - if (version == null) + if (version is null) { throw new ArgumentNullException(nameof(version)); } @@ -57,7 +57,7 @@ public string VersionString { get { - if (_versionString == null) + if (_versionString is null) { string os; switch (_platform) @@ -90,7 +90,7 @@ public string VersionString /// Case-insensitive platform name. Examples: Browser, Linux, FreeBSD, Android, iOS, macOS, tvOS, watchOS, Windows. public static bool IsOSPlatform(string platform) { - if (platform == null) + if (platform is null) { throw new ArgumentNullException(nameof(platform)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Progress.cs b/src/libraries/System.Private.CoreLib/src/System/Progress.cs index 6cc12c448c767c..5209d9e82cd512 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Progress.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Progress.cs @@ -32,7 +32,7 @@ public Progress() // Capture the current synchronization context. // If there is no current context, we use a default instance targeting the ThreadPool. _synchronizationContext = SynchronizationContext.Current ?? ProgressStatics.DefaultContext; - Debug.Assert(_synchronizationContext != null); + Debug.Assert(_synchronizationContext is not null); _invokeHandlers = new SendOrPostCallback(InvokeHandlers); } @@ -66,7 +66,7 @@ protected virtual void OnReport(T value) // an event handler is removed between now and then. Action? handler = _handler; EventHandler? changedEvent = ProgressChanged; - if (handler != null || changedEvent != null) + if (handler is not null || changedEvent is not null) { // Post the processing to the sync context. // (If T is a value type, it will get boxed here.) diff --git a/src/libraries/System.Private.CoreLib/src/System/ReadOnlyMemory.cs b/src/libraries/System.Private.CoreLib/src/System/ReadOnlyMemory.cs index e26612c07ef67a..ea76d8e5e53383 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ReadOnlyMemory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ReadOnlyMemory.cs @@ -42,7 +42,7 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[]? array) { - if (array == null) + if (array is null) { this = default; return; // returns default @@ -68,7 +68,7 @@ public ReadOnlyMemory(T[]? array) [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[]? array, int start, int length) { - if (array == null) + if (array is null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -99,7 +99,7 @@ internal ReadOnlyMemory(object? obj, int start, int length) // No validation performed in release builds; caller must provide any necessary validation. // 'obj is T[]' below also handles things like int[] <-> uint[] being convertible - Debug.Assert((obj == null) + Debug.Assert((obj is null) || (typeof(T) == typeof(char) && obj is string) #if FEATURE_UTF8STRING || ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String) @@ -215,7 +215,7 @@ public unsafe ReadOnlySpan Span // Copy this field into a local so that it can't change out from under us mid-operation. object? tmpObject = _object; - if (tmpObject != null) + if (tmpObject is not null) { if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string)) { @@ -330,7 +330,7 @@ public unsafe MemoryHandle Pin() // and we're not required to keep this as safe as the other Span-based APIs. object? tmpObject = _object; - if (tmpObject != null) + if (tmpObject is not null) { if (typeof(T) == typeof(char) && tmpObject is string s) { @@ -417,7 +417,7 @@ public override int GetHashCode() { // We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash // code is based on object identity and referential equality, not deep equality (as common with string). - return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; + return (_object is not null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; } /// Gets the state of the memory as individual fields. diff --git a/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs b/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs index 465fc78674df53..d0301e0f553c45 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs @@ -36,7 +36,7 @@ public readonly ref struct ReadOnlySpan [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array) { - if (array == null) + if (array is null) { this = default; return; // returns default @@ -60,7 +60,7 @@ public ReadOnlySpan(T[]? array) [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array, int start, int length) { - if (array == null) + if (array is null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs index bd6dd45fb0b45e..4962d05cfa0fc9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs @@ -32,7 +32,7 @@ public virtual IEnumerable DefinedTypes for (int i = 0; i < types.Length; i++) { TypeInfo typeinfo = types[i].GetTypeInfo(); - if (typeinfo == null) + if (typeinfo is null) throw new NotSupportedException(SR.Format(SR.NotSupported_NoTypeInfo, types[i].FullName)); typeinfos[i] = typeinfo; @@ -127,7 +127,7 @@ public virtual IEnumerable ExportedTypes public virtual object? CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object[]? args, CultureInfo? culture, object[]? activationAttributes) { Type? t = GetType(typeName, throwOnError: false, ignoreCase: ignoreCase); - if (t == null) + if (t is null) return null; return Activator.CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes); @@ -175,7 +175,7 @@ public override string ToString() [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Assembly? left, Assembly? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { @@ -198,11 +198,11 @@ public override string ToString() public static Assembly? GetAssembly(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); Module m = type.Module; - if (m == null) + if (m is null) return null; else return m.Assembly; @@ -228,7 +228,7 @@ public override string ToString() [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) { - if (rawAssembly == null) + if (rawAssembly is null) throw new ArgumentNullException(nameof(rawAssembly)); if (rawAssembly.Length == 0) @@ -244,7 +244,7 @@ public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly LoadFile(string path) { - if (path == null) + if (path is null) throw new ArgumentNullException(nameof(path)); if (PathInternal.IsPartiallyQualified(path)) @@ -271,7 +271,7 @@ public static Assembly LoadFile(string path) private static Assembly? LoadFromResolveHandler(object? sender, ResolveEventArgs args) { Assembly? requestingAssembly = args.RequestingAssembly; - if (requestingAssembly == null) + if (requestingAssembly is null) { return null; } @@ -328,7 +328,7 @@ public static Assembly LoadFile(string path) [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly LoadFrom(string assemblyFile) { - if (assemblyFile == null) + if (assemblyFile is null) throw new ArgumentNullException(nameof(assemblyFile)); string fullPath = Path.GetFullPath(assemblyFile); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs index c547a30e50c89a..62196e9e4c7c8f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs @@ -56,7 +56,7 @@ public CultureInfo? CultureInfo public string? CultureName { get => _cultureInfo?.Name; - set => _cultureInfo = (value == null) ? null : new CultureInfo(value); + set => _cultureInfo = (value is null) ? null : new CultureInfo(value); } public string? CodeBase @@ -69,7 +69,7 @@ public string? EscapedCodeBase { get { - if (_codeBase == null) + if (_codeBase is null) return null; else return EscapeCodeBase(_codeBase); @@ -141,7 +141,7 @@ public object Clone() */ public static AssemblyName GetAssemblyName(string assemblyFile) { - if (assemblyFile == null) + if (assemblyFile is null) throw new ArgumentNullException(nameof(assemblyFile)); return GetFileInformationCore(assemblyFile); @@ -156,7 +156,7 @@ public void SetPublicKey(byte[]? publicKey) { _publicKey = publicKey; - if (publicKey == null) + if (publicKey is null) _flags &= ~AssemblyNameFlags.PublicKey; else _flags |= AssemblyNameFlags.PublicKey; @@ -210,7 +210,7 @@ public string FullName { get { - if (this.Name == null) + if (this.Name is null) return string.Empty; // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. byte[]? pkt = _publicKeyToken ?? ComputePublicKeyToken(); @@ -221,7 +221,7 @@ public string FullName public override string ToString() { string s = FullName; - if (s == null) + if (s is null) return base.ToString()!; else return s; @@ -247,10 +247,10 @@ public static bool ReferenceMatchesDefinition(AssemblyName? reference, AssemblyN if (object.ReferenceEquals(reference, definition)) return true; - if (reference == null) + if (reference is null) throw new ArgumentNullException(nameof(reference)); - if (definition == null) + if (definition is null) throw new ArgumentNullException(nameof(definition)); string refName = reference.Name ?? string.Empty; @@ -260,12 +260,12 @@ public static bool ReferenceMatchesDefinition(AssemblyName? reference, AssemblyN internal static string EscapeCodeBase(string? codebase) { - if (codebase == null) + if (codebase is null) return string.Empty; int position = 0; char[]? dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); - if (dest == null) + if (dest is null) return codebase; return new string(dest, 0, position); @@ -365,7 +365,7 @@ internal static string EscapeCodeBase(string? codebase) if (prevInputPos != i) { // need to fill up the dest array ? - if (prevInputPos != start || dest != null) + if (prevInputPos != start || dest is not null) dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs index f5b0e46ca19463..047dc03ddee904 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs @@ -18,12 +18,12 @@ public static string ComputeDisplayName(string? name, Version? version, string? throw new FileLoadException(); StringBuilder sb = new StringBuilder(); - if (name != null) + if (name is not null) { sb.AppendQuoted(name); } - if (version != null) + if (version is not null) { Version canonicalizedVersion = version.CanonicalizeVersion(); if (canonicalizedVersion.Major != ushort.MaxValue) @@ -51,7 +51,7 @@ public static string ComputeDisplayName(string? name, Version? version, string? } } - if (cultureName != null) + if (cultureName is not null) { if (cultureName.Length == 0) cultureName = "neutral"; @@ -59,7 +59,7 @@ public static string ComputeDisplayName(string? name, Version? version, string? sb.AppendQuoted(cultureName); } - if (pkt != null) + if (pkt is not null) { if (pkt.Length > PUBLIC_KEY_TOKEN_LEN) throw new ArgumentException(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs index 178c872b34b1de..bf8bcd90d4e342 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs @@ -24,7 +24,7 @@ protected ConstructorInfo() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ConstructorInfo? left, ConstructorInfo? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs index fafdb5b1d49880..904f3899144d2d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs @@ -13,7 +13,7 @@ public readonly partial struct CustomAttributeNamedArgument public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value) { - if (memberInfo == null) + if (memberInfo is null) throw new ArgumentNullException(nameof(memberInfo)); Type type; @@ -42,7 +42,7 @@ public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedA public override string ToString() { - if (m_memberInfo == null) + if (m_memberInfo is null) return base.ToString()!; return string.Format("{0} = {1}", MemberInfo.Name, TypedValue.ToString(ArgumentType != typeof(object))); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs index e848262a6e28dd..6e63a30a37b7fc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs @@ -17,7 +17,7 @@ public readonly partial struct CustomAttributeTypedArgument public CustomAttributeTypedArgument(Type argumentType, object? value) { // value can be null. - if (argumentType == null) + if (argumentType is null) throw new ArgumentNullException(nameof(argumentType)); m_value = (value is null) ? null : CanonicalizeValue(value); @@ -27,7 +27,7 @@ public CustomAttributeTypedArgument(Type argumentType, object? value) public CustomAttributeTypedArgument(object value) { // value cannot be null. - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); m_value = CanonicalizeValue(value); @@ -39,12 +39,12 @@ public CustomAttributeTypedArgument(object value) internal string ToString(bool typed) { - if (m_argumentType == null) + if (m_argumentType is null) return base.ToString()!; if (ArgumentType.IsEnum) return string.Format(typed ? "{0}" : "({1}){0}", Value, ArgumentType.FullName); - else if (Value == null) + else if (Value is null) return string.Format(typed ? "null" : "({0})null", ArgumentType.Name); else if (ArgumentType == typeof(string)) return string.Format("\"{0}\"", Value); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/Opcode.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/Opcode.cs index cb40f1af0ef49c..86e60ff4bf593a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/Opcode.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/Opcode.cs @@ -73,7 +73,7 @@ public string? Name // Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.) // Note that we do not any locks here because of we always get the same names. The last one wins. string[]? nameCache = g_nameCache; - if (nameCache == null) + if (nameCache is null) { nameCache = new string[0x11f]; g_nameCache = nameCache; @@ -98,7 +98,7 @@ public string? Name } string name = Volatile.Read(ref nameCache[idx]); - if (name != null) + if (name is not null) return name; // Create ilasm style name from the enum value name. 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 569bd36754d39a..0ade165eb46ce5 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 @@ -94,7 +94,7 @@ private void CloseGenericArgument() private void AddName(string name) { - Debug.Assert(name != null); + Debug.Assert(name is not null); if (_nestedName) Append('+'); @@ -128,7 +128,7 @@ private void AddArray(int rank) private void AddAssemblySpec(string assemblySpec) { - if (assemblySpec != null && !assemblySpec.Equals("")) + if (assemblySpec is not null && !assemblySpec.Equals("")) { Append(", "); @@ -305,7 +305,7 @@ private void AddAssemblyQualifiedName(Type type, Format format) // Append namespace + nesting + name var nestings = new List(); - for (Type? t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType) + for (Type? t = rootType; t is not null; t = t.IsGenericParameter ? null : t.DeclaringType) nestings.Add(t); for (int i = nestings.Count - 1; i >= 0; i--) @@ -313,7 +313,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 && enclosingType.Namespace is not null && enclosingType.Namespace.Length != 0) name = enclosingType.Namespace + "." + name; AddName(name); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs index 02f19f16bbbd57..fb2f704bab7e60 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs @@ -63,7 +63,7 @@ public virtual void AddEventHandler(object? target, Delegate? handler) { MethodInfo? addMethod = GetAddMethod(nonPublic: false); - if (addMethod == null) + if (addMethod is null) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); addMethod.Invoke(target, new object?[] { handler }); @@ -75,7 +75,7 @@ public virtual void RemoveEventHandler(object? target, Delegate? handler) { MethodInfo? removeMethod = GetRemoveMethod(nonPublic: false); - if (removeMethod == null) + if (removeMethod is null) throw new InvalidOperationException(SR.InvalidOperation_NoPublicRemoveMethod); removeMethod.Invoke(target, new object?[] { handler }); @@ -87,7 +87,7 @@ public virtual void RemoveEventHandler(object? target, Delegate? handler) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(EventInfo? left, EventInfo? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs index a50821d7ed02bb..501a44265ad3b0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs @@ -42,7 +42,7 @@ protected FieldInfo() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(FieldInfo? left, FieldInfo? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs index 648f61ab653ae9..ca6e99ab8dad20 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs @@ -7,7 +7,7 @@ public static class IntrospectionExtensions { public static TypeInfo GetTypeInfo(this Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); if (type is IReflectableType reflectableType) diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs index 61381b7edc8f27..0402e3c8a933ed 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs @@ -46,7 +46,7 @@ public virtual Module Module [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MemberInfo? left, MemberInfo? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs index dd3add242f4992..1d1199670dcd08 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs @@ -61,7 +61,7 @@ this is ConstructorInfo && [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MethodBase? left, MethodBase? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs index 532899524e4975..d02a98ed0e47ad 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs @@ -37,7 +37,7 @@ protected MethodInfo() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MethodInfo? left, MethodInfo? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs index 4fe3b9ad74747a..896d6fcc817fdd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs @@ -33,7 +33,7 @@ protected Module() { } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo? GetMethod(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, null, null); @@ -44,13 +44,13 @@ protected Module() { } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (types == null) + if (types is null) throw new ArgumentNullException(nameof(types)); for (int i = 0; i < types.Length; i++) { - if (types[i] == null) + if (types[i] is null) throw new ArgumentNullException(nameof(types)); } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); @@ -91,7 +91,7 @@ public virtual Type[] FindTypes(TypeFilter? filter, object? filterCriteria) int cnt = 0; for (int i = 0; i < c.Length; i++) { - if (filter != null && !filter(c[i], filterCriteria)) + if (filter is not null && !filter(c[i], filterCriteria)) c[i] = null!; else cnt++; @@ -103,7 +103,7 @@ public virtual Type[] FindTypes(TypeFilter? filter, object? filterCriteria) cnt = 0; for (int i = 0; i < c.Length; i++) { - if (c[i] != null) + if (c[i] is not null) ret[cnt++] = c[i]; } return ret; @@ -144,7 +144,7 @@ public virtual Type[] FindTypes(TypeFilter? filter, object? filterCriteria) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Module? left, Module? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs index c9ec1cfb7dd254..595be86643d2f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs @@ -28,7 +28,7 @@ protected ParameterInfo() { } public virtual bool IsDefined(Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); return false; @@ -40,7 +40,7 @@ public virtual bool IsDefined(Type attributeType, bool inherit) public virtual object[] GetCustomAttributes(bool inherit) => Array.Empty(); public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); return Array.Empty(); @@ -56,7 +56,7 @@ public object GetRealObject(StreamingContext context) // Once all the serializable fields have come in we can set up the real // instance based on just two of them (MemberImpl and PositionImpl). - if (MemberImpl == null) + if (MemberImpl is null) throw new SerializationException(SR.Serialization_InsufficientState); ParameterInfo[] args; @@ -75,7 +75,7 @@ public object GetRealObject(StreamingContext context) { args = ((MethodBase)MemberImpl).GetParametersNoCopy(); - if (args != null && PositionImpl < args.Length) + if (args is not null && PositionImpl < args.Length) return args[PositionImpl]; else throw new SerializationException(SR.Serialization_BadParameterInfo); @@ -84,7 +84,7 @@ public object GetRealObject(StreamingContext context) case MemberTypes.Property: args = ((PropertyInfo)MemberImpl).GetIndexParameters(); - if (args != null && PositionImpl > -1 && PositionImpl < args.Length) + if (args is not null && PositionImpl > -1 && PositionImpl < args.Length) return args[PositionImpl]; else throw new SerializationException(SR.Serialization_BadParameterInfo); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs index 098ddfdcebaff1..96ef674828a74f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs @@ -22,7 +22,7 @@ private Pointer(void* ptr, Type ptrType) public static object Box(void* ptr, Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); if (!type.IsPointer) throw new ArgumentException(SR.Arg_MustBePointer, nameof(ptr)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs index c13ad761a0752f..670a6d6733842d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs @@ -61,7 +61,7 @@ protected PropertyInfo() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(PropertyInfo? left, PropertyInfo? right) { - // Test "right" first to allow branch elimination when inlined for null checks (== null) + // Test "right" first to allow branch elimination when inlined for null checks (is null) // so it can become a simple test if (right is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs index 7cb11c5abe6dc7..1ad38df847b730 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs @@ -13,7 +13,7 @@ protected ReflectionContext() { } public virtual TypeInfo GetTypeForObject(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); return MapType(value.GetType().GetTypeInfo()); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionTypeLoadException.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionTypeLoadException.cs index 61b658c47df407..a5bcb0aba23d92 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionTypeLoadException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionTypeLoadException.cs @@ -59,7 +59,7 @@ private string CreateString(bool isMessage) var text = new StringBuilder(baseValue); foreach (Exception? e in exceptions) { - if (e != null) + if (e is not null) { text.AppendLine().Append(isMessage ? e.Message : e.ToString()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs index 20ae2d3b49b64a..263e7490b6c6c9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs @@ -14,7 +14,7 @@ public static IEnumerable GetRuntimeFields( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -25,7 +25,7 @@ public static IEnumerable GetRuntimeMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -36,7 +36,7 @@ public static IEnumerable GetRuntimeProperties( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -47,7 +47,7 @@ public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -58,7 +58,7 @@ public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type, string name) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -69,7 +69,7 @@ public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type, string name, Type[] parameters) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -80,7 +80,7 @@ public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type, string name) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -91,7 +91,7 @@ public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type, string name) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -100,7 +100,7 @@ public static IEnumerable GetRuntimeEvents( public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method) { - if (method == null) + if (method is null) { throw new ArgumentNullException(nameof(method)); } @@ -109,7 +109,7 @@ public static IEnumerable GetRuntimeEvents( public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, Type interfaceType) { - if (typeInfo == null) + if (typeInfo is null) { throw new ArgumentNullException(nameof(typeInfo)); } @@ -118,7 +118,7 @@ public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, Ty public static MethodInfo GetMethodInfo(this Delegate del) { - if (del == null) + if (del is null) { throw new ArgumentNullException(nameof(del)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs index 9c4d73d5b18909..1795f4c0b6d2df 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs @@ -9,7 +9,7 @@ internal abstract class SignatureHasElementType : SignatureType { protected SignatureHasElementType(SignatureType elementType) { - Debug.Assert(elementType != null); + Debug.Assert(elementType is not null); _elementType = elementType; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs index 61012c67dd1c74..bbee933b9705bd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs @@ -141,7 +141,7 @@ internal static bool MatchesExactly(this SignatureType pattern, Type actual) if (genericTypeArgument is SignatureType signatureGenericTypeArgument) { newGenericTypeArguments[i] = signatureGenericTypeArgument.TryResolve(genericMethodParameters); - if (newGenericTypeArguments[i] == null) + if (newGenericTypeArguments[i] is null) return null; } else diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs index ee5ffafa706c44..790a28a6c68207 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs @@ -11,7 +11,7 @@ public class StrongNameKeyPair : IDeserializationCallback, ISerializable // Build key pair from file. public StrongNameKeyPair(FileStream keyPairFile) { - if (keyPairFile == null) + if (keyPairFile is null) throw new ArgumentNullException(nameof(keyPairFile)); int length = (int)keyPairFile.Length; @@ -22,7 +22,7 @@ public StrongNameKeyPair(FileStream keyPairFile) // Build key pair from byte array in memory. public StrongNameKeyPair(byte[] keyPairArray) { - if (keyPairArray == null) + if (keyPairArray is null) throw new ArgumentNullException(nameof(keyPairArray)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs index 9c0cf16aa5c5af..62c112e80150f9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs @@ -14,7 +14,7 @@ public class TypeDelegator : TypeInfo { public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { - if (typeInfo == null) + if (typeInfo is null) return false; return IsAssignableFrom(typeInfo.AsType()); } @@ -70,7 +70,7 @@ public TypeDelegator([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes. { // This is interesting there are two paths into the impl. One that validates // type as non-null and one where type may be null. - if (types == null) + if (types is null) return typeImpl.GetMethod(name, bindingAttr); else return typeImpl.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); @@ -99,7 +99,7 @@ public TypeDelegator([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes. protected override PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { - if (returnType == null && types == null) + if (returnType is null && types is null) return typeImpl.GetProperty(name, bindingAttr); else return typeImpl.GetProperty(name, bindingAttr, binder, returnType, types!, modifiers); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs index 41591aedfcb675..b521f18cf0f1cf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs @@ -103,7 +103,7 @@ public virtual IEnumerable DeclaredProperties // a re-implementation of ISAF from Type, skipping the use of UnderlyingType public virtual bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { - if (typeInfo == null) + if (typeInfo is null) return false; if (this == typeInfo) diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index 16c585d4fe6345..0e19d0ade138bb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -172,9 +172,9 @@ private ResourceManager(string baseName, string resourceDir, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type? userResourceSet) { - if (null == baseName) + if (baseName is null) throw new ArgumentNullException(nameof(baseName)); - if (null == resourceDir) + if (resourceDir is null) throw new ArgumentNullException(nameof(resourceDir)); BaseNameField = baseName; @@ -190,9 +190,9 @@ private ResourceManager(string baseName, string resourceDir, public ResourceManager(string baseName, Assembly assembly) { - if (null == baseName) + if (baseName is null) throw new ArgumentNullException(nameof(baseName)); - if (null == assembly) + if (assembly is null) throw new ArgumentNullException(nameof(assembly)); if (!assembly.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -207,9 +207,9 @@ public ResourceManager(string baseName, Assembly assembly, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type? usingResourceSet) { - if (null == baseName) + if (baseName is null) throw new ArgumentNullException(nameof(baseName)); - if (null == assembly) + if (assembly is null) throw new ArgumentNullException(nameof(assembly)); if (!assembly.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -226,7 +226,7 @@ public ResourceManager(string baseName, Assembly assembly, public ResourceManager(Type resourceSource) { - if (null == resourceSource) + if (resourceSource is null) throw new ArgumentNullException(nameof(resourceSource)); if (!resourceSource.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -394,7 +394,7 @@ protected virtual string GetResourceFileName(CultureInfo culture) // public virtual ResourceSet? GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { - if (null == culture) + if (culture is null) throw new ArgumentNullException(nameof(culture)); Dictionary? localResourceSets = _resourceSets; @@ -601,7 +601,7 @@ internal static bool IsDefaultType(string asmTypeName, // public virtual string? GetString(string name, CultureInfo? culture) { - if (null == name) + if (name is null) throw new ArgumentNullException(nameof(name)); culture ??= CultureInfo.CurrentUICulture; @@ -668,10 +668,10 @@ internal static bool IsDefaultType(string asmTypeName, private object? GetObject(string name, CultureInfo? culture, bool wrapUnmanagedMemStream) { - if (null == name) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (null == culture) + if (culture is null) { culture = CultureInfo.CurrentUICulture; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs index b49250a36db23c..396838ccab24a4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -61,7 +61,7 @@ public string FullTypeName get => _rootTypeName; set { - if (null == value) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -76,7 +76,7 @@ public string AssemblyName get => _rootTypeAssemblyName; set { - if (null == value) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -160,7 +160,7 @@ public void AddValue(string name, object? value, Type type) public void AddValue(string name, object? value) { - if (null == value) + if (value is null) { AddValue(name, value, typeof(object)); } @@ -285,8 +285,8 @@ internal void AddValueInternal(string name, object? value, Type type) /// The type of the data being added. public void UpdateValue(string name, object value, Type type) { - Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); - Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); + Debug.Assert(name is not null, "[SerializationInfo.UpdateValue]name!=null"); + Debug.Assert(value is not null, "[SerializationInfo.UpdateValue]value!=null"); Debug.Assert(type is not null, "[SerializationInfo.UpdateValue]type!=null"); int index = FindElement(name); @@ -303,7 +303,7 @@ public void UpdateValue(string name, object value, Type type) private int FindElement(string name) { - if (null == name) + if (name is null) { throw new ArgumentNullException(nameof(name)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/PlatformAttributes.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/PlatformAttributes.cs index 66564c1c26c42d..aedf31886257a6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/PlatformAttributes.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/PlatformAttributes.cs @@ -102,4 +102,4 @@ public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } } -} \ No newline at end of file +} diff --git a/src/libraries/System.Private.CoreLib/src/System/SR.cs b/src/libraries/System.Private.CoreLib/src/System/SR.cs index c7db4dcdf29604..6fe03d8a1babc1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SR.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SR.cs @@ -57,7 +57,7 @@ private static string InternalGetResourceString(string key) // Are we recursively looking up the same resource? Note - our backout code will set // the ResourceHelper's currentlyLoading stack to null if an exception occurs. - if (_currentlyLoading != null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) != -1) + if (_currentlyLoading is not null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) != -1) { // We can start infinitely recursing for one resource lookup, // then during our failure reporting, start infinitely recursing again. @@ -94,7 +94,7 @@ private static string InternalGetResourceString(string key) string? s = ResourceManager.GetString(key, null); _currentlyLoading.RemoveAt(_currentlyLoading.Count - 1); // Pop - Debug.Assert(s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString. Resource name was: \"" + key + "\""); + Debug.Assert(s is not null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString. Resource name was: \"" + key + "\""); return s ?? key; } catch diff --git a/src/libraries/System.Private.CoreLib/src/System/Span.cs b/src/libraries/System.Private.CoreLib/src/System/Span.cs index 735380233d9a36..b8af70b3dcd90b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Span.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Span.cs @@ -37,7 +37,7 @@ public readonly ref struct Span [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array) { - if (array == null) + if (array is null) { this = default; return; // returns default @@ -64,7 +64,7 @@ public Span(T[]? array) [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array, int start, int length) { - if (array == null) + if (array is null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs index 44deea83bf0054..692d4eddf98783 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs @@ -20,8 +20,8 @@ public partial class String [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsHelper(string strA, string strB) { - Debug.Assert(strA != null); - Debug.Assert(strB != null); + Debug.Assert(strA is not null); + Debug.Assert(strB is not null); Debug.Assert(strA.Length == strB.Length); return SpanHelpers.SequenceEqual( @@ -33,8 +33,8 @@ ref Unsafe.As(ref strB.GetRawStringData()), [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB) { - Debug.Assert(strA != null); - Debug.Assert(strB != null); + Debug.Assert(strA is not null); + Debug.Assert(strB is not null); Debug.Assert(indexA >= 0 && indexB >= 0); Debug.Assert(countA >= 0 && countB >= 0); Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length); @@ -71,8 +71,8 @@ private static bool EqualsOrdinalIgnoreCaseNoLengthCheck(string strA, string str private static unsafe int CompareOrdinalHelper(string strA, string strB) { - Debug.Assert(strA != null); - Debug.Assert(strB != null); + Debug.Assert(strA is not null); + Debug.Assert(strB is not null); // NOTE: This may be subject to change if eliminating the check // in the callers makes them small enough to be inlined @@ -219,12 +219,12 @@ public static int Compare(string? strA, string? strB, StringComparison compariso } // They can't both be null at this point. - if (strA == null) + if (strA is null) { CheckStringComparison(comparisonType); return -1; } - if (strB == null) + if (strB is null) { CheckStringComparison(comparisonType); return 1; @@ -314,12 +314,12 @@ public static int Compare(string? strA, int indexA, string? strB, int indexB, in int lengthA = length; int lengthB = length; - if (strA != null) + if (strA is not null) { lengthA = Math.Min(lengthA, strA.Length - indexA); } - if (strB != null) + if (strB is not null) { lengthB = Math.Min(lengthB, strB.Length - indexB); } @@ -349,12 +349,12 @@ public static int Compare(string? strA, int indexA, string? strB, int indexB, in int lengthA = length; int lengthB = length; - if (strA != null) + if (strA is not null) { lengthA = Math.Min(lengthA, strA.Length - indexA); } - if (strB != null) + if (strB is not null) { lengthB = Math.Min(lengthB, strB.Length - indexB); } @@ -366,7 +366,7 @@ public static int Compare(string? strA, int indexA, string? strB, int indexB, in { CheckStringComparison(comparisonType); - if (strA == null || strB == null) + if (strA is null || strB is null) { if (object.ReferenceEquals(strA, strB)) { @@ -374,7 +374,7 @@ public static int Compare(string? strA, int indexA, string? strB, int indexB, in return 0; } - return strA == null ? -1 : 1; + return strA is null ? -1 : 1; } if (length < 0) @@ -431,11 +431,11 @@ public static int CompareOrdinal(string? strA, string? strB) } // They can't both be null at this point. - if (strA == null) + if (strA is null) { return -1; } - if (strB == null) + if (strB is null) { return 1; } @@ -458,7 +458,7 @@ internal static int CompareOrdinal(ReadOnlySpan strA, ReadOnlySpan s // public static int CompareOrdinal(string? strA, int indexA, string? strB, int indexB, int length) { - if (strA == null || strB == null) + if (strA is null || strB is null) { if (object.ReferenceEquals(strA, strB)) { @@ -466,7 +466,7 @@ public static int CompareOrdinal(string? strA, int indexA, string? strB, int ind return 0; } - return strA == null ? -1 : 1; + return strA is null ? -1 : 1; } // COMPAT: Checking for nulls should become before the arguments are validated, @@ -506,7 +506,7 @@ public static int CompareOrdinal(string? strA, int indexA, string? strB, int ind // public int CompareTo(object? value) { - if (value == null) + if (value is null) { return 1; } @@ -581,7 +581,7 @@ public bool EndsWith(string value, StringComparison comparisonType) public bool EndsWith(string value, bool ignoreCase, CultureInfo? culture) { - if (null == value) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -626,7 +626,7 @@ public bool Equals(string? value) // If either side of an == comparison between strings // is null, Roslyn generates a simple ceq instruction // instead of calling string.op_Equality. - if (value == null) + if (value is null) return false; if (this.Length != value.Length) @@ -940,7 +940,7 @@ ref Unsafe.As(ref value.GetRawStringData()), public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture) { - if (null == value) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/String.cs b/src/libraries/System.Private.CoreLib/src/System/String.cs index 510c1fe97f1263..edeb11872eef63 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.cs @@ -54,7 +54,7 @@ public sealed partial class String : IComparable, IEnumerable, IConvertible, IEn #endif string Ctor(char[]? value) { - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) return Empty; string result = FastAllocateString(value.Length); @@ -77,7 +77,7 @@ string Ctor(char[]? value) #endif string Ctor(char[] value, int startIndex, int length) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0) @@ -113,7 +113,7 @@ string Ctor(char[] value, int startIndex, int length) #endif unsafe string Ctor(char* ptr) { - if (ptr == null) + if (ptr is null) return Empty; int count = wcslen(ptr); @@ -156,7 +156,7 @@ unsafe string Ctor(char* ptr, int startIndex, int length) if (length == 0) return Empty; - if (ptr == null) + if (ptr is null) throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); string result = FastAllocateString(length); @@ -181,7 +181,7 @@ unsafe string Ctor(char* ptr, int startIndex, int length) unsafe string Ctor(sbyte* value) { byte* pb = (byte*)value; - if (pb == null) + if (pb is null) return Empty; int numBytes = strlen((byte*)value); @@ -206,7 +206,7 @@ unsafe string Ctor(sbyte* value, int startIndex, int length) if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - if (value == null) + if (value is null) { if (length == 0) return Empty; @@ -261,7 +261,7 @@ private static unsafe string CreateStringForSByteConstructor(byte* pb, int numBy #endif unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding? enc) { - if (enc == null) + if (enc is null) return new string(value, startIndex, length); if (length < 0) @@ -270,7 +270,7 @@ unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding? enc) if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - if (value == null) + if (value is null) { if (length == 0) return Empty; @@ -358,7 +358,7 @@ unsafe string Ctor(ReadOnlySpan value) public static string Create(int length, TState state, SpanAction action) { - if (action == null) + if (action is null) throw new ArgumentNullException(nameof(action)); if (length <= 0) @@ -375,7 +375,7 @@ public static string Create(int length, TState state, SpanAction(string? value) => - value != null ? new ReadOnlySpan(ref value.GetRawStringData(), value.Length) : default; + value is not null ? new ReadOnlySpan(ref value.GetRawStringData(), value.Length) : default; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetSpan(int startIndex, int count, out ReadOnlySpan slice) @@ -406,7 +406,7 @@ public object Clone() public static unsafe string Copy(string str) { - if (str == null) + if (str is null) throw new ArgumentNullException(nameof(str)); string result = FastAllocateString(str.Length); @@ -426,7 +426,7 @@ public static unsafe string Copy(string str) // public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { - if (destination == null) + if (destination is null) throw new ArgumentNullException(nameof(destination)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); @@ -489,12 +489,12 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] string? value) { // Ternary operator returning true/false prevents redundant asm generation: // https://github.com/dotnet/runtime/issues/4207 - return (value == null || 0 == value.Length) ? true : false; + return (value is null || 0 == value.Length) ? true : false; } public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value) { - if (value == null) return true; + if (value is null) return true; for (int i = 0; i < value.Length; i++) { @@ -518,7 +518,7 @@ public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value) internal static unsafe string CreateStringFromEncoding( byte* bytes, int byteLength, Encoding encoding) { - Debug.Assert(bytes != null); + Debug.Assert(bytes is not null); Debug.Assert(byteLength >= 0); // Get our string length diff --git a/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs index f858bb7d2b72a0..b20c6ee79cd8f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs @@ -14,7 +14,7 @@ public static bool IsNormalized(this string strInput) public static bool IsNormalized(this string strInput, NormalizationForm normalizationForm) { - if (strInput == null) + if (strInput is null) { throw new ArgumentNullException(nameof(strInput)); } @@ -30,7 +30,7 @@ public static string Normalize(this string strInput) public static string Normalize(this string strInput, NormalizationForm normalizationForm) { - if (strInput == null) + if (strInput is null) { throw new ArgumentNullException(nameof(strInput)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs index c0ef4599d9f7de..c1ad61713685d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs @@ -129,7 +129,7 @@ public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } @@ -159,7 +159,7 @@ private unsafe int GetByteCountCommon(char* pChars, int charCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -305,7 +305,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int { // Validate Parameters - if (chars == null || bytes == null) + if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, @@ -340,9 +340,9 @@ private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -466,7 +466,7 @@ public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } @@ -496,7 +496,7 @@ private unsafe int GetCharCountCommon(byte* pBytes, int byteCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -624,9 +624,9 @@ private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs index 38498176e4591f..5e44d2c90910fd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs @@ -33,11 +33,11 @@ public DecoderFallback? Fallback get => _fallback; set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // Can't change fallback if buffer is wrong - if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); @@ -52,9 +52,9 @@ public DecoderFallbackBuffer FallbackBuffer { get { - if (_fallbackBuffer == null) + if (_fallbackBuffer is null) { - if (_fallback != null) + if (_fallback is not null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); @@ -64,7 +64,7 @@ public DecoderFallbackBuffer FallbackBuffer } } - internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; + internal bool InternalHasFallbackBuffer => _fallbackBuffer is not null; // Reset the Decoder // @@ -102,7 +102,7 @@ public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -173,8 +173,8 @@ public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate input parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) @@ -239,8 +239,8 @@ public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) @@ -268,7 +268,7 @@ public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && - (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); + (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0)); return; } @@ -295,8 +295,8 @@ public virtual unsafe void Convert(byte* bytes, int byteCount, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) @@ -313,7 +313,7 @@ public virtual unsafe void Convert(byte* bytes, int byteCount, { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && - (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); + (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0)); return; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderFallback.cs index da8d1236f4479e..7cba20c979b6ec 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderFallback.cs @@ -106,7 +106,7 @@ internal static DecoderFallbackBuffer CreateAndInitialize(Encoding encoding, Dec // Don't touch ref chars unless we succeed internal virtual unsafe bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { - Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(byteStart is not null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) @@ -161,7 +161,7 @@ internal virtual unsafe int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { - Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(byteStart is not null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs index 6c640af1cbef73..9115e3b936c0a4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs @@ -49,7 +49,7 @@ public override int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -69,7 +69,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -82,7 +82,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, bool flush) _throwOnOverflow = true; // By default just call the encoding version, no flush by default - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetCharCount(bytes, count, this); } @@ -96,8 +96,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) @@ -126,8 +126,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) @@ -139,7 +139,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, _throwOnOverflow = true; // By default just call the encodings version - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } @@ -150,8 +150,8 @@ public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) @@ -188,8 +188,8 @@ public override unsafe void Convert(byte* bytes, int byteCount, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) @@ -202,7 +202,7 @@ public override unsafe void Convert(byte* bytes, int byteCount, _bytesUsed = 0; // Do conversion - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; @@ -256,7 +256,7 @@ internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan bytes, out int combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charCount = 0; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: @@ -314,7 +314,7 @@ internal int DrainLeftoverDataForGetChars(ReadOnlySpan bytes, Span c bool persistNewCombinedBuffer = false; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs index 6bdc618b495762..f7a342d35e0b5a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs @@ -19,7 +19,7 @@ public DecoderReplacementFallback() : this("?") public DecoderReplacementFallback(string replacement) { - if (replacement == null) + if (replacement is null) throw new ArgumentNullException(nameof(replacement)); // Make sure it doesn't have bad surrogate pairs diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs index 04c3bd93fa09f9..342a379ec119d9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs @@ -33,11 +33,11 @@ public EncoderFallback? Fallback get => _fallback; set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // Can't change fallback if buffer is wrong - if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); @@ -52,9 +52,9 @@ public EncoderFallbackBuffer FallbackBuffer { get { - if (_fallbackBuffer == null) + if (_fallbackBuffer is null) { - if (_fallback != null) + if (_fallback is not null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); @@ -64,7 +64,7 @@ public EncoderFallbackBuffer FallbackBuffer } } - internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; + internal bool InternalHasFallbackBuffer => _fallbackBuffer is not null; // Reset the Encoder // @@ -80,7 +80,7 @@ public virtual void Reset() char[] charTemp = Array.Empty(); byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); - if (_fallbackBuffer != null) + if (_fallbackBuffer is not null) _fallbackBuffer.Reset(); } @@ -100,7 +100,7 @@ public virtual void Reset() public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); @@ -168,8 +168,8 @@ public virtual unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate input parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) @@ -233,8 +233,8 @@ public virtual void Convert(char[] chars, int charIndex, int charCount, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) @@ -264,7 +264,7 @@ public virtual void Convert(char[] chars, int charIndex, int charCount, { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = (charsUsed == charCount && - (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); + (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0)); return; } @@ -290,8 +290,8 @@ public virtual unsafe void Convert(char* chars, int charCount, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), @@ -307,7 +307,7 @@ public virtual unsafe void Convert(char* chars, int charCount, { bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush); completed = (charsUsed == charCount && - (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); + (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0)); return; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderFallback.cs index e1d60465765dba..609a151efd1f4a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderFallback.cs @@ -194,7 +194,7 @@ internal bool TryDrainRemainingDataForGetBytes(Span bytes, out int bytesWr { int originalBytesLength = bytes.Length; - Debug.Assert(encoding != null); + Debug.Assert(encoding is not null); Rune thisRune; while ((thisRune = GetNextRune()).Value != 0) { @@ -244,7 +244,7 @@ internal int DrainRemainingDataForGetByteCount() { int totalByteCount = 0; - Debug.Assert(encoding != null); + Debug.Assert(encoding is not null); Rune thisRune; while ((thisRune = GetNextRune()).Value != 0) { @@ -296,7 +296,7 @@ private Rune GetNextRune() internal virtual unsafe bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart - Debug.Assert(charStart != null, + Debug.Assert(charStart is not null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); // Get our index, remember chars was preincremented to point at next char, so have to -1 @@ -310,7 +310,7 @@ internal virtual unsafe bool InternalFallback(char ch, ref char* chars) { // Nothing left in input buffer // No input, return 0 if mustflush is false - if (this.encoder != null && !this.encoder.MustFlush) + if (this.encoder is not null && !this.encoder.MustFlush) { // Done, nothing to fallback if (this.setEncoder) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs index 3a83763ea6a2b0..09ac9df3361ab7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs @@ -123,7 +123,7 @@ private static char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; - Debug.Assert(s_arrayCharBestFit != null); + Debug.Assert(s_arrayCharBestFit is not null); int highBound = s_arrayCharBestFit.Length; int index; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs index 630ebbd3202283..9605ebe5be4741 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs @@ -38,14 +38,14 @@ internal EncoderNLS(Encoding encoding) public override void Reset() { _charLeftOver = (char)0; - if (_fallbackBuffer != null) + if (_fallbackBuffer is not null) _fallbackBuffer.Reset(); } public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); @@ -69,7 +69,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count, bool public override unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); @@ -79,7 +79,7 @@ public override unsafe int GetByteCount(char* chars, int count, bool flush) _mustFlush = flush; _throwOnOverflow = true; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetByteCount(chars, count, this); } @@ -87,8 +87,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) @@ -117,8 +117,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) @@ -127,7 +127,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int _mustFlush = flush; _throwOnOverflow = true; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetBytes(chars, charCount, bytes, byteCount, this); } @@ -138,8 +138,8 @@ public override unsafe void Convert(char[] chars, int charIndex, int charCount, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) @@ -176,8 +176,8 @@ public override unsafe void Convert(char* chars, int charCount, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), @@ -189,7 +189,7 @@ public override unsafe void Convert(char* chars, int charCount, _charsUsed = 0; // Do conversion - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = _charsUsed; @@ -233,7 +233,7 @@ public Encoding Encoding { get { - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding; } } @@ -243,7 +243,7 @@ public Encoding Encoding /// /// States whether a call to must first drain data on this instance. /// - internal bool HasLeftoverData => _charLeftOver != default || (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0); + internal bool HasLeftoverData => _charLeftOver != default || (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0); // Anything left in our encoder? internal virtual bool HasState => _charLeftOver != (char)0; @@ -260,7 +260,7 @@ internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. - if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, Encoding.EncodingName, _fallbackBuffer.GetType())); } @@ -306,7 +306,7 @@ internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int { charsConsumed = 1; // consumed the leftover high surrogate + the first char in the input buffer - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); if (_encoding.TryGetByteCount(rune, out int byteCount)) { Debug.Assert(byteCount >= 0, "Encoding shouldn't have returned a negative byte count."); @@ -329,7 +329,7 @@ internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int } // Now tally the number of bytes that would've been emitted as part of fallback. - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(_fallbackBuffer is not null); return _fallbackBuffer.DrainRemainingDataForGetByteCount(); } } @@ -380,7 +380,7 @@ internal bool TryDrainLeftoverDataForGetBytes(ReadOnlySpan chars, Span chars, Span 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) { return _fallbackBuffer.TryDrainRemainingDataForGetBytes(bytes, out bytesWritten); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs index a67e210b5b2b10..4f45441692a0fd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs @@ -20,7 +20,7 @@ public EncoderReplacementFallback() : this("?") public EncoderReplacementFallback(string replacement) { // Must not be null - if (replacement == null) + if (replacement is null) throw new ArgumentNullException(nameof(replacement)); // Make sure it doesn't have bad surrogate pairs diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.Internal.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.Internal.cs index 6d55ee8ad0f817..543ab88d2b2942 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.Internal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.Internal.cs @@ -121,9 +121,9 @@ internal virtual bool TryGetByteCount(Rune value, out int byteCount) /// internal virtual unsafe int GetByteCount(char* pChars, int charCount, EncoderNLS? encoder) { - Debug.Assert(encoder != null, "This code path should only be called from EncoderNLS."); + Debug.Assert(encoder is not null, "This code path should only be called from EncoderNLS."); Debug.Assert(charCount >= 0, "Caller should've checked this condition."); - Debug.Assert(pChars != null || charCount == 0, "Cannot provide a null pointer and a non-zero count."); + Debug.Assert(pChars is not null || charCount == 0, "Cannot provide a null pointer and a non-zero count."); // We're going to try to stay on the fast-path as much as we can. That means that we have // no leftover data to drain and the entire source buffer can be consumed in a single @@ -255,7 +255,7 @@ private protected unsafe int GetByteCountWithFallback(char* pCharsOriginal, int /// private unsafe int GetByteCountWithFallback(char* pOriginalChars, int originalCharCount, int charsConsumedSoFar, EncoderNLS encoder) { - Debug.Assert(encoder != null, "This code path should only be called from EncoderNLS."); + Debug.Assert(encoder is not null, "This code path should only be called from EncoderNLS."); Debug.Assert(0 <= charsConsumedSoFar && charsConsumedSoFar <= originalCharCount, "Caller should've checked this condition."); // First, try draining any data that already exists on the encoder instance. If we can't complete @@ -327,7 +327,7 @@ private protected virtual unsafe int GetByteCountWithFallback(ReadOnlySpan // or (b) the encoding can't translate this scalar value. if (Rune.DecodeFromUtf16(chars, out Rune firstScalarValue, out int charsConsumedThisIteration) == OperationStatus.NeedMoreData - && encoder != null + && encoder is not null && !encoder.MustFlush) { // We saw a standalone high surrogate at the end of the buffer, and the @@ -398,11 +398,11 @@ private protected virtual unsafe int GetByteCountWithFallback(ReadOnlySpan /// internal virtual unsafe int GetBytes(char* pChars, int charCount, byte* pBytes, int byteCount, EncoderNLS? encoder) { - Debug.Assert(encoder != null, "This code path should only be called from EncoderNLS."); + Debug.Assert(encoder is not null, "This code path should only be called from EncoderNLS."); Debug.Assert(charCount >= 0, "Caller should've checked this condition."); - Debug.Assert(pChars != null || charCount == 0, "Cannot provide a null pointer and a non-zero count."); + Debug.Assert(pChars is not null || charCount == 0, "Cannot provide a null pointer and a non-zero count."); Debug.Assert(byteCount >= 0, "Caller should've checked this condition."); - Debug.Assert(pBytes != null || byteCount == 0, "Cannot provide a null pointer and a non-zero count."); + Debug.Assert(pBytes is not null || byteCount == 0, "Cannot provide a null pointer and a non-zero count."); // We're going to try to stay on the fast-path as much as we can. That means that we have // no leftover data to drain and the entire source buffer can be transcoded in a single @@ -521,7 +521,7 @@ private protected unsafe int GetBytesWithFallback(char* pOriginalChars, int orig /// private unsafe int GetBytesWithFallback(char* pOriginalChars, int originalCharCount, byte* pOriginalBytes, int originalByteCount, int charsConsumedSoFar, int bytesWrittenSoFar, EncoderNLS encoder) { - Debug.Assert(encoder != null, "This code path should only be called from EncoderNLS."); + Debug.Assert(encoder is not null, "This code path should only be called from EncoderNLS."); Debug.Assert(0 <= charsConsumedSoFar && charsConsumedSoFar <= originalCharCount, "Caller should've checked this condition."); Debug.Assert(0 <= bytesWrittenSoFar && bytesWrittenSoFar <= originalByteCount, "Caller should've checked this condition."); @@ -685,13 +685,13 @@ private protected virtual unsafe int GetBytesWithFallback(ReadOnlySpan cha // If an EncoderNLS instance is active, update its "total consumed character count" value. - if (encoder != null) + if (encoder is not null) { Debug.Assert(originalCharsLength >= chars.Length, "About to report a negative number of chars used?"); encoder._charsUsed = originalCharsLength - chars.Length; // number of chars consumed } - Debug.Assert(fallbackBuffer.Remaining == 0 || encoder != null, "Shouldn't have any leftover data in fallback buffer unless an EncoderNLS is in use."); + Debug.Assert(fallbackBuffer.Remaining == 0 || encoder is not null, "Shouldn't have any leftover data in fallback buffer unless an EncoderNLS is in use."); return originalBytesLength - bytes.Length; } @@ -706,9 +706,9 @@ private protected virtual unsafe int GetBytesWithFallback(ReadOnlySpan cha /// internal virtual unsafe int GetCharCount(byte* pBytes, int byteCount, DecoderNLS? decoder) { - Debug.Assert(decoder != null, "This code path should only be called from DecoderNLS."); + Debug.Assert(decoder is not null, "This code path should only be called from DecoderNLS."); Debug.Assert(byteCount >= 0, "Caller should've checked this condition."); - Debug.Assert(pBytes != null || byteCount == 0, "Cannot provide a null pointer and a non-zero count."); + Debug.Assert(pBytes is not null || byteCount == 0, "Cannot provide a null pointer and a non-zero count."); // We're going to try to stay on the fast-path as much as we can. That means that we have // no leftover data to drain and the entire source buffer can be consumed in a single @@ -841,7 +841,7 @@ private protected unsafe int GetCharCountWithFallback(byte* pBytesOriginal, int /// private unsafe int GetCharCountWithFallback(byte* pOriginalBytes, int originalByteCount, int bytesConsumedSoFar, DecoderNLS decoder) { - Debug.Assert(decoder != null, "This code path should only be called from DecoderNLS."); + Debug.Assert(decoder is not null, "This code path should only be called from DecoderNLS."); Debug.Assert(0 <= bytesConsumedSoFar && bytesConsumedSoFar <= originalByteCount, "Caller should've checked this condition."); // First, try draining any data that already exists on the decoder instance. If we can't complete @@ -918,7 +918,7 @@ private unsafe int GetCharCountWithFallback(ReadOnlySpan bytes, int origin // There are two scenarios: (a) the source buffer contained invalid data, or it contained incomplete data. if (DecodeFirstRune(bytes, out Rune firstScalarValue, out int bytesConsumedThisIteration) == OperationStatus.NeedMoreData - && decoder != null + && decoder is not null && !decoder.MustFlush) { // We saw incomplete data at the end of the buffer, and the active DecoderNLS isntance @@ -986,11 +986,11 @@ private unsafe int GetCharCountWithFallback(ReadOnlySpan bytes, int origin /// internal virtual unsafe int GetChars(byte* pBytes, int byteCount, char* pChars, int charCount, DecoderNLS? decoder) { - Debug.Assert(decoder != null, "This code path should only be called from DecoderNLS."); + Debug.Assert(decoder is not null, "This code path should only be called from DecoderNLS."); Debug.Assert(byteCount >= 0, "Caller should've checked this condition."); - Debug.Assert(pBytes != null || byteCount == 0, "Cannot provide a null pointer and a non-zero count."); + Debug.Assert(pBytes is not null || byteCount == 0, "Cannot provide a null pointer and a non-zero count."); Debug.Assert(charCount >= 0, "Caller should've checked this condition."); - Debug.Assert(pChars != null || charCount == 0, "Cannot provide a null pointer and a non-zero count."); + Debug.Assert(pChars is not null || charCount == 0, "Cannot provide a null pointer and a non-zero count."); // We're going to try to stay on the fast-path as much as we can. That means that we have // no leftover data to drain and the entire source buffer can be transcoded in a single @@ -1109,7 +1109,7 @@ private protected unsafe int GetCharsWithFallback(byte* pOriginalBytes, int orig /// private protected unsafe int GetCharsWithFallback(byte* pOriginalBytes, int originalByteCount, char* pOriginalChars, int originalCharCount, int bytesConsumedSoFar, int charsWrittenSoFar, DecoderNLS decoder) { - Debug.Assert(decoder != null, "This code path should only be called from DecoderNLS."); + Debug.Assert(decoder is not null, "This code path should only be called from DecoderNLS."); Debug.Assert(0 <= bytesConsumedSoFar && bytesConsumedSoFar <= originalByteCount, "Caller should've checked this condition."); Debug.Assert(0 <= charsWrittenSoFar && charsWrittenSoFar <= originalCharCount, "Caller should've checked this condition."); @@ -1274,7 +1274,7 @@ private protected virtual unsafe int GetCharsWithFallback(ReadOnlySpan byt // If a DecoderNLS instance is active, update its "total consumed byte count" value. - if (decoder != null) + if (decoder is not null) { Debug.Assert(originalBytesLength >= bytes.Length, "About to report a negative number of bytes used?"); decoder._bytesUsed = originalBytesLength - bytes.Length; // number of bytes consumed diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs index 6bedf38c786a25..a7424d5f674f49 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs @@ -178,7 +178,7 @@ internal virtual void SetDefaultFallbacks() public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes)); return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length); @@ -192,12 +192,12 @@ public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { - if (srcEncoding == null || dstEncoding == null) + if (srcEncoding is null || dstEncoding is null) { - throw new ArgumentNullException(srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding), + throw new ArgumentNullException(srcEncoding is null ? nameof(srcEncoding) : nameof(dstEncoding), SR.ArgumentNull_Array); } - if (bytes == null) + if (bytes is null) { throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -215,7 +215,7 @@ public static void RegisterProvider(EncodingProvider provider) public static Encoding GetEncoding(int codepage) { Encoding? result = FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(codepage)); - if (result != null) + if (result is not null) return result; switch (codepage) @@ -272,7 +272,7 @@ public static Encoding GetEncoding(int codepage, { Encoding? baseEncoding = FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(codepage, encoderFallback, decoderFallback)); - if (baseEncoding != null) + if (baseEncoding is not null) return baseEncoding; // Get the default encoding (which is cached and read only) @@ -332,7 +332,7 @@ public static Encoding GetEncoding(string name, public static EncodingInfo[] GetEncodings() { Dictionary? result = EncodingProvider.GetEncodingListFromProviders(); - return result == null ? EncodingTable.GetEncodings() : EncodingTable.GetEncodings(result); + return result is null ? EncodingTable.GetEncodings() : EncodingTable.GetEncodings(result); } public virtual byte[] GetPreamble() => Array.Empty(); @@ -341,10 +341,10 @@ public static EncodingInfo[] GetEncodings() private void GetDataItem() { - if (_dataItem == null) + if (_dataItem is null) { _dataItem = EncodingTable.GetCodePageDataItem(_codePage); - if (_dataItem == null) + if (_dataItem is null) { throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, _codePage)); } @@ -358,7 +358,7 @@ public virtual string BodyName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -371,7 +371,7 @@ public virtual string EncodingName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -387,7 +387,7 @@ public virtual string HeaderName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -400,7 +400,7 @@ public virtual string WebName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -414,7 +414,7 @@ public virtual int WindowsCodePage { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -428,7 +428,7 @@ public virtual bool IsBrowserDisplay { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -442,7 +442,7 @@ public virtual bool IsBrowserSave { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -456,7 +456,7 @@ public virtual bool IsMailNewsDisplay { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -471,7 +471,7 @@ public virtual bool IsMailNewsSave { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -491,7 +491,7 @@ public EncoderFallback EncoderFallback if (this.IsReadOnly) throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); encoderFallback = value; @@ -506,7 +506,7 @@ public DecoderFallback DecoderFallback if (this.IsReadOnly) throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); decoderFallback = value; @@ -541,7 +541,7 @@ public bool IsReadOnly // public virtual int GetByteCount(char[] chars) { - if (chars == null) + if (chars is null) { throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); @@ -552,7 +552,7 @@ public virtual int GetByteCount(char[] chars) public virtual int GetByteCount(string s) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); char[] chars = s.ToCharArray(); @@ -568,7 +568,7 @@ public virtual int GetByteCount(string s) // public int GetByteCount(string s, int index, int count) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s), SR.ArgumentNull_String); if (index < 0) @@ -598,7 +598,7 @@ public int GetByteCount(string s, int index, int count) public virtual unsafe int GetByteCount(char* chars, int count) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); @@ -624,7 +624,7 @@ public virtual unsafe int GetByteCount(ReadOnlySpan chars) // public virtual byte[] GetBytes(char[] chars) { - if (chars == null) + if (chars is null) { throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); @@ -659,7 +659,7 @@ public abstract int GetBytes(char[] chars, int charIndex, int charCount, // public virtual byte[] GetBytes(string s) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s), SR.ArgumentNull_String); @@ -675,7 +675,7 @@ public virtual byte[] GetBytes(string s) // public byte[] GetBytes(string s, int index, int count) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s), SR.ArgumentNull_String); if (index < 0) @@ -710,7 +710,7 @@ public byte[] GetBytes(string s, int index, int count) public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex); } @@ -737,8 +737,8 @@ public virtual unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate input parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) @@ -784,7 +784,7 @@ public virtual unsafe int GetBytes(ReadOnlySpan chars, Span bytes) // public virtual int GetCharCount(byte[] bytes) { - if (bytes == null) + if (bytes is null) { throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -803,7 +803,7 @@ public virtual int GetCharCount(byte[] bytes) public virtual unsafe int GetCharCount(byte* bytes, int count) { // Validate input parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -829,7 +829,7 @@ public virtual unsafe int GetCharCount(ReadOnlySpan bytes) // public virtual char[] GetChars(byte[] bytes) { - if (bytes == null) + if (bytes is null) { throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -882,8 +882,8 @@ public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate input parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) @@ -927,7 +927,7 @@ public virtual unsafe int GetChars(ReadOnlySpan bytes, Span chars) [CLSCompliant(false)] public unsafe string GetString(byte* bytes, int byteCount) { - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0) @@ -1020,7 +1020,7 @@ public virtual bool IsAlwaysNormalized(NormalizationForm form) => // public virtual string GetString(byte[] bytes) { - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); @@ -1136,9 +1136,9 @@ internal void ThrowBytesOverflow() => internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) { - if (encoder == null || encoder._throwOnOverflow || nothingEncoded) + if (encoder is null || encoder._throwOnOverflow || nothingEncoded) { - if (encoder != null && encoder.InternalHasFallbackBuffer) + if (encoder is not null && encoder.InternalHasFallbackBuffer) encoder.FallbackBuffer.InternalReset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented an encoder fallback with a broken GetMaxCharCount @@ -1164,9 +1164,9 @@ internal void ThrowCharsOverflow() => internal void ThrowCharsOverflow(DecoderNLS? decoder, bool nothingDecoded) { - if (decoder == null || decoder._throwOnOverflow || nothingDecoded) + if (decoder is null || decoder._throwOnOverflow || nothingDecoded) { - if (decoder != null && decoder.InternalHasFallbackBuffer) + if (decoder is not null && decoder.InternalHasFallbackBuffer) decoder.FallbackBuffer.InternalReset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken @@ -1320,7 +1320,7 @@ internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS? decoder, char* char _bytes = byteStart; _byteEnd = byteStart + byteCount; - if (_decoder == null) + if (_decoder is null) _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); else _fallbackBuffer = _decoder.FallbackBuffer; @@ -1334,7 +1334,7 @@ internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS? decoder, char* char internal unsafe bool AddChar(char ch, int numBytes) { - if (_chars != null) + if (_chars is not null) { if (_chars >= _charEnd) { @@ -1417,7 +1417,7 @@ internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) internal unsafe bool Fallback(byte[] byteBuffer) { // Do the fallback and add the data. - if (_chars != null) + if (_chars is not null) { char* pTemp = _chars; if (!_fallbackBuffer.InternalFallback(byteBuffer, _bytes, ref _chars)) @@ -1468,7 +1468,7 @@ internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS? inEncoder, _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; - if (_encoder == null) + if (_encoder is null) this.fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); else { @@ -1479,13 +1479,13 @@ internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS? inEncoder, throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback!.GetType())); } - fallbackBuffer.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); + fallbackBuffer.InternalInitialize(_chars, _charEnd, _encoder, _bytes is not null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); - if (_bytes != null) + if (_bytes is not null) { if (_bytes >= _byteEnd - moreBytesExpected) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs index a2475ebc75642f..fb8dadaab48087 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs @@ -15,9 +15,9 @@ public sealed class EncodingInfo /// public EncodingInfo(EncodingProvider provider, int codePage, string name, string displayName) : this(codePage, name, displayName) { - if (name == null || displayName == null || provider == null) + if (name is null || displayName is null || provider is null) { - throw new ArgumentNullException(name == null ? nameof(name) : (displayName == null ? nameof(displayName) : nameof(provider))); + throw new ArgumentNullException(name is null ? nameof(name) : (displayName is null ? nameof(displayName) : nameof(provider))); } Provider = provider; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs index e39e75b52551c0..5d6088f95999c9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs @@ -15,7 +15,7 @@ public EncodingProvider() { } public virtual Encoding? GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { Encoding? enc = GetEncoding(name); - if (enc != null) + if (enc is not null) { enc = (Encoding)enc.Clone(); enc.EncoderFallback = encoderFallback; @@ -28,7 +28,7 @@ public EncodingProvider() { } public virtual Encoding? GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { Encoding? enc = GetEncoding(codepage); - if (enc != null) + if (enc is not null) { enc = (Encoding)enc.Clone(); enc.EncoderFallback = encoderFallback; @@ -42,12 +42,12 @@ public EncodingProvider() { } internal static void AddProvider(EncodingProvider provider) { - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); lock (s_InternalSyncObject) { - if (s_providers == null) + if (s_providers is null) { s_providers = new EncodingProvider[1] { provider }; return; @@ -68,13 +68,13 @@ internal static void AddProvider(EncodingProvider provider) internal static Encoding? GetEncodingFromProvider(int codepage) { EncodingProvider[]? providers = s_providers; - if (providers == null) + if (providers is null) return null; foreach (EncodingProvider provider in providers) { Encoding? enc = provider.GetEncoding(codepage); - if (enc != null) + if (enc is not null) return enc; } @@ -84,7 +84,7 @@ internal static void AddProvider(EncodingProvider provider) internal static Dictionary? GetEncodingListFromProviders() { EncodingProvider[]? providers = s_providers; - if (providers == null) + if (providers is null) return null; Dictionary result = new Dictionary(); @@ -92,7 +92,7 @@ internal static void AddProvider(EncodingProvider provider) foreach (EncodingProvider provider in providers) { IEnumerable? encodingInfoList = provider.GetEncodings(); - if (encodingInfoList != null) + if (encodingInfoList is not null) { foreach (EncodingInfo ei in encodingInfoList) { @@ -106,14 +106,14 @@ internal static void AddProvider(EncodingProvider provider) internal static Encoding? GetEncodingFromProvider(string encodingName) { - if (s_providers == null) + if (s_providers is null) return null; EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { Encoding? enc = provider.GetEncoding(encodingName); - if (enc != null) + if (enc is not null) return enc; } @@ -122,14 +122,14 @@ internal static void AddProvider(EncodingProvider provider) internal static Encoding? GetEncodingFromProvider(int codepage, EncoderFallback enc, DecoderFallback dec) { - if (s_providers == null) + if (s_providers is null) return null; EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { Encoding? encoding = provider.GetEncoding(codepage, enc, dec); - if (encoding != null) + if (encoding is not null) return encoding; } @@ -138,14 +138,14 @@ internal static void AddProvider(EncodingProvider provider) internal static Encoding? GetEncodingFromProvider(string encodingName, EncoderFallback enc, DecoderFallback dec) { - if (s_providers == null) + if (s_providers is null) return null; EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { Encoding? encoding = provider.GetEncoding(encodingName, enc, dec); - if (encoding != null) + if (encoding is not null) return encoding; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs index bdf608fc76b6e7..b7ae4a842a5224 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs @@ -30,12 +30,12 @@ internal static partial class EncodingTable internal static int GetCodePageFromName(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); object? codePageObj = s_nameToCodePage[name]; - if (codePageObj != null) + if (codePageObj is not null) { return (int)codePageObj; } @@ -135,7 +135,7 @@ internal static EncodingInfo[] GetEncodings() internal static EncodingInfo[] GetEncodings(Dictionary encodingInfoList) { - Debug.Assert(encodingInfoList != null); + Debug.Assert(encodingInfoList is not null); ushort[] mappedCodePages = s_mappedCodePages; string webNames = s_webNames; int[] webNameIndices = s_webNameIndices; @@ -176,7 +176,7 @@ internal static EncodingInfo[] GetEncodings(Dictionary encodi internal static CodePageDataItem? GetCodePageDataItem(int codePage) { - if (s_codePageToCodePageData == null) + if (s_codePageToCodePageData is null) { Interlocked.CompareExchange(ref s_codePageToCodePageData, new CodePageDataItem[s_mappedCodePages.Length], null); } @@ -214,7 +214,7 @@ internal static EncodingInfo[] GetEncodings(Dictionary encodi } CodePageDataItem? data = s_codePageToCodePageData[index]; - if (data == null) + if (data is null) { Interlocked.CompareExchange(ref s_codePageToCodePageData[index], InternalGetCodePageDataItem(codePage, index), null); data = s_codePageToCodePageData[index]; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs index 01f6710a9632f5..6a62d1b7d8ce56 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs @@ -42,7 +42,7 @@ public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } @@ -112,7 +112,7 @@ private unsafe int GetByteCountCommon(char* pChars, int charCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. // Don't bother providing a fallback mechanism; our fast path doesn't use it. @@ -183,7 +183,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int { // Validate Parameters - if (chars == null || bytes == null) + if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, @@ -289,9 +289,9 @@ private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -330,7 +330,7 @@ public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes); } @@ -594,9 +594,9 @@ private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // If we already know ahead of time that the destination buffer isn't large enough to hold // the widened data, fail immediately. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs index f2e1aa0c14acb2..17318131cd8335 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs @@ -201,7 +201,7 @@ public int Utf8SequenceLength private static Rune ChangeCaseCultureAware(Rune rune, TextInfo textInfo, bool toUpper) { Debug.Assert(!GlobalizationMode.Invariant, "This should've been checked by the caller."); - Debug.Assert(textInfo != null, "This should've been checked by the caller."); + Debug.Assert(textInfo is not null, "This should've been checked by the caller."); Span original = stackalloc char[MaxUtf16CharsPerRune]; Span modified = stackalloc char[MaxUtf16CharsPerRune]; @@ -236,7 +236,7 @@ private static Rune ChangeCaseCultureAware(Rune rune, TextInfo textInfo, bool to private static Rune ChangeCaseCultureAware(Rune rune, CultureInfo culture, bool toUpper) { Debug.Assert(!GlobalizationMode.Invariant, "This should've been checked by the caller."); - Debug.Assert(culture != null, "This should've been checked by the caller."); + Debug.Assert(culture is not null, "This should've been checked by the caller."); Span original = stackalloc char[MaxUtf16CharsPerRune]; // worst case scenario = 2 code units (for a surrogate pair) Span modified = stackalloc char[MaxUtf16CharsPerRune]; // case change should preserve UTF-16 code unit count diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.Debug.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.Debug.cs index 149143ed5588ad..9a9566129ef461 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.Debug.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.Debug.cs @@ -13,7 +13,7 @@ private void ShowChunks(int maxChunksToShow = 10) StringBuilder head = this; StringBuilder? current = this; - while (current != null) + while (current is not null) { if (count < maxChunksToShow) { @@ -21,7 +21,7 @@ private void ShowChunks(int maxChunksToShow = 10) } else { - Debug.Assert(head.m_ChunkPrevious != null); + Debug.Assert(head.m_ChunkPrevious is not null); head = head.m_ChunkPrevious; } current = current.m_ChunkPrevious; @@ -32,7 +32,7 @@ private void ShowChunks(int maxChunksToShow = 10) for (int i = count; i > 0; i--) { chunks[i - 1] = new string(current.m_ChunkChars).Replace('\0', '.'); - Debug.Assert(current.m_ChunkPrevious != null); + Debug.Assert(current.m_ChunkPrevious is not null); current = current.m_ChunkPrevious; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index dfdf689194d0b0..beeb5967bd20fc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -127,7 +127,7 @@ public StringBuilder(string? value, int startIndex, int length, int capacity) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); } - if (value == null) + if (value is null) { value = string.Empty; } @@ -186,7 +186,7 @@ public StringBuilder(int capacity, int maxCapacity) private StringBuilder(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -219,7 +219,7 @@ private StringBuilder(SerializationInfo info, StreamingContext context) } // Check values and set defaults - if (persistedString == null) + if (persistedString is null) { persistedString = string.Empty; } @@ -249,7 +249,7 @@ private StringBuilder(SerializationInfo info, StreamingContext context) void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -273,14 +273,14 @@ private void AssertInvariants() { // All blocks have the same max capacity. Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity); - Debug.Assert(currentBlock.m_ChunkChars != null); + Debug.Assert(currentBlock.m_ChunkChars is not null); Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length); Debug.Assert(currentBlock.m_ChunkLength >= 0); Debug.Assert(currentBlock.m_ChunkOffset >= 0); StringBuilder? prevBlock = currentBlock.m_ChunkPrevious; - if (prevBlock == null) + if (prevBlock is null) { Debug.Assert(currentBlock.m_ChunkOffset == 0); break; @@ -383,7 +383,7 @@ public override string ToString() } chunk = chunk.m_ChunkPrevious; } - while (chunk != null); + while (chunk is not null); return result; } @@ -452,7 +452,7 @@ public int Length throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } - if (value == 0 && m_ChunkPrevious == null) + if (value == 0 && m_ChunkPrevious is null) { m_ChunkLength = 0; m_ChunkOffset = 0; @@ -517,7 +517,7 @@ public char this[int index] return chunk.m_ChunkChars[indexInBlock]; } chunk = chunk.m_ChunkPrevious; - if (chunk == null) + if (chunk is null) { throw new IndexOutOfRangeException(); } @@ -539,7 +539,7 @@ public char this[int index] return; } chunk = chunk.m_ChunkPrevious; - if (chunk == null) + if (chunk is null) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } @@ -605,7 +605,7 @@ public bool MoveNext() } - if (_manyChunks != null) + if (_manyChunks is not null) { return _manyChunks.MoveNext(ref _currentChunk); } @@ -613,7 +613,7 @@ public bool MoveNext() StringBuilder next = _firstChunk; while (next.m_ChunkPrevious != _currentChunk) { - Debug.Assert(next.m_ChunkPrevious != null); + Debug.Assert(next.m_ChunkPrevious is not null); next = next.m_ChunkPrevious; } _currentChunk = next; @@ -627,7 +627,7 @@ public ReadOnlyMemory Current { get { - if (_currentChunk == null) + if (_currentChunk is null) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } @@ -639,7 +639,7 @@ public ReadOnlyMemory Current #region private internal ChunkEnumerator(StringBuilder stringBuilder) { - Debug.Assert(stringBuilder != null); + Debug.Assert(stringBuilder is not null); _firstChunk = stringBuilder; _currentChunk = null; // MoveNext will find the last chunk if we do this. _manyChunks = null; @@ -660,7 +660,7 @@ internal ChunkEnumerator(StringBuilder stringBuilder) private static int ChunkCount(StringBuilder? stringBuilder) { int ret = 0; - while (stringBuilder != null) + while (stringBuilder is not null) { ret++; stringBuilder = stringBuilder.m_ChunkPrevious; @@ -692,7 +692,7 @@ public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount) _chunks = new StringBuilder[chunkCount]; while (0 <= --chunkCount) { - Debug.Assert(stringBuilder != null); + Debug.Assert(stringBuilder is not null); _chunks[chunkCount] = stringBuilder; stringBuilder = stringBuilder.m_ChunkPrevious; } @@ -766,7 +766,7 @@ public StringBuilder Append(char[]? value, int startIndex, int charCount) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive); } - if (value == null) + if (value is null) { if (startIndex == 0 && charCount == 0) { @@ -801,7 +801,7 @@ public StringBuilder Append(char[]? value, int startIndex, int charCount) /// The string to append. public StringBuilder Append(string? value) { - if (value != null) + if (value is not null) { // We could have just called AppendHelper here; this is a hand-specialization of that code. char[] chunkChars = m_ChunkChars; @@ -874,7 +874,7 @@ public StringBuilder Append(string? value, int startIndex, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); } - if (value == null) + if (value is null) { if (startIndex == 0 && count == 0) { @@ -905,7 +905,7 @@ public StringBuilder Append(string? value, int startIndex, int count) public StringBuilder Append(StringBuilder? value) { - if (value != null && value.Length != 0) + if (value is not null && value.Length != 0) { return AppendCore(value, 0, value.Length); } @@ -924,7 +924,7 @@ public StringBuilder Append(StringBuilder? value, int startIndex, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); } - if (value == null) + if (value is null) { if (startIndex == 0 && count == 0) { @@ -988,7 +988,7 @@ public StringBuilder AppendLine(string? value) public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } @@ -1030,7 +1030,7 @@ public void CopyTo(int sourceIndex, Span destination, int count) int curDestIndex = count; while (count > 0) { - Debug.Assert(chunk != null); + Debug.Assert(chunk is not null); int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset; if (chunkEndIndex >= 0) { @@ -1210,7 +1210,7 @@ internal StringBuilder AppendSpanFormattable(T value, string? format, IFormat return Append(value.ToString(format, provider)); } - public StringBuilder Append(object? value) => (value == null) ? this : Append(value.ToString()); + public StringBuilder Append(object? value) => (value is null) ? this : Append(value.ToString()); public StringBuilder Append(char[]? value) { @@ -1290,15 +1290,15 @@ public unsafe StringBuilder AppendJoin(char separator, params string?[] values) private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLength, IEnumerable values) { - Debug.Assert(separator != null); + Debug.Assert(separator is not null); Debug.Assert(separatorLength >= 0); - if (values == null) + if (values is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } - Debug.Assert(values != null); + Debug.Assert(values is not null); using (IEnumerator en = values.GetEnumerator()) { if (!en.MoveNext()) @@ -1307,7 +1307,7 @@ private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLen } T value = en.Current; - if (value != null) + if (value is not null) { Append(value.ToString()); } @@ -1316,7 +1316,7 @@ private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLen { Append(separator, separatorLength); value = en.Current; - if (value != null) + if (value is not null) { Append(value.ToString()); } @@ -1327,18 +1327,18 @@ private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLen private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLength, T[] values) { - if (values == null) + if (values is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } - Debug.Assert(values != null); + Debug.Assert(values is not null); if (values.Length == 0) { return this; } - if (values[0] != null) + if (values[0] is not null) { Append(values[0]!.ToString()); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } @@ -1346,7 +1346,7 @@ private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLen for (int i = 1; i < values.Length; i++) { Append(separator, separatorLength); - if (values[i] != null) + if (values[i] is not null) { Append(values[i]!.ToString()); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } @@ -1363,7 +1363,7 @@ public StringBuilder Insert(int index, string? value) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - if (value != null) + if (value is not null) { unsafe { @@ -1399,7 +1399,7 @@ public StringBuilder Insert(int index, char[]? value) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - if (value != null) + if (value is not null) { Insert(index, value, 0, value.Length); } @@ -1414,7 +1414,7 @@ public StringBuilder Insert(int index, char[]? value, int startIndex, int charCo throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - if (value == null) + if (value is null) { if (startIndex == 0 && charCount == 0) { @@ -1468,7 +1468,7 @@ public StringBuilder Insert(int index, char[]? value, int startIndex, int charCo [CLSCompliant(false)] public StringBuilder Insert(int index, ulong value) => Insert(index, value.ToString(), 1); - public StringBuilder Insert(int index, object? value) => (value == null) ? this : Insert(index, value.ToString(), 1); + public StringBuilder Insert(int index, object? value) => (value is null) ? this : Insert(index, value.ToString(), 1); public StringBuilder Insert(int index, ReadOnlySpan value) { @@ -1496,11 +1496,11 @@ public StringBuilder Insert(int index, ReadOnlySpan value) public StringBuilder AppendFormat(string format, params object?[] args) { - if (args == null) + if (args is null) { // To preserve the original exception behavior, throw an exception about format if both // args and format are null. The actual null check for format is in AppendFormatHelper. - string paramName = (format == null) ? nameof(format) : nameof(args); + string paramName = (format is null) ? nameof(format) : nameof(args); throw new ArgumentNullException(paramName); } @@ -1515,11 +1515,11 @@ public StringBuilder AppendFormat(string format, params object?[] args) public StringBuilder AppendFormat(IFormatProvider? provider, string format, params object?[] args) { - if (args == null) + if (args is null) { // To preserve the original exception behavior, throw an exception about format if both // args and format are null. The actual null check for format is in AppendFormatHelper. - string paramName = (format == null) ? nameof(format) : nameof(args); + string paramName = (format is null) ? nameof(format) : nameof(args); throw new ArgumentNullException(paramName); } @@ -1537,7 +1537,7 @@ private static void FormatError() internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string format, ParamsArray args) { - if (format == null) + if (format is null) { throw new ArgumentNullException(nameof(format)); } @@ -1547,7 +1547,7 @@ internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string form char ch = '\x0'; ICustomFormatter? cf = null; - if (provider != null) + if (provider is not null) { cf = (ICustomFormatter?)provider.GetFormat(typeof(ICustomFormatter)); } @@ -1745,7 +1745,7 @@ internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string form string? s = null; string? itemFormat = null; - if (cf != null) + if (cf is not null) { if (itemFormatSpan.Length != 0) { @@ -1754,7 +1754,7 @@ internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string form s = cf.Format(itemFormat, arg, provider); } - if (s == null) + if (s is null) { // If arg is ISpanFormattable and the beginning doesn't need padding, // try formatting it into the remaining current chunk. @@ -1784,13 +1784,13 @@ internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string form } s = formattableArg.ToString(itemFormat, provider); } - else if (arg != null) + else if (arg is not null) { s = arg.ToString(); } } // Append it to the final output of the Format String. - if (s == null) + if (s is null) { s = string.Empty; } @@ -1827,7 +1827,7 @@ internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string form /// The other builder. public bool Equals(StringBuilder? sb) { - if (sb == null) + if (sb is null) { return false; } @@ -1851,7 +1851,7 @@ public bool Equals(StringBuilder? sb) while (thisChunkIndex < 0) { thisChunk = thisChunk.m_ChunkPrevious; - if (thisChunk == null) + if (thisChunk is null) { break; } @@ -1861,7 +1861,7 @@ public bool Equals(StringBuilder? sb) while (sbChunkIndex < 0) { sbChunk = sbChunk.m_ChunkPrevious; - if (sbChunk == null) + if (sbChunk is null) { break; } @@ -1877,7 +1877,7 @@ public bool Equals(StringBuilder? sb) return false; } - Debug.Assert(thisChunk != null && sbChunk != null); + Debug.Assert(thisChunk is not null && sbChunk is not null); if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex]) { return false; @@ -1912,7 +1912,7 @@ public bool Equals(ReadOnlySpan span) } sbChunk = sbChunk.m_ChunkPrevious; - } while (sbChunk != null); + } while (sbChunk is not null); Debug.Assert(offset == Length); return true; @@ -1940,7 +1940,7 @@ public StringBuilder Replace(string oldValue, string? newValue, int startIndex, { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index); } - if (oldValue == null) + if (oldValue is null) { throw new ArgumentNullException(nameof(oldValue)); } @@ -1959,14 +1959,14 @@ public StringBuilder Replace(string oldValue, string? newValue, int startIndex, int indexInChunk = startIndex - chunk.m_ChunkOffset; while (count > 0) { - Debug.Assert(chunk != null, "chunk was null in replace"); + Debug.Assert(chunk is not null, "chunk was null in replace"); // Look for a match in the chunk,indexInChunk pointer if (StartsWith(chunk, indexInChunk, count, oldValue)) { // Push it on the replacements array (with growth), we will do all replacements in a // given chunk in one operation below (see ReplaceAllInChunk) so we don't have to slide // many times. - if (replacements == null) + if (replacements is null) { replacements = new int[5]; } @@ -1990,7 +1990,7 @@ public StringBuilder Replace(string oldValue, string? newValue, int startIndex, int index = indexInChunk + chunk.m_ChunkOffset; // See if we accumulated any replacements, if so apply them. - Debug.Assert(replacements != null || replacementsCount == 0, "replacements was null and replacementsCount != 0"); + Debug.Assert(replacements is not null || replacementsCount == 0, "replacements was null and replacementsCount != 0"); ReplaceAllInChunk(replacements, replacementsCount, chunk, oldValue.Length, newValue); // The replacement has affected the logical index. Adjust it. index += ((newValue.Length - oldValue.Length) * replacementsCount); @@ -1998,7 +1998,7 @@ public StringBuilder Replace(string oldValue, string? newValue, int startIndex, chunk = FindChunkForIndex(index); indexInChunk = index - chunk.m_ChunkOffset; - Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely!"); + Debug.Assert(chunk is not null || count == 0, "Chunks ended prematurely!"); } } @@ -2059,7 +2059,7 @@ public StringBuilder Replace(char oldChar, char newChar, int startIndex, int cou break; } - Debug.Assert(chunk.m_ChunkPrevious != null); + Debug.Assert(chunk.m_ChunkPrevious is not null); chunk = chunk.m_ChunkPrevious; } @@ -2161,7 +2161,7 @@ private void ReplaceAllInChunk(int[]? replacements, int replacementsCount, Strin { fixed (char* valuePtr = value) { - Debug.Assert(replacements != null, "replacements was null when replacementsCount > 0"); + Debug.Assert(replacements is not null, "replacements was null when replacementsCount > 0"); // calculate the total amount of extra space or space needed for all the replacements. long longDelta = (value.Length - removeCount) * (long)replacementsCount; int delta = (int)longDelta; @@ -2237,7 +2237,7 @@ private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, string if (indexInChunk >= chunk.m_ChunkLength) { chunk = Next(chunk)!; - if (chunk == null) + if (chunk is null) { return false; } @@ -2276,7 +2276,7 @@ private unsafe void ReplaceInPlaceAtChunk(ref StringBuilder? chunk, ref int inde { while (true) { - Debug.Assert(chunk != null, "chunk should not be null at this point"); + Debug.Assert(chunk is not null, "chunk should not be null at this point"); int lengthInChunk = chunk.m_ChunkLength - indexInChunk; Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk."); @@ -2355,11 +2355,11 @@ private StringBuilder FindChunkForIndex(int index) StringBuilder result = this; while (result.m_ChunkOffset > index) { - Debug.Assert(result.m_ChunkPrevious != null); + Debug.Assert(result.m_ChunkPrevious is not null); result = result.m_ChunkPrevious; } - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } @@ -2495,7 +2495,7 @@ private void MakeRoom(int index, int count, out StringBuilder chunk, out int ind while (chunk.m_ChunkOffset > index) { chunk.m_ChunkOffset += count; - Debug.Assert(chunk.m_ChunkPrevious != null); + Debug.Assert(chunk.m_ChunkPrevious is not null); chunk = chunk.m_ChunkPrevious; } indexInChunk = index - chunk.m_ChunkOffset; @@ -2564,7 +2564,7 @@ private StringBuilder(int size, int maxCapacity, StringBuilder? previousBlock) m_ChunkChars = GC.AllocateUninitializedArray(size); m_MaxCapacity = maxCapacity; m_ChunkPrevious = previousBlock; - if (previousBlock != null) + if (previousBlock is not null) { m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength; } @@ -2596,7 +2596,7 @@ private void Remove(int startIndex, int count, out StringBuilder chunk, out int { if (endIndex - chunk.m_ChunkOffset >= 0) { - if (endChunk == null) + if (endChunk is null) { endChunk = chunk; endIndexInChunk = endIndex - endChunk.m_ChunkOffset; @@ -2612,10 +2612,10 @@ private void Remove(int startIndex, int count, out StringBuilder chunk, out int chunk.m_ChunkOffset -= count; } - Debug.Assert(chunk.m_ChunkPrevious != null); + Debug.Assert(chunk.m_ChunkPrevious is not null); chunk = chunk.m_ChunkPrevious; } - Debug.Assert(chunk != null, "We fell off the beginning of the string!"); + Debug.Assert(chunk is not null, "We fell off the beginning of the string!"); int copyTargetIndexInChunk = indexInChunk; int copyCount = endChunk.m_ChunkLength - endIndexInChunk; @@ -2647,7 +2647,7 @@ private void Remove(int startIndex, int count, out StringBuilder chunk, out int ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount); } - Debug.Assert(chunk != null, "We fell off the beginning of the string!"); + Debug.Assert(chunk is not null, "We fell off the beginning of the string!"); AssertInvariants(); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/TranscodingStream.cs b/src/libraries/System.Private.CoreLib/src/System/Text/TranscodingStream.cs index 930d7df28c27cb..1b057563b928d5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/TranscodingStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/TranscodingStream.cs @@ -52,9 +52,9 @@ internal sealed class TranscodingStream : Stream internal TranscodingStream(Stream innerStream, Encoding innerEncoding, Encoding thisEncoding, bool leaveOpen) { - Debug.Assert(innerStream != null); - Debug.Assert(innerEncoding != null); - Debug.Assert(thisEncoding != null); + Debug.Assert(innerStream is not null); + Debug.Assert(innerEncoding is not null); + Debug.Assert(thisEncoding is not null); _innerStream = innerStream; _leaveOpen = leaveOpen; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs index 6bcb50fdc282c4..f191baa3d30ab9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs @@ -92,7 +92,7 @@ internal override void SetDefaultFallbacks() public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -118,7 +118,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) public override unsafe int GetByteCount(string s) { // Validate input - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -133,7 +133,7 @@ public override unsafe int GetByteCount(string s) public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) @@ -151,8 +151,8 @@ public override unsafe int GetByteCount(char* chars, int count) public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s == null || bytes == null) - throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); + if (s is null || bytes is null) + throw new ArgumentNullException(s is null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -187,8 +187,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -219,8 +219,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -239,7 +239,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -265,7 +265,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) @@ -283,8 +283,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -315,8 +315,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -335,7 +335,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -357,7 +357,7 @@ public override unsafe string GetString(byte[] bytes, int index, int count) // internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null"); + Debug.Assert(chars is not null, "[UTF32Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0"); char* end = chars + count; @@ -370,7 +370,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? en EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; - if (encoder != null) + if (encoder is not null) { highSurrogate = encoder._charLeftOver; fallbackBuffer = encoder.FallbackBuffer; @@ -462,7 +462,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? en } // May have to do our last surrogate - if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) + if ((encoder is null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate charsForFallback = chars; @@ -489,8 +489,8 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? en internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null"); - Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null"); + Debug.Assert(chars is not null, "[UTF32Encoding.GetBytes]chars!=null"); + Debug.Assert(bytes is not null, "[UTF32Encoding.GetBytes]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0"); @@ -505,7 +505,7 @@ internal override unsafe int GetBytes(char* chars, int charCount, EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; - if (encoder != null) + if (encoder is not null) { highSurrogate = encoder._charLeftOver; fallbackBuffer = encoder.FallbackBuffer; @@ -660,7 +660,7 @@ internal override unsafe int GetBytes(char* chars, int charCount, } // May have to do our last surrogate - if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) + if ((encoder is null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate charsForFallback = chars; @@ -672,10 +672,10 @@ internal override unsafe int GetBytes(char* chars, int charCount, } // Fix our encoder if we have one - Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), + Debug.Assert(highSurrogate == 0 || (encoder is not null && !encoder.MustFlush), "[UTF32Encoding.GetBytes]Expected encoder to be flushed."); - if (encoder != null) + if (encoder is not null) { // Remember our left over surrogate (or 0 if flushing) encoder._charLeftOver = highSurrogate; @@ -690,7 +690,7 @@ internal override unsafe int GetBytes(char* chars, int charCount, internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { - Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null"); + Debug.Assert(bytes is not null, "[UTF32Encoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0"); UTF32Decoder? decoder = (UTF32Decoder?)baseDecoder; @@ -708,7 +708,7 @@ internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? ba DecoderFallbackBuffer? fallbackBuffer = null; // See if there's anything in our decoder - if (decoder != null) + if (decoder is not null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; @@ -793,7 +793,7 @@ internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? ba } // See if we have something left over that has to be decoded - if (readCount > 0 && (decoder == null || decoder.MustFlush)) + if (readCount > 0 && (decoder is null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; @@ -833,8 +833,8 @@ internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? ba internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { - Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null"); - Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null"); + Debug.Assert(chars is not null, "[UTF32Encoding.GetChars]chars!=null"); + Debug.Assert(bytes is not null, "[UTF32Encoding.GetChars]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0"); @@ -856,11 +856,11 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, char* charsForFallback; // See if there's anything in our decoder - if (decoder != null) + if (decoder is not null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; - Debug.Assert(baseDecoder != null); + Debug.Assert(baseDecoder is not null); fallbackBuffer = baseDecoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetChars @@ -986,7 +986,7 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, } // See if we have something left over that has to be decoded - if (readCount > 0 && (decoder == null || decoder.MustFlush)) + if (readCount > 0 && (decoder is null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; @@ -1029,7 +1029,7 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, } // Remember any left over stuff, clearing buffer as well for MustFlush - if (decoder != null) + if (decoder is not null) { decoder.iChar = (int)iChar; decoder.readByteCount = readCount; @@ -1178,7 +1178,7 @@ public override void Reset() { this.iChar = 0; this.readByteCount = 0; - if (_fallbackBuffer != null) + if (_fallbackBuffer is not null) _fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs index 7b416f1b4b4a96..8e135b0a5d0fe2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs @@ -136,7 +136,7 @@ public override int GetHashCode() public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -162,7 +162,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) public override unsafe int GetByteCount(string s) { // Validate input - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -177,7 +177,7 @@ public override unsafe int GetByteCount(string s) public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) @@ -195,8 +195,8 @@ public override unsafe int GetByteCount(char* chars, int count) public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s == null || bytes == null) - throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); + if (s is null || bytes is null) + throw new ArgumentNullException(s is null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -231,8 +231,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -263,8 +263,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -283,7 +283,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -309,7 +309,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) @@ -327,8 +327,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -359,8 +359,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -379,7 +379,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -401,10 +401,10 @@ public override unsafe string GetString(byte[] bytes, int index, int count) // internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? baseEncoder) { - Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); + Debug.Assert(chars is not null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); - // Just call GetBytes with bytes == null + // Just call GetBytes with bytes is null return GetBytes(chars, count, null, 0, baseEncoder); } @@ -412,7 +412,7 @@ internal sealed override unsafe int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); - Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); + Debug.Assert(chars is not null, "[UTF7Encoding.GetBytes]chars!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info @@ -426,7 +426,7 @@ internal sealed override unsafe int GetBytes( Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); - if (encoder != null) + if (encoder is not null) { bits = encoder.bits; bitCount = encoder.bitCount; @@ -510,7 +510,7 @@ internal sealed override unsafe int GetBytes( // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting - if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) + if (bitCount >= 0 && (encoder is null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) @@ -536,8 +536,8 @@ internal sealed override unsafe int GetBytes( } // Do we have an encoder we're allowed to use? - // bytes == null if counting, so don't use encoder then - if (bytes != null && encoder != null) + // bytes is null if counting, so don't use encoder then + if (bytes is not null && encoder is not null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; @@ -551,7 +551,7 @@ internal sealed override unsafe int GetBytes( internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); - Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); + Debug.Assert(bytes is not null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); @@ -561,7 +561,7 @@ internal sealed override unsafe int GetChars( byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); - Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); + Debug.Assert(bytes is not null, "[UTF7Encoding.GetChars]bytes!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder @@ -575,7 +575,7 @@ internal sealed override unsafe int GetChars( int bits = 0; int bitCount = -1; bool firstByte = false; - if (decoder != null) + if (decoder is not null) { bits = decoder.bits; bitCount = decoder.bitCount; @@ -699,8 +699,8 @@ internal sealed override unsafe int GetChars( } } - // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) - if (chars != null && decoder != null) + // Stick stuff in the decoder if we can (chars is null if counting, so don't store decoder) + if (chars is not null && decoder is not null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) @@ -800,7 +800,7 @@ public override void Reset() this.bits = 0; this.bitCount = -1; this.firstByte = false; - if (_fallbackBuffer != null) + if (_fallbackBuffer is not null) _fallbackBuffer.Reset(); } @@ -829,7 +829,7 @@ public override void Reset() { this.bitCount = -1; this.bits = 0; - if (_fallbackBuffer != null) + if (_fallbackBuffer is not null) _fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.Sealed.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.Sealed.cs index 8a0041028df210..130b9fd8aeb88a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.Sealed.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.Sealed.cs @@ -52,7 +52,7 @@ public override byte[] GetBytes(string s) private unsafe byte[] GetBytesForSmallInput(string s) { - Debug.Assert(s != null); + Debug.Assert(s is not null); Debug.Assert(s.Length <= MaxSmallInputElementCount); byte* pDestination = stackalloc byte[MaxSmallInputElementCount * MaxUtf8BytesPerChar]; @@ -86,7 +86,7 @@ public override string GetString(byte[] bytes) private unsafe string GetStringForSmallInput(byte[] bytes) { - Debug.Assert(bytes != null); + Debug.Assert(bytes is not null); Debug.Assert(bytes.Length <= MaxSmallInputElementCount); char* pDestination = stackalloc char[MaxSmallInputElementCount]; // each byte produces at most one char diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs index 534b0e3db5da9a..ee174282d9afbf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs @@ -178,7 +178,7 @@ public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } @@ -208,7 +208,7 @@ private unsafe int GetByteCountCommon(char* pChars, int charCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. // Don't bother providing a fallback mechanism; our fast path doesn't use it. @@ -351,7 +351,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int { // Validate Parameters - if (chars == null || bytes == null) + if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, @@ -386,9 +386,9 @@ private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -463,7 +463,7 @@ public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } @@ -578,9 +578,9 @@ private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -698,7 +698,7 @@ private unsafe int GetCharCountCommon(byte* pBytes, int byteCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. // Don't bother providing a fallback mechanism; our fast path doesn't use it. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf16Utility.Validation.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf16Utility.Validation.cs index 2600dff49a3dac..192b3189745e33 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf16Utility.Validation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf16Utility.Validation.cs @@ -45,7 +45,7 @@ static Utf16Utility() public static char* GetPointerToFirstInvalidChar(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment) { Debug.Assert(inputLength >= 0, "Input length must not be negative."); - Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); + Debug.Assert(pInputBuffer is not null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); // First, we'll handle the common case of all-ASCII. If this is able to // consume the entire buffer, we'll skip the remainder of this method's logic. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Transcoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Transcoding.cs index b0c1376611b9e7..2c776a1ae8b1ba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Transcoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Transcoding.cs @@ -23,10 +23,10 @@ internal static unsafe partial class Utf8Utility public static OperationStatus TranscodeToUtf16(byte* pInputBuffer, int inputLength, char* pOutputBuffer, int outputCharsRemaining, out byte* pInputBufferRemaining, out char* pOutputBufferRemaining) { Debug.Assert(inputLength >= 0, "Input length must not be negative."); - Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); + Debug.Assert(pInputBuffer is not null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); Debug.Assert(outputCharsRemaining >= 0, "Destination length must not be negative."); - Debug.Assert(pOutputBuffer != null || outputCharsRemaining == 0, "Destination length must be zero if destination buffer pointer is null."); + Debug.Assert(pOutputBuffer is not null || outputCharsRemaining == 0, "Destination length must be zero if destination buffer pointer is null."); // First, try vectorized conversion. @@ -844,10 +844,10 @@ public static OperationStatus TranscodeToUtf8(char* pInputBuffer, int inputLengt const int CharsPerDWord = sizeof(uint) / sizeof(char); Debug.Assert(inputLength >= 0, "Input length must not be negative."); - Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); + Debug.Assert(pInputBuffer is not null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); Debug.Assert(outputBytesRemaining >= 0, "Destination length must not be negative."); - Debug.Assert(pOutputBuffer != null || outputBytesRemaining == 0, "Destination length must be zero if destination buffer pointer is null."); + Debug.Assert(pOutputBuffer is not null || outputBytesRemaining == 0, "Destination length must be zero if destination buffer pointer is null."); // First, try vectorized conversion. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Validation.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Validation.cs index 7730708030ebaf..19f65b77a00691 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Validation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8Utility.Validation.cs @@ -27,7 +27,7 @@ internal static unsafe partial class Utf8Utility public static byte* GetPointerToFirstInvalidByte(byte* pInputBuffer, int inputLength, out int utf16CodeUnitCountAdjustment, out int scalarCountAdjustment) { Debug.Assert(inputLength >= 0, "Input length must not be negative."); - Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); + Debug.Assert(pInputBuffer is not null || inputLength == 0, "Input length must be zero if input buffer pointer is null."); // First, try to drain off as many ASCII bytes as we can from the beginning. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs index 792344ae806883..18a1f298d30a7e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs @@ -85,7 +85,7 @@ internal sealed override void SetDefaultFallbacks() public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -111,7 +111,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) public override unsafe int GetByteCount(string s) { // Validate input - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -126,7 +126,7 @@ public override unsafe int GetByteCount(string s) public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) @@ -144,8 +144,8 @@ public override unsafe int GetByteCount(char* chars, int count) public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s == null || bytes == null) - throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); + if (s is null || bytes is null) + throw new ArgumentNullException(s is null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -180,8 +180,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -212,8 +212,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -232,7 +232,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -258,7 +258,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) @@ -276,8 +276,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -308,8 +308,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -328,7 +328,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -350,7 +350,7 @@ public override unsafe string GetString(byte[] bytes, int index, int count) // internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UnicodeEncoding.GetByteCount]chars!=null"); + Debug.Assert(chars is not null, "[UnicodeEncoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); // Start by assuming each char gets 2 bytes @@ -372,7 +372,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder._charLeftOver; @@ -395,7 +395,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder char ch; TryAgain: - while (((ch = (fallbackBuffer == null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) + while (((ch = (fallbackBuffer is null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { // First unwind any fallback if (ch == 0) @@ -503,9 +503,9 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // Fallback the previous surrogate // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -537,9 +537,9 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // fallback this one // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -570,9 +570,9 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // fallback previous chars // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -600,7 +600,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder byteCount -= 2; // If we have to flush, stick it in fallback and try again - if (encoder == null || encoder.MustFlush) + if (encoder is null || encoder.MustFlush) { if (wasHereBefore) { @@ -611,9 +611,9 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder else { // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -633,7 +633,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check _throwOnOverflow for count) - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end"); // Don't remember fallbackBuffer.encoder for counting @@ -643,10 +643,10 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder internal sealed override unsafe int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UnicodeEncoding.GetBytes]chars!=null"); + Debug.Assert(chars is not null, "[UnicodeEncoding.GetBytes]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetBytes]byteCount >=0"); Debug.Assert(charCount >= 0, "[UnicodeEncoding.GetBytes]charCount >=0"); - Debug.Assert(bytes != null, "[UnicodeEncoding.GetBytes]bytes!=null"); + Debug.Assert(bytes is not null, "[UnicodeEncoding.GetBytes]bytes!=null"); char charLeftOver = (char)0; char ch; @@ -662,7 +662,7 @@ internal sealed override unsafe int GetBytes( char* charsForFallback; // Get our encoder, but don't clear it yet. - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder._charLeftOver; @@ -680,7 +680,7 @@ internal sealed override unsafe int GetBytes( } TryAgain: - while (((ch = (fallbackBuffer == null) ? + while (((ch = (fallbackBuffer is null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { @@ -789,9 +789,9 @@ internal sealed override unsafe int GetBytes( // Fallback the previous surrogate // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -818,9 +818,9 @@ internal sealed override unsafe int GetBytes( { // We'll fall back this one // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -839,7 +839,7 @@ internal sealed override unsafe int GetBytes( if (bytes + 3 >= byteEnd) { // Not enough room to add this surrogate pair - if (fallbackBuffer != null && fallbackBuffer.bFallingBack) + if (fallbackBuffer is not null && fallbackBuffer.bFallingBack) { // These must have both been from the fallbacks. // Both of these MUST have been from a fallback because if the 1st wasn't @@ -888,9 +888,9 @@ internal sealed override unsafe int GetBytes( // fallback previous chars // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -912,7 +912,7 @@ internal sealed override unsafe int GetBytes( if (bytes + 1 >= byteEnd) { // Couldn't add this char - if (fallbackBuffer != null && fallbackBuffer.bFallingBack) + if (fallbackBuffer is not null && fallbackBuffer.bFallingBack) fallbackBuffer.MovePrevious(); // Not using this fallback char else { @@ -942,7 +942,7 @@ internal sealed override unsafe int GetBytes( if (charLeftOver > 0) { // If we aren't flushing we need to fall this back - if (encoder == null || encoder.MustFlush) + if (encoder is null || encoder.MustFlush) { if (wasHereBefore) { @@ -954,9 +954,9 @@ internal sealed override unsafe int GetBytes( { // If we have to flush, stick it in fallback and try again // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) + if (encoder is null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -978,7 +978,7 @@ internal sealed override unsafe int GetBytes( } // Not flushing, remember it in the encoder - if (encoder != null) + if (encoder is not null) { encoder._charLeftOver = charLeftOver; encoder._charsUsed = (int)(chars - charStart); @@ -986,11 +986,11 @@ internal sealed override unsafe int GetBytes( // Remember charLeftOver if we must, or clear it if we're flushing // (charLeftOver should be 0 if we're flushing) - Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, + Debug.Assert((encoder is not null && !encoder.MustFlush) || charLeftOver == (char)0, "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing"); - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || - encoder == null || !encoder._throwOnOverflow, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0 || + encoder is null || !encoder._throwOnOverflow, "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting"); return (int)(bytes - byteStart); @@ -998,7 +998,7 @@ internal sealed override unsafe int GetBytes( internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { - Debug.Assert(bytes != null, "[UnicodeEncoding.GetCharCount]bytes!=null"); + Debug.Assert(bytes is not null, "[UnicodeEncoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); UnicodeEncoding.Decoder? decoder = (UnicodeEncoding.Decoder?)baseDecoder; @@ -1016,7 +1016,7 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder // For fallback we may need a fallback buffer DecoderFallbackBuffer? fallbackBuffer = null; - if (decoder != null) + if (decoder is not null) { lastByte = decoder.lastByte; lastChar = decoder.lastChar; @@ -1156,9 +1156,9 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1197,9 +1197,9 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)ch), unchecked((byte)(ch >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1236,9 +1236,9 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1258,7 +1258,7 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder } // Extra space if we can't use decoder - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { if (lastChar > 0) { @@ -1276,9 +1276,9 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1294,9 +1294,9 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder if (lastByte >= 0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1317,7 +1317,7 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check _throwOnOverflow for count) - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end"); return charCount; @@ -1326,10 +1326,10 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder internal sealed override unsafe int GetChars( byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { - Debug.Assert(chars != null, "[UnicodeEncoding.GetChars]chars!=null"); + Debug.Assert(chars is not null, "[UnicodeEncoding.GetChars]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UnicodeEncoding.GetChars]charCount >=0"); - Debug.Assert(bytes != null, "[UnicodeEncoding.GetChars]bytes!=null"); + Debug.Assert(bytes is not null, "[UnicodeEncoding.GetChars]bytes!=null"); UnicodeEncoding.Decoder? decoder = (UnicodeEncoding.Decoder?)baseDecoder; @@ -1338,7 +1338,7 @@ internal sealed override unsafe int GetChars( char lastChar = (char)0; // Get our decoder (but don't clear it yet) - if (decoder != null) + if (decoder is not null) { lastByte = decoder.lastByte; lastChar = decoder.lastChar; @@ -1481,9 +1481,9 @@ internal sealed override unsafe int GetChars( { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1533,9 +1533,9 @@ internal sealed override unsafe int GetChars( { unchecked((byte)ch), unchecked((byte)(ch >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1595,9 +1595,9 @@ internal sealed override unsafe int GetChars( { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1643,7 +1643,7 @@ internal sealed override unsafe int GetChars( } // Remember our decoder if we must - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { if (lastChar > 0) { @@ -1660,9 +1660,9 @@ internal sealed override unsafe int GetChars( { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1699,9 +1699,9 @@ internal sealed override unsafe int GetChars( if (lastByte >= 0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1734,7 +1734,7 @@ internal sealed override unsafe int GetChars( End: // Remember our decoder if we must - if (decoder != null) + if (decoder is not null) { Debug.Assert(!decoder.MustFlush || ((lastChar == (char)0) && (lastByte == -1)), "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing" @@ -1748,7 +1748,7 @@ internal sealed override unsafe int GetChars( // Shouldn't have anything in fallback buffer for GetChars // (don't have to check _throwOnOverflow for count or chars) - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end"); return (int)(chars - charStart); @@ -1865,7 +1865,7 @@ public override void Reset() { lastByte = -1; lastChar = '\0'; - if (_fallbackBuffer != null) + if (_fallbackBuffer is not null) _fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Utf8StringComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Utf8StringComparer.cs index 8e56da74425947..d94863057897ea 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Utf8StringComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Utf8StringComparer.cs @@ -69,7 +69,7 @@ private sealed class CultureAwareComparer : Utf8StringComparer internal CultureAwareComparer(CompareInfo compareInfo, CompareOptions options) { - Debug.Assert(compareInfo != null); + Debug.Assert(compareInfo is not null); _compareInfo = compareInfo; _options = options; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs b/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs index fd2472e649df73..f75e5fe5ba28fd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs @@ -13,11 +13,11 @@ internal ref partial struct ValueStringBuilder public void AppendFormat(string format, params object?[] args) { - if (args == null) + if (args is null) { // To preserve the original exception behavior, throw an exception about format if both // args and format are null. The actual null check for format is in AppendFormatHelper. - string paramName = (format == null) ? nameof(format) : nameof(args); + string paramName = (format is null) ? nameof(format) : nameof(args); throw new ArgumentNullException(paramName); } @@ -32,11 +32,11 @@ public void AppendFormat(string format, params object?[] args) public void AppendFormat(IFormatProvider? provider, string format, params object?[] args) { - if (args == null) + if (args is null) { // To preserve the original exception behavior, throw an exception about format if both // args and format are null. The actual null check for format is in AppendFormatHelper. - string paramName = (format == null) ? nameof(format) : nameof(args); + string paramName = (format is null) ? nameof(format) : nameof(args); throw new ArgumentNullException(paramName); } @@ -52,7 +52,7 @@ private void AppendSpanFormattable(T value) where T : ISpanFormattable else { string? s = value.ToString(); - if (s != null) + if (s is not null) { Append(s); } @@ -79,7 +79,7 @@ internal void AppendFormatHelper(IFormatProvider? provider, string format, Param const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit - if (format == null) + if (format is null) { throw new ArgumentNullException(nameof(format)); } @@ -282,7 +282,7 @@ internal void AppendFormatHelper(IFormatProvider? provider, string format, Param string? s = null; string? itemFormat = null; - if (cf != null) + if (cf is not null) { if (itemFormatSpan.Length != 0) { @@ -291,7 +291,7 @@ internal void AppendFormatHelper(IFormatProvider? provider, string format, Param s = cf.Format(itemFormat, arg, provider); } - if (s == null) + if (s is null) { // If arg is ISpanFormattable and the beginning doesn't need padding, // try formatting it into the remaining current chunk. @@ -321,13 +321,13 @@ internal void AppendFormatHelper(IFormatProvider? provider, string format, Param } s = formattableArg.ToString(itemFormat, provider); } - else if (arg != null) + else if (arg is not null) { s = arg.ToString(); } } // Append it to the final output of the Format String. - if (s == null) + if (s is null) { s = string.Empty; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/AsyncLocal.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/AsyncLocal.cs index 288ffbd32e6903..04f91fd08693d2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/AsyncLocal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/AsyncLocal.cs @@ -62,16 +62,16 @@ public T Value get { object? obj = ExecutionContext.GetLocalValue(this); - return (obj == null) ? default : (T)obj; + return (obj is null) ? default : (T)obj; } - set => ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null); + set => ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler is not null); } void IAsyncLocal.OnValueChanged(object? previousValueObj, object? currentValueObj, bool contextChanged) { - Debug.Assert(m_valueChangedHandler != null); - T previousValue = previousValueObj == null ? default! : (T)previousValueObj; - T currentValue = currentValueObj == null ? default! : (T)currentValueObj; + Debug.Assert(m_valueChangedHandler is not null); + T previousValue = previousValueObj is null ? default! : (T)previousValueObj; + T currentValue = currentValueObj is null ? default! : (T)currentValueObj; m_valueChangedHandler(new AsyncLocalValueChangedArgs(previousValue, currentValue, contextChanged)); } } @@ -123,7 +123,7 @@ internal static class AsyncLocalValueMap public static bool IsEmpty(IAsyncLocalValueMap asyncLocalValueMap) { - Debug.Assert(asyncLocalValueMap != null); + Debug.Assert(asyncLocalValueMap is not null); Debug.Assert(asyncLocalValueMap == Empty || asyncLocalValueMap.GetType() != typeof(EmptyAsyncLocalValueMap)); return asyncLocalValueMap == Empty; @@ -133,7 +133,7 @@ public static IAsyncLocalValueMap Create(IAsyncLocal key, object? value, bool tr { // If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map // to store the key/value pair. Otherwise, use the empty map. - return value != null || !treatNullValueAsNonexistent ? + return value is not null || !treatNullValueAsNonexistent ? new OneElementAsyncLocalValueMap(key, value) : Empty; } @@ -145,7 +145,7 @@ public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullVal { // If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map // to store the key/value pair. Otherwise, use the empty map. - return value != null || !treatNullValueAsNonexistent ? + return value is not null || !treatNullValueAsNonexistent ? new OneElementAsyncLocalValueMap(key, value) : (IAsyncLocalValueMap)this; } @@ -170,7 +170,7 @@ public OneElementAsyncLocalValueMap(IAsyncLocal key, object? value) public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent) { - if (value != null || !treatNullValueAsNonexistent) + if (value is not null || !treatNullValueAsNonexistent) { // If the key matches one already contained in this map, then create a new one-element map with the updated // value, otherwise create a two-element map with the additional key/value. @@ -217,7 +217,7 @@ public TwoElementAsyncLocalValueMap(IAsyncLocal key1, object? value1, IAsyncLoca public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent) { - if (value != null || !treatNullValueAsNonexistent) + if (value is not null || !treatNullValueAsNonexistent) { // If the key matches one already contained in this map, then create a new two-element map with the updated // value, otherwise create a three-element map with the additional key/value. @@ -272,7 +272,7 @@ public ThreeElementAsyncLocalValueMap(IAsyncLocal key1, object? value1, IAsyncLo public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent) { - if (value != null || !treatNullValueAsNonexistent) + if (value is not null || !treatNullValueAsNonexistent) { // If the key matches one already contained in this map, then create a new three-element map with the // updated value. @@ -352,7 +352,7 @@ public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullVal if (ReferenceEquals(key, _keyValues[i].Key)) { // The key is in the map. - if (value != null || !treatNullValueAsNonexistent) + if (value is not null || !treatNullValueAsNonexistent) { // Create a new map of the same size that has all of the same pairs, with this new key/value pair // overwriting the old. @@ -385,7 +385,7 @@ public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullVal // The key does not already exist in this map. - if (value == null && treatNullValueAsNonexistent) + if (value is null && treatNullValueAsNonexistent) { // We can simply return this same map, as there's nothing to add or remove. return this; @@ -438,7 +438,7 @@ public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullVal // If the value being set exists, create a new many map, copy all of the elements from this one, // and then store the new key/value pair into it. This is the most common case. - if (value != null || !treatNullValueAsNonexistent) + if (value is not null || !treatNullValueAsNonexistent) { var map = new ManyElementAsyncLocalValueMap(count + (containsKey ? 0 : 1)); foreach (KeyValuePair pair in this) diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs index 18d7194fbd770a..14ad51af88b4c9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs @@ -68,7 +68,7 @@ public readonly struct CancellationToken /// particularly in situations where related objects are being canceled concurrently. /// /// - public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested; + public bool IsCancellationRequested => _source is not null && _source.IsCancellationRequested; /// /// Gets whether this token is capable of being in the canceled state. @@ -78,7 +78,7 @@ public readonly struct CancellationToken /// into a canceled state, meaning that will never /// return true. /// - public bool CanBeCanceled => _source != null; + public bool CanBeCanceled => _source is not null; /// /// Gets a that is signaled when the token is canceled. @@ -294,11 +294,11 @@ public CancellationTokenRegistration UnsafeRegister(ActionCancellationTokenSource has been disposed. private CancellationTokenRegistration Register(Delegate callback, object? state, bool useSynchronizationContext, bool useExecutionContext) { - if (callback == null) + if (callback is null) throw new ArgumentNullException(nameof(callback)); CancellationTokenSource? source = _source; - return source != null ? + return source is not null ? source.InternalRegister(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) : default; // Nothing to do for tokens than can never reach the canceled state. Give back a dummy registration. } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs index 5b892c91cf2ac5..ae970a29df40a6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs @@ -31,7 +31,7 @@ internal CancellationTokenRegistration(long id, CancellationTokenSource.Callback public void Dispose() { CancellationTokenSource.CallbackNode node = _node; - if (node != null && !node.Partition.Unregister(_id, node)) + if (node is not null && !node.Partition.Unregister(_id, node)) { WaitForCallbackIfNecessary(); } @@ -47,7 +47,7 @@ public void Dispose() public ValueTask DisposeAsync() { CancellationTokenSource.CallbackNode node = _node; - return node != null && !node.Partition.Unregister(_id, node) ? + return node is not null && !node.Partition.Unregister(_id, node) ? WaitForCallbackIfNecessaryAsync() : default; } @@ -63,7 +63,7 @@ public CancellationToken Token get { CancellationTokenSource.CallbackNode node = _node; - return node != null ? + return node is not null ? new CancellationToken(node.Partition.Source) : // avoid CTS.Token, which throws after disposal default; } @@ -76,7 +76,7 @@ public CancellationToken Token public bool Unregister() { CancellationTokenSource.CallbackNode node = _node; - return node != null && node.Partition.Unregister(_id, node); + return node is not null && node.Partition.Unregister(_id, node); } private void WaitForCallbackIfNecessary() @@ -165,6 +165,6 @@ private ValueTask WaitForCallbackIfNecessaryAsync() /// Serves as a hash function for a CancellationTokenRegistration.. /// /// A hash code for the current CancellationTokenRegistration instance. - public override int GetHashCode() => _node != null ? _node.GetHashCode() ^ _id.GetHashCode() : _id.GetHashCode(); + public override int GetHashCode() => _node is not null ? _node.GetHashCode() ^ _id.GetHashCode() : _id.GetHashCode(); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs index c83625ffce15d7..c262766ebb954d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -114,14 +114,14 @@ internal WaitHandle WaitHandle ThrowIfDisposed(); // Return the handle if it was already allocated. - if (_kernelEvent != null) + if (_kernelEvent is not null) { return _kernelEvent; } // Lazily-initialize the handle. var mre = new ManualResetEvent(false); - if (Interlocked.CompareExchange(ref _kernelEvent, mre, null) != null) + if (Interlocked.CompareExchange(ref _kernelEvent, mre, null) is not null) { mre.Dispose(); } @@ -359,7 +359,7 @@ public void CancelAfter(int millisecondsDelay) // Dispose() is not thread-safe and should not be called concurrently with CancelAfter(). TimerQueueTimer? timer = _timer; - if (timer == null) + if (timer is null) { // Lazily initialize the timer in a thread-safe fashion. // Initially set to "never go off" because we don't want to take a @@ -367,7 +367,7 @@ public void CancelAfter(int millisecondsDelay) // cancelling the token before it (the timer) can be disposed. timer = new TimerQueueTimer(s_timerCallback, this, Timeout.UnsignedInfinite, Timeout.UnsignedInfinite, flowExecutionContext: false); TimerQueueTimer? currentTimer = Interlocked.CompareExchange(ref _timer, timer, null); - if (currentTimer != null) + if (currentTimer is not null) { // We did not initialize the timer. Dispose the new timer. timer.Close(); @@ -430,7 +430,7 @@ protected virtual void Dispose(bool disposing) // happen at the same time the external entity is requesting cancellation). TimerQueueTimer? timer = _timer; - if (timer != null) + if (timer is not null) { _timer = null; timer.Close(); // TimerQueueTimer.Close is thread-safe @@ -443,10 +443,10 @@ protected virtual void Dispose(bool disposing) // interlocked exchange it to be null, and then we check whether cancellation is currently // in progress. NotifyCancellation will only try to set the event if it exists after it's // transitioned to and while it's in the NotifyingState. - if (_kernelEvent != null) + if (_kernelEvent is not null) { ManualResetEvent? mre = Interlocked.Exchange(ref _kernelEvent!, null); - if (mre != null && _state != NotifyingState) + if (mre is not null && _state != NotifyingState) { mre.Dispose(); } @@ -499,7 +499,7 @@ internal CancellationTokenRegistration InternalRegister( // Get the partitions... CallbackPartition?[]? partitions = _callbackPartitions; - if (partitions == null) + if (partitions is null) { partitions = new CallbackPartition[s_numPartitions]; partitions = Interlocked.CompareExchange(ref _callbackPartitions, partitions, null) ?? partitions; @@ -509,7 +509,7 @@ internal CancellationTokenRegistration InternalRegister( int partitionIndex = Environment.CurrentManagedThreadId & s_numPartitionsMask; Debug.Assert(partitionIndex < partitions.Length, $"Expected {partitionIndex} to be less than {partitions.Length}"); CallbackPartition? partition = partitions[partitionIndex]; - if (partition == null) + if (partition is null) { partition = new CallbackPartition(this); partition = Interlocked.CompareExchange(ref partitions[partitionIndex], partition, null) ?? partition; @@ -528,10 +528,10 @@ internal CancellationTokenRegistration InternalRegister( // Get a node, from the free list if possible or else a new one. node = partition.FreeNodeList; - if (node != null) + if (node is not null) { partition.FreeNodeList = node.Next; - Debug.Assert(node.Prev == null, "Nodes in the free list should all have a null Prev"); + Debug.Assert(node.Prev is null, "Nodes in the free list should all have a null Prev"); // node.Next will be overwritten below so no need to set it here. } else @@ -548,7 +548,7 @@ internal CancellationTokenRegistration InternalRegister( // Add it to the callbacks list. node.Next = partition.Callbacks; - if (node.Next != null) + if (node.Next is not null) { node.Next.Prev = node; } @@ -583,7 +583,7 @@ private void NotifyCancellation(bool throwOnFirstException) { // Dispose of the timer, if any. Dispose may be running concurrently here, but TimerQueueTimer.Close is thread-safe. TimerQueueTimer? timer = _timer; - if (timer != null) + if (timer is not null) { _timer = null; timer.Close(); @@ -616,7 +616,7 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) // If there are no callbacks to run, we can safely exit. Any race conditions to lazy initialize it // will see IsCancellationRequested and will then run the callback themselves. CallbackPartition?[]? partitions = Interlocked.Exchange(ref _callbackPartitions, null); - if (partitions == null) + if (partitions is null) { Interlocked.Exchange(ref _state, NotifyingCompleteState); return; @@ -630,7 +630,7 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) // This is intended to help with nesting scenarios so that child enlisters cancel before their parents. foreach (CallbackPartition? partition in partitions) { - if (partition == null) + if (partition is null) { // Uninitialized partition. Nothing to do. continue; @@ -648,15 +648,15 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) { // Pop the next registration from the callbacks list. node = partition.Callbacks; - if (node == null) + if (node is null) { // No more registrations to process. break; } else { - Debug.Assert(node.Prev == null); - if (node.Next != null) node.Next.Prev = null; + Debug.Assert(node.Prev is null); + if (node.Next is not null) node.Next.Prev = null; partition.Callbacks = node.Next; } @@ -679,7 +679,7 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) // target sync context if there is one. try { - if (node.SynchronizationContext != null) + if (node.SynchronizationContext is not null) { // Transition to the target syncContext and continue there. node.SynchronizationContext.Send(static s => @@ -716,7 +716,7 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) Interlocked.MemoryBarrier(); // for safety, prevent reorderings crossing this point and seeing inconsistent state. } - if (exceptionList != null) + if (exceptionList is not null) { Debug.Assert(exceptionList.Count > 0, $"Expected {exceptionList.Count} > 0"); throw new AggregateException(exceptionList); @@ -769,7 +769,7 @@ public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken /// is null. public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens) { - if (tokens == null) + if (tokens is null) { throw new ArgumentNullException(nameof(tokens)); } @@ -906,7 +906,7 @@ protected override void Dispose(bool disposing) } CancellationTokenRegistration[]? linkingRegistrations = _linkingRegistrations; - if (linkingRegistrations != null) + if (linkingRegistrations is not null) { _linkingRegistrations = null; // release for GC once we're done enumerating for (int i = 0; i < linkingRegistrations.Length; i++) @@ -934,13 +934,13 @@ internal sealed class CallbackPartition public CallbackPartition(CancellationTokenSource source) { - Debug.Assert(source != null, "Expected non-null source"); + Debug.Assert(source is not null, "Expected non-null source"); Source = source; } internal bool Unregister(long id, CallbackNode node) { - Debug.Assert(node != null, "Expected non-null node"); + Debug.Assert(node is not null, "Expected non-null node"); if (id == 0) { @@ -969,16 +969,16 @@ internal bool Unregister(long id, CallbackNode node) // The registration must still be in the callbacks list. Remove it. if (Callbacks == node) { - Debug.Assert(node.Prev == null); + Debug.Assert(node.Prev is null); Callbacks = node.Next; } else { - Debug.Assert(node.Prev != null); + Debug.Assert(node.Prev is not null); node.Prev.Next = node.Next; } - if (node.Next != null) + if (node.Next is not null) { node.Next.Prev = node.Prev; } @@ -1020,7 +1020,7 @@ internal sealed class CallbackNode public CallbackNode(CallbackPartition partition) { - Debug.Assert(partition != null, "Expected non-null partition"); + Debug.Assert(partition is not null, "Expected non-null partition"); Partition = partition; } @@ -1029,7 +1029,7 @@ public void ExecuteCallback() ExecutionContext? context = ExecutionContext; if (context is null) { - Debug.Assert(Callback != null); + Debug.Assert(Callback is not null); Invoke(Callback, CallbackState, Partition.Source); } else @@ -1037,7 +1037,7 @@ public void ExecuteCallback() ExecutionContext.RunInternal(context, static s => { var node = (CallbackNode)s!; - Debug.Assert(node.Callback != null); + Debug.Assert(node.Callback is not null); Invoke(node.Callback, node.CallbackState, node.Partition.Source); }, this); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs index be997e3c0965b7..d6e6c592ba0696 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs @@ -33,7 +33,7 @@ public static CompressedStack GetCompressedStack() public static void Run(CompressedStack compressedStack, ContextCallback callback, object? state) { - if (compressedStack == null) + if (compressedStack is null) { throw new ArgumentNullException(nameof(compressedStack)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs index 4c142bc7f3ca1c..55212acdfc0b9f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs @@ -19,7 +19,7 @@ private EventWaitHandle(SafeWaitHandle handle) private void CreateEventCore(bool initialState, EventResetMode mode, string? name, out bool createdNew) { #if TARGET_UNIX || TARGET_BROWSER - if (name != null) + if (name is not null) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #endif uint eventFlags = initialState ? Interop.Kernel32.CREATE_EVENT_INITIAL_SET : 0; @@ -44,7 +44,7 @@ private void CreateEventCore(bool initialState, EventResetMode mode, string? nam private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle? result) { #if TARGET_WINDOWS - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs index f17eaddb5d132b..aba6014a84e225 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs @@ -40,7 +40,7 @@ public static EventWaitHandle OpenExisting(string name) case OpenExistingResult.PathNotFound: throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)); default: - Debug.Assert(result != null, "result should be non-null on success"); + Debug.Assert(result is not null, "result should be non-null on success"); return result; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs index ba855b4f4dce0e..e7307a5c9c616a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs @@ -55,7 +55,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) public static ExecutionContext? Capture() { ExecutionContext? executionContext = Thread.CurrentThread._executionContext; - if (executionContext == null) + if (executionContext is null) { executionContext = Default; } @@ -86,7 +86,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) { Debug.Assert(isFlowSuppressed != m_isFlowSuppressed); - if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues)) + if (m_localValues is null || AsyncLocalValueMap.IsEmpty(m_localValues)) { return isFlowSuppressed ? DefaultFlowSuppressed : @@ -116,7 +116,7 @@ public static void RestoreFlow() { Thread currentThread = Thread.CurrentThread; ExecutionContext? executionContext = currentThread._executionContext; - if (executionContext == null || !executionContext.m_isFlowSuppressed) + if (executionContext is null || !executionContext.m_isFlowSuppressed) { throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow); } @@ -127,17 +127,17 @@ public static void RestoreFlow() public static bool IsFlowSuppressed() { ExecutionContext? executionContext = Thread.CurrentThread._executionContext; - return executionContext != null && executionContext.m_isFlowSuppressed; + return executionContext is not null && executionContext.m_isFlowSuppressed; } - internal bool HasChangeNotifications => m_localChangeNotifications != null; + internal bool HasChangeNotifications => m_localChangeNotifications is not null; internal bool IsDefault => m_isDefault; public static void Run(ExecutionContext executionContext, ContextCallback callback, object? state) { // Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc. - if (executionContext == null) + if (executionContext is null) { ThrowNullContext(); } @@ -156,7 +156,7 @@ internal static void RunInternal(ExecutionContext? executionContext, ContextCall Thread currentThread0 = Thread.CurrentThread; Thread currentThread = currentThread0; ExecutionContext? previousExecutionCtx0 = currentThread0._executionContext; - if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault) + if (previousExecutionCtx0 is not null && previousExecutionCtx0.m_isDefault) { // Default is a null ExecutionContext internally previousExecutionCtx0 = null; @@ -169,7 +169,7 @@ internal static void RunInternal(ExecutionContext? executionContext, ContextCall ExecutionContext? previousExecutionCtx = previousExecutionCtx0; SynchronizationContext? previousSyncCtx = currentThread0._synchronizationContext; - if (executionContext != null && executionContext.m_isDefault) + if (executionContext is not null && executionContext.m_isDefault) { // Default is a null ExecutionContext internally executionContext = null; @@ -224,7 +224,7 @@ internal static void RunInternal(ExecutionContext? executionContext, ContextCall /// The ExecutionContext to set. public static void Restore(ExecutionContext executionContext) { - if (executionContext == null) + if (executionContext is null) { ThrowNullContext(); } @@ -237,13 +237,13 @@ internal static void RestoreInternal(ExecutionContext? executionContext) Thread currentThread = Thread.CurrentThread; ExecutionContext? currentExecutionCtx = currentThread._executionContext; - if (currentExecutionCtx != null && currentExecutionCtx.m_isDefault) + if (currentExecutionCtx is not null && currentExecutionCtx.m_isDefault) { // Default is a null ExecutionContext internally currentExecutionCtx = null; } - if (executionContext != null && executionContext.m_isDefault) + if (executionContext is not null && executionContext.m_isDefault) { // Default is a null ExecutionContext internally executionContext = null; @@ -262,7 +262,7 @@ internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, Exec // ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null) // Default is a null ExecutionContext internally - if (executionContext != null && !executionContext.m_isDefault) + if (executionContext is not null && !executionContext.m_isDefault) { // Non-Default context to restore RestoreChangedContextToThread(threadPoolThread, contextToRestore: executionContext, currentContext: null); @@ -288,7 +288,7 @@ internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, Exec // Restore changed SynchronizationContext back to Default currentThread._synchronizationContext = null; - if (currentExecutionCtx != null) + if (currentExecutionCtx is not null) { // The EC always needs to be reset for this overload, as it will flow back to the caller if it performs // extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points @@ -305,7 +305,7 @@ internal static void RunForThreadPoolUnsafe(ExecutionContext executionCo // will crash or its a ThreadAbortException. CheckThreadPoolAndContextsAreDefault(); - Debug.Assert(executionContext != null && !executionContext.m_isDefault, "ExecutionContext argument is Default."); + Debug.Assert(executionContext is not null && !executionContext.m_isDefault, "ExecutionContext argument is Default."); // Restore Non-Default context Thread.CurrentThread._executionContext = executionContext; @@ -326,8 +326,8 @@ internal static void RestoreChangedContextToThread(Thread currentThread, Executi // Restore changed ExecutionContext back to previous currentThread._executionContext = contextToRestore; - if ((currentContext != null && currentContext.HasChangeNotifications) || - (contextToRestore != null && contextToRestore.HasChangeNotifications)) + if ((currentContext is not null && currentContext.HasChangeNotifications) || + (contextToRestore is not null && contextToRestore.HasChangeNotifications)) { // There are change notifications; trigger any affected OnValuesChanged(currentContext, contextToRestore); @@ -344,7 +344,7 @@ internal static void ResetThreadPoolThread(Thread currentThread) currentThread._synchronizationContext = null; currentThread._executionContext = null; - if (currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications) + if (currentExecutionCtx is not null && currentExecutionCtx.HasChangeNotifications) { OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null); @@ -358,8 +358,8 @@ internal static void ResetThreadPoolThread(Thread currentThread) internal static void CheckThreadPoolAndContextsAreDefault() { Debug.Assert(!Thread.IsThreadStartSupported || Thread.CurrentThread.IsThreadPoolThread); // there are no dedicated threadpool threads on runtimes where we can't start threads - Debug.Assert(Thread.CurrentThread._executionContext == null, "ThreadPool thread not on Default ExecutionContext."); - Debug.Assert(Thread.CurrentThread._synchronizationContext == null, "ThreadPool thread not on Default SynchronizationContext."); + Debug.Assert(Thread.CurrentThread._executionContext is null, "ThreadPool thread not on Default ExecutionContext."); + Debug.Assert(Thread.CurrentThread._synchronizationContext is null, "ThreadPool thread not on Default SynchronizationContext."); } internal static void OnValuesChanged(ExecutionContext? previousExecutionCtx, ExecutionContext? nextExecutionCtx) @@ -371,16 +371,16 @@ internal static void OnValuesChanged(ExecutionContext? previousExecutionCtx, Exe IAsyncLocal[]? nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications; // At least one side must have notifications - Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null); + Debug.Assert(previousChangeNotifications is not null || nextChangeNotifications is not null); // Fire Change Notifications try { - if (previousChangeNotifications != null && nextChangeNotifications != null) + if (previousChangeNotifications is not null && nextChangeNotifications is not null) { // Notifications can't exist without values - Debug.Assert(previousExecutionCtx!.m_localValues != null); - Debug.Assert(nextExecutionCtx!.m_localValues != null); + Debug.Assert(previousExecutionCtx!.m_localValues is not null); + Debug.Assert(nextExecutionCtx!.m_localValues is not null); // Both contexts have change notifications, check previousExecutionCtx first foreach (IAsyncLocal local in previousChangeNotifications) { @@ -411,29 +411,29 @@ internal static void OnValuesChanged(ExecutionContext? previousExecutionCtx, Exe } } } - else if (previousChangeNotifications != null) + else if (previousChangeNotifications is not null) { // Notifications can't exist without values - Debug.Assert(previousExecutionCtx!.m_localValues != null); + Debug.Assert(previousExecutionCtx!.m_localValues is not null); // No current values, so just check previous against null foreach (IAsyncLocal local in previousChangeNotifications) { previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue); - if (previousValue != null) + if (previousValue is not null) { local.OnValueChanged(previousValue, null, contextChanged: true); } } } - else // Implied: nextChangeNotifications != null + else // Implied: nextChangeNotifications is not null { // Notifications can't exist without values - Debug.Assert(nextExecutionCtx!.m_localValues != null); + Debug.Assert(nextExecutionCtx!.m_localValues is not null); // No previous values, so just check current against null foreach (IAsyncLocal local in nextChangeNotifications!) { nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue); - if (currentValue != null) + if (currentValue is not null) { local.OnValueChanged(null, currentValue, contextChanged: true); } @@ -458,13 +458,13 @@ private static void ThrowNullContext() internal static object? GetLocalValue(IAsyncLocal local) { ExecutionContext? current = Thread.CurrentThread._executionContext; - if (current == null) + if (current is null) { return null; } Debug.Assert(!current.IsDefault); - Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context"); + Debug.Assert(current.m_localValues is not null, "Only the default context should have null, and we shouldn't be here on the default context"); current.m_localValues.TryGetValue(local, out object? value); return value; } @@ -475,10 +475,10 @@ internal static void SetLocalValue(IAsyncLocal local, object? newValue, bool nee object? previousValue = null; bool hadPreviousValue = false; - if (current != null) + if (current is not null) { Debug.Assert(!current.IsDefault); - Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context"); + Debug.Assert(current.m_localValues is not null, "Only the default context should have null, and we shouldn't be here on the default context"); hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue); } @@ -498,10 +498,10 @@ internal static void SetLocalValue(IAsyncLocal local, object? newValue, bool nee IAsyncLocal[]? newChangeNotifications = null; IAsyncLocalValueMap newValues; bool isFlowSuppressed = false; - if (current != null) + if (current is not null) { Debug.Assert(!current.IsDefault); - Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context"); + Debug.Assert(current.m_localValues is not null, "Only the default context should have null, and we shouldn't be here on the default context"); isFlowSuppressed = current.m_isFlowSuppressed; newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications); @@ -520,10 +520,10 @@ internal static void SetLocalValue(IAsyncLocal local, object? newValue, bool nee { if (hadPreviousValue) { - Debug.Assert(newChangeNotifications != null); + Debug.Assert(newChangeNotifications is not null); Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0); } - else if (newChangeNotifications == null) + else if (newChangeNotifications is null) { newChangeNotifications = new IAsyncLocal[1] { local }; } @@ -569,7 +569,7 @@ internal void Initialize(Thread currentThread) public void Undo() { - if (_thread == null) + if (_thread is null) { throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs index b2703e7bdbb446..a13b4a1a942572 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs @@ -67,7 +67,7 @@ public static class LazyInitializer throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT); } - Debug.Assert(target != null); + Debug.Assert(target is not null); return target; } @@ -112,13 +112,13 @@ public static T EnsureInitialized([NotNull] ref T? target, Func valueFacto private static T EnsureInitializedCore([NotNull] ref T? target, Func valueFactory) where T : class { T value = valueFactory(); - if (value == null) + if (value is null) { throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation); } Interlocked.CompareExchange(ref target, value, null!); - Debug.Assert(target != null); + Debug.Assert(target is not null); return target; } @@ -264,17 +264,17 @@ private static T EnsureInitializedCore([NotNull] ref T? target, [NotNull] ref // Lazily initialize the lock if necessary and then double check if initialization is still required. lock (EnsureLockInitialized(ref syncLock)) { - if (Volatile.Read(ref target) == null) + if (Volatile.Read(ref target) is null) { Volatile.Write(ref target, valueFactory()); - if (target == null) + if (target is null) { throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation); } } } - Debug.Assert(target != null); + Debug.Assert(target is not null); return target; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs index ab4dedc4a5a528..6dcf92ab690fcc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs @@ -30,7 +30,7 @@ public void Initialize() private void DisposeCore() { - if (_pMonitor == null) + if (_pMonitor is null) { return; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs index e10c63e2ba6bc9..8ce6f2308a531d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs @@ -48,7 +48,7 @@ public void VerifyIsNotLocked() private void VerifyIsNotLockedByAnyThread() { #if DEBUG - Debug.Assert(_ownerThread == null); + Debug.Assert(_ownerThread is null); #endif } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs index 9af60a64ff757d..226ea691449fb2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs @@ -77,11 +77,11 @@ public WaitHandle WaitHandle get { ThrowIfDisposed(); - if (m_eventObj == null) + if (m_eventObj is null) { // Lazily initialize the event object if needed. LazyInitializeEvent(); - Debug.Assert(m_eventObj != null); + Debug.Assert(m_eventObj is not null); } return m_eventObj; @@ -209,7 +209,7 @@ private void Initialize(bool initialState, int spinCount) /// private void EnsureLockObjectCreated() { - if (m_lock != null) + if (m_lock is not null) return; object newObj = new object(); @@ -229,7 +229,7 @@ private void LazyInitializeEvent() // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. - if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) + if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) is not null) { // Someone else set the value due to a race condition. Destroy the garbage event. newEventObj.Dispose(); @@ -284,7 +284,7 @@ private void Set(bool duringCancellation) // If there are waiting threads, we need to pulse them. if (Waiters > 0) { - Debug.Assert(m_lock != null); // if waiters>0, then m_lock has already been created. + Debug.Assert(m_lock is not null); // if waiters>0, then m_lock has already been created. lock (m_lock) { Monitor.PulseAll(m_lock); @@ -296,7 +296,7 @@ private void Set(bool duringCancellation) // Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly // It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic - if (eventObj != null && !duringCancellation) + if (eventObj is not null && !duringCancellation) { // We must surround this call to Set in a lock. The reason is fairly subtle. // Sometimes a thread will issue a Wait and wake up after we have set m_state, @@ -311,7 +311,7 @@ private void Set(bool duringCancellation) lock (eventObj) { - if (m_eventObj != null) + if (m_eventObj is not null) { // If somebody is waiting, we must set the event. m_eventObj.Set(); @@ -331,7 +331,7 @@ public void Reset() { ThrowIfDisposed(); // If there's an event, reset it. - if (m_eventObj != null) + if (m_eventObj is not null) { m_eventObj.Reset(); } @@ -623,7 +623,7 @@ protected virtual void Dispose(bool disposing) // We will dispose of the event object. We do this under a lock to protect // against the race condition outlined in the Set method above. ManualResetEvent? eventObj = m_eventObj; - if (eventObj != null) + if (eventObj is not null) { lock (eventObj) { @@ -651,7 +651,7 @@ private static void CancellationTokenCallback(object? obj) { Debug.Assert(obj is ManualResetEventSlim, "Expected a ManualResetEventSlim"); ManualResetEventSlim mre = (ManualResetEventSlim)obj; - Debug.Assert(mre.m_lock != null); // the lock should have been created before this callback is registered for use. + Debug.Assert(mre.m_lock is not null); // the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs index cc444faf68a3f8..4f31af6e3f2e9a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs @@ -41,7 +41,7 @@ private void CreateMutexCore(bool initiallyOwned, string? name, out bool created private static OpenExistingResult OpenExistingWorker(string name, out Mutex? result) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.cs index a0ee43673bc9cc..27cb32edbaa573 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.cs @@ -50,7 +50,7 @@ public static Mutex OpenExisting(string name) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)); default: - Debug.Assert(result != null, "result should be non-null on success"); + Debug.Assert(result is not null, "result should be non-null on success"); return result; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs index 78a3b2db8291be..8699a43c529259 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs @@ -23,7 +23,7 @@ internal void RegisterWaitHandle(RegisteredWaitHandle handle) _waitThreadLock.Acquire(); try { - if (_waitThreadsHead == null) // Lazily create the first wait thread. + if (_waitThreadsHead is null) // Lazily create the first wait thread. { _waitThreadsHead = new WaitThreadNode { @@ -42,7 +42,7 @@ internal void RegisterWaitHandle(RegisteredWaitHandle handle) } prev = current; current = current.Next; - } while (current != null); + } while (current is not null); // If all wait threads are full, create a new one. prev.Next = new WaitThreadNode @@ -100,11 +100,11 @@ private void RemoveWaitThread(WaitThread thread) { prev = current; current = current.Next; - } while (current != null && current.Thread != thread); + } while (current is not null && current.Thread != thread); - Debug.Assert(current != null, "The wait thread to remove was not found in the list of thread pool wait threads."); + Debug.Assert(current is not null, "The wait thread to remove was not found in the list of thread pool wait threads."); - if (current != null) + if (current is not null) { prev.Next = current.Next; } @@ -229,7 +229,7 @@ private void WaitThreadStart() RegisteredWaitHandle? signaledHandle = signaledHandleIndex != WaitHandle.WaitTimeout ? _registeredWaits[signaledHandleIndex - 1] : null; - if (signaledHandle != null) + if (signaledHandle is not null) { QueueWaitCompletion(signaledHandle, false); } @@ -296,7 +296,7 @@ private void ProcessRemovals() break; } } - Debug.Assert(_pendingRemoves[i] == null); + Debug.Assert(_pendingRemoves[i] is null); } _numPendingRemoves = 0; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs index f2d7f91d287055..46c52e058a95c2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs @@ -197,12 +197,12 @@ private bool IsRwHashEntryChanged(ReaderWriterCount lrwc) { ReaderWriterCount? rwc = t_rwc; ReaderWriterCount? empty = null; - while (rwc != null) + while (rwc is not null) { if (rwc.lockID == _lockID) return rwc; - if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc)) + if (!dontAllocate && empty is null && IsRWEntryEmpty(rwc)) empty = rwc; rwc = rwc.next; @@ -211,7 +211,7 @@ private bool IsRwHashEntryChanged(ReaderWriterCount lrwc) if (dontAllocate) return null; - if (empty == null) + if (empty is null) { empty = new ReaderWriterCount(); empty.next = t_rwc; @@ -398,7 +398,7 @@ private bool TryEnterReadLockCore(TimeoutTracker timeout) } // Drat, we need to wait. Mark that we have waiters and wait. - if (_readEvent == null) // Create the needed event + if (_readEvent is null) // Create the needed event { LazyCreateEvent(ref _readEvent, EnterLockType.Read); if (IsRwHashEntryChanged(lrwc)) @@ -471,7 +471,7 @@ private bool TryEnterWriteLockCore(TimeoutTracker timeout) lrwc = GetThreadRWCount(dontAllocate: true); // Can't acquire write lock with reader lock held. - if (lrwc != null && lrwc.readercount > 0) + if (lrwc is not null && lrwc.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed); @@ -544,7 +544,7 @@ private bool TryEnterWriteLockCore(TimeoutTracker timeout) } else if (readercount == 2) { - if (lrwc != null) + if (lrwc is not null) { if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(dontAllocate: false)!; @@ -580,7 +580,7 @@ private bool TryEnterWriteLockCore(TimeoutTracker timeout) if (upgradingToWrite) { - if (_waitUpgradeEvent == null) // Create the needed event + if (_waitUpgradeEvent is null) // Create the needed event { LazyCreateEvent(ref _waitUpgradeEvent, EnterLockType.UpgradeToWrite); continue; // since we left the lock, start over. @@ -597,7 +597,7 @@ private bool TryEnterWriteLockCore(TimeoutTracker timeout) else { // Drat, we need to wait. Mark that we have waiters and wait. - if (_writeEvent == null) // create the needed event. + if (_writeEvent is null) // create the needed event. { LazyCreateEvent(ref _writeEvent, EnterLockType.Write); continue; // since we left the lock, start over. @@ -614,7 +614,7 @@ private bool TryEnterWriteLockCore(TimeoutTracker timeout) if (_fIsReentrant) { - Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method"); + Debug.Assert(lrwc is not null, "Initialized based on _fIsReentrant earlier in the method"); if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(dontAllocate: false)!; lrwc.writercount++; @@ -671,7 +671,7 @@ private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); lrwc = GetThreadRWCount(dontAllocate: true); // Can't acquire upgrade lock with reader lock held. - if (lrwc != null && lrwc.readercount > 0) + if (lrwc is not null && lrwc.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed); @@ -741,7 +741,7 @@ private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) } // Drat, we need to wait. Mark that we have waiters and wait. - if (_upgradeEvent == null) // Create the needed event + if (_upgradeEvent is null) // Create the needed event { LazyCreateEvent(ref _upgradeEvent, EnterLockType.UpgradeableRead); continue; // since we left the lock, start over. @@ -757,7 +757,7 @@ private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) { // The lock may have been dropped getting here, so make a quick check to see whether some other // thread did not grab the entry. - Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method"); + Debug.Assert(lrwc is not null, "Initialized based on _fIsReentrant earlier in the method"); if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(dontAllocate: false)!; lrwc.upgradecount++; @@ -774,7 +774,7 @@ public void ExitReadLock() ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true); - if (lrwc == null || lrwc.readercount < 1) + if (lrwc is null || lrwc.readercount < 1) { // You have to be holding the read lock to make this call. _spinLock.Exit(); @@ -823,7 +823,7 @@ public void ExitWriteLock() _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite); lrwc = GetThreadRWCount(dontAllocate: false)!; - if (lrwc == null) + if (lrwc is null) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); @@ -870,7 +870,7 @@ public void ExitUpgradeableReadLock() _spinLock.Enter(EnterSpinLockReason.ExitAnyRead); lrwc = GetThreadRWCount(dontAllocate: true); - if (lrwc == null) + if (lrwc is null) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); @@ -909,7 +909,7 @@ private void LazyCreateEvent([NotNull] ref EventWaitHandle? waitEvent, EnterLock { #if DEBUG Debug.Assert(_spinLock.IsHeld); - Debug.Assert(waitEvent == null); + Debug.Assert(waitEvent is null); #endif _spinLock.Exit(); @@ -938,7 +938,7 @@ private void LazyCreateEvent([NotNull] ref EventWaitHandle? waitEvent, EnterLock } _spinLock.Enter(enterMyLockReason); - if (waitEvent == null) // maybe someone snuck in. + if (waitEvent is null) // maybe someone snuck in. waitEvent = newEvent; else newEvent.Dispose(); @@ -1261,25 +1261,25 @@ private void Dispose(bool disposing) if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose); - if (_writeEvent != null) + if (_writeEvent is not null) { _writeEvent.Dispose(); _writeEvent = null; } - if (_readEvent != null) + if (_readEvent is not null) { _readEvent.Dispose(); _readEvent = null; } - if (_upgradeEvent != null) + if (_upgradeEvent is not null) { _upgradeEvent.Dispose(); _upgradeEvent = null; } - if (_waitUpgradeEvent != null) + if (_waitUpgradeEvent is not null) { _waitUpgradeEvent.Dispose(); _waitUpgradeEvent = null; @@ -1357,7 +1357,7 @@ public int RecursiveReadCount { int count = 0; ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true); - if (lrwc != null) + if (lrwc is not null) count = lrwc.readercount; return count; @@ -1373,7 +1373,7 @@ public int RecursiveUpgradeCount int count = 0; ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true); - if (lrwc != null) + if (lrwc is not null) count = lrwc.upgradecount; return count; @@ -1397,7 +1397,7 @@ public int RecursiveWriteCount int count = 0; ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true); - if (lrwc != null) + if (lrwc is not null) count = lrwc.writercount; return count; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs index d96882eb185716..e43aa6d0556532 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs @@ -24,7 +24,7 @@ private void CreateSemaphoreCore(int initialCount, int maximumCount, string? nam Debug.Assert(initialCount <= maximumCount); #if TARGET_UNIX || TARGET_BROWSER - if (name != null) + if (name is not null) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #endif SafeWaitHandle myHandle = Interop.Kernel32.CreateSemaphoreEx(IntPtr.Zero, initialCount, maximumCount, name, 0, AccessRights); @@ -45,7 +45,7 @@ private void CreateSemaphoreCore(int initialCount, int maximumCount, string? nam private static OpenExistingResult OpenExistingWorker(string name, out Semaphore? result) { #if TARGET_WINDOWS - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs index fb386e9e8be9d0..63dccd1f91261e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs @@ -45,7 +45,7 @@ public static Semaphore OpenExisting(string name) case OpenExistingResult.PathNotFound: throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); default: - Debug.Assert(result != null, "result should be non-null on success"); + Debug.Assert(result is not null, "result should be non-null on success"); return result; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs index 3d4a05cda6ab6c..c26df82c0ba59c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs @@ -107,13 +107,13 @@ public WaitHandle AvailableWaitHandle CheckDispose(); // Return it directly if it is not null - if (m_waitHandle != null) + if (m_waitHandle is not null) return m_waitHandle; // lock the count to avoid multiple threads initializing the handle if it is null lock (m_lockObjAndDisposed) { - if (m_waitHandle == null) + if (m_waitHandle is null) { // The initial state for the wait handle is true if the count is greater than zero // false otherwise @@ -356,9 +356,9 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) // If there are any async waiters, for fairness we'll get in line behind // then by translating our synchronous wait into an asynchronous one that we // then block on (once we've released the lock). - if (m_asyncHead != null) + if (m_asyncHead is not null) { - Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't"); + Debug.Assert(m_asyncTail is not null, "tail should not be null if head isn't"); asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken); } // There are no async waiters, so we can proceed with normal synchronous waiting. @@ -397,13 +397,13 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) waitSuccessful = true; m_currentCount--; } - else if (oce != null) + else if (oce is not null) { throw oce; } // Exposing wait handle which is lazily initialized if needed - if (m_waitHandle != null && m_currentCount == 0) + if (m_waitHandle is not null && m_currentCount == 0) { m_waitHandle.Reset(); } @@ -428,7 +428,7 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) // wait, and whether we successfully acquired the semaphore is // stored in waitSuccessful. - return (asyncWaitTask != null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful; + return (asyncWaitTask is not null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful; } /// @@ -624,7 +624,7 @@ public Task WaitAsync(int millisecondsTimeout, CancellationToken cancellat if (m_currentCount > 0) { --m_currentCount; - if (m_waitHandle != null && m_currentCount == 0) m_waitHandle.Reset(); + if (m_waitHandle is not null && m_currentCount == 0) m_waitHandle.Reset(); return s_trueTask; } else if (millisecondsTimeout == 0) @@ -656,15 +656,15 @@ private TaskNode CreateAndAddAsyncWaiter() var task = new TaskNode(); // Add it to the linked list - if (m_asyncHead == null) + if (m_asyncHead is null) { - Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail"); + Debug.Assert(m_asyncTail is null, "If head is null, so too should be tail"); m_asyncHead = task; m_asyncTail = task; } else { - Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail"); + Debug.Assert(m_asyncTail is not null, "If head is not null, neither should be tail"); m_asyncTail.Next = task; task.Prev = m_asyncTail; m_asyncTail = task; @@ -679,18 +679,18 @@ private TaskNode CreateAndAddAsyncWaiter() /// true if the waiter was in the list; otherwise, false. private bool RemoveAsyncWaiter(TaskNode task) { - Debug.Assert(task != null, "Expected non-null task"); + Debug.Assert(task is not null, "Expected non-null task"); Debug.Assert(Monitor.IsEntered(m_lockObjAndDisposed), "Requires the lock be held"); // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. - bool wasInList = m_asyncHead == task || task.Prev != null; + bool wasInList = m_asyncHead == task || task.Prev is not null; // Remove it from the linked list - if (task.Next != null) task.Next.Prev = task.Prev; - if (task.Prev != null) task.Prev.Next = task.Next; + if (task.Next is not null) task.Next.Prev = task.Prev; + if (task.Prev is not null) task.Prev.Next = task.Next; if (m_asyncHead == task) m_asyncHead = task.Next; if (m_asyncTail == task) m_asyncTail = task.Prev; - Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null"); + Debug.Assert((m_asyncHead is null) == (m_asyncTail is null), "Head is null iff tail is null"); // Make sure not to leak task.Next = task.Prev = null; @@ -706,7 +706,7 @@ private bool RemoveAsyncWaiter(TaskNode task) /// The task to return to the caller. private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) { - Debug.Assert(asyncWaiter != null, "Waiter should have been constructed"); + Debug.Assert(asyncWaiter is not null, "Waiter should have been constructed"); Debug.Assert(Monitor.IsEntered(m_lockObjAndDisposed), "Requires the lock be held"); if (millisecondsTimeout != Timeout.Infinite) @@ -836,11 +836,11 @@ public int Release(int releaseCount) // asynchronous waiters, we assume that all synchronous waiters will eventually // acquire the semaphore. That could be a faulty assumption if those synchronous // waits are canceled, but the wait code path will handle that. - if (m_asyncHead != null) + if (m_asyncHead is not null) { - Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null"); + Debug.Assert(m_asyncTail is not null, "tail should not be null if head isn't null"); int maxAsyncToRelease = currentCount - waitCount; - while (maxAsyncToRelease > 0 && m_asyncHead != null) + while (maxAsyncToRelease > 0 && m_asyncHead is not null) { --currentCount; --maxAsyncToRelease; @@ -854,7 +854,7 @@ public int Release(int releaseCount) m_currentCount = currentCount; // Exposing wait handle if it is not null - if (m_waitHandle != null && returnCount == 0 && currentCount > 0) + if (m_waitHandle is not null && returnCount == 0 && currentCount > 0) { m_waitHandle.Set(); } @@ -893,7 +893,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { WaitHandle? wh = m_waitHandle; - if (wh != null) + if (wh is not null) { wh.Dispose(); m_waitHandle = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs index b45cc7d5d3803a..3537dd4366af52 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs @@ -314,7 +314,7 @@ public static bool SpinUntil(Func condition, int millisecondsTimeout) throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong); } - if (condition == null) + if (condition is null) { throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs index b3ed9d1b9691f9..d40b9bc16a0938 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs @@ -44,7 +44,7 @@ public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTime [CLSCompliant(false)] protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { - if (waitHandles == null) + if (waitHandles is null) { throw new ArgumentNullException(nameof(waitHandles)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index cec1ef48a1c090..95bd129902c10f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -99,7 +99,7 @@ public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConc public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments - if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); + if (taskScheduler is null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); @@ -148,7 +148,7 @@ private CompletionState EnsureCompletionStateInitialized() => LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); /// Gets whether completion has been requested. - private bool CompletionRequested => m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); + private bool CompletionRequested => m_completionState is not null && Volatile.Read(ref m_completionState.m_completionRequested); /// Sets that completion has been requested. private void RequestCompletion() @@ -180,7 +180,7 @@ private bool ReadyToComplete // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. CompletionState cs = EnsureCompletionStateInitialized(); return - (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || + (cs.m_exceptions is not null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } @@ -204,7 +204,7 @@ private void CompleteTaskAsync() Debug.Assert(!localThis.m_completionState!.IsCompleted, "Completion should only happen once."); List? exceptions = localThis.m_completionState.m_exceptions; - bool success = (exceptions != null && exceptions.Count > 0) ? + bool success = (exceptions is not null && exceptions.Count > 0) ? localThis.m_completionState.TrySetException(exceptions) : localThis.m_completionState.TrySetResult(); Debug.Assert(success, "Expected to complete completion task."); @@ -218,7 +218,7 @@ private void CompleteTaskAsync() /// The faulted worker task that's initiating the shutdown. private void FaultWithTask(Task faultedTask) { - Debug.Assert(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception!.InnerExceptions.Count > 0, + Debug.Assert(faultedTask is not null && faultedTask.IsFaulted && faultedTask.Exception!.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); @@ -513,7 +513,7 @@ private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler /// The processing mode of this scheduler. internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { - Debug.Assert(pair != null, "Scheduler must be associated with a valid pair."); + Debug.Assert(pair is not null, "Scheduler must be associated with a valid pair."); Debug.Assert(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Debug.Assert( @@ -536,7 +536,7 @@ internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, /// The task to be queued. protected internal override void QueueTask(Task task) { - Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task is not null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled @@ -552,7 +552,7 @@ protected internal override void QueueTask(Task task) /// The task to be executed. internal void ExecuteTask(Task task) { - Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task is not null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } @@ -562,7 +562,7 @@ internal void ExecuteTask(Task task) /// true if the task could be executed; otherwise, false. protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { - Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task is not null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: @@ -670,7 +670,7 @@ private sealed class DebugView /// The scheduler being debugged. public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { - Debug.Assert(scheduler != null, "Need a scheduler with which to construct the debug view."); + Debug.Assert(scheduler is not null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } @@ -693,7 +693,7 @@ private sealed class DebugView /// The pair being debugged. public DebugView(ConcurrentExclusiveSchedulerPair pair) { - Debug.Assert(pair != null, "Need a pair with which to construct the debug view."); + Debug.Assert(pair is not null, "Need a pair with which to construct the debug view."); m_pair = pair; } @@ -716,7 +716,7 @@ private ProcessingMode ModeForDebugger get { // If our completion task is done, so are we. - if (m_completionState != null && m_completionState.IsCompleted) return ProcessingMode.Completed; + if (m_completionState is not null && m_completionState.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. ProcessingMode mode = ProcessingMode.NotCurrentlyProcessing; @@ -733,7 +733,7 @@ private ProcessingMode ModeForDebugger [Conditional("DEBUG")] private static void ContractAssertMonitorStatus(object syncObj, bool held) { - Debug.Assert(syncObj != null, "The monitor object to check must be provided."); + Debug.Assert(syncObj is not null, "The monitor object to check must be provided."); Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs index 32dceb94def788..8a1f0eb812c2cd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs @@ -318,11 +318,11 @@ internal Task(Delegate valueSelector, object? state, Task? parent, CancellationT internal static Task StartNew(Task? parent, Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { - if (function == null) + if (function is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -338,11 +338,11 @@ internal static Task StartNew(Task? parent, Func function, Can internal static Task StartNew(Task? parent, Func function, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { - if (function == null) + if (function is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -366,7 +366,7 @@ internal static Task StartNew(Task? parent, Func func // internal helper function breaks out logic used by TaskCompletionSource internal bool TrySetResult(TResult? result) { - Debug.Assert(m_action == null, "Task.TrySetResult(): non-null m_action"); + Debug.Assert(m_action is null, "Task.TrySetResult(): non-null m_action"); bool returnValue = false; @@ -389,7 +389,7 @@ internal bool TrySetResult(TResult? result) // FinishStageTwo, omitting everything that doesn't pertain to TrySetResult. Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_RAN_TO_COMPLETION); ContingentProperties? props = m_contingentProperties; - if (props != null) + if (props is not null) { NotifyParentIfPotentiallyAttachedTask(); props.SetCompleted(); @@ -412,7 +412,7 @@ internal void DangerousSetResult(TResult result) Debug.Assert(!IsCompleted, "The promise must not yet be completed."); // If we have a parent, we need to notify it of the completion. Take the slow path to handle that. - if (m_contingentProperties?.m_parent != null) + if (m_contingentProperties?.m_parent is not null) { bool success = TrySetResult(result); @@ -491,7 +491,7 @@ internal TResult GetResultCore(bool waitCompletionNotification) internal override void InnerInvoke() { // Invoke the delegate - Debug.Assert(m_action != null); + Debug.Assert(m_action is not null); if (m_action is Func func) { m_result = func(); @@ -688,12 +688,12 @@ public Task ContinueWith(Action> continuationAction, CancellationT internal Task ContinueWith(Action> continuationAction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) + if (continuationAction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -879,12 +879,12 @@ public Task ContinueWith(Action, object?> continuationAction, obje internal Task ContinueWith(Action, object?> continuationAction, object? state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) + if (continuationAction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -1093,12 +1093,12 @@ public Task ContinueWith(Func, TNewResult> internal Task ContinueWith(Func, TNewResult> continuationFunction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) + if (continuationFunction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -1314,12 +1314,12 @@ public Task ContinueWith(Func, object?, TN internal Task ContinueWith(Func, object?, TNewResult> continuationFunction, object? state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) + if (continuationFunction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -1353,7 +1353,7 @@ internal class SystemThreadingTasks_FutureDebugView public SystemThreadingTasks_FutureDebugView(Task task) { - Debug.Assert(task != null); + Debug.Assert(task is not null); m_task = task; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs index b2ca3898176ce8..d4463e155189fa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs @@ -40,8 +40,8 @@ public class TaskFactory // sister method to above property -- avoids a TLS lookup private TaskScheduler GetDefaultScheduler(Task? currTask) { - if (m_defaultScheduler != null) return m_defaultScheduler; - else if ((currTask != null) + if (m_defaultScheduler is not null) return m_defaultScheduler; + else if ((currTask is not null) && ((currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0) ) return currTask.ExecutingTaskScheduler!; // a "current" task must be executing, which means it must have a scheduler @@ -495,7 +495,7 @@ private static void FromAsyncCoreLogic( Task promise, bool requiresSynchronization) { - Debug.Assert((endFunction != null) != (endAction != null), "Expected exactly one of endFunction/endAction to be non-null"); + Debug.Assert((endFunction is not null) != (endAction is not null), "Expected exactly one of endFunction/endAction to be non-null"); Exception? ex = null; OperationCanceledException? oce = null; @@ -503,7 +503,7 @@ private static void FromAsyncCoreLogic( try { - if (endFunction != null) + if (endFunction is not null) { result = endFunction(iar); } @@ -516,11 +516,11 @@ private static void FromAsyncCoreLogic( catch (Exception e) { ex = e; } finally { - if (oce != null) + if (oce is not null) { promise.TrySetCanceled(oce.CancellationToken, oce); } - else if (ex != null) + else if (ex is not null) { promise.TrySetException(ex); } @@ -633,15 +633,15 @@ internal static Task FromAsyncImpl( TaskCreationOptions creationOptions, TaskScheduler scheduler) { - if (asyncResult == null) + if (asyncResult is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); - if (endFunction == null && endAction == null) + if (endFunction is null && endAction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); - Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); + Debug.Assert((endFunction is not null) != (endAction is not null), "Both endFunction and endAction were non-null"); - if (scheduler == null) + if (scheduler is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); TaskFactory.CheckFromAsyncOptions(creationOptions, false); @@ -751,13 +751,13 @@ internal static Task FromAsyncImpl(Func? endFunction, Action? endAction, object? state, TaskCreationOptions creationOptions) { - if (beginMethod == null) + if (beginMethod is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); - if (endFunction == null && endAction == null) + if (endFunction is null && endAction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); - Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); + Debug.Assert((endFunction is not null) != (endAction is not null), "Both endFunction and endAction were non-null"); TaskFactory.CheckFromAsyncOptions(creationOptions, true); @@ -868,13 +868,13 @@ internal static Task FromAsyncImpl(Func? endFunction, Action? endAction, TArg1 arg1, object? state, TaskCreationOptions creationOptions) { - if (beginMethod == null) + if (beginMethod is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); - if (endFunction == null && endAction == null) + if (endFunction is null && endAction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endFunction); - Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); + Debug.Assert((endFunction is not null) != (endAction is not null), "Both endFunction and endAction were non-null"); TaskFactory.CheckFromAsyncOptions(creationOptions, true); @@ -993,13 +993,13 @@ internal static Task FromAsyncImpl(Func? endFunction, Action? endAction, TArg1 arg1, TArg2 arg2, object? state, TaskCreationOptions creationOptions) { - if (beginMethod == null) + if (beginMethod is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); - if (endFunction == null && endAction == null) + if (endFunction is null && endAction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); - Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); + Debug.Assert((endFunction is not null) != (endAction is not null), "Both endFunction and endAction were non-null"); TaskFactory.CheckFromAsyncOptions(creationOptions, true); @@ -1126,13 +1126,13 @@ internal static Task FromAsyncImpl(Func? endFunction, Action? endAction, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state, TaskCreationOptions creationOptions) { - if (beginMethod == null) + if (beginMethod is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); - if (endFunction == null && endAction == null) + if (endFunction is null && endAction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); - Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); + Debug.Assert((endFunction is not null) != (endAction is not null), "Both endFunction and endAction were non-null"); TaskFactory.CheckFromAsyncOptions(creationOptions, true); @@ -1193,9 +1193,9 @@ internal static Task FromAsyncTrim( where TInstance : class { // Validate arguments, but only with asserts, as this is an internal only implementation. - Debug.Assert(thisRef != null, "Expected a non-null thisRef"); - Debug.Assert(beginMethod != null, "Expected a non-null beginMethod"); - Debug.Assert(endMethod != null, "Expected a non-null endMethod"); + Debug.Assert(thisRef is not null, "Expected a non-null thisRef"); + Debug.Assert(beginMethod is not null, "Expected a non-null beginMethod"); + Debug.Assert(endMethod is not null, "Expected a non-null endMethod"); // Create the promise and start the operation. // No try/catch is necessary here as we want exceptions to bubble out, and because @@ -1236,8 +1236,8 @@ private sealed class FromAsyncTrimPromise : Task where TInst /// The end method. internal FromAsyncTrimPromise(TInstance thisRef, Func endMethod) { - Debug.Assert(thisRef != null, "Expected a non-null thisRef"); - Debug.Assert(endMethod != null, "Expected a non-null endMethod"); + Debug.Assert(thisRef is not null, "Expected a non-null thisRef"); + Debug.Assert(endMethod is not null, "Expected a non-null endMethod"); m_thisRef = thisRef; m_endMethod = endMethod; } @@ -1250,23 +1250,23 @@ internal FromAsyncTrimPromise(TInstance thisRef, Func; - if (promise == null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); + if (promise is null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); // Grab the relevant state and then null it out so that the task doesn't hold onto the state unnecessarily TInstance? thisRef = promise.m_thisRef; Func? endMethod = promise.m_endMethod; promise.m_thisRef = default; promise.m_endMethod = null; - if (endMethod == null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); + if (endMethod is null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); // Complete the promise. If the IAsyncResult completed synchronously, // we'll instead complete the promise at the call site. if (!asyncResult.CompletedSynchronously) { - Debug.Assert(thisRef != null); + Debug.Assert(thisRef is not null); promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: true); } } @@ -1346,7 +1346,7 @@ private static Task CreateCanceledTask(TaskContinuationOptions continua /// array is empty. public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1374,7 +1374,7 @@ public Task ContinueWhenAll(Task[] tasks, Func continu /// public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1408,7 +1408,7 @@ public Task ContinueWhenAll(Task[] tasks, Func continu /// public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1453,7 +1453,7 @@ public Task ContinueWhenAll(Task[] tasks, Func continu public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1477,7 +1477,7 @@ public Task ContinueWhenAll(Task[] tasks, Func continu /// array is empty. public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1507,7 +1507,7 @@ public Task ContinueWhenAll(Task[ public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1543,7 +1543,7 @@ public Task ContinueWhenAll(Task[ public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1589,7 +1589,7 @@ public Task ContinueWhenAll(Task[ public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1603,10 +1603,10 @@ internal static Task ContinueWhenAllImpl(Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks); @@ -1623,7 +1623,7 @@ internal static Task ContinueWhenAllImpl(Task[]> starter = TaskFactory.CommonCWAllLogic(tasksCopy); // returned continuation task, off of starter - if (continuationFunction != null) + if (continuationFunction is not null) { return starter.ContinueWith( GenericDelegateCache.CWAllFuncDelegate, @@ -1631,7 +1631,7 @@ internal static Task ContinueWhenAllImpl(Task( GenericDelegateCache.CWAllActionDelegate, @@ -1647,10 +1647,10 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, { // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); // ArgumentNullException of continuationFunction or continuationAction is checked by the caller - Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); - if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); + Debug.Assert((continuationFunction is not null) != (continuationAction is not null), "Expected exactly one of endFunction/endAction to be non-null"); + if (scheduler is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); // Check tasks array and make defensive copy Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks); @@ -1667,7 +1667,7 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, Task starter = TaskFactory.CommonCWAllLogic(tasksCopy); // returned continuation task, off of starter - if (continuationFunction != null) + if (continuationFunction is not null) { return starter.ContinueWith( static (completedTasks, state) => @@ -1680,7 +1680,7 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, } else { - Debug.Assert(continuationAction != null); + Debug.Assert(continuationAction is not null); return starter.ContinueWith( static (completedTasks, state) => { @@ -1714,7 +1714,7 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, /// array is empty. public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1742,7 +1742,7 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat /// public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1776,7 +1776,7 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat /// public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1821,7 +1821,7 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1845,7 +1845,7 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat /// array is empty. public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1875,7 +1875,7 @@ public Task ContinueWhenAny(Task[ public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1911,7 +1911,7 @@ public Task ContinueWhenAny(Task[ public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1957,7 +1957,7 @@ public Task ContinueWhenAny(Task[ public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); + if (continuationFunction is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1970,12 +1970,12 @@ internal static Task ContinueWhenAnyImpl(Task[] tasks, { // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); // ArgumentNullException of continuationFunction or continuationAction is checked by the caller - Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); - if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); + Debug.Assert((continuationFunction is not null) != (continuationAction is not null), "Expected exactly one of endFunction/endAction to be non-null"); + if (scheduler is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); // Call common ContinueWhenAny() setup logic, extract starter Task starter = TaskFactory.CommonCWAnyLogic(tasks); @@ -1989,7 +1989,7 @@ internal static Task ContinueWhenAnyImpl(Task[] tasks, } // returned continuation task, off of starter - if (continuationFunction != null) + if (continuationFunction is not null) { return starter.ContinueWith( static (completedTask, state) => @@ -2001,7 +2001,7 @@ internal static Task ContinueWhenAnyImpl(Task[] tasks, } else { - Debug.Assert(continuationAction != null); + Debug.Assert(continuationAction is not null); return starter.ContinueWith( static (completedTask, state) => { @@ -2022,11 +2022,11 @@ internal static Task ContinueWhenAnyImpl(Task starter = TaskFactory.CommonCWAnyLogic(tasks); @@ -2040,7 +2040,7 @@ internal static Task ContinueWhenAnyImpl(Task( GenericDelegateCache.CWAnyFuncDelegate, @@ -2048,7 +2048,7 @@ internal static Task ContinueWhenAnyImpl(Task( GenericDelegateCache.CWAnyActionDelegate, continuationAction, scheduler, cancellationToken, continuationOptions); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs index b1ef1c1b0339b6..39ab1bfa7b963f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs @@ -163,7 +163,7 @@ public void Enqueue(T item) /// The segment in which to first attempt to store the item. private void EnqueueSlow(T item, ref Segment segment) { - Debug.Assert(segment != null, "Expected a non-null segment."); + Debug.Assert(segment is not null, "Expected a non-null segment."); if (segment.m_state.m_firstCopy != segment.m_state.m_first) { @@ -219,8 +219,8 @@ public bool TryDequeue([MaybeNullWhen(false)] out T result) /// true if an item could be dequeued; otherwise, false. private bool TryDequeueSlow(ref Segment segment, ref T[] array, [MaybeNullWhen(false)] out T result) { - Debug.Assert(segment != null, "Expected a non-null segment."); - Debug.Assert(array != null, "Expected a non-null item array."); + Debug.Assert(segment is not null, "Expected a non-null segment."); + Debug.Assert(array is not null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { @@ -228,7 +228,7 @@ private bool TryDequeueSlow(ref Segment segment, ref T[] array, [MaybeNullWhen(f return TryDequeue(out result); // will only recur once for this dequeue operation } - if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) + if (segment.m_next is not null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; @@ -261,7 +261,7 @@ public bool IsEmpty Segment head = m_head; if (head.m_state.m_first != head.m_state.m_lastCopy) return false; // m_first is volatile, so the read of m_lastCopy cannot get reordered if (head.m_state.m_first != head.m_state.m_last) return false; - return head.m_next == null; + return head.m_next is null; } } @@ -269,7 +269,7 @@ public bool IsEmpty /// WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently. public IEnumerator GetEnumerator() { - for (Segment? segment = m_head; segment != null; segment = segment.m_next) + for (Segment? segment = m_head; segment is not null; segment = segment.m_next) { for (int pt = segment.m_state.m_first; pt != segment.m_state.m_last; @@ -290,7 +290,7 @@ public int Count get { int count = 0; - for (Segment? segment = m_head; segment != null; segment = segment.m_next) + for (Segment? segment = m_head; segment is not null; segment = segment.m_next) { int arraySize = segment.m_array.Length; int first, last; @@ -360,7 +360,7 @@ private sealed class SingleProducerSingleConsumerQueue_DebugView /// The queue being debugged. public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue queue) { - Debug.Assert(queue != null, "Expected a non-null queue."); + Debug.Assert(queue is not null, "Expected a non-null queue."); m_queue = queue; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs index 647e4d7686b315..a0e6ef163f214c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs @@ -80,8 +80,8 @@ public ValueTaskSourceStatus GetStatus(short token) { ValidateToken(token); return - _continuation == null || !_completed ? ValueTaskSourceStatus.Pending : - _error == null ? ValueTaskSourceStatus.Succeeded : + _continuation is null || !_completed ? ValueTaskSourceStatus.Pending : + _error is null ? ValueTaskSourceStatus.Succeeded : _error.SourceException is OperationCanceledException ? ValueTaskSourceStatus.Canceled : ValueTaskSourceStatus.Faulted; } @@ -108,7 +108,7 @@ public TResult GetResult(short token) /// The flags describing the behavior of the continuation. public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) { - if (continuation == null) + if (continuation is null) { throw new ArgumentNullException(nameof(continuation)); } @@ -122,7 +122,7 @@ public void OnCompleted(Action continuation, object? state, short token if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext? sc = SynchronizationContext.Current; - if (sc != null && sc.GetType() != typeof(SynchronizationContext)) + if (sc is not null && sc.GetType() != typeof(SynchronizationContext)) { _capturedContext = sc; } @@ -145,13 +145,13 @@ public void OnCompleted(Action continuation, object? state, short token // is already set to something other than the completion sentinel. object? oldContinuation = _continuation; - if (oldContinuation == null) + if (oldContinuation is null) { _continuationState = state; oldContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null); } - if (oldContinuation != null) + if (oldContinuation is not null) { // Operation already completed, so we need to queue the supplied callback. if (!ReferenceEquals(oldContinuation, ManualResetValueTaskSourceCoreShared.s_sentinel)) @@ -162,7 +162,7 @@ public void OnCompleted(Action continuation, object? state, short token switch (_capturedContext) { case null: - if (_executionContext != null) + if (_executionContext is not null) { ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true); } @@ -241,8 +241,8 @@ private void InvokeContinuationWithContext() // for the surrounding code to become less efficent (stack spills etc) // and it is an uncommon path. - Debug.Assert(_continuation != null); - Debug.Assert(_executionContext != null); + Debug.Assert(_continuation is not null); + Debug.Assert(_executionContext is not null); ExecutionContext? currentContext = ExecutionContext.CaptureForRestore(); // Restore the captured ExecutionContext before executing anything. @@ -312,8 +312,8 @@ private void InvokeContinuationWithContext() /// private void InvokeSchedulerContinuation() { - Debug.Assert(_capturedContext != null); - Debug.Assert(_continuation != null); + Debug.Assert(_capturedContext is not null); + Debug.Assert(_continuation is not null); switch (_capturedContext) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index c6cbb14b0e5e42..05a9c4cf903b5b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -190,7 +190,7 @@ public class Task : IAsyncResult, IDisposable // activate dummy tasks. Specifically the AsyncTaskMethodBuilder and AsyncTaskMethodBuilder<> internal static bool AddToActiveTasks(Task task) { - Debug.Assert(task != null, "Null Task objects can't be added to the ActiveTasks collection"); + Debug.Assert(task is not null, "Null Task objects can't be added to the ActiveTasks collection"); LazyInitializer.EnsureInitialized(ref s_currentActiveTasks, () => new Dictionary()); @@ -205,7 +205,7 @@ internal static bool AddToActiveTasks(Task task) internal static void RemoveFromActiveTasks(Task task) { - if (s_currentActiveTasks == null) + if (s_currentActiveTasks is null) return; int taskId = task.Id; @@ -255,7 +255,7 @@ internal class ContingentProperties internal void SetCompleted() { ManualResetEventSlim? mres = m_completionEvent; - if (mres != null) mres.Set(); + if (mres is not null) mres.Set(); } /// @@ -265,7 +265,7 @@ internal void SetCompleted() /// internal void UnregisterCancellationCallback() { - if (m_cancellationRegistration != null) + if (m_cancellationRegistration is not null) { // Harden against ODEs thrown from disposing of the CTR. // Since the task has already been put into a final state by the time this @@ -326,7 +326,7 @@ internal Task(object? state, TaskCreationOptions creationOptions, bool promiseSt if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0) { Task? parent = Task.InternalCurrent; - if (parent != null) + if (parent is not null) { EnsureContingentPropertiesInitializedUnsafe().m_parent = parent; } @@ -493,20 +493,20 @@ public Task(Action action, object? state, CancellationToken cancellatio internal Task(Delegate action, object? state, Task? parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler? scheduler) { - if (action == null) + if (action is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } // Keep a link to the parent if attached - if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0) + if (parent is not null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0) { EnsureContingentPropertiesInitializedUnsafe().m_parent = parent; } TaskConstructorCore(action, state, cancellationToken, creationOptions, internalOptions, scheduler); - Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null, + Debug.Assert(m_contingentProperties is null || m_contingentProperties.m_capturedContext is null, "Captured an ExecutionContext when one was already captured."); CapturedContext = ExecutionContext.Capture(); } @@ -556,7 +556,7 @@ internal void TaskConstructorCore(Delegate? action, object? state, CancellationT Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags"); Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits"); int tmpFlags = (int)creationOptions | (int)internalOptions; // one write to the volatile m_stateFlags instead of two when setting the above options - m_stateFlags = m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0 ? + m_stateFlags = m_action is null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0 ? tmpFlags | TASK_STATE_WAITINGFORACTIVATION : tmpFlags; @@ -566,10 +566,10 @@ internal void TaskConstructorCore(Delegate? action, object? state, CancellationT // because at this point we are already on its thread of execution. ContingentProperties? props = m_contingentProperties; - if (props != null) + if (props is not null) { Task? parent = props.m_parent; - if (parent != null + if (parent is not null && ((creationOptions & TaskCreationOptions.AttachedToParent) != 0) && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0)) { @@ -616,14 +616,14 @@ private void AssignCancellationToken(CancellationToken cancellationToken, Task? { // Regular path for an uncanceled cancellationToken CancellationTokenRegistration ctr; - if (antecedent == null) + if (antecedent is null) { // if no antecedent was specified, use this task's reference as the cancellation state object ctr = cancellationToken.UnsafeRegister(static t => ((Task)t!).InternalCancel(), this); } else { - Debug.Assert(continuation != null); + Debug.Assert(continuation is not null); // If an antecedent was specified, pack this task, its antecedent and the TaskContinuation together as a tuple // and use it as the cancellation state object. This will be unpacked in the cancellation callback so that @@ -650,7 +650,7 @@ private void AssignCancellationToken(CancellationToken cancellationToken, Task? // If we have an exception related to our CancellationToken, then we need to subtract ourselves // from our parent before throwing it. Task? parent = m_contingentProperties?.m_parent; - if ((parent != null) && + if ((parent is not null) && ((Options & TaskCreationOptions.AttachedToParent) != 0) && ((parent.Options & TaskCreationOptions.DenyChildAttach) == 0)) { @@ -763,10 +763,10 @@ internal bool NotifyDebuggerOfWaitCompletionIfNecessary() /// true if any of the tasks require notification; otherwise, false. internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task?[] tasks) { - Debug.Assert(tasks != null, "Expected non-null array of tasks"); + Debug.Assert(tasks is not null, "Expected non-null array of tasks"); foreach (Task? task in tasks) { - if (task != null && + if (task is not null && task.IsWaitNotificationEnabled && task.ShouldNotifyDebuggerOfWaitCompletion) // potential recursion { @@ -843,8 +843,8 @@ internal void FireTaskScheduledIfNeeded(TaskScheduler ts) { Task? currentTask = Task.InternalCurrent; Task? parentTask = m_contingentProperties?.m_parent; - TplEventSource.Log.TaskScheduled(ts.Id, currentTask == null ? 0 : currentTask.Id, - this.Id, parentTask == null ? 0 : parentTask.Id, (int)this.Options); + TplEventSource.Log.TaskScheduled(ts.Id, currentTask is null ? 0 : currentTask.Id, + this.Id, parentTask is null ? 0 : parentTask.Id, (int)this.Options); } } } @@ -930,14 +930,14 @@ public void Start(TaskScheduler scheduler) // Read the volatile m_stateFlags field once and cache it for subsequent operations int flags = m_stateFlags; - // Need to check this before (m_action == null) because completed tasks will - // set m_action to null. We would want to know if this is the reason that m_action == null. + // Need to check this before (m_action is null) because completed tasks will + // set m_action to null. We would want to know if this is the reason that m_action is null. if (IsCompletedMethod(flags)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_TaskCompleted); } - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -953,7 +953,7 @@ public void Start(TaskScheduler scheduler) } // Make sure that Task only gets started once. Or else throw an exception. - if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null) + if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) is not null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_AlreadyStarted); } @@ -1015,7 +1015,7 @@ public void RunSynchronously() /// The scheduler on which to attempt to run this task inline. public void RunSynchronously(TaskScheduler scheduler) { - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -1028,7 +1028,7 @@ public void RunSynchronously(TaskScheduler scheduler) // internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion) { - Debug.Assert(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler"); + Debug.Assert(scheduler is not null, "Task.InternalRunSynchronously(): null TaskScheduler"); // Read the volatile m_stateFlags field once and cache it for subsequent operations int flags = m_stateFlags; @@ -1053,7 +1053,7 @@ internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForComp } // Make sure that Task only gets started once. Or else throw an exception. - if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null) + if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) is not null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_AlreadyStarted); } @@ -1099,8 +1099,8 @@ internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForComp // call Wait() on this task. // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException() Debug.Assert( - (m_contingentProperties != null) && - (m_contingentProperties.m_exceptionsHolder != null) && + (m_contingentProperties is not null) && + (m_contingentProperties.m_exceptionsHolder is not null) && (m_contingentProperties.m_exceptionsHolder.ContainsFaultList), "Task.InternalRunSynchronously(): Expected m_contingentProperties.m_exceptionsHolder to exist " + "and to have faults recorded."); @@ -1131,7 +1131,7 @@ internal static Task InternalStartNew( TaskCreationOptions options, InternalTaskOptions internalOptions) { // Validate arguments. - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -1197,7 +1197,7 @@ public static int? CurrentId get { Task? currentTask = InternalCurrent; - if (currentTask != null) + if (currentTask is not null) return currentTask.Id; else return null; @@ -1245,7 +1245,7 @@ public AggregateException? Exception // Only return an exception in faulted state (skip manufactured exceptions) // A "benevolent" race condition makes it possible to return null when IsFaulted is // true (i.e., if IsFaulted is set just after the check to IsFaulted above). - Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted"); + Debug.Assert((e is null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted"); return e; } @@ -1303,7 +1303,7 @@ internal bool IsCancellationRequested { // check both the internal cancellation request flag and the CancellationToken attached to this task ContingentProperties? props = Volatile.Read(ref m_contingentProperties); - return props != null && + return props is not null && (props.m_internalCancellationRequested == CANCELLATION_REQUESTED || props.m_cancellationToken.IsCancellationRequested); } @@ -1336,7 +1336,7 @@ internal CancellationToken CancellationToken get { ContingentProperties? props = Volatile.Read(ref m_contingentProperties); - return (props == null) ? default : props.m_cancellationToken; + return (props is null) ? default : props.m_cancellationToken; } } @@ -1460,11 +1460,11 @@ internal ManualResetEventSlim CompletedEvent get { ContingentProperties contingentProps = EnsureContingentPropertiesInitialized(); - if (contingentProps.m_completionEvent == null) + if (contingentProps.m_completionEvent is null) { bool wasCompleted = IsCompleted; ManualResetEventSlim newMre = new ManualResetEventSlim(wasCompleted); - if (Interlocked.CompareExchange(ref contingentProps.m_completionEvent, newMre, null) != null) + if (Interlocked.CompareExchange(ref contingentProps.m_completionEvent, newMre, null) is not null) { // Someone else already set the value, so we will just close the event right away. newMre.Dispose(); @@ -1489,7 +1489,7 @@ internal bool ExceptionRecorded get { ContingentProperties? props = Volatile.Read(ref m_contingentProperties); - return (props != null) && (props.m_exceptionsHolder != null) && (props.m_exceptionsHolder.ContainsFaultList); + return (props is not null) && (props.m_exceptionsHolder is not null) && (props.m_exceptionsHolder.ContainsFaultList); } } @@ -1526,7 +1526,7 @@ internal ExecutionContext? CapturedContext set { // There is no need to atomically set this bit because this set() method is only called during construction, and therefore there should be no contending accesses to m_stateFlags - if (value == null) + if (value is null) { m_stateFlags |= TASK_STATE_EXECUTIONCONTEXT_IS_NULL; } @@ -1593,13 +1593,13 @@ protected virtual void Dispose(bool disposing) // Dispose of the underlying completion event if it exists ContingentProperties? cp = Volatile.Read(ref m_contingentProperties); - if (cp != null) + if (cp is not null) { // Make a copy to protect against racing Disposes. // If we wanted to make this a bit safer, we could use an interlocked here, // but we state that Dispose is not thread safe. ManualResetEventSlim? ev = cp.m_completionEvent; - if (ev != null) + if (ev is not null) { // Null out the completion event in contingent props; we'll use our copy from here on out cp.m_completionEvent = null; @@ -1638,7 +1638,7 @@ protected virtual void Dispose(bool disposing) /// are not a problem. internal void ScheduleAndStart(bool needsProtection) { - Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected"); + Debug.Assert(m_taskScheduler is not null, "expected a task scheduler to have been selected"); Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started"); // Set the TASK_STATE_STARTED bit @@ -1661,7 +1661,7 @@ internal void ScheduleAndStart(bool needsProtection) if (TplEventSource.Log.IsEnabled() && (Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0) { // For all other task than TaskContinuations we want to log. TaskContinuations log in their constructor - Debug.Assert(m_action != null, "Must have a delegate to be in ScheduleAndStart"); + Debug.Assert(m_action is not null, "Must have a delegate to be in ScheduleAndStart"); TplEventSource.Log.TraceOperationBegin(this.Id, "Task: " + m_action.Method.Name, 0); } @@ -1687,8 +1687,8 @@ internal void ScheduleAndStart(bool needsProtection) { // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException() Debug.Assert( - (m_contingentProperties != null) && - (m_contingentProperties.m_exceptionsHolder != null) && + (m_contingentProperties is not null) && + (m_contingentProperties.m_exceptionsHolder is not null) && (m_contingentProperties.m_exceptionsHolder.ContainsFaultList), "Task.ScheduleAndStart(): Expected m_contingentProperties.m_exceptionsHolder to exist " + "and to have faults recorded."); @@ -1706,7 +1706,7 @@ internal void ScheduleAndStart(bool needsProtection) /// An object representing either an Exception or a collection of Exceptions. internal void AddException(object exceptionObject) { - Debug.Assert(exceptionObject != null, "Task.AddException: Expected a non-null exception object"); + Debug.Assert(exceptionObject is not null, "Task.AddException: Expected a non-null exception object"); AddException(exceptionObject, representsCancellation: false); } @@ -1717,7 +1717,7 @@ internal void AddException(object exceptionObject) /// Whether the exceptionObject is an OperationCanceledException representing cancellation. internal void AddException(object exceptionObject, bool representsCancellation) { - Debug.Assert(exceptionObject != null, "Task.AddException: Expected a non-null exception object"); + Debug.Assert(exceptionObject is not null, "Task.AddException: Expected a non-null exception object"); #if DEBUG var eoAsException = exceptionObject as Exception; @@ -1726,15 +1726,15 @@ internal void AddException(object exceptionObject, bool representsCancellation) var eoAsEnumerableEdi = exceptionObject as IEnumerable; Debug.Assert( - eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null, + eoAsException is not null || eoAsEnumerableException is not null || eoAsEdi is not null || eoAsEnumerableEdi is not null, "Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those"); var eoAsOce = exceptionObject as OperationCanceledException; Debug.Assert( !representsCancellation || - eoAsOce != null || - (eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException), + eoAsOce is not null || + (eoAsEdi is not null && eoAsEdi.SourceException is OperationCanceledException), "representsCancellation should be true only if an OCE was provided."); #endif @@ -1746,10 +1746,10 @@ internal void AddException(object exceptionObject, bool representsCancellation) // Lazily initialize the holder, ensuring only one thread wins. ContingentProperties props = EnsureContingentPropertiesInitialized(); - if (props.m_exceptionsHolder == null) + if (props.m_exceptionsHolder is null) { TaskExceptionHolder holder = new TaskExceptionHolder(this); - if (Interlocked.CompareExchange(ref props.m_exceptionsHolder, holder, null) != null) + if (Interlocked.CompareExchange(ref props.m_exceptionsHolder, holder, null) is not null) { // If someone else already set the value, suppress finalization. holder.MarkAsHandled(false); @@ -1823,13 +1823,13 @@ internal void AddException(object exceptionObject, bool representsCancellation) { // There are exceptions; get the aggregate and optionally add the canceled // exception to the aggregate (if applicable). - Debug.Assert(m_contingentProperties != null && m_contingentProperties.m_exceptionsHolder != null, "ExceptionRecorded should imply this"); + Debug.Assert(m_contingentProperties is not null && m_contingentProperties.m_exceptionsHolder is not null, "ExceptionRecorded should imply this"); // No need to lock around this, as other logic prevents the consumption of exceptions // before they have been completely processed. return m_contingentProperties.m_exceptionsHolder.CreateExceptionObject(false, canceledException); } - else if (canceledException != null) + else if (canceledException is not null) { // No exceptions, but there was a cancelation. Aggregate and return it. return new AggregateException(canceledException); @@ -1861,7 +1861,7 @@ internal void ThrowIfExceptional(bool includeTaskCanceledExceptions) Debug.Assert(IsCompleted, "ThrowIfExceptional(): Expected IsCompleted == true"); Exception? exception = GetExceptions(includeTaskCanceledExceptions); - if (exception != null) + if (exception is not null) { UpdateExceptionObservedStatus(); throw exception; @@ -1878,7 +1878,7 @@ internal static void ThrowAsync(Exception exception, SynchronizationContext? tar var edi = ExceptionDispatchInfo.Capture(exception); // If the user supplied a SynchronizationContext... - if (targetContext != null) + if (targetContext is not null) { try { @@ -1917,7 +1917,7 @@ internal static void ThrowAsync(Exception exception, SynchronizationContext? tar internal void UpdateExceptionObservedStatus() { Task? parent = m_contingentProperties?.m_parent; - if ((parent != null) + if ((parent is not null) && ((Options & TaskCreationOptions.AttachedToParent) != 0) && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0) && Task.InternalCurrent == parent) @@ -1951,7 +1951,7 @@ internal void UpdateExceptionObservedStatus() /// internal void Finish(bool userDelegateExecute) { - if (m_contingentProperties == null) + if (m_contingentProperties is null) { FinishStageTwo(); } @@ -1963,7 +1963,7 @@ internal void Finish(bool userDelegateExecute) private void FinishSlow(bool userDelegateExecute) { - Debug.Assert(userDelegateExecute || m_contingentProperties != null); + Debug.Assert(userDelegateExecute || m_contingentProperties is not null); if (!userDelegateExecute) { @@ -2000,7 +2000,7 @@ private void FinishSlow(bool userDelegateExecute) // Now is the time to prune exceptional children. We'll walk the list and removes the ones whose exceptions we might have observed after they threw. // we use a local variable for exceptional children here because some other thread may be nulling out m_contingentProperties.m_exceptionalChildren List? exceptionalChildren = props.m_exceptionalChildren; - if (exceptionalChildren != null) + if (exceptionalChildren is not null) { lock (exceptionalChildren) { @@ -2021,7 +2021,7 @@ private void FinishStageTwo() // we can transition our task to a completion state. ContingentProperties? cp = Volatile.Read(ref m_contingentProperties); - if (cp != null) + if (cp is not null) { AddExceptionsFromChildren(cp); } @@ -2069,7 +2069,7 @@ private void FinishStageTwo() // Set the completion event if it's been lazy allocated. // And if we made a cancellation registration, it's now unnecessary. cp = Volatile.Read(ref m_contingentProperties); // need to re-read after updating state - if (cp != null) + if (cp is not null) { cp.SetCompleted(); cp.UnregisterCancellationCallback(); @@ -2094,7 +2094,7 @@ internal void FinishStageThree() m_action = null; ContingentProperties? cp = m_contingentProperties; - if (cp != null) + if (cp is not null) { // Similarly, null out any ExecutionContext we may have captured, // to avoid keeping state like async locals alive unnecessarily @@ -2112,7 +2112,7 @@ internal void FinishStageThree() internal void NotifyParentIfPotentiallyAttachedTask() { Task? parent = m_contingentProperties?.m_parent; - if (parent != null + if (parent is not null && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0) && (((TaskCreationOptions)(m_stateFlags & OptionsMask)) & TaskCreationOptions.AttachedToParent) != 0) { @@ -2125,7 +2125,7 @@ internal void NotifyParentIfPotentiallyAttachedTask() /// internal void ProcessChildCompletion(Task childTask) { - Debug.Assert(childTask != null); + Debug.Assert(childTask is not null); Debug.Assert(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task"); Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task"); @@ -2136,7 +2136,7 @@ internal void ProcessChildCompletion(Task childTask) if (childTask.IsFaulted && !childTask.IsExceptionObservedByParent) { // Lazily initialize the child exception list - if (props!.m_exceptionalChildren == null) + if (props!.m_exceptionalChildren is null) { Interlocked.CompareExchange(ref props.m_exceptionalChildren, new List(), null); } @@ -2146,7 +2146,7 @@ internal void ProcessChildCompletion(Task childTask) // out at the same time that we're processing it, resulting in a NullReferenceException here. We'll protect // ourselves by caching m_exceptionChildren in a local variable. List? tmp = props.m_exceptionalChildren; - if (tmp != null) + if (tmp is not null) { lock (tmp) { @@ -2170,7 +2170,7 @@ internal void ProcessChildCompletion(Task childTask) /// internal void AddExceptionsFromChildren(ContingentProperties props) { - Debug.Assert(props != null); + Debug.Assert(props is not null); // In rare occurrences during AppDomainUnload() processing, it is possible for this method to be called // simultaneously on the same task from two different contexts. This can result in m_exceptionalChildren @@ -2178,7 +2178,7 @@ internal void AddExceptionsFromChildren(ContingentProperties props) // protect ourselves, we'll cache m_exceptionalChildren in a local variable. List? exceptionalChildren = props.m_exceptionalChildren; - if (exceptionalChildren != null) + if (exceptionalChildren is not null) { // This lock is necessary because even though AddExceptionsFromChildren is last to execute, it may still // be racing with the code segment at the bottom of Finish() that prunes the exceptional child array. @@ -2192,7 +2192,7 @@ internal void AddExceptionsFromChildren(ContingentProperties props) if (task.IsFaulted && !task.IsExceptionObservedByParent) { TaskExceptionHolder? exceptionHolder = Volatile.Read(ref task.m_contingentProperties)!.m_exceptionsHolder; - Debug.Assert(exceptionHolder != null); + Debug.Assert(exceptionHolder is not null); // No locking necessary since child task is finished adding exceptions // and concurrent CreateExceptionObject() calls do not constitute @@ -2287,7 +2287,7 @@ private void ExecuteWithThreadLocal(ref Task? currentTaskSlot, Thread? threadPoo if (log.TasksSetActivityIds) EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(this.Id), out savedActivityID); // previousTask holds the actual "current task" we want to report in the event - if (previousTask != null) + if (previousTask is not null) log.TaskStarted(previousTask.m_taskScheduler!.Id, previousTask.Id, this.Id); else log.TaskStarted(TaskScheduler.Current.Id, 0, this.Id); @@ -2304,7 +2304,7 @@ private void ExecuteWithThreadLocal(ref Task? currentTaskSlot, Thread? threadPoo try { ExecutionContext? ec = CapturedContext; - if (ec == null) + if (ec is null) { // No context, just run the task directly. InnerInvoke(); @@ -2341,7 +2341,7 @@ private void ExecuteWithThreadLocal(ref Task? currentTaskSlot, Thread? threadPoo if (etwIsEnabled) { // previousTask holds the actual "current task" we want to report in the event - if (previousTask != null) + if (previousTask is not null) log.TaskCompleted(previousTask.m_taskScheduler!.Id, previousTask.Id, this.Id, IsFaulted); else log.TaskCompleted(TaskScheduler.Current.Id, 0, this.Id, IsFaulted); @@ -2365,7 +2365,7 @@ private void ExecuteWithThreadLocal(ref Task? currentTaskSlot, Thread? threadPoo internal virtual void InnerInvoke() { // Invoke the delegate - Debug.Assert(m_action != null, "Null action in InnerInvoke()"); + Debug.Assert(m_action is not null, "Null action in InnerInvoke()"); if (m_action is Action action) { action(); @@ -2387,7 +2387,7 @@ internal virtual void InnerInvoke() /// The exception that went unhandled. private void HandleException(Exception unhandledException) { - Debug.Assert(unhandledException != null); + Debug.Assert(unhandledException is not null); if (unhandledException is OperationCanceledException exceptionAsOce && IsCancellationRequested && m_contingentProperties!.m_cancellationToken == exceptionAsOce.CancellationToken) @@ -2442,7 +2442,7 @@ public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) internal void SetContinuationForAwait( Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext) { - Debug.Assert(continuationAction != null); + Debug.Assert(continuationAction is not null); // Create the best AwaitTaskContinuation object given the request. // If this remains null by the end of the function, we can use the @@ -2459,7 +2459,7 @@ internal void SetContinuationForAwait( // of work items, but more so it ensures that if code happens to publish the default context // as current, it won't prevent usage of a current task scheduler if there is one. SynchronizationContext? syncCtx = SynchronizationContext.Current; - if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext)) + if (syncCtx is not null && syncCtx.GetType() != typeof(SynchronizationContext)) { tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, continuationAction, flowExecutionContext); } @@ -2468,14 +2468,14 @@ internal void SetContinuationForAwait( // If there was no SynchronizationContext, then try for the current scheduler. // We only care about it if it's not the default. TaskScheduler? scheduler = TaskScheduler.InternalCurrent; - if (scheduler != null && scheduler != TaskScheduler.Default) + if (scheduler is not null && scheduler != TaskScheduler.Default) { tc = new TaskSchedulerAwaitTaskContinuation(scheduler, continuationAction, flowExecutionContext); } } } - if (tc == null && flowExecutionContext) + if (tc is null && flowExecutionContext) { // We're targeting the default scheduler, so we can use the faster path // that assumes the default, and thus we don't need to store it. If we're flowing @@ -2488,7 +2488,7 @@ internal void SetContinuationForAwait( // Now register the continuation, and if we couldn't register it because the task is already completing, // process the continuation directly (in which case make sure we schedule the continuation // rather than inlining it, the latter of which could result in a rare but possible stack overflow). - if (tc != null) + if (tc is not null) { if (!AddTaskContinuation(tc, addBeforeOthers: false)) tc.Run(this, canInlineContinuationTask: false); @@ -2513,7 +2513,7 @@ internal void SetContinuationForAwait( /// The awaiter was not properly initialized. internal void UnsafeSetContinuationForAwait(IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { - Debug.Assert(stateMachineBox != null); + Debug.Assert(stateMachineBox is not null); // This code path doesn't emit all expected TPL-related events, such as for continuations. // It's expected that all callers check whether events are enabled before calling this function, @@ -2527,7 +2527,7 @@ internal void UnsafeSetContinuationForAwait(IAsyncStateMachineBox stateMachineBo if (continueOnCapturedContext) { SynchronizationContext? syncCtx = SynchronizationContext.Current; - if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext)) + if (syncCtx is not null && syncCtx.GetType() != typeof(SynchronizationContext)) { var tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, stateMachineBox.MoveNextAction, flowExecutionContext: false); if (!AddTaskContinuation(tc, addBeforeOthers: false)) @@ -2539,7 +2539,7 @@ internal void UnsafeSetContinuationForAwait(IAsyncStateMachineBox stateMachineBo else { TaskScheduler? scheduler = TaskScheduler.InternalCurrent; - if (scheduler != null && scheduler != TaskScheduler.Default) + if (scheduler is not null && scheduler != TaskScheduler.Default) { var tc = new TaskSchedulerAwaitTaskContinuation(scheduler, stateMachineBox.MoveNextAction, flowExecutionContext: false); if (!AddTaskContinuation(tc, addBeforeOthers: false)) @@ -2726,7 +2726,7 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) // and rethrows it. private bool WrappedTryRunInline() { - if (m_taskScheduler == null) + if (m_taskScheduler is null) return false; try @@ -2765,7 +2765,7 @@ private bool InternalWaitCore(int millisecondsTimeout, CancellationToken cancell { Task? currentTask = Task.InternalCurrent; log.TaskWaitBegin( - currentTask != null ? currentTask.m_taskScheduler!.Id : TaskScheduler.Default.Id, currentTask != null ? currentTask.Id : 0, + currentTask is not null ? currentTask.m_taskScheduler!.Id : TaskScheduler.Default.Id, currentTask is not null ? currentTask.Id : 0, this.Id, TplEventSource.TaskWaitBehavior.Synchronous, 0); } @@ -2795,7 +2795,7 @@ private bool InternalWaitCore(int millisecondsTimeout, CancellationToken cancell if (etwIsEnabled) { Task? currentTask = Task.InternalCurrent; - if (currentTask != null) + if (currentTask is not null) { log.TaskWaitEnd(currentTask.m_taskScheduler!.Id, currentTask.Id, this.Id); } @@ -2916,7 +2916,7 @@ internal void InternalCancel() TaskScheduler? ts = m_taskScheduler; try { - popped = (ts != null) && ts.TryDequeue(this); + popped = (ts is not null) && ts.TryDequeue(this); } catch (Exception e) { @@ -2958,7 +2958,7 @@ internal void InternalCancel() CancellationCleanupLogic(); } - if (tse != null) + if (tse is not null) { throw tse; } @@ -3010,16 +3010,16 @@ internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord, } // Store the supplied cancellation exception - if (cancellationException != null) + if (cancellationException is not null) { #if DEBUG var oce = cancellationException as OperationCanceledException; - if (oce == null) + if (oce is null) { var edi = cancellationException as ExceptionDispatchInfo; - Debug.Assert(edi != null, "Expected either an OCE or an EDI"); + Debug.Assert(edi is not null, "Expected either an OCE or an EDI"); oce = edi.SourceException as OperationCanceledException; - Debug.Assert(oce != null, "Expected EDI to contain an OCE"); + Debug.Assert(oce is not null, "Expected EDI to contain an OCE"); } Debug.Assert(oce.CancellationToken == tokenToRecord, "Expected OCE's token to match the provided token."); @@ -3034,7 +3034,7 @@ internal void CancellationCleanupLogic() { Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved."); // We'd like to be able to: - // Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set."); + // Debug.Assert((m_completionEvent is null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set."); // However, there is a small window for a race condition. If someone calls Wait() between InternalCancel() and // here, that will set m_completionEvent, leading to a meaningless/harmless assertion. @@ -3043,7 +3043,7 @@ internal void CancellationCleanupLogic() // Fire completion event if it has been lazily initialized ContingentProperties? cp = Volatile.Read(ref m_contingentProperties); - if (cp != null) + if (cp is not null) { cp.SetCompleted(); cp.UnregisterCancellationCallback(); @@ -3075,14 +3075,14 @@ private void SetCancellationAcknowledged() /// true if the task was transitioned to ran to completion; false if it was already completed. internal bool TrySetResult() { - Debug.Assert(m_action == null, "Task.TrySetResult(): non-null m_action"); + Debug.Assert(m_action is null, "Task.TrySetResult(): non-null m_action"); if (AtomicStateUpdate( TASK_STATE_COMPLETION_RESERVED | TASK_STATE_RAN_TO_COMPLETION, TASK_STATE_COMPLETION_RESERVED | TASK_STATE_RAN_TO_COMPLETION | TASK_STATE_FAULTED | TASK_STATE_CANCELED)) { ContingentProperties? props = m_contingentProperties; - if (props != null) + if (props is not null) { NotifyParentIfPotentiallyAttachedTask(); props.SetCompleted(); @@ -3103,10 +3103,10 @@ internal bool TrySetResult() // Called from TaskCompletionSource.SetException(IEnumerable). internal bool TrySetException(object exceptionObject) { - Debug.Assert(m_action == null, "Task.TrySetException(): non-null m_action"); + Debug.Assert(m_action is null, "Task.TrySetException(): non-null m_action"); // TCS.{Try}SetException() should have checked for this - Debug.Assert(exceptionObject != null, "Expected non-null exceptionObject argument"); + Debug.Assert(exceptionObject is not null, "Expected non-null exceptionObject argument"); // Only accept these types. Debug.Assert( @@ -3151,9 +3151,9 @@ internal bool TrySetCanceled(CancellationToken tokenToRecord) // This method is only valid for promise tasks. internal bool TrySetCanceled(CancellationToken tokenToRecord, object? cancellationException) { - Debug.Assert(m_action == null, "Task.TrySetCanceled(): non-null m_action"); + Debug.Assert(m_action is null, "Task.TrySetCanceled(): non-null m_action"); Debug.Assert( - cancellationException == null || + cancellationException is null || cancellationException is OperationCanceledException || (cancellationException as ExceptionDispatchInfo)?.SourceException is OperationCanceledException, "Expected null or an OperationCanceledException"); @@ -3190,7 +3190,7 @@ internal void FinishContinuations() // result in the continuations being run/launched directly rather than being added to the continuation list. // Then if we grabbed any continuations, run them. object? continuationObject = Interlocked.Exchange(ref m_continuationObject, s_taskCompletionSentinel); - if (continuationObject != null) + if (continuationObject is not null) { RunContinuations(continuationObject); } @@ -3198,7 +3198,7 @@ internal void FinishContinuations() private void RunContinuations(object continuationObject) // separated out of FinishContinuations to enable it to be inlined { - Debug.Assert(continuationObject != null); + Debug.Assert(continuationObject is not null); TplEventSource log = TplEventSource.Log; bool etwIsEnabled = log.IsEnabled(); @@ -3266,7 +3266,7 @@ private void RunContinuations(object continuationObject) // separated out of Fin // delay an await continuation behind other arbitrary user code created as a previous await continuation. object? currentContinuation = continuations[i]; - if (currentContinuation == null) + if (currentContinuation is null) { // The continuation was unregistered and null'd out, so just skip it. continue; @@ -3313,7 +3313,7 @@ private void RunContinuations(object continuationObject) // separated out of Fin for (int i = 0; i < continuationCount; i++) { object? currentContinuation = continuations[i]; - if (currentContinuation == null) + if (currentContinuation is null) { continue; } @@ -3521,13 +3521,13 @@ private Task ContinueWith(Action continuationAction, TaskScheduler schedul CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { // Throw on continuation with null action - if (continuationAction == null) + if (continuationAction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } // Throw on continuation with null TaskScheduler - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -3709,13 +3709,13 @@ private Task ContinueWith(Action continuationAction, object? stat CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { // Throw on continuation with null action - if (continuationAction == null) + if (continuationAction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } // Throw on continuation with null TaskScheduler - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -3909,13 +3909,13 @@ private Task ContinueWith(Func continuationFunc CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { // Throw on continuation with null function - if (continuationFunction == null) + if (continuationFunction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } // Throw on continuation with null task scheduler - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -4113,13 +4113,13 @@ private Task ContinueWith(Func continu CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { // Throw on continuation with null function - if (continuationFunction == null) + if (continuationFunction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } // Throw on continuation with null task scheduler - if (scheduler == null) + if (scheduler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } @@ -4207,8 +4207,8 @@ internal void ContinueWithCore(Task continuationTask, CancellationToken cancellationToken, TaskContinuationOptions options) { - Debug.Assert(continuationTask != null, "Task.ContinueWithCore(): null continuationTask"); - Debug.Assert(scheduler != null, "Task.ContinueWithCore(): null scheduler"); + Debug.Assert(continuationTask is not null, "Task.ContinueWithCore(): null continuationTask"); + Debug.Assert(scheduler is not null, "Task.ContinueWithCore(): null scheduler"); Debug.Assert(!continuationTask.IsCompleted, "Did not expect continuationTask to be completed"); // Create a TaskContinuation @@ -4293,7 +4293,7 @@ internal void AddCompletionAction(ITaskCompletionAction action, bool addBeforeOt // care of in the calling method, AddTaskContinuation(). private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) { - Debug.Assert(tc != null, "Expected non-null tc object in AddTaskContinuationComplex"); + Debug.Assert(tc is not null, "Expected non-null tc object in AddTaskContinuationComplex"); object? oldValue = m_continuationObject; @@ -4311,13 +4311,13 @@ private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) // m_continuationObject is guaranteed at this point to be either a List or // s_taskCompletionSentinel. List? list = m_continuationObject as List; - Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel), + Debug.Assert((list is not null) || (m_continuationObject == s_taskCompletionSentinel), "Expected m_continuationObject to be list or sentinel"); // If list is null, it can only mean that s_taskCompletionSentinel has been exchanged // into m_continuationObject. Thus, the task has completed and we should return false // from this method, as we will not be queuing up the continuation. - if (list != null) + if (list is not null) { lock (list) { @@ -4330,7 +4330,7 @@ private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) // result from RemoveContinuations() if (list.Count == list.Capacity) { - list.RemoveAll(l => l == null); + list.RemoveAll(l => l is null); } if (addBeforeOthers) @@ -4351,14 +4351,14 @@ private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) // Return true if and only if we successfully queued a continuation. private bool AddTaskContinuation(object tc, bool addBeforeOthers) { - Debug.Assert(tc != null); + Debug.Assert(tc is not null); // Make sure that, if someone calls ContinueWith() right after waiting for the predecessor to complete, // we don't queue up a continuation. if (IsCompleted) return false; // Try to just jam tc into m_continuationObject - if ((m_continuationObject != null) || (Interlocked.CompareExchange(ref m_continuationObject, tc, null) != null)) + if ((m_continuationObject is not null) || (Interlocked.CompareExchange(ref m_continuationObject, tc, null) is not null)) { // If we get here, it means that we failed to CAS tc into m_continuationObject. // Therefore, we must go the more complicated route. @@ -4396,8 +4396,8 @@ internal void RemoveContinuation(object continuationObject) // could be TaskCont } } - // if continuationsLocalRef == null it means s_taskCompletionSentinel has been set already and there is nothing else to do. - if (continuationsLocalListRef != null) + // if continuationsLocalRef is null it means s_taskCompletionSentinel has been set already and there is nothing else to do. + if (continuationsLocalListRef is not null) { lock (continuationsLocalListRef) { @@ -4594,7 +4594,7 @@ public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationTo // to be able to see the method on the stack and inspect arguments). private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { - if (tasks == null) + if (tasks is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } @@ -4625,7 +4625,7 @@ private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, Cancellat { Task task = tasks[i]; - if (task == null) + if (task is null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_WaitMulti_NullTask, ExceptionArgument.tasks); } @@ -4656,7 +4656,7 @@ private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, Cancellat } } - if (waitedOnTaskList != null) + if (waitedOnTaskList is not null) { // Block waiting for the tasks to complete. returnValue = WaitAllBlockingCore(waitedOnTaskList, millisecondsTimeout, cancellationToken); @@ -4683,7 +4683,7 @@ private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, Cancellat // Now that we're done and about to exit, if the wait completed and if we have // any tasks with a notification bit set, signal the debugger if any requires it. - if (returnValue && notificationTasks != null) + if (returnValue && notificationTasks is not null) { // Loop through each task tha that had its bit set, and notify the debugger // about the first one that requires it. The debugger will reset the bit @@ -4707,7 +4707,7 @@ private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, Cancellat // Now gather up and throw all of the exceptions. foreach (Task task in tasks) AddExceptionsForCompletedTask(ref exceptions, task); - Debug.Assert(exceptions != null, "Should have seen at least one exception"); + Debug.Assert(exceptions is not null, "Should have seen at least one exception"); ThrowHelper.ThrowAggregateException(exceptions); } @@ -4732,7 +4732,7 @@ private static void AddToList(T item, ref List? list, int initSize) /// true if all of the tasks completed; otherwise, false. private static bool WaitAllBlockingCore(List tasks, int millisecondsTimeout, CancellationToken cancellationToken) { - Debug.Assert(tasks != null, "Expected a non-null list of tasks"); + Debug.Assert(tasks is not null, "Expected a non-null list of tasks"); Debug.Assert(tasks.Count > 0, "Expected at least one task"); bool waitCompleted = false; @@ -4800,7 +4800,7 @@ public void Invoke(Task completingTask) internal static void AddExceptionsForCompletedTask(ref List? exceptions, Task t) { AggregateException? ex = t.GetExceptions(true); - if (ex != null) + if (ex is not null) { // make sure the task's exception observed status is set appropriately // it's possible that WaitAll was called by the parent of an attached child, @@ -4965,7 +4965,7 @@ public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationTok // to be able to inspect arguments). private static int WaitAnyCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { - if (tasks == null) + if (tasks is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } @@ -4985,7 +4985,7 @@ private static int WaitAnyCore(Task[] tasks, int millisecondsTimeout, Cancellati { Task task = tasks[taskIndex]; - if (task == null) + if (task is null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_WaitMulti_NullTask, ExceptionArgument.tasks); } @@ -5039,7 +5039,7 @@ public static Task FromResult(TResult result) /// The faulted task. public static Task FromException(Exception exception) { - if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); + if (exception is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); var task = new Task(); bool succeeded = task.TrySetException(exception); @@ -5053,7 +5053,7 @@ public static Task FromException(Exception exception) /// The faulted task. public static Task FromException(Exception exception) { - if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); + if (exception is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); var task = new Task(); bool succeeded = task.TrySetException(exception); @@ -5087,7 +5087,7 @@ public static Task FromCanceled(CancellationToken cancellation /// The canceled task. internal static Task FromCanceled(OperationCanceledException exception) { - Debug.Assert(exception != null); + Debug.Assert(exception is not null); var task = new Task(); bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception); @@ -5101,7 +5101,7 @@ internal static Task FromCanceled(OperationCanceledException exception) /// The canceled task. internal static Task FromCanceled(OperationCanceledException exception) { - Debug.Assert(exception != null); + Debug.Assert(exception is not null); var task = new Task(); bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception); @@ -5207,7 +5207,7 @@ public static Task Run(Func function) public static Task Run(Func function, CancellationToken cancellationToken) { // Check arguments - if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); + if (function is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); // Short-circuit if we are given a pre-canceled token if (cancellationToken.IsCancellationRequested) @@ -5252,7 +5252,7 @@ public static Task Run(Func?> function) public static Task Run(Func?> function, CancellationToken cancellationToken) { // Check arguments - if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); + if (function is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); // Short-circuit if we are given a pre-canceled token if (cancellationToken.IsCancellationRequested) @@ -5482,18 +5482,18 @@ public static Task WhenAll(IEnumerable tasks) taskArray = new Task[taskCollection.Count]; foreach (Task task in tasks) { - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); taskArray[index++] = task; } return InternalWhenAll(taskArray); } // Do some argument checking and convert tasks to a List (and later an array). - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); List taskList = new List(); foreach (Task task in tasks) { - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); taskList.Add(task); } @@ -5531,7 +5531,7 @@ public static Task WhenAll(IEnumerable tasks) public static Task WhenAll(params Task[] tasks) { // Do some argument checking and make a defensive copy of the tasks array - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); int taskCount = tasks.Length; if (taskCount == 0) return InternalWhenAll(tasks); // Small optimization in the case of an empty array. @@ -5540,7 +5540,7 @@ public static Task WhenAll(params Task[] tasks) for (int i = 0; i < taskCount; i++) { Task task = tasks[i]; - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); tasksCopy[i] = task; } @@ -5552,7 +5552,7 @@ public static Task WhenAll(params Task[] tasks) // tasks should be a defensive copy. private static Task InternalWhenAll(Task[] tasks) { - Debug.Assert(tasks != null, "Expected a non-null tasks array"); + Debug.Assert(tasks is not null, "Expected a non-null tasks array"); return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait Task.CompletedTask : new WhenAllPromise(tasks); @@ -5582,7 +5582,7 @@ private sealed class WhenAllPromise : Task, ITaskCompletionAction internal WhenAllPromise(Task[] tasks) { - Debug.Assert(tasks != null, "Expected a non-null task array"); + Debug.Assert(tasks is not null, "Expected a non-null task array"); Debug.Assert(tasks.Length > 0, "Expected a non-zero length task array"); if (TplEventSource.Log.IsEnabled()) @@ -5620,7 +5620,7 @@ public void Invoke(Task completedTask) for (int i = 0; i < m_tasks.Length; i++) { Task? task = m_tasks[i]; - Debug.Assert(task != null, "Constituent task in WhenAll should never be null"); + Debug.Assert(task is not null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted) { @@ -5638,7 +5638,7 @@ public void Invoke(Task completedTask) else m_tasks[i] = null; // avoid holding onto tasks unnecessarily } - if (observedExceptions != null) + if (observedExceptions is not null) { Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception"); @@ -5646,7 +5646,7 @@ public void Invoke(Task completedTask) TrySetException(observedExceptions); } - else if (canceledTask != null) + else if (canceledTask is not null) { TrySetCanceled(canceledTask.CancellationToken, canceledTask.GetCancellationExceptionDispatchInfo()); } @@ -5720,18 +5720,18 @@ public static Task WhenAll(IEnumerable> tasks) taskArray = new Task[taskCollection.Count]; foreach (Task task in tasks) { - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); taskArray[index++] = task; } return InternalWhenAll(taskArray); } // Do some argument checking and convert tasks into a List (later an array) - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); List> taskList = new List>(); foreach (Task task in tasks) { - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); taskList.Add(task); } @@ -5772,7 +5772,7 @@ public static Task WhenAll(IEnumerable> tasks) public static Task WhenAll(params Task[] tasks) { // Do some argument checking and make a defensive copy of the tasks array - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); int taskCount = tasks.Length; if (taskCount == 0) return InternalWhenAll(tasks); // small optimization in the case of an empty task array @@ -5781,7 +5781,7 @@ public static Task WhenAll(params Task[] tasks) for (int i = 0; i < taskCount; i++) { Task task = tasks[i]; - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); tasksCopy[i] = task; } @@ -5792,7 +5792,7 @@ public static Task WhenAll(params Task[] tasks) // Some common logic to support WhenAll methods private static Task InternalWhenAll(Task[] tasks) { - Debug.Assert(tasks != null, "Expected a non-null tasks array"); + Debug.Assert(tasks is not null, "Expected a non-null tasks array"); return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait new Task(false, Array.Empty(), TaskCreationOptions.None, default) : new WhenAllPromise(tasks); @@ -5815,7 +5815,7 @@ private sealed class WhenAllPromise : Task, ITaskCompletionAction internal WhenAllPromise(Task[] tasks) { - Debug.Assert(tasks != null, "Expected a non-null task array"); + Debug.Assert(tasks is not null, "Expected a non-null task array"); Debug.Assert(tasks.Length > 0, "Expected a non-zero length task array"); m_tasks = tasks; @@ -5854,7 +5854,7 @@ public void Invoke(Task ignored) for (int i = 0; i < m_tasks.Length; i++) { Task? task = m_tasks[i]; - Debug.Assert(task != null, "Constituent task in WhenAll should never be null"); + Debug.Assert(task is not null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted) { @@ -5877,7 +5877,7 @@ public void Invoke(Task ignored) else m_tasks[i] = null; // avoid holding onto tasks unnecessarily } - if (observedExceptions != null) + if (observedExceptions is not null) { Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception"); @@ -5885,7 +5885,7 @@ public void Invoke(Task ignored) TrySetException(observedExceptions); } - else if (canceledTask != null) + else if (canceledTask is not null) { TrySetCanceled(canceledTask.CancellationToken, canceledTask.GetCancellationExceptionDispatchInfo()); } @@ -5933,7 +5933,7 @@ public void Invoke(Task ignored) /// public static Task WhenAny(params Task[] tasks) { - if (tasks == null) + if (tasks is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } @@ -5955,7 +5955,7 @@ public static Task WhenAny(params Task[] tasks) for (int i = 0; i < taskCount; i++) { Task task = tasks[i]; - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); tasksCopy[i] = task; } @@ -5993,7 +5993,7 @@ private sealed class TwoTaskWhenAnyPromise : Task, ITaskCompletion /// Instantiate the promise and register it with both tasks as a completion action. public TwoTaskWhenAnyPromise(TTask task1, TTask task2) { - Debug.Assert(task1 != null && task2 != null); + Debug.Assert(task1 is not null && task2 is not null); _task1 = task1; _task2 = task2; @@ -6024,12 +6024,12 @@ public TwoTaskWhenAnyPromise(TTask task1, TTask task2) public void Invoke(Task completingTask) { Task? task1; - if ((task1 = Interlocked.Exchange(ref _task1, null)) != null) + if ((task1 = Interlocked.Exchange(ref _task1, null)) is not null) { Task? task2 = _task2; _task2 = null; - Debug.Assert(task1 != null && task2 != null); + Debug.Assert(task1 is not null && task2 is not null); Debug.Assert(task1.IsCompleted || task2.IsCompleted); if (TplEventSource.Log.IsEnabled()) @@ -6090,20 +6090,20 @@ public static Task WhenAny(IEnumerable tasks) taskArray = new Task[taskCollection.Count]; foreach (Task task in tasks) { - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); taskArray[index++] = task; } return TaskFactory.CommonCWAnyLogic(taskArray); } - if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); + if (tasks is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); // Make a defensive copy, as the user may manipulate the tasks collection // after we return but before the WhenAny asynchronously completes. List taskList = new List(); foreach (Task task in tasks) { - if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); + if (task is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); taskList.Add(task); } @@ -6137,7 +6137,7 @@ public static Task> WhenAny(params Task[] tasks) // return (Task>) WhenAny( (Task[]) tasks); // but classes are not covariant to enable casting Task to Task>. - if (tasks != null && tasks.Length == 2) + if (tasks is not null && tasks.Length == 2) { return WhenAny(tasks[0], tasks[1]); } @@ -6199,7 +6199,7 @@ public static Task> WhenAny(IEnumerable> ta internal static Task CreateUnwrapPromise(Task outerTask, bool lookForOce) { - Debug.Assert(outerTask != null); + Debug.Assert(outerTask is not null); return new UnwrapPromise(outerTask, lookForOce); } @@ -6215,7 +6215,7 @@ internal static Task CreateUnwrapPromise(Task outerTask, bool private static Delegate[]? GetDelegatesFromContinuationObject(object? continuationObject) { - if (continuationObject != null) + if (continuationObject is not null) { if (continuationObject is Action singleAction) { @@ -6229,9 +6229,9 @@ internal static Task CreateUnwrapPromise(Task outerTask, bool if (continuationObject is Task continuationTask) { - Debug.Assert(continuationTask.m_action == null); + Debug.Assert(continuationTask.m_action is null); Delegate[]? delegates = continuationTask.GetDelegateContinuationsForDebugger(); - if (delegates != null) + if (delegates is not null) return delegates; } @@ -6248,11 +6248,11 @@ internal static Task CreateUnwrapPromise(Task outerTask, bool foreach (object? obj in continuationList) { Delegate[]? innerDelegates = GetDelegatesFromContinuationObject(obj); - if (innerDelegates != null) + if (innerDelegates is not null) { foreach (Delegate del in innerDelegates) { - if (del != null) + if (del is not null) result.Add(del); } } @@ -6538,7 +6538,7 @@ internal sealed class UnwrapPromise : Task, ITaskCompletionAct public UnwrapPromise(Task outerTask, bool lookForOce) : base((object?)null, outerTask.CreationOptions & TaskCreationOptions.AttachedToParent) { - Debug.Assert(outerTask != null, "Expected non-null outerTask"); + Debug.Assert(outerTask is not null, "Expected non-null outerTask"); _lookForOce = lookForOce; if (TplEventSource.Log.IsEnabled()) @@ -6619,7 +6619,7 @@ private void InvokeCoreAsync(Task completingTask) /// The now-completed outer task. private void ProcessCompletedOuterTask(Task task) { - Debug.Assert(task != null && task.IsCompleted, "Expected non-null, completed outer task"); + Debug.Assert(task is not null && task.IsCompleted, "Expected non-null, completed outer task"); Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!"); // Bump our state before proceeding any further @@ -6649,7 +6649,7 @@ private void ProcessCompletedOuterTask(Task task) /// true if the transfer was successful; otherwise, false. private bool TrySetFromTask(Task task, bool lookForOce) { - Debug.Assert(task != null && task.IsCompleted, "TrySetFromTask: Expected task to have completed."); + Debug.Assert(task is not null && task.IsCompleted, "TrySetFromTask: Expected task to have completed."); if (TplEventSource.Log.IsEnabled()) TplEventSource.Log.TraceOperationRelation(this.Id, CausalityRelation.Join); @@ -6665,7 +6665,7 @@ private bool TrySetFromTask(Task task, bool lookForOce) ReadOnlyCollection edis = task.GetExceptionDispatchInfos(); ExceptionDispatchInfo oceEdi; if (lookForOce && edis.Count > 0 && - (oceEdi = edis[0]) != null && + (oceEdi = edis[0]) is not null && oceEdi.SourceException is OperationCanceledException oce) { result = TrySetCanceled(oce.CancellationToken, oceEdi); @@ -6697,7 +6697,7 @@ private bool TrySetFromTask(Task task, bool lookForOce) private void ProcessInnerTask(Task? task) { // If the inner task is null, the proxy should be canceled. - if (task == null) + if (task is null) { TrySetCanceled(default); _state = STATE_DONE; // ... and record that we are done diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskCanceledException.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskCanceledException.cs index 1cc01ab6ef0014..422b9990c95508 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskCanceledException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskCanceledException.cs @@ -68,7 +68,7 @@ public TaskCanceledException(string? message, Exception? innerException, Cancell /// /// A task that has been canceled. public TaskCanceledException(Task? task) : - base(SR.TaskCanceledException_ctor_DefaultMessage, task != null ? task.CancellationToken : CancellationToken.None) + base(SR.TaskCanceledException_ctor_DefaultMessage, task is not null ? task.CancellationToken : CancellationToken.None) { _canceledTask = task; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs index 18feb9a226698e..a0cacc49b1db58 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs @@ -28,7 +28,7 @@ internal override void InnerInvoke() // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent is not null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; @@ -36,7 +36,7 @@ internal override void InnerInvoke() antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Debug.Assert(m_action != null); + Debug.Assert(m_action is not null); if (m_action is Action action) { action(antecedent); @@ -74,7 +74,7 @@ internal override void InnerInvoke() // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent is not null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; @@ -82,7 +82,7 @@ internal override void InnerInvoke() antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Debug.Assert(m_action != null); + Debug.Assert(m_action is not null); if (m_action is Func func) { m_result = func(antecedent); @@ -120,7 +120,7 @@ internal override void InnerInvoke() // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent is not null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; @@ -128,7 +128,7 @@ internal override void InnerInvoke() antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Debug.Assert(m_action != null); + Debug.Assert(m_action is not null); if (m_action is Action> action) { action(antecedent); @@ -166,7 +166,7 @@ internal override void InnerInvoke() // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent is not null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; @@ -174,7 +174,7 @@ internal override void InnerInvoke() antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Debug.Assert(m_action != null); + Debug.Assert(m_action is not null); if (m_action is Func, TResult> func) { m_result = func(antecedent); @@ -213,8 +213,8 @@ internal abstract class TaskContinuation /// protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { - Debug.Assert(task != null); - Debug.Assert(task.m_taskScheduler != null); + Debug.Assert(task is not null); + Debug.Assert(task.m_taskScheduler is not null); // Set the TASK_STATE_STARTED flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it @@ -271,8 +271,8 @@ internal sealed class ContinueWithTaskContinuation : TaskContinuation /// The scheduler to use for the continuation. internal ContinueWithTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { - Debug.Assert(task != null, "TaskContinuation ctor: task is null"); - Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); + Debug.Assert(task is not null, "TaskContinuation ctor: task is null"); + Debug.Assert(scheduler is not null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; @@ -288,11 +288,11 @@ internal ContinueWithTaskContinuation(Task task, TaskContinuationOptions options /// Whether the continuation can be inlined. internal override void Run(Task completedTask, bool canInlineContinuationTask) { - Debug.Assert(completedTask != null); + Debug.Assert(completedTask is not null); Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); Task? continuationTask = m_task; - Debug.Assert(continuationTask != null); + Debug.Assert(continuationTask is not null); m_task = null; // Check if the completion status of the task works with the desired @@ -382,7 +382,7 @@ internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { - Debug.Assert(context != null); + Debug.Assert(context is not null); m_syncContext = context; } @@ -463,7 +463,7 @@ internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { - Debug.Assert(scheduler != null); + Debug.Assert(scheduler is not null); m_scheduler = scheduler; } @@ -531,7 +531,7 @@ internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem /// Whether to capture and restore ExecutionContext. internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { - Debug.Assert(action != null); + Debug.Assert(action is not null); m_action = action; if (flowExecutionContext) { @@ -546,8 +546,8 @@ internal AwaitTaskContinuation(Action action, bool flowExecutionContext) /// The created task. protected Task CreateTask(Action action, object? state, TaskScheduler scheduler) { - Debug.Assert(action != null); - Debug.Assert(scheduler != null); + Debug.Assert(action is not null); + Debug.Assert(scheduler is not null); return new Task( action, state, null, default, @@ -608,12 +608,12 @@ internal static bool IsValidLocationForInlining // If there's a SynchronizationContext, we'll be conservative and say // this is a bad location to inline. SynchronizationContext? ctx = SynchronizationContext.Current; - if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false; + if (ctx is not null && ctx.GetType() != typeof(SynchronizationContext)) return false; // Similarly, if there's a non-default TaskScheduler, we'll be conservative // and say this is a bad location to inline. TaskScheduler? sched = TaskScheduler.InternalCurrent; - return sched == null || sched == TaskScheduler.Default; + return sched is null || sched == TaskScheduler.Default; } } @@ -622,7 +622,7 @@ void IThreadPoolWorkItem.Execute() TplEventSource log = TplEventSource.Log; ExecutionContext? context = m_capturedContext; - if (!log.IsEnabled() && context == null) + if (!log.IsEnabled() && context is null) { m_action(); return; @@ -642,7 +642,7 @@ void IThreadPoolWorkItem.Execute() ExecutionContext.CheckThreadPoolAndContextsAreDefault(); // If there's no execution context or Default, just invoke the delegate as ThreadPool is on Default context. // We don't have to use ExecutionContext.Run for the Default context here as there is no extra processing after the delegate - if (context == null || context.IsDefault) + if (context is null || context.IsDefault) { m_action(); } @@ -680,7 +680,7 @@ void IThreadPoolWorkItem.Execute() /// A reference to Task.t_currentTask. protected void RunCallback(ContextCallback callback, object? state, ref Task? currentTask) { - Debug.Assert(callback != null); + Debug.Assert(callback is not null); Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent @@ -688,10 +688,10 @@ protected void RunCallback(ContextCallback callback, object? state, ref Task? cu Task? prevCurrentTask = currentTask; try { - if (prevCurrentTask != null) currentTask = null; + if (prevCurrentTask is not null) currentTask = null; ExecutionContext? context = m_capturedContext; - if (context == null) + if (context is null) { // If there's no captured context, just run the callback directly. callback(state); @@ -709,7 +709,7 @@ protected void RunCallback(ContextCallback callback, object? state, ref Task? cu finally { // Restore the current task information - if (prevCurrentTask != null) currentTask = prevCurrentTask; + if (prevCurrentTask is not null) currentTask = prevCurrentTask; } } @@ -739,7 +739,7 @@ internal static void RunOrScheduleAction(Action action, bool allowInlining) // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { - if (prevCurrentTask != null) currentTask = null; + if (prevCurrentTask is not null) currentTask = null; action(); } catch (Exception exception) @@ -748,7 +748,7 @@ internal static void RunOrScheduleAction(Action action, bool allowInlining) } finally { - if (prevCurrentTask != null) currentTask = prevCurrentTask; + if (prevCurrentTask is not null) currentTask = prevCurrentTask; } } @@ -791,7 +791,7 @@ internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowIn // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { - if (prevCurrentTask != null) currentTask = null; + if (prevCurrentTask is not null) currentTask = null; box.MoveNext(); } catch (Exception exception) @@ -800,7 +800,7 @@ internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowIn } finally { - if (prevCurrentTask != null) currentTask = prevCurrentTask; + if (prevCurrentTask is not null) currentTask = prevCurrentTask; } } @@ -812,7 +812,7 @@ internal static void UnsafeScheduleAction(Action action, Task? task) AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false); TplEventSource log = TplEventSource.Log; - if (log.IsEnabled() && task != null) + if (log.IsEnabled() && task is not null) { atc.m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, atc.m_continuationId); @@ -823,7 +823,7 @@ internal static void UnsafeScheduleAction(Action action, Task? task) internal override Delegate[] GetDelegateContinuationsForDebugger() { - Debug.Assert(m_action != null); + Debug.Assert(m_action is not null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs index c3565cafbf5c48..b5f49550b4e79e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs @@ -44,7 +44,7 @@ internal class TaskExceptionHolder /// The task this holder belongs to. internal TaskExceptionHolder(Task task) { - Debug.Assert(task != null, "Expected a non-null task."); + Debug.Assert(task is not null, "Expected a non-null task."); m_task = task; } @@ -53,7 +53,7 @@ internal TaskExceptionHolder(Task task) /// ~TaskExceptionHolder() { - if (m_faultExceptions != null && !m_isHandled) + if (m_faultExceptions is not null && !m_isHandled) { // We will only propagate if this is truly unhandled. The reason this could // ever occur is somewhat subtle: if a Task's exceptions are observed in some @@ -70,7 +70,7 @@ internal TaskExceptionHolder(Task task) } /// Gets whether the exception holder is currently storing any exceptions for faults. - internal bool ContainsFaultList => m_faultExceptions != null; + internal bool ContainsFaultList => m_faultExceptions is not null; /// /// Add an exception to the holder. This will ensure the holder is @@ -89,7 +89,7 @@ internal TaskExceptionHolder(Task task) /// internal void Add(object exceptionObject, bool representsCancellation) { - Debug.Assert(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject"); + Debug.Assert(exceptionObject is not null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject"); Debug.Assert( exceptionObject is Exception || exceptionObject is IEnumerable || exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable, @@ -106,14 +106,14 @@ exceptionObject is Exception || exceptionObject is IEnumerable || /// private void SetCancellationException(object exceptionObject) { - Debug.Assert(exceptionObject != null, "Expected exceptionObject to be non-null."); + Debug.Assert(exceptionObject is not null, "Expected exceptionObject to be non-null."); - Debug.Assert(m_cancellationException == null, + Debug.Assert(m_cancellationException is null, "Expected SetCancellationException to be called only once."); // Breaking this assumption will overwrite a previously OCE, // and implies something may be wrong elsewhere, since there should only ever be one. - Debug.Assert(m_faultExceptions == null, + Debug.Assert(m_faultExceptions is null, "Expected SetCancellationException to be called before any faults were added."); // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere. // If this changes, make sure to only conditionally mark as handled below. @@ -126,7 +126,7 @@ private void SetCancellationException(object exceptionObject) else { var edi = exceptionObject as ExceptionDispatchInfo; - Debug.Assert(edi != null && edi.SourceException is OperationCanceledException, + Debug.Assert(edi is not null && edi.SourceException is OperationCanceledException, "Expected an OCE or an EDI that contained an OCE"); m_cancellationException = edi; } @@ -142,11 +142,11 @@ private void SetCancellationException(object exceptionObject) /// private void AddFaultException(object exceptionObject) { - Debug.Assert(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject"); + Debug.Assert(exceptionObject is not null, "AddFaultException(): Expected a non-null exceptionObject"); // Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions. List? exceptions = m_faultExceptions; - if (exceptions == null) m_faultExceptions = exceptions = new List(1); + if (exceptions is null) m_faultExceptions = exceptions = new List(1); else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that @@ -172,7 +172,7 @@ private void AddFaultException(object exceptionObject) foreach (Exception exc in exColl) { #if DEBUG - Debug.Assert(exc != null, "No exceptions should be null"); + Debug.Assert(exc is not null, "No exceptions should be null"); numExceptions++; #endif exceptions.Add(ExceptionDispatchInfo.Capture(exc)); @@ -191,7 +191,7 @@ private void AddFaultException(object exceptionObject) Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); foreach (ExceptionDispatchInfo tmp in exceptions) { - Debug.Assert(tmp != null, "No dispatch infos should be null"); + Debug.Assert(tmp is not null, "No dispatch infos should be null"); } #endif } @@ -254,7 +254,7 @@ internal void MarkAsHandled(bool calledFromFinalizer) internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception? includeThisException) { List? exceptions = m_faultExceptions; - Debug.Assert(exceptions != null, "Expected an initialized list."); + Debug.Assert(exceptions is not null, "Expected an initialized list."); Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); // Mark as handled and aggregate the exceptions. @@ -262,7 +262,7 @@ internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exce // If we're only including the previously captured exceptions, // return them immediately in an aggregate. - if (includeThisException == null) + if (includeThisException is null) return new AggregateException(exceptions); // Otherwise, the caller wants a specific exception to be included, @@ -284,7 +284,7 @@ internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exce internal ReadOnlyCollection GetExceptionDispatchInfos() { List? exceptions = m_faultExceptions; - Debug.Assert(exceptions != null, "Expected an initialized list."); + Debug.Assert(exceptions is not null, "Expected an initialized list."); Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); MarkAsHandled(false); return new ReadOnlyCollection(exceptions); @@ -300,7 +300,7 @@ internal ReadOnlyCollection GetExceptionDispatchInfos() internal ExceptionDispatchInfo? GetCancellationExceptionDispatchInfo() { ExceptionDispatchInfo? edi = m_cancellationException; - Debug.Assert(edi == null || edi.SourceException is OperationCanceledException, + Debug.Assert(edi is null || edi.SourceException is OperationCanceledException, "Expected the EDI to be for an OperationCanceledException"); return edi; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs index ca622b686d813d..cd678bc806e113 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs @@ -11,7 +11,7 @@ public static class TaskExtensions /// A that represents the asynchronous operation of the provided . public static Task Unwrap(this Task task) { - if (task == null) + if (task is null) { throw new ArgumentNullException(nameof(task)); } @@ -30,7 +30,7 @@ public static Task Unwrap(this Task task) /// A that represents the asynchronous operation of the provided wrapped . public static Task Unwrap(this Task> task) { - if (task == null) + if (task is null) { throw new ArgumentNullException(nameof(task)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs index 2326611c17fa50..081270080a9381 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs @@ -46,7 +46,7 @@ private TaskScheduler GetDefaultScheduler(Task? currTask) { return m_defaultScheduler ?? - (currTask != null && (currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0 ? currTask.ExecutingTaskScheduler! : // a "current" task must be executing, which means it must have a scheduler + (currTask is not null && (currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0 ? currTask.ExecutingTaskScheduler! : // a "current" task must be executing, which means it must have a scheduler TaskScheduler.Default); } @@ -1552,7 +1552,7 @@ private sealed class CompleteOnCountdownPromise : Task, ITaskCompletionA internal CompleteOnCountdownPromise(Task[] tasksCopy) { - Debug.Assert((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); + Debug.Assert((tasksCopy is not null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); _tasks = tasksCopy; _count = tasksCopy.Length; @@ -1596,7 +1596,7 @@ public void Invoke(Task completingTask) // Performs some logic common to all ContinueWhenAll() overloads internal static Task CommonCWAllLogic(Task[] tasksCopy) { - Debug.Assert(tasksCopy != null); + Debug.Assert(tasksCopy is not null); // Create a promise task to be returned to the user CompleteOnCountdownPromise promise = new CompleteOnCountdownPromise(tasksCopy); @@ -1622,7 +1622,7 @@ private sealed class CompleteOnCountdownPromise : Task[]>, ITaskCompl internal CompleteOnCountdownPromise(Task[] tasksCopy) { - Debug.Assert((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); + Debug.Assert((tasksCopy is not null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); _tasks = tasksCopy; _count = tasksCopy.Length; @@ -1666,7 +1666,7 @@ public void Invoke(Task completingTask) internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) { - Debug.Assert(tasksCopy != null); + Debug.Assert(tasksCopy is not null); // Create a promise task to be returned to the user CompleteOnCountdownPromise promise = new CompleteOnCountdownPromise(tasksCopy); @@ -1697,7 +1697,7 @@ internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) /// array is empty. public Task ContinueWhenAll(Task[] tasks, Action continuationAction) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1726,7 +1726,7 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction) /// public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1760,7 +1760,7 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can /// public Task ContinueWhenAll(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1805,7 +1805,7 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Tas public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1829,7 +1829,7 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can /// array is empty. public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1860,7 +1860,7 @@ public Task ContinueWhenAll(Task[] tasks, public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1896,7 +1896,7 @@ public Task ContinueWhenAll(Task[] tasks, public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1942,7 +1942,7 @@ public Task ContinueWhenAll(Task[] tasks, public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1969,7 +1969,7 @@ public Task ContinueWhenAll(Task[] tasks, /// array is empty. public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2002,7 +2002,7 @@ public Task ContinueWhenAll(Task[] tasks, Func public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2040,7 +2040,7 @@ public Task ContinueWhenAll(Task[] tasks, Func public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2089,7 +2089,7 @@ public Task ContinueWhenAll(Task[] tasks, Func ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2118,7 +2118,7 @@ public Task ContinueWhenAll(Task[] tasks, Func array is empty. public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2152,7 +2152,7 @@ public Task ContinueWhenAll(Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2192,7 +2192,7 @@ public Task ContinueWhenAll(Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2242,7 +2242,7 @@ public Task ContinueWhenAll(Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2272,7 +2272,7 @@ internal sealed class CompleteOnInvokePromise : Task, ITaskCompletionActio public CompleteOnInvokePromise(IList tasks, bool isSyncBlocking) { - Debug.Assert(tasks != null, "Expected non-null collection of tasks"); + Debug.Assert(tasks is not null, "Expected non-null collection of tasks"); _tasks = tasks; if (isSyncBlocking) @@ -2315,12 +2315,12 @@ public void Invoke(Task completingTask) // Note that we may be attempting to remove a continuation from a task that hasn't had it // added yet; while there's overhead there, the operation won't hurt anything. IList? tasks = _tasks; - Debug.Assert(tasks != null, "Should not have been nulled out yet."); + Debug.Assert(tasks is not null, "Should not have been nulled out yet."); int numTasks = tasks.Count; for (int i = 0; i < numTasks; i++) { Task task = tasks[i]; - if (task != null && // if an element was erroneously nulled out concurrently, just skip it; worst case is we don't remove a continuation + if (task is not null && // if an element was erroneously nulled out concurrently, just skip it; worst case is we don't remove a continuation !task.IsCompleted) task.RemoveContinuation(this); } _tasks = null; @@ -2336,7 +2336,7 @@ public void Invoke(Task completingTask) // asynchronously (e.g. WhenAny) rather than synchronously (e.g. WaitAny). internal static Task CommonCWAnyLogic(IList tasks, bool isSyncBlocking = false) { - Debug.Assert(tasks != null); + Debug.Assert(tasks is not null); // Create a promise task to be returned to the user. // (If this logic ever changes, also update CommonCWAnyLogicCleanup.) @@ -2349,7 +2349,7 @@ internal static Task CommonCWAnyLogic(IList tasks, bool isSyncBlocki for (int i = 0; i < numTasks; i++) { Task task = tasks[i]; - if (task == null) throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks)); + if (task is null) throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks)); if (checkArgsOnly) continue; @@ -2417,7 +2417,7 @@ internal static void CommonCWAnyLogicCleanup(Task continuation) /// array is empty. public Task ContinueWhenAny(Task[] tasks, Action continuationAction) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2445,7 +2445,7 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction) /// public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2479,7 +2479,7 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance /// public Task ContinueWhenAny(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2524,7 +2524,7 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, TaskC public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -2552,7 +2552,7 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance /// array is empty. public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2584,7 +2584,7 @@ public Task ContinueWhenAny(Task[] tasks, Func /// public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2622,7 +2622,7 @@ public Task ContinueWhenAny(Task[] tasks, Func /// public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2671,7 +2671,7 @@ public Task ContinueWhenAny(Task[] tasks, Func public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2699,7 +2699,7 @@ public Task ContinueWhenAny(Task[] tasks, Func /// array is empty. public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2732,7 +2732,7 @@ public Task ContinueWhenAny(Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2772,7 +2772,7 @@ public Task ContinueWhenAny(Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2822,7 +2822,7 @@ public Task ContinueWhenAny(Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); + if (continuationFunction is null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2847,7 +2847,7 @@ public Task ContinueWhenAny(Task array is empty. public Task ContinueWhenAny(Task[] tasks, Action> continuationAction) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2877,7 +2877,7 @@ public Task ContinueWhenAny(Task[] tasks, public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2913,7 +2913,7 @@ public Task ContinueWhenAny(Task[] tasks, public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2959,7 +2959,7 @@ public Task ContinueWhenAny(Task[] tasks, public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); + if (continuationAction is null) throw new ArgumentNullException(nameof(continuationAction)); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -2968,7 +2968,7 @@ public Task ContinueWhenAny(Task[] tasks, // Used with ContinueWhenAll()/ContinueWhenAny(). internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { - if (tasks == null) + if (tasks is null) throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); @@ -2978,7 +2978,7 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { tasksCopy[i] = tasks[i]; - if (tasksCopy[i] == null) + if (tasksCopy[i] is null) throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks)); } @@ -2987,7 +2987,7 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { - if (tasks == null) + if (tasks is null) throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); @@ -2997,7 +2997,7 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task { tasksCopy[i] = tasks[i]; - if (tasksCopy[i] == null) + if (tasksCopy[i] is null) throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs index e416fe36519957..686cb5d4a39881 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs @@ -164,16 +164,16 @@ public abstract class TaskScheduler /// True if it ran, false otherwise. internal bool TryRunInline(Task task, bool taskWasPreviouslyQueued) { - // Do not inline unstarted tasks (i.e., task.ExecutingTaskScheduler == null). + // Do not inline unstarted tasks (i.e., task.ExecutingTaskScheduler is null). // Do not inline TaskCompletionSource-style (a.k.a. "promise") tasks. // No need to attempt inlining if the task body was already run (i.e. either TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bits set) TaskScheduler? ets = task.ExecutingTaskScheduler; // Delegate cross-scheduler inlining requests to target scheduler - if (ets != this && ets != null) return ets.TryRunInline(task, taskWasPreviouslyQueued); + if (ets != this && ets is not null) return ets.TryRunInline(task, taskWasPreviouslyQueued); - if ((ets == null) || - (task.m_action == null) || + if ((ets is null) || + (task.m_action is null) || task.IsDelegateInvoked || task.IsCanceled || !RuntimeHelpers.TryEnsureSufficientExecutionStack()) @@ -229,7 +229,7 @@ internal virtual void NotifyWorkItemProgress() /// internal void InternalQueueTask(Task task) { - Debug.Assert(task != null); + Debug.Assert(task is not null); if (TplEventSource.Log.IsEnabled()) task.FireTaskScheduledIfNeeded(this); @@ -283,7 +283,7 @@ protected TaskScheduler() private void AddToActiveTaskSchedulers() { ConditionalWeakTable? activeTaskSchedulers = s_activeTaskSchedulers; - if (activeTaskSchedulers == null) + if (activeTaskSchedulers is null) { Interlocked.CompareExchange(ref s_activeTaskSchedulers, new ConditionalWeakTable(), null); activeTaskSchedulers = s_activeTaskSchedulers; @@ -317,7 +317,7 @@ internal static TaskScheduler? InternalCurrent get { Task? currentTask = Task.InternalCurrent; - return ((currentTask != null) + return ((currentTask is not null) && ((currentTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0) ) ? currentTask.ExecutingTaskScheduler : null; } @@ -455,7 +455,7 @@ internal static void PublishUnobservedTaskException(object sender, UnobservedTas // at the moment. We should let the debugger receive that exception so that it can indicate it in the UI IEnumerable? activeTasksSource = GetScheduledTasks(); - if (activeTasksSource == null) + if (activeTasksSource is null) return null; // If it can be cast to an array, use it directly @@ -484,7 +484,7 @@ internal static void PublishUnobservedTaskException(object sender, UnobservedTas /// An array of TaskScheduler instances. internal static TaskScheduler[] GetTaskSchedulersForDebugger() { - if (s_activeTaskSchedulers == null) + if (s_activeTaskSchedulers is null) { // No schedulers were tracked. Just give back the default. return new TaskScheduler[] { s_defaultTaskScheduler }; @@ -506,7 +506,7 @@ internal static TaskScheduler[] GetTaskSchedulersForDebugger() TaskScheduler[] arr = schedulers.ToArray(); foreach (TaskScheduler scheduler in arr) { - Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed"); + Debug.Assert(scheduler is not null, "Table returned an incorrect Count or CopyTo failed"); _ = scheduler.Id; // force Ids for debugger } return arr; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TplEventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TplEventSource.cs index ea85eab23cfeea..c2a9d3bb032a5c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TplEventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TplEventSource.cs @@ -530,11 +530,11 @@ public void NewID(int TaskID) [NonEvent] public void IncompleteAsyncMethod(IAsyncStateMachineBox stateMachineBox) { - System.Diagnostics.Debug.Assert(stateMachineBox != null); + System.Diagnostics.Debug.Assert(stateMachineBox is not null); if (IsEnabled() && IsEnabled(EventLevel.Warning, Keywords.AsyncMethod)) { IAsyncStateMachine stateMachine = stateMachineBox.GetStateMachineObject(); - if (stateMachine != null) + if (stateMachine is not null) { string description = AsyncMethodBuilderCore.GetAsyncStateMachineDescription(stateMachine); IncompleteAsyncMethod(description); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs index afc8f5a00f3a00..cab057729659bd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs @@ -74,7 +74,7 @@ namespace System.Threading.Tasks [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { - if (task == null) + if (task is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task); } @@ -91,7 +91,7 @@ public ValueTask(Task task) [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -173,15 +173,15 @@ obj is ValueTask && public Task AsTask() { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); return - obj == null ? Task.CompletedTask : + obj is null ? Task.CompletedTask : obj as Task ?? GetTaskForValueTaskSource(Unsafe.As(obj)); } /// Gets a that may be used at any point in the future. - public ValueTask Preserve() => _obj == null ? this : new ValueTask(AsTask()); + public ValueTask Preserve() => _obj is null ? this : new ValueTask(AsTask()); /// Creates a to represent the . /// @@ -290,9 +290,9 @@ public bool IsCompleted get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return true; } @@ -313,9 +313,9 @@ public bool IsCompletedSuccessfully get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return true; } @@ -335,9 +335,9 @@ public bool IsFaulted get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return false; } @@ -362,9 +362,9 @@ public bool IsCanceled get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return false; } @@ -383,9 +383,9 @@ public bool IsCanceled internal void ThrowIfCompletedUnsuccessfully() { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj != null) + if (obj is not null) { if (obj is Task t) { @@ -472,7 +472,7 @@ public ValueTask(TResult result) [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { - if (task == null) + if (task is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task); } @@ -490,7 +490,7 @@ public ValueTask(Task task) [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { - if (source == null) + if (source is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } @@ -519,8 +519,8 @@ private ValueTask(object? obj, TResult? result, short token, bool continueOnCapt /// Returns the hash code for this instance. public override int GetHashCode() => - _obj != null ? _obj.GetHashCode() : - _result != null ? _result.GetHashCode() : + _obj is not null ? _obj.GetHashCode() : + _result is not null ? _result.GetHashCode() : 0; /// Returns a value indicating whether this value is equal to a specified . @@ -530,7 +530,7 @@ obj is ValueTask && /// Returns a value indicating whether this value is equal to a specified value. public bool Equals(ValueTask other) => - _obj != null || other._obj != null ? + _obj is not null || other._obj is not null ? _obj == other._obj && _token == other._token : EqualityComparer.Default.Equals(_result, other._result); @@ -552,9 +552,9 @@ public bool Equals(ValueTask other) => public Task AsTask() { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return AsyncTaskMethodBuilder.GetTaskForResult(_result!); } @@ -568,7 +568,7 @@ public Task AsTask() } /// Gets a that may be used at any point in the future. - public ValueTask Preserve() => _obj == null ? this : new ValueTask(AsTask()); + public ValueTask Preserve() => _obj is null ? this : new ValueTask(AsTask()); /// Creates a to represent the . /// @@ -603,7 +603,7 @@ private Task GetTaskForValueTaskSource(IValueTaskSource t) } Task? canceledTask = s_canceledTask; - if (canceledTask == null) + if (canceledTask is null) { // Benign race condition to initialize cached task, as identity doesn't matter. s_canceledTask = canceledTask = Task.FromCanceled(new CancellationToken(true)); @@ -681,9 +681,9 @@ public bool IsCompleted get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return true; } @@ -704,9 +704,9 @@ public bool IsCompletedSuccessfully get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return true; } @@ -726,9 +726,9 @@ public bool IsFaulted get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return false; } @@ -753,9 +753,9 @@ public bool IsCanceled get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return false; } @@ -777,9 +777,9 @@ public TResult Result get { object? obj = _obj; - Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + Debug.Assert(obj is null || obj is Task || obj is IValueTaskSource); - if (obj == null) + if (obj is null) { return _result!; } @@ -814,7 +814,7 @@ public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCaptu Debugger.NotifyOfCrossThreadDependency(); // prevent debugger evaluation from invalidating an underling IValueTaskSource unless forced TResult result = Result; - if (result != null) + if (result is not null) { return result.ToString(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs index bf85ffe8d78be2..539f045202f9d8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -21,7 +21,7 @@ public sealed partial class Thread : CriticalFinalizerObject public Thread(ThreadStart start) : this() { - if (start == null) + if (start is null) { throw new ArgumentNullException(nameof(start)); } @@ -32,7 +32,7 @@ public Thread(ThreadStart start) public Thread(ThreadStart start, int maxStackSize) : this() { - if (start == null) + if (start is null) { throw new ArgumentNullException(nameof(start)); } @@ -47,7 +47,7 @@ public Thread(ThreadStart start, int maxStackSize) public Thread(ParameterizedThreadStart start) : this() { - if (start == null) + if (start is null) { throw new ArgumentNullException(nameof(start)); } @@ -58,7 +58,7 @@ public Thread(ParameterizedThreadStart start) public Thread(ParameterizedThreadStart start, int maxStackSize) : this() { - if (start == null) + if (start is null) { throw new ArgumentNullException(nameof(start)); } @@ -80,7 +80,7 @@ private void RequireCurrentThread() private void SetCultureOnUnstartedThread(CultureInfo value, bool uiCulture) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -165,7 +165,7 @@ public string? Name { lock (this) { - if (_name != null) + if (_name is not null) { throw new InvalidOperationException(SR.InvalidOperation_WriteOnce); } @@ -326,7 +326,7 @@ public static LocalDataStoreSlot AllocateSlot() private static Dictionary EnsureNameToSlotMap() { Dictionary? nameToSlotMap = s_nameToSlotMap; - if (nameToSlotMap != null) + if (nameToSlotMap is not null) { return nameToSlotMap; } @@ -371,12 +371,12 @@ public static void FreeNamedSlot(string name) private static ThreadLocal GetThreadLocal(LocalDataStoreSlot slot) { - if (slot == null) + if (slot is null) { throw new ArgumentNullException(nameof(slot)); } - Debug.Assert(slot.Data != null); + Debug.Assert(slot.Data is not null); return slot.Data; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadInt64PersistentCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadInt64PersistentCounter.cs index 5867f0c30d9a29..129ac082013be4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadInt64PersistentCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadInt64PersistentCounter.cs @@ -21,7 +21,7 @@ internal sealed class ThreadInt64PersistentCounter public void Increment() { ThreadLocalNode? node = _threadLocalNode.Value; - if (node != null) + if (node is not null) { node.Increment(); return; @@ -33,7 +33,7 @@ public void Increment() [MethodImpl(MethodImplOptions.NoInlining)] private void TryCreateNode() { - Debug.Assert(_threadLocalNode.Value == null); + Debug.Assert(_threadLocalNode.Value is null); try { @@ -57,7 +57,7 @@ public long Count count = _overflowCount; foreach (ThreadLocalNode node in _threadLocalNode.ValuesAsEnumerable) { - if (node != null) + if (node is not null) { count += node.Count; } @@ -84,7 +84,7 @@ private sealed class ThreadLocalNode public ThreadLocalNode(ThreadInt64PersistentCounter counter) { - Debug.Assert(counter != null); + Debug.Assert(counter is not null); _count = 1; _counter = counter; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs index 4d7188e8580692..86b3d7afacad4e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs @@ -91,7 +91,7 @@ public ThreadLocal(bool trackAllValues) /// public ThreadLocal(Func valueFactory) { - if (valueFactory == null) + if (valueFactory is null) throw new ArgumentNullException(nameof(valueFactory)); Initialize(valueFactory, false); @@ -111,7 +111,7 @@ public ThreadLocal(Func valueFactory) /// public ThreadLocal(Func valueFactory, bool trackAllValues) { - if (valueFactory == null) + if (valueFactory is null) throw new ArgumentNullException(nameof(valueFactory)); Initialize(valueFactory, trackAllValues); @@ -185,12 +185,12 @@ protected virtual void Dispose(bool disposing) } _initialized = false; - Debug.Assert(_linkedSlot != null, "Should be non-null if not yet disposed"); - for (LinkedSlot? linkedSlot = _linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) + Debug.Assert(_linkedSlot is not null, "Should be non-null if not yet disposed"); + for (LinkedSlot? linkedSlot = _linkedSlot._next; linkedSlot is not null; linkedSlot = linkedSlot._next) { LinkedSlotVolatile[]? slotArray = linkedSlot._slotArray; - if (slotArray == null) + if (slotArray is null) { // The thread that owns this slotArray has already finished. continue; @@ -260,10 +260,10 @@ public T Value // // Attempt to get the value using the fast path // - if (slotArray != null // Has the slot array been initialized? + if (slotArray is not null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? - && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? + && (slot = slotArray[id].Value) is not null // Has a LinkedSlot object has been allocated for this ID? && _initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? ) { @@ -284,10 +284,10 @@ public T Value int id = ~_idComplement; // Attempt to set the value using the fast path - if (slotArray != null // Has the slot array been initialized? + if (slotArray is not null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? - && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? + && (slot = slotArray[id].Value) is not null // Has a LinkedSlot object has been allocated for this ID? && _initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? ) { @@ -318,7 +318,7 @@ public T Value // Determine the initial value T value; - if (_valueFactory == null) + if (_valueFactory is null) { value = default!; } @@ -348,7 +348,7 @@ private void SetValueSlow(T value, LinkedSlotVolatile[]? slotArray) } // If a slot array has not been created on this thread yet, create it. - if (slotArray == null) + if (slotArray is null) { slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)]; ts_finalizationHelper = new FinalizationHelper(slotArray, _trackAllValues); @@ -359,14 +359,14 @@ private void SetValueSlow(T value, LinkedSlotVolatile[]? slotArray) if (id >= slotArray.Length) { GrowTable(ref slotArray!, id + 1); - Debug.Assert(ts_finalizationHelper != null, "Should have been initialized when this thread's slot array was created."); + Debug.Assert(ts_finalizationHelper is not null, "Should have been initialized when this thread's slot array was created."); ts_finalizationHelper.SlotArray = slotArray; ts_slotArray = slotArray; } // If we are using the slot in this table for the first time, create a new LinkedSlot and add it into // the linked list for this ThreadLocal instance. - if (slotArray[id].Value == null) + if (slotArray[id].Value is null) { CreateLinkedSlot(slotArray, id, value); } @@ -408,7 +408,7 @@ private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value) throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } - Debug.Assert(_linkedSlot != null, "Should only be null if disposed"); + Debug.Assert(_linkedSlot is not null, "Should only be null if disposed"); LinkedSlot? firstRealNode = _linkedSlot._next; // Insert linkedSlot between nodes m_linkedSlot and firstRealNode. @@ -417,7 +417,7 @@ private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value) linkedSlot._previous = _linkedSlot; linkedSlot._value = value; - if (firstRealNode != null) + if (firstRealNode is not null) { firstRealNode._previous = linkedSlot; } @@ -446,7 +446,7 @@ public IList Values } List? list = GetValuesAsList(); // returns null if disposed - if (list == null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed); + if (list is null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed); return list; } } @@ -456,14 +456,14 @@ public IList Values { LinkedSlot? linkedSlot = _linkedSlot; int id = ~_idComplement; - if (id == -1 || linkedSlot == null) + if (id == -1 || linkedSlot is null) { return null; } // Walk over the linked list of slots and gather the values associated with this ThreadLocal instance. var valueList = new List(); - for (linkedSlot = linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) + for (linkedSlot = linkedSlot._next; linkedSlot is not null; linkedSlot = linkedSlot._next) { // We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot // objects will never be assigned to another ThreadLocal instance. @@ -484,13 +484,13 @@ internal IEnumerable ValuesAsEnumerable LinkedSlot? linkedSlot = _linkedSlot; int id = ~_idComplement; - if (id == -1 || linkedSlot == null) + if (id == -1 || linkedSlot is null) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } // Walk over the linked list of slots and gather the values associated with this ThreadLocal instance. - for (linkedSlot = linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) + for (linkedSlot = linkedSlot._next; linkedSlot is not null; linkedSlot = linkedSlot._next) { // We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot // objects will never be assigned to another ThreadLocal instance. @@ -505,7 +505,7 @@ private int ValuesCountForDebugDisplay get { int count = 0; - for (LinkedSlot? linkedSlot = _linkedSlot?._next; linkedSlot != null; linkedSlot = linkedSlot._next) + for (LinkedSlot? linkedSlot = _linkedSlot?._next; linkedSlot is not null; linkedSlot = linkedSlot._next) { count++; } @@ -530,7 +530,7 @@ public bool IsValueCreated } LinkedSlotVolatile[]? slotArray = ts_slotArray; - return slotArray != null && id < slotArray.Length && slotArray[id].Value != null; + return slotArray is not null && id < slotArray.Length && slotArray[id].Value is not null; } } @@ -545,7 +545,7 @@ internal T? ValueForDebugDisplay int id = ~_idComplement; LinkedSlot? slot; - if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !_initialized) + if (slotArray is null || id >= slotArray.Length || (slot = slotArray[id].Value) is null || !_initialized) return default; return slot._value; } @@ -577,7 +577,7 @@ private static void GrowTable(ref LinkedSlotVolatile[] table, int minLength) for (int i = 0; i < table.Length; i++) { LinkedSlot? linkedSlot = table[i].Value; - if (linkedSlot != null && linkedSlot._slotArray != null) + if (linkedSlot is not null && linkedSlot._slotArray is not null) { linkedSlot._slotArray = newTable; newTable[i] = table[i]; @@ -747,12 +747,12 @@ internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues) ~FinalizationHelper() { LinkedSlotVolatile[] slotArray = SlotArray; - Debug.Assert(slotArray != null); + Debug.Assert(slotArray is not null); for (int i = 0; i < slotArray.Length; i++) { LinkedSlot? linkedSlot = slotArray[i].Value; - if (linkedSlot == null) + if (linkedSlot is null) { // This slot in the table is empty continue; @@ -769,13 +769,13 @@ internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues) // the table will be have been removed, and so the table can get GC'd. lock (s_idManager) { - if (linkedSlot._next != null) + if (linkedSlot._next is not null) { linkedSlot._next._previous = linkedSlot._previous; } // Since the list uses a dummy head node, the Previous reference should never be null. - Debug.Assert(linkedSlot._previous != null); + Debug.Assert(linkedSlot._previous is not null); linkedSlot._previous._next = linkedSlot._next; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs index 7b49045defd237..6720db68d1a077 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs @@ -29,7 +29,7 @@ internal RegisteredWaitHandle(WaitHandle waitHandle, _ThreadPoolWaitOrTimerCallb ~RegisteredWaitHandle() { - if (WaitThread != null) + if (WaitThread is not null) { Unregister(null); } @@ -43,7 +43,7 @@ private static AutoResetEvent RentEvent() => private static void ReturnEvent(AutoResetEvent resetEvent) { - if (Interlocked.CompareExchange(ref s_cachedEvent, resetEvent, null) != null) + if (Interlocked.CompareExchange(ref s_cachedEvent, resetEvent, null) is not null) { resetEvent.Dispose(); } @@ -156,12 +156,12 @@ public bool Unregister(WaitHandle? waitObject) } catch (Exception) // Rollback state on exception { - if (_removed != null) + if (_removed is not null) { ReturnEvent(_removed); _removed = null; } - else if (_callbacksComplete != null) + else if (_callbacksComplete is not null) { ReturnEvent(_callbacksComplete); _callbacksComplete = null; @@ -408,10 +408,10 @@ private static RegisteredWaitHandle RegisterWaitForSingleObject( bool executeOnlyOnce, bool flowExecutionContext) { - if (waitObject == null) + if (waitObject is null) throw new ArgumentNullException(nameof(waitObject)); - if (callBack == null) + if (callBack is null) throw new ArgumentNullException(nameof(callBack)); RegisteredWaitHandle registeredHandle = new RegisteredWaitHandle( diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.cs index a05c688694331b..c52c595a11adab 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.cs @@ -35,7 +35,7 @@ internal static class WorkStealingQueueList public static void Add(WorkStealingQueue queue) { - Debug.Assert(queue != null); + Debug.Assert(queue is not null); while (true) { WorkStealingQueue[] oldQueues = _queues; @@ -53,7 +53,7 @@ public static void Add(WorkStealingQueue queue) public static void Remove(WorkStealingQueue queue) { - Debug.Assert(queue != null); + Debug.Assert(queue is not null); while (true) { WorkStealingQueue[] oldQueues = _queues; @@ -195,8 +195,8 @@ public bool LocalFindAndPop(object obj) if (m_array[(m_tailIndex - 1) & m_mask] == obj) { object? unused = LocalPop(); - Debug.Assert(unused == null || unused == obj); - return unused != null; + Debug.Assert(unused is null || unused == obj); + return unused is not null; } // Else, do an O(N) search for the work item. The theory of work stealing and our @@ -218,7 +218,7 @@ public bool LocalFindAndPop(object obj) m_foreignLock.Enter(ref lockTaken); // If we encountered a race condition, bail. - if (m_array[i & m_mask] == null) + if (m_array[i & m_mask] is null) return false; // Otherwise, null out the element. @@ -268,7 +268,7 @@ public bool LocalFindAndPop(object obj) object? obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. - if (obj == null) continue; + if (obj is null) continue; m_array[idx] = null; return obj; @@ -288,7 +288,7 @@ public bool LocalFindAndPop(object obj) object? obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. - if (obj == null) continue; + if (obj is null) continue; m_array[idx] = null; return obj; @@ -333,7 +333,7 @@ public bool LocalFindAndPop(object obj) object? obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. - if (obj == null) continue; + if (obj is null) continue; m_array[idx] = null; return obj; @@ -399,7 +399,7 @@ public ThreadPoolWorkQueueThreadLocals GetOrCreateThreadLocals() => [MethodImpl(MethodImplOptions.NoInlining)] private ThreadPoolWorkQueueThreadLocals CreateThreadLocals() { - Debug.Assert(ThreadPoolWorkQueueThreadLocals.threadLocals == null); + Debug.Assert(ThreadPoolWorkQueueThreadLocals.threadLocals is null); return ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this); } @@ -457,7 +457,7 @@ public void Enqueue(object callback, bool forceGlobal) if (!forceGlobal) tl = ThreadPoolWorkQueueThreadLocals.threadLocals; - if (null != tl) + if (tl is not null) { tl.workStealingQueue.LocalPush(callback); } @@ -472,7 +472,7 @@ public void Enqueue(object callback, bool forceGlobal) internal static bool LocalFindAndPop(object callback) { ThreadPoolWorkQueueThreadLocals? tl = ThreadPoolWorkQueueThreadLocals.threadLocals; - return tl != null && tl.workStealingQueue.LocalFindAndPop(callback); + return tl is not null && tl.workStealingQueue.LocalFindAndPop(callback); } public object? Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal) @@ -480,7 +480,7 @@ internal static bool LocalFindAndPop(object callback) WorkStealingQueue localWsq = tl.workStealingQueue; object? callback; - if ((callback = localWsq.LocalPop()) == null && // first try the local queue + if ((callback = localWsq.LocalPop()) is null && // first try the local queue !workItems.TryDequeue(out callback)) // then try the global queue { // finally try to steal from another thread's local queue @@ -496,7 +496,7 @@ internal static bool LocalFindAndPop(object callback) if (otherQueue != localWsq && otherQueue.CanSteal) { callback = otherQueue.TrySteal(ref missedSteal); - if (callback != null) + if (callback is not null) { break; } @@ -580,7 +580,7 @@ internal static bool Dispatch() // Use operate on workItem local to try block so it can be enregistered object? workItem = workQueue.Dequeue(tl, ref missedSteal); - if (workItem == null) + if (workItem is null) { // // No work. @@ -724,14 +724,14 @@ public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq) ~ThreadPoolWorkQueueThreadLocals() { // Transfer any pending workitems into the global queue so that they will be executed by another thread - if (null != workStealingQueue) + if (workStealingQueue is not null) { - if (null != workQueue) + if (workQueue is not null) { object? cb; - while ((cb = workStealingQueue.LocalPop()) != null) + while ((cb = workStealingQueue.LocalPop()) is not null) { - Debug.Assert(null != cb); + Debug.Assert(cb is not null); workQueue.Enqueue(cb, forceGlobal: true); } } @@ -777,7 +777,7 @@ internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase private static readonly Action s_executionContextShim = quwi => { - Debug.Assert(quwi._callback != null); + Debug.Assert(quwi._callback is not null); WaitCallback callback = quwi._callback; quwi._callback = null; @@ -786,7 +786,7 @@ internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase internal QueueUserWorkItemCallback(WaitCallback callback, object? state, ExecutionContext context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); _callback = callback; _state = state; @@ -809,7 +809,7 @@ internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallb internal QueueUserWorkItemCallback(Action callback, TState state, ExecutionContext context) { - Debug.Assert(callback != null); + Debug.Assert(callback is not null); _callback = callback; _state = state; @@ -820,7 +820,7 @@ public override void Execute() { base.Execute(); - Debug.Assert(_callback != null); + Debug.Assert(_callback is not null); Action callback = _callback; _callback = null; @@ -835,7 +835,7 @@ internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkIte internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object? state) { - Debug.Assert(callback != null); + Debug.Assert(callback is not null); _callback = callback; _state = state; @@ -846,7 +846,7 @@ public override void Execute() ExecutionContext.CheckThreadPoolAndContextsAreDefault(); base.Execute(); - Debug.Assert(_callback != null); + Debug.Assert(_callback is not null); WaitCallback callback = _callback; _callback = null; @@ -863,7 +863,7 @@ internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUse internal QueueUserWorkItemCallbackDefaultContext(Action callback, TState state) { - Debug.Assert(callback != null); + Debug.Assert(callback is not null); _callback = callback; _state = state; @@ -874,7 +874,7 @@ public override void Execute() ExecutionContext.CheckThreadPoolAndContextsAreDefault(); base.Execute(); - Debug.Assert(_callback != null); + Debug.Assert(_callback is not null); Action callback = _callback; _callback = null; @@ -919,10 +919,10 @@ private static void WaitOrTimerCallback_Context(object? state, bool timedOut) // call back helper internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut) { - Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!"); + Debug.Assert(helper is not null, "Null state passed to PerformWaitOrTimerCallback!"); // call directly if it is an unsafe call OR EC flow is suppressed ExecutionContext? context = helper._executionContext; - if (context == null) + if (context is null) { WaitOrTimerCallback callback = helper._waitOrTimerCallback; callback(helper._state, timedOut); @@ -1079,14 +1079,14 @@ public static bool QueueUserWorkItem(WaitCallback callBack) => public static bool QueueUserWorkItem(WaitCallback callBack, object? state) { - if (callBack == null) + if (callBack is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } ExecutionContext? context = ExecutionContext.Capture(); - object tpcallBack = (context == null || context.IsDefault) ? + object tpcallBack = (context is null || context.IsDefault) ? new QueueUserWorkItemCallbackDefaultContext(callBack!, state) : (object)new QueueUserWorkItemCallback(callBack!, state, context); @@ -1097,14 +1097,14 @@ public static bool QueueUserWorkItem(WaitCallback callBack, object? state) public static bool QueueUserWorkItem(Action callBack, TState state, bool preferLocal) { - if (callBack == null) + if (callBack is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } ExecutionContext? context = ExecutionContext.Capture(); - object tpcallBack = (context == null || context.IsDefault) ? + object tpcallBack = (context is null || context.IsDefault) ? new QueueUserWorkItemCallbackDefaultContext(callBack!, state) : (object)new QueueUserWorkItemCallback(callBack!, state, context); @@ -1115,7 +1115,7 @@ public static bool QueueUserWorkItem(Action callBack, TState sta public static bool UnsafeQueueUserWorkItem(Action callBack, TState state, bool preferLocal) { - if (callBack == null) + if (callBack is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } @@ -1146,7 +1146,7 @@ public static bool UnsafeQueueUserWorkItem(Action callBack, TSta public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state) { - if (callBack == null) + if (callBack is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } @@ -1160,7 +1160,7 @@ public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state) public static bool UnsafeQueueUserWorkItem(IThreadPoolWorkItem callBack, bool preferLocal) { - if (callBack == null) + if (callBack is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } @@ -1185,7 +1185,7 @@ internal static void UnsafeQueueUserWorkItemInternal(object callBack, bool prefe // This method tries to take the target callback out of the current thread's queue. internal static bool TryPopCustomWorkItem(object workItem) { - Debug.Assert(null != workItem); + Debug.Assert(workItem is not null); return ThreadPoolWorkQueue.LocalFindAndPop(workItem); } @@ -1201,13 +1201,13 @@ internal static IEnumerable GetQueuedWorkItems() // Enumerate each local queue foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues) { - if (wsq != null && wsq.m_array != null) + if (wsq is not null && wsq.m_array is not null) { object?[] items = wsq.m_array; for (int i = 0; i < items.Length; i++) { object? item = items[i]; - if (item != null) + if (item is not null) { yield return item; } @@ -1219,13 +1219,13 @@ internal static IEnumerable GetQueuedWorkItems() internal static IEnumerable GetLocallyQueuedWorkItems() { ThreadPoolWorkQueue.WorkStealingQueue? wsq = ThreadPoolWorkQueueThreadLocals.threadLocals?.workStealingQueue; - if (wsq != null && wsq.m_array != null) + if (wsq is not null && wsq.m_array is not null) { object?[] items = wsq.m_array; for (int i = 0; i < items.Length; i++) { object? item = items[i]; - if (item != null) + if (item is not null) yield return item; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.PlatformNotSupported.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.PlatformNotSupported.cs index 3e34c04ff6a592..c852e63e7e6b6b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.PlatformNotSupported.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.PlatformNotSupported.cs @@ -15,7 +15,7 @@ private ThreadPoolBoundHandle() public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { - if (handle == null) + if (handle is null) throw new ArgumentNullException(nameof(handle)); if (handle.IsClosed || handle.IsInvalid) @@ -27,7 +27,7 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData) { - if (callback == null) + if (callback is null) throw new ArgumentNullException(nameof(callback)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); @@ -36,7 +36,7 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { - if (preAllocated == null) + if (preAllocated is null) throw new ArgumentNullException(nameof(preAllocated)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); @@ -45,7 +45,7 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) [CLSCompliant(false)] public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { - if (overlapped == null) + if (overlapped is null) throw new ArgumentNullException(nameof(overlapped)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); @@ -54,7 +54,7 @@ public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) [CLSCompliant(false)] public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped) { - if (overlapped == null) + if (overlapped is null) throw new ArgumentNullException(nameof(overlapped)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs index 6486053794a5f5..1c5ae3800b881d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -142,7 +142,7 @@ private void FireNextTimers() TimerQueueTimer? timer = _shortTimers; for (int listNum = 0; listNum < 2; listNum++) // short == 0, long == 1 { - while (timer != null) + while (timer is not null) { Debug.Assert(timer._dueTime != Timeout.UnsignedInfinite, "A timer in the list must have a valid due time."); @@ -199,7 +199,7 @@ private void FireNextTimers() // If this is the first timer, we'll fire it on this thread (after processing // all others). Otherwise, queue it to the ThreadPool. - if (timerToFireOnThisThread == null) + if (timerToFireOnThisThread is null) { timerToFireOnThisThread = timer; } @@ -242,7 +242,7 @@ private void FireNextTimers() long remaining = _currentAbsoluteThreshold - nowTicks; if (remaining > 0) { - if (_shortTimers == null && _longTimers != null) + if (_shortTimers is null && _longTimers is not null) { // We don't have any short timers left and we haven't examined the long list, // which means we likely don't have an accurate nextTimerDuration. @@ -327,7 +327,7 @@ private void LinkTimer(TimerQueueTimer timer) // Use timer._short to decide to which list to add. ref TimerQueueTimer? listHead = ref timer._short ? ref _shortTimers : ref _longTimers; timer._next = listHead; - if (timer._next != null) + if (timer._next is not null) { timer._next._prev = timer; } @@ -338,7 +338,7 @@ private void LinkTimer(TimerQueueTimer timer) private void UnlinkTimer(TimerQueueTimer timer) { TimerQueueTimer? t = timer._next; - if (t != null) + if (t is not null) { t._prev = timer._prev; } @@ -355,7 +355,7 @@ private void UnlinkTimer(TimerQueueTimer timer) } t = timer._prev; - if (t != null) + if (t is not null) { t._next = timer._next; } @@ -552,13 +552,13 @@ public ValueTask CloseAsync() } Debug.Assert( - notifyWhenNoCallbacksRunning == null || + notifyWhenNoCallbacksRunning is null || notifyWhenNoCallbacksRunning is Task); // There are callbacks queued or running, so we need to store a Task // that'll be used to signal the caller when all callbacks complete. Do so as long as // there wasn't a previous CloseAsync call that did. - if (notifyWhenNoCallbacksRunning == null) + if (notifyWhenNoCallbacksRunning is null) { var t = new Task((object?)null, TaskCreationOptions.RunContinuationsAsynchronously); _notifyWhenNoCallbacksRunning = t; @@ -592,7 +592,7 @@ internal void Fire(bool isThreadPool = false) lock (_associatedTimerQueue) { _callbacksRunning--; - if (_canceled && _callbacksRunning == 0 && _notifyWhenNoCallbacksRunning != null) + if (_canceled && _callbacksRunning == 0 && _notifyWhenNoCallbacksRunning is not null) shouldSignal = true; } @@ -622,7 +622,7 @@ internal void CallCallback(bool isThreadPool) // Call directly if EC flow is suppressed ExecutionContext? context = _executionContext; - if (context == null) + if (context is null) { _timerCallback(_state); } @@ -781,7 +781,7 @@ private void TimerSetup(TimerCallback callback, uint period, bool flowExecutionContext = true) { - if (callback == null) + if (callback is null) throw new ArgumentNullException(nameof(callback)); _timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, flowExecutionContext)); @@ -844,7 +844,7 @@ public static long ActiveCount public bool Dispose(WaitHandle notifyObject) { - if (notifyObject == null) + if (notifyObject is null) throw new ArgumentNullException(nameof(notifyObject)); return _timer.Close(notifyObject); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs index 72afc1f40e6fb4..fd9eb9498953a9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs @@ -29,7 +29,7 @@ private TimerQueue(int id) private static List InitializeScheduledTimerManager_Locked() { - Debug.Assert(s_scheduledTimers == null); + Debug.Assert(s_scheduledTimers is null); var timers = new List(Instances.Length); s_scheduledTimersToFire ??= new List(Instances.Length); @@ -53,7 +53,7 @@ private bool SetTimer(uint actualDuration) if (!_isScheduled) { List? timers = s_scheduledTimers; - if (timers == null) + if (timers is null) { timers = InitializeScheduledTimerManager_Locked(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index ee840501d031cb..248fb63bd06e7e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -51,7 +51,7 @@ protected WaitHandle() [Obsolete("Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { - get => _waitHandle == null ? InvalidHandle : _waitHandle.DangerousGetHandle(); + get => _waitHandle is null ? InvalidHandle : _waitHandle.DangerousGetHandle(); set { if (value == InvalidHandle) @@ -62,7 +62,7 @@ public virtual IntPtr Handle // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.SetHandleAsInvalid(); _waitHandle = null; @@ -135,7 +135,7 @@ private bool WaitOneNoCheck(int millisecondsTimeout) waitHandle.DangerousAddRef(ref success); SynchronizationContext? context = SynchronizationContext.Current; - if (context != null && context.IsWaitNotificationRequired()) + if (context is not null && context.IsWaitNotificationRequired()) { waitResult = context.Wait(new[] { waitHandle.DangerousGetHandle() }, false, millisecondsTimeout); } @@ -169,7 +169,7 @@ private bool WaitOneNoCheck(int millisecondsTimeout) // t_safeWaitHandlesForRent can be null when it was not initialized yet or // if a re-entrant wait is performed and the array is already rented. In // that case we just allocate a new one and reuse it as necessary. - int currentLength = (safeWaitHandles != null) ? safeWaitHandles.Length : 0; + int currentLength = (safeWaitHandles is not null) ? safeWaitHandles.Length : 0; if (currentLength < capacity) { safeWaitHandles = new SafeWaitHandle[Math.Max(capacity, @@ -202,7 +202,7 @@ private static void ObtainSafeWaitHandles( for (int i = 0; i < waitHandles.Length; ++i) { WaitHandle waitHandle = waitHandles[i]; - if (waitHandle == null) + if (waitHandle is null) { throw new ArgumentNullException("waitHandles[" + i + ']', SR.ArgumentNull_ArrayElement); } @@ -223,7 +223,7 @@ private static void ObtainSafeWaitHandles( for (int i = 0; i < waitHandles.Length; ++i) { SafeWaitHandle? safeWaitHandle = safeWaitHandles[i]; - if (safeWaitHandle == null) + if (safeWaitHandle is null) { break; } @@ -238,7 +238,7 @@ private static void ObtainSafeWaitHandles( if (!lastSuccess) { - Debug.Assert(lastSafeWaitHandle != null); + Debug.Assert(lastSafeWaitHandle is not null); lastSafeWaitHandle.DangerousRelease(); } @@ -248,7 +248,7 @@ private static void ObtainSafeWaitHandles( private static int WaitMultiple(WaitHandle[] waitHandles, bool waitAll, int millisecondsTimeout) { - if (waitHandles == null) + if (waitHandles is null) { throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles); } @@ -272,7 +272,7 @@ private static int WaitMultiple(ReadOnlySpan waitHandles, bool waitA } SynchronizationContext? context = SynchronizationContext.Current; - bool useWaitContext = context != null && context.IsWaitNotificationRequired(); + bool useWaitContext = context is not null && context.IsWaitNotificationRequired(); SafeWaitHandle?[]? safeWaitHandles = RentSafeWaitHandleArray(waitHandles.Length); try @@ -311,7 +311,7 @@ private static int WaitMultiple(ReadOnlySpan waitHandles, bool waitA { for (int i = 0; i < waitHandles.Length; ++i) { - if (safeWaitHandles[i] != null) + if (safeWaitHandles[i] is not null) { safeWaitHandles[i]!.DangerousRelease(); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) safeWaitHandles[i] = null; @@ -324,11 +324,11 @@ private static int WaitMultiple(ReadOnlySpan waitHandles, bool waitA private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout) { - if (toSignal == null) + if (toSignal is null) { throw new ArgumentNullException(nameof(toSignal)); } - if (toWaitOn == null) + if (toWaitOn is null) { throw new ArgumentNullException(nameof(toWaitOn)); } @@ -341,7 +341,7 @@ private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int // to ensure that one instance is used in all places in this method SafeWaitHandle? safeWaitHandleToSignal = toSignal._waitHandle; SafeWaitHandle? safeWaitHandleToWaitOn = toWaitOn._waitHandle; - if (safeWaitHandleToSignal == null || safeWaitHandleToWaitOn == null) + if (safeWaitHandleToSignal is null || safeWaitHandleToWaitOn is null) { // Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs index f68aa84db76394..4f9cb4516ae397 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs @@ -14,7 +14,7 @@ public static class WaitHandleExtensions /// A representing the native operating system handle. public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle) { - if (waitHandle == null) + if (waitHandle is null) { throw new ArgumentNullException(nameof(waitHandle)); } @@ -29,7 +29,7 @@ public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle) /// A representing the native operating system handle. public static void SetSafeWaitHandle(this WaitHandle waitHandle, SafeWaitHandle? value) { - if (waitHandle == null) + if (waitHandle is null) { throw new ArgumentNullException(nameof(waitHandle)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeSpan.cs b/src/libraries/System.Private.CoreLib/src/System/TimeSpan.cs index d7551477aa8995..9133babcc7e6c8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeSpan.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeSpan.cs @@ -137,7 +137,7 @@ public static int Compare(TimeSpan t1, TimeSpan t2) // Returns a value less than zero if this object public int CompareTo(object? value) { - if (value == null) return 1; + if (value is null) return 1; if (!(value is TimeSpan)) throw new ArgumentException(SR.Arg_MustBeTimeSpan); long t = ((TimeSpan)value)._ticks; @@ -276,13 +276,13 @@ private static void ValidateStyles(TimeSpanStyles style, string parameterName) } public static TimeSpan Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } public static TimeSpan Parse(string input, IFormatProvider? formatProvider) { - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan Parse(ReadOnlySpan input, IFormatProvider? formatProvider = null) @@ -291,20 +291,20 @@ public static TimeSpan Parse(ReadOnlySpan input, IFormatProvider? formatPr } public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider) { - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (format is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider) { - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (format is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } @@ -316,7 +316,7 @@ public static TimeSpan ParseExact(ReadOnlySpan input, ReadOnlySpan f public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); - if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); + if (input is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static TimeSpan ParseExact(ReadOnlySpan input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) @@ -326,7 +326,7 @@ public static TimeSpan ParseExact(ReadOnlySpan input, string[] formats, IF } public static bool TryParse([NotNullWhen(true)] string? s, out TimeSpan result) { - if (s == null) + if (s is null) { result = default; return false; @@ -340,7 +340,7 @@ public static bool TryParse(ReadOnlySpan s, out TimeSpan result) public static bool TryParse([NotNullWhen(true)] string? input, IFormatProvider? formatProvider, out TimeSpan result) { - if (input == null) + if (input is null) { result = default; return false; @@ -353,7 +353,7 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider? formatPro } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string? format, IFormatProvider? formatProvider, out TimeSpan result) { - if (input == null || format == null) + if (input is null || format is null) { result = default; return false; @@ -367,7 +367,7 @@ public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan fo } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result) { - if (input == null) + if (input is null) { result = default; return false; @@ -382,7 +382,7 @@ public static bool TryParseExact(ReadOnlySpan input, [NotNullWhen(true)] s public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string? format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); - if (input == null || format == null) + if (input is null || format is null) { result = default; return false; @@ -399,7 +399,7 @@ public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan fo public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); - if (input == null) + if (input is null) { result = default; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZone.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZone.cs index ae37dc9c14e926..907530041ce79a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZone.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZone.cs @@ -33,7 +33,7 @@ private static object InternalSyncObject { get { - if (s_InternalSyncObject == null) + if (s_InternalSyncObject is null) { object o = new object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); @@ -53,7 +53,7 @@ public static TimeZone CurrentTimeZone // Grabbing the cached value is required at the top of this function so that // we don't incur a race condition with the ResetTimeZone method below. TimeZone? tz = currentTimeZone; - if (tz == null) + if (tz is null) { lock (InternalSyncObject) { @@ -71,7 +71,7 @@ public static TimeZone CurrentTimeZone // with the CurrentTimeZone property above. internal static void ResetTimeZone() { - if (currentTimeZone != null) + if (currentTimeZone is not null) { lock (InternalSyncObject) { @@ -206,7 +206,7 @@ public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTime // internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { - if (daylightTimes == null) + if (daylightTimes is null) { return TimeSpan.Zero; } diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs index 878863cac5eaab..d94fff7bd4305f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs @@ -44,7 +44,7 @@ public sealed class AdjustmentRule : IEquatable, ISerializable, (DaylightTransitionEnd != default && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1)); public bool Equals(AdjustmentRule? other) => - other != null && + other is not null && _dateStart == other._dateStart && _dateEnd == other._dateEnd && _daylightDelta == other._daylightDelta && @@ -226,7 +226,7 @@ void IDeserializationCallback.OnDeserialization(object? sender) void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -242,7 +242,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex private AdjustmentRule(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -254,13 +254,13 @@ private AdjustmentRule(SerializationInfo info, StreamingContext context) _daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime))!; // Do not rename (binary serialization) object? o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan)); // Do not rename (binary serialization) - if (o != null) + if (o is not null) { _baseUtcOffsetDelta = (TimeSpan)o; } o = info.GetValueNoThrow("NoDaylightTransitions", typeof(bool)); // Do not rename (binary serialization) - if (o != null) + if (o is not null) { _noDaylightTransitions = (bool)o; } diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.StringSerializer.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.StringSerializer.cs index 405df10d08f55b..6c1fc6ad9b148b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.StringSerializer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.StringSerializer.cs @@ -377,7 +377,7 @@ private int GetNextInt32Value() // individual AdjustmentRule array elements do not require semicolons AdjustmentRule? rule = GetNextAdjustmentRuleValue(); - while (rule != null) + while (rule is not null) { rules.Add(rule); count++; diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs index 0be8b50a064f6d..de279b5b94f7cc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs @@ -112,7 +112,7 @@ private TimeZoneInfo(byte[] data, string id, bool dstDisabled) /// public AdjustmentRule[] GetAdjustmentRules() { - if (_adjustmentRules == null) + if (_adjustmentRules is null) { return Array.Empty(); } @@ -206,7 +206,7 @@ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out value = GetTimeZoneFromTzData(rawData, id); - if (value == null) + if (value is null) { e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath)); return TimeZoneInfoResult.InvalidTimeZoneException; @@ -230,7 +230,7 @@ private static List GetTimeZoneIds(string timeZoneDirectory) using (StreamReader sr = new StreamReader(Path.Combine(timeZoneDirectory, ZoneTabFileName), Encoding.UTF8)) { string? zoneTabFileLine; - while ((zoneTabFileLine = sr.ReadLine()) != null) + while ((zoneTabFileLine = sr.ReadLine()) is not null) { if (!string.IsNullOrEmpty(zoneTabFileLine) && zoneTabFileLine[0] != '#') { @@ -285,7 +285,7 @@ private static bool TryGetLocalTzFile([NotNullWhen(true)] out byte[]? rawData, [ string? tzVariable = GetTzEnvironmentVariable(); // If the env var is null, use the localtime file - if (tzVariable == null) + if (tzVariable is null) { return TryLoadTzFile("/etc/localtime", ref rawData, ref id) || @@ -362,7 +362,7 @@ private static bool TryLoadTzFile(string tzFilePath, [NotNullWhen(true)] ref byt string? id = null; string? symlinkPath = Interop.Sys.ReadLink(tzFilePath); - if (symlinkPath != null) + if (symlinkPath is not null) { // symlinkPath can be relative path, use Path to get the full absolute path. symlinkPath = Path.GetFullPath(symlinkPath, Path.GetDirectoryName(tzFilePath)!); @@ -419,7 +419,7 @@ private static unsafe void EnumerateFilesRecursively(string path, Predicate.Shared.Return(dirBuffer); } } @@ -584,7 +584,7 @@ private static TimeZoneInfo GetLocalTimeZoneFromTzFile() if (TryGetLocalTzFile(out rawData, out id)) { TimeZoneInfo? result = GetTimeZoneFromTzData(rawData, id); - if (result != null) + if (result is not null) { return result; } @@ -596,7 +596,7 @@ private static TimeZoneInfo GetLocalTimeZoneFromTzFile() private static TimeZoneInfo? GetTimeZoneFromTzData(byte[]? rawData, string id) { - if (rawData != null) + if (rawData is not null) { try { @@ -619,7 +619,7 @@ private static string GetTimeZoneDirectory() { string? tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable); - if (tzDirectory == null) + if (tzDirectory is null) { tzDirectory = DefaultTimeZoneDirectory; } @@ -649,7 +649,7 @@ public static TimeZoneInfo FindSystemTimeZoneById(string id) return Utc; } - if (id == null) + if (id is null) { throw new ArgumentNullException(nameof(id)); } @@ -843,7 +843,7 @@ private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[]? rules, Ti } rules = rulesList.ToArray(); - if (rules != null && rules.Length == 0) + if (rules is not null && rules.Length == 0) { rules = null; } @@ -954,7 +954,7 @@ private static void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZone TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset) : null; - if (r == null) + if (r is null) { // just use the last transition as the rule which will be used until the end of time @@ -1073,7 +1073,7 @@ private static TZifType TZif_GetEarlyDateTransitionType(TZifType[] transitionTyp TransitionTime? dstStart = TZif_CreateTransitionTimeFromPosixRule(start, startTime); TransitionTime? dstEnd = TZif_CreateTransitionTimeFromPosixRule(end, endTime); - if (dstStart == null || dstEnd == null) + if (dstStart is null || dstEnd is null) { return null; } @@ -1638,7 +1638,7 @@ private struct TZifType public TZifType(byte[] data, int index) { - if (data == null || data.Length < index + Length) + if (data is null || data.Length < index + Length) { throw new ArgumentException(SR.Argument_TimeZoneInfoInvalidTZif, nameof(data)); } @@ -1664,7 +1664,7 @@ private struct TZifHead public TZifHead(byte[] data, int index) { - if (data == null || data.Length < Length) + if (data is null || data.Length < Length) { throw new ArgumentException("bad data", nameof(data)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs index dacf92875a71d6..7761a192e2dac1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs @@ -69,7 +69,7 @@ private TimeZoneInfo CreateLocal() lock (this) { TimeZoneInfo? timeZone = _localTimeZone; - if (timeZone == null) + if (timeZone is null) { timeZone = GetLocalTimeZone(this); @@ -158,7 +158,7 @@ public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) bool isAmbiguous = false; AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out int? ruleIndex); - if (rule != null && rule.HasDaylightSaving) + if (rule is not null && rule.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime); @@ -217,7 +217,7 @@ public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) bool isAmbiguous = false; AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out int? ruleIndex); - if (rule != null && rule.HasDaylightSaving) + if (rule is not null && rule.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime); @@ -250,7 +250,7 @@ public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) private AdjustmentRule? GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex) { AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex); - if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving) + if (rule is not null && rule.NoDaylightTransitions && !rule.HasDaylightSaving) { // When using NoDaylightTransitions rules, each rule is only for one offset. // When looking for the Daylight savings rules, and we found the non-DST rule, @@ -269,7 +269,7 @@ public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex) { Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules."); - Debug.Assert(_adjustmentRules != null); + Debug.Assert(_adjustmentRules is not null); if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length) { @@ -404,7 +404,7 @@ internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags) dateTime; AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out int? ruleIndex); - if (rule != null && rule.HasDaylightSaving) + if (rule is not null && rule.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); return GetIsAmbiguousTime(adjustedTime, rule, daylightTime); @@ -448,7 +448,7 @@ private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, // time, it is defaulted to "Standard" (i.e. this will return false). // For Invalid times, we will return false - if (!_supportsDaylightSavingTime || _adjustmentRules == null) + if (!_supportsDaylightSavingTime || _adjustmentRules is null) { return false; } @@ -487,7 +487,7 @@ private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, // handle the normal cases... // AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out int? ruleIndex); - if (rule != null && rule.HasDaylightSaving) + if (rule is not null && rule.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); return GetIsDaylightSavings(adjustedTime, rule, daylightTime); @@ -511,7 +511,7 @@ public bool IsInvalidTime(DateTime dateTime) // only check Unspecified and (Local when this TimeZoneInfo instance is Local) AdjustmentRule? rule = GetAdjustmentRuleForTime(dateTime, out int? ruleIndex); - if (rule != null && rule.HasDaylightSaving) + if (rule is not null && rule.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex); isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime); @@ -576,7 +576,7 @@ public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string s /// public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) { - if (destinationTimeZone == null) + if (destinationTimeZone is null) { throw new ArgumentNullException(nameof(destinationTimeZone)); } @@ -599,7 +599,7 @@ public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZone /// public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) { - if (destinationTimeZone == null) + if (destinationTimeZone is null) { throw new ArgumentNullException(nameof(destinationTimeZone)); } @@ -628,12 +628,12 @@ internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZ private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) { - if (sourceTimeZone == null) + if (sourceTimeZone is null) { throw new ArgumentNullException(nameof(sourceTimeZone)); } - if (destinationTimeZone == null) + if (destinationTimeZone is null) { throw new ArgumentNullException(nameof(destinationTimeZone)); } @@ -655,7 +655,7 @@ private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZo AdjustmentRule? sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out int? sourceRuleIndex); TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset; - if (sourceRule != null) + if (sourceRule is not null) { sourceOffset += sourceRule.BaseUtcOffsetDelta; if (sourceRule.HasDaylightSaving) @@ -744,7 +744,7 @@ public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTi /// String objects (DisplayName, StandardName, DaylightName). /// public bool Equals(TimeZoneInfo? other) => - other != null && + other is not null && string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) && HasSameRules(other); @@ -752,7 +752,7 @@ public bool Equals(TimeZoneInfo? other) => public static TimeZoneInfo FromSerializedString(string source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -778,13 +778,13 @@ public static ReadOnlyCollection GetSystemTimeZones() lock (cachedData) { - if (cachedData._readOnlySystemTimeZones == null) + if (cachedData._readOnlySystemTimeZones is null) { PopulateAllSystemTimeZones(cachedData); cachedData._allSystemTimeZonesRead = true; List list; - if (cachedData._systemTimeZones != null) + if (cachedData._systemTimeZones is not null) { // return a collection of the cached system time zones list = new List(cachedData._systemTimeZones.Values); @@ -814,7 +814,7 @@ public static ReadOnlyCollection GetSystemTimeZones() /// public bool HasSameRules(TimeZoneInfo other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } @@ -831,8 +831,8 @@ public bool HasSameRules(TimeZoneInfo other) AdjustmentRule[]? otherRules = other._adjustmentRules; sameRules = - (currentRules == null && otherRules == null) || - (currentRules != null && otherRules != null); + (currentRules is null && otherRules is null) || + (currentRules is not null && otherRules is not null); if (!sameRules) { @@ -840,7 +840,7 @@ public bool HasSameRules(TimeZoneInfo other) return false; } - if (currentRules != null) + if (currentRules is not null) { if (currentRules.Length != otherRules!.Length) { @@ -1003,7 +1003,7 @@ void IDeserializationCallback.OnDeserialization(object? sender) void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -1019,7 +1019,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex private TimeZoneInfo(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -1036,14 +1036,14 @@ private TimeZoneInfo(SerializationInfo info, StreamingContext context) private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex) { AdjustmentRule? result = GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, ruleIndex: out ruleIndex); - Debug.Assert(result == null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set."); + Debug.Assert(result is null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set."); return result; } private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex) { - if (_adjustmentRules == null || _adjustmentRules.Length == 0) + if (_adjustmentRules is null || _adjustmentRules.Length == 0) { ruleIndex = null; return null; @@ -1226,7 +1226,7 @@ private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? r /// private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) { - if (rule == null) + if (rule is null) { return false; } @@ -1328,7 +1328,7 @@ private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpa { isAmbiguousLocalDst = false; - if (rule == null) + if (rule is null) { return false; } @@ -1355,7 +1355,7 @@ private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpa AdjustmentRule? previousYearRule = zone.GetAdjustmentRuleForTime( new DateTime(daylightTime.Start.Year - 1, 12, 31), out int? previousYearRuleIndex); - if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear()) + if (previousYearRule is not null && previousYearRule.IsEndDateMarkerForEndOfYear()) { DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime( daylightTime.Start.Year - 1, @@ -1381,7 +1381,7 @@ private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpa AdjustmentRule? nextYearRule = zone.GetAdjustmentRuleForTime( new DateTime(daylightTime.End.Year + 1, 1, 1), out int? nextYearRuleIndex); - if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear()) + if (nextYearRule is not null && nextYearRule.IsStartDateMarkerForBeginningOfYear()) { if (nextYearRule.IsEndDateMarkerForEndOfYear()) { @@ -1514,7 +1514,7 @@ private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTi private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) { bool isAmbiguous = false; - if (rule == null || rule.DaylightDelta == TimeSpan.Zero) + if (rule is null || rule.DaylightDelta == TimeSpan.Zero) { return isAmbiguous; } @@ -1584,7 +1584,7 @@ private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, Dayli private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) { bool isInvalid = false; - if (rule == null || rule.DaylightDelta == TimeSpan.Zero) + if (rule is null || rule.DaylightDelta == TimeSpan.Zero) { return isInvalid; } @@ -1652,7 +1652,7 @@ private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone) TimeSpan baseOffset = zone.BaseUtcOffset; AdjustmentRule? rule = zone.GetAdjustmentRuleForTime(time, out int? ruleIndex); - if (rule != null) + if (rule is not null) { baseOffset += rule.BaseUtcOffsetDelta; if (rule.HasDaylightSaving) @@ -1706,7 +1706,7 @@ internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, o else { rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, ruleIndex: out ruleIndex); - Debug.Assert(rule == null || ruleIndex.HasValue, + Debug.Assert(rule is null || ruleIndex.HasValue, "If GetAdjustmentRuleForTime returned an AdjustmentRule, ruleIndex should also be set."); // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset, @@ -1717,7 +1717,7 @@ internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, o year = targetTime.Year; } - if (rule != null) + if (rule is not null) { baseOffset += rule.BaseUtcOffsetDelta; if (rule.HasDaylightSaving) @@ -1817,7 +1817,7 @@ private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, ou e = null; // check the cache - if (cachedData._systemTimeZones != null) + if (cachedData._systemTimeZones is not null) { if (cachedData._systemTimeZones.TryGetValue(id, out TimeZoneInfo? match)) { @@ -1901,7 +1901,7 @@ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool /// private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[]? adjustmentRules, out bool adjustmentRulesSupportDst) { - if (id == null) + if (id is null) { throw new ArgumentNullException(nameof(id)); } @@ -1929,7 +1929,7 @@ private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, Adju // are sorted in chronological order // - if (adjustmentRules != null && adjustmentRules.Length != 0) + if (adjustmentRules is not null && adjustmentRules.Length != 0) { adjustmentRulesSupportDst = true; AdjustmentRule? prev = null; @@ -1939,7 +1939,7 @@ private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, Adju prev = current; current = adjustmentRules[i]; - if (current == null) + if (current is null) { throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls); } @@ -1949,7 +1949,7 @@ private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, Adju throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta); } - if (prev != null && current.DateStart <= prev.DateEnd) + if (prev is not null && current.DateStart <= prev.DateEnd) { // verify the rules are in chronological order and the DateStart/DateEnd do not overlap throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs index a025edbb312f7d..656008bf9dc0b3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs @@ -19,7 +19,7 @@ public abstract partial class Type { public virtual bool IsEnumDefined(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!IsEnum) @@ -66,7 +66,7 @@ public virtual bool IsEnumDefined(object value) public virtual string? GetEnumName(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!IsEnum) diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs index d28dcd8b0b07a6..710babf972c319 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs @@ -31,7 +31,7 @@ public virtual bool IsSerializable underlyingType = underlyingType.BaseType; } - while (underlyingType != null); + while (underlyingType is not null); } return false; @@ -116,7 +116,7 @@ public bool IsVisible public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) { - if (filter == null) + if (filter is null) throw new ArgumentNullException(nameof(filter)); Type?[] c = GetInterfaces(); @@ -135,7 +135,7 @@ public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) cnt = 0; for (int i = 0; i < c.Length; i++) { - if (c[i] != null) + if (c[i] is not null) ret[cnt++] = c[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } return ret; @@ -159,7 +159,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if ((memberType & MemberTypes.Method) != 0) { m = GetMethods(bindingAttr); - if (filter != null) + if (filter is not null) { for (i = 0; i < m.Length; i++) if (!filter(m[i]!, filterCriteria)) @@ -177,7 +177,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if ((memberType & MemberTypes.Constructor) != 0) { c = GetConstructors(bindingAttr); - if (filter != null) + if (filter is not null) { for (i = 0; i < c.Length; i++) if (!filter(c[i]!, filterCriteria)) @@ -195,7 +195,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if ((memberType & MemberTypes.Field) != 0) { f = GetFields(bindingAttr); - if (filter != null) + if (filter is not null) { for (i = 0; i < f.Length; i++) if (!filter(f[i]!, filterCriteria)) @@ -213,7 +213,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if ((memberType & MemberTypes.Property) != 0) { p = GetProperties(bindingAttr); - if (filter != null) + if (filter is not null) { for (i = 0; i < p.Length; i++) if (!filter(p[i]!, filterCriteria)) @@ -231,7 +231,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if ((memberType & MemberTypes.Event) != 0) { e = GetEvents(bindingAttr); - if (filter != null) + if (filter is not null) { for (i = 0; i < e.Length; i++) if (!filter(e[i]!, filterCriteria)) @@ -249,7 +249,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if ((memberType & MemberTypes.NestedType) != 0) { t = GetNestedTypes(bindingAttr); - if (filter != null) + if (filter is not null) { for (i = 0; i < t.Length; i++) if (!filter(t[i]!, filterCriteria)) @@ -268,50 +268,50 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin // Copy the Methods cnt = 0; - if (m != null) + if (m is not null) { for (i = 0; i < m.Length; i++) - if (m[i] != null) + if (m[i] is not null) ret[cnt++] = m[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Constructors - if (c != null) + if (c is not null) { for (i = 0; i < c.Length; i++) - if (c[i] != null) + if (c[i] is not null) ret[cnt++] = c[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Fields - if (f != null) + if (f is not null) { for (i = 0; i < f.Length; i++) - if (f[i] != null) + if (f[i] is not null) ret[cnt++] = f[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Properties - if (p != null) + if (p is not null) { for (i = 0; i < p.Length; i++) - if (p[i] != null) + if (p[i] is not null) ret[cnt++] = p[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Events - if (e != null) + if (e is not null) { for (i = 0; i < e.Length; i++) - if (e[i] != null) + if (e[i] is not null) ret[cnt++] = e[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Types - if (t != null) + if (t is not null) { for (i = 0; i < t.Length; i++) - if (t[i] != null) + if (t[i] is not null) ret[cnt++] = t[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } @@ -323,7 +323,7 @@ public virtual bool IsSubclassOf(Type c) Type? p = this; if (p == c) return false; - while (p != null) + while (p is not null) { if (p == c) return true; @@ -335,7 +335,7 @@ public virtual bool IsSubclassOf(Type c) [Intrinsic] public virtual bool IsAssignableFrom([NotNullWhen(true)] Type? c) { - if (c == null) + if (c is null) return false; if (this == c) @@ -371,17 +371,17 @@ public virtual bool IsAssignableFrom([NotNullWhen(true)] Type? c) internal bool ImplementInterface(Type ifaceType) { Type? t = this; - while (t != null) + while (t is not null) { Type[] interfaces = t.GetInterfaces(); - if (interfaces != null) + if (interfaces is not null) { for (int i = 0; i < interfaces.Length; i++) { // Interfaces don't derive from other interfaces, they implement them. // So instead of IsSubclassOf, we should use ImplementInterface instead. if (interfaces[i] == ifaceType || - (interfaces[i] != null && interfaces[i].ImplementInterface(ifaceType))) + (interfaces[i] is not null && interfaces[i].ImplementInterface(ifaceType))) return true; } } @@ -398,7 +398,7 @@ internal bool ImplementInterface(Type ifaceType) private static bool FilterAttributeImpl(MemberInfo m, object filterCriteria) { // Check that the criteria object is an Integer object - if (filterCriteria == null) + if (filterCriteria is null) throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); switch (m.MemberType) diff --git a/src/libraries/System.Private.CoreLib/src/System/TypeLoadException.cs b/src/libraries/System.Private.CoreLib/src/System/TypeLoadException.cs index e1a5bedc8daadd..ec30b709ee022b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TypeLoadException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TypeLoadException.cs @@ -55,7 +55,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont info.AddValue("TypeLoadResourceID", _resourceId); } - // If ClassName != null, GetMessage will construct on the fly using it + // If ClassName is not null, GetMessage will construct on the fly using it // and ResourceId (mscorrc.dll). This allows customization of the // class name format depending on the language environment. private string? _className; diff --git a/src/libraries/System.Private.CoreLib/src/System/UInt64.cs b/src/libraries/System.Private.CoreLib/src/System/UInt64.cs index 638821178f1dcc..8bdfe53152d600 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UInt64.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UInt64.cs @@ -28,7 +28,7 @@ namespace System // public int CompareTo(object? value) { - if (value == null) + if (value is null) { return 1; } @@ -102,27 +102,27 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan public static ulong Parse(string s) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static ulong Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt64(s, style, NumberFormatInfo.CurrentInfo); } public static ulong Parse(string s, IFormatProvider? provider) { - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static ulong Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); + if (s is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider)); } @@ -134,7 +134,7 @@ public static ulong Parse(ReadOnlySpan s, NumberStyles style = NumberStyle public static bool TryParse([NotNullWhen(true)] string? s, out ulong result) { - if (s == null) + if (s is null) { result = 0; return false; @@ -152,7 +152,7 @@ public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, I { NumberFormatInfo.ValidateParseStyleInteger(style); - if (s == null) + if (s is null) { result = 0; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs b/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs index 96540328271a4d..a5b095ad0ec4de 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs @@ -62,7 +62,7 @@ private unsafe UIntPtr(SerializationInfo info, StreamingContext context) void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) throw new ArgumentNullException(nameof(info)); info.AddValue("value", ToUInt64()); diff --git a/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs b/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs index f3abc8aeae499c..bc73470d369bff 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs @@ -34,7 +34,7 @@ internal static void GetUnitySerializationInfo(SerializationInfo info, int unity public UnitySerializationHolder(SerializationInfo info, StreamingContext context) #pragma warning restore CA2229 { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/ValueTuple.cs b/src/libraries/System.Private.CoreLib/src/System/ValueTuple.cs index f814bbb7a2c37e..fb4a23d499503d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ValueTuple.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ValueTuple.cs @@ -58,7 +58,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -83,7 +83,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -311,7 +311,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -320,7 +320,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -347,7 +347,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -504,7 +504,7 @@ public bool Equals(ValueTuple other) /// bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -514,7 +514,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -542,7 +542,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -695,7 +695,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -706,7 +706,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -737,7 +737,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -902,7 +902,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -914,7 +914,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -948,7 +948,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1127,7 +1127,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -1140,7 +1140,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1177,7 +1177,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1370,7 +1370,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -1384,7 +1384,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1424,7 +1424,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1631,7 +1631,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -1646,7 +1646,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1689,7 +1689,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1916,7 +1916,7 @@ public bool Equals(ValueTuple other) bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { - if (other == null || !(other is ValueTuple)) return false; + if (other is null || !(other is ValueTuple)) return false; var objTuple = (ValueTuple)other; @@ -1932,7 +1932,7 @@ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) int IComparable.CompareTo(object? other) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { @@ -1978,7 +1978,7 @@ public int CompareTo(ValueTuple other) int IStructuralComparable.CompareTo(object? other, IComparer comparer) { - if (other == null) return 1; + if (other is null) return 1; if (!(other is ValueTuple)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs b/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs index 870221d5f2049b..a411daf8161ef7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs +++ b/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs @@ -26,7 +26,7 @@ public WeakReference(object? target, bool trackResurrection) protected WeakReference(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } @@ -39,7 +39,7 @@ protected WeakReference(SerializationInfo info, StreamingContext context) public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) + if (info is null) { throw new ArgumentNullException(nameof(info)); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs index 9da06545c254d2..0a103a5d8b83aa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs @@ -133,14 +133,14 @@ private void ReadArraySize(XmlReaderDelegator reader) private void ReadXsiType(XmlReaderDelegator reader) { string xsiTypeString = reader.Value; - if (xsiTypeString != null && xsiTypeString.Length > 0) + if (xsiTypeString is not null && xsiTypeString.Length > 0) XmlObjectSerializerReadContext.ParseQualifiedName(xsiTypeString, reader, out XsiTypeName, out XsiTypeNamespace, out XsiTypePrefix); } private void ReadFactoryType(XmlReaderDelegator reader) { string factoryTypeString = reader.Value; - if (factoryTypeString != null && factoryTypeString.Length > 0) + if (factoryTypeString is not null && factoryTypeString.Length > 0) XmlObjectSerializerReadContext.ParseQualifiedName(factoryTypeString, reader, out FactoryTypeName, out FactoryTypeNamespace, out FactoryTypePrefix); } } 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 22f02e15a9728b..c90ba711416d07 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 @@ -67,13 +67,13 @@ public XmlDictionaryString?[]? ChildElementNamespaces { get { - if (_childElementNamespaces == null) + if (_childElementNamespaces is null) { lock (this) { - if (_childElementNamespaces == null) + if (_childElementNamespaces is null) { - if (_helper.ChildElementNamespaces == null) + if (_helper.ChildElementNamespaces is null) { XmlDictionaryString?[]? tempChildElementamespaces = CreateChildElementNamespaces(); Interlocked.MemoryBarrier(); @@ -183,7 +183,7 @@ internal MethodInfo? GetKeyValuePairMethodInfo internal ConstructorInfo? GetNonAttributedTypeConstructor() { - if (_nonAttributedTypeConstructor == null) + if (_nonAttributedTypeConstructor is null) { // Cache the ConstructorInfo to improve performance. _nonAttributedTypeConstructor = _helper.GetNonAttributedTypeConstructor(); @@ -197,7 +197,7 @@ private Func MakeNewInstance { get { - if (_makeNewInstance == null) + if (_makeNewInstance is null) { _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType); } @@ -209,7 +209,7 @@ private Func MakeNewInstance internal bool CreateNewInstanceViaDefaultConstructor([NotNullWhen(true)] out object? obj) { ConstructorInfo? ci = GetNonAttributedTypeConstructor(); - if (ci == null) + if (ci is null) { obj = null; return false; @@ -237,11 +237,11 @@ internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { - if (_helper.XmlFormatWriterDelegate == null) + if (_helper.XmlFormatWriterDelegate is null) { lock (this) { - if (_helper.XmlFormatWriterDelegate == null) + if (_helper.XmlFormatWriterDelegate is null) { XmlFormatClassWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate(); Interlocked.MemoryBarrier(); @@ -265,11 +265,11 @@ internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { - if (_helper.XmlFormatReaderDelegate == null) + if (_helper.XmlFormatReaderDelegate is null) { lock (this) { - if (_helper.XmlFormatReaderDelegate == null) + if (_helper.XmlFormatReaderDelegate is null) { XmlFormatClassReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate(); Interlocked.MemoryBarrier(); @@ -287,7 +287,7 @@ internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { ClassDataContract? cdc = (ClassDataContract?)DataContract.GetDataContractFromGeneratedAssembly(type); - if (cdc == null) + if (cdc is null) { return new ClassDataContract(type, ns, memberNames); } @@ -321,7 +321,7 @@ internal static void CheckAndAddMember(List members, DataMember memb { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) - && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) + && DataContract.GetBuiltInDataContract(childType) is null && childType != Globals.TypeOfDBNull) { string ns = DataContract.GetStableName(childType).Namespace; if (ns.Length > 0 && ns != dataContract.Namespace.Value) @@ -388,7 +388,7 @@ internal static bool IsNonAttributedTypeValidForSerialization(Type type) else { return (type.IsVisible && - type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Array.Empty(), null) != null); + type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Array.Empty(), null) is not null); } } @@ -439,13 +439,13 @@ internal static bool IsNonSerializedMember(Type type, string memberName) private XmlDictionaryString?[]? CreateChildElementNamespaces() { - if (Members == null) + if (Members is null) return null; XmlDictionaryString?[]? baseChildElementNamespaces = null; - if (this.BaseContract != null) + if (this.BaseContract is not null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; - int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; + int baseChildElementNamespaceCount = (baseChildElementNamespaces is not null) ? baseChildElementNamespaces.Length : 0; XmlDictionaryString?[] childElementNamespaces = new XmlDictionaryString?[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) Array.Copy(baseChildElementNamespaces!, childElementNamespaces, baseChildElementNamespaces!.Length); @@ -466,7 +466,7 @@ private void EnsureMethodsImported() public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); if (_isScriptObject) { @@ -497,7 +497,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -507,7 +507,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) } return true; } - if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException)) + if (this.BaseContract is not null && this.BaseContract.RequiresMemberAccessForRead(securityException)) return true; if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor())) @@ -516,7 +516,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) { return true; } - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -529,7 +529,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) if (MethodRequiresMemberAccess(this.OnDeserializing)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -543,7 +543,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) if (MethodRequiresMemberAccess(this.OnDeserialized)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -555,13 +555,13 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) return true; } - if (this.Members != null) + if (this.Members is not null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForSet()) { - if (securityException != null) + if (securityException is not null) { if (this.Members[i].MemberInfo is FieldInfo) { @@ -601,7 +601,7 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) if (!IsTypeVisible(UnderlyingType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -612,12 +612,12 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) return true; } - if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException)) + if (this.BaseContract is not null && this.BaseContract.RequiresMemberAccessForWrite(securityException)) return true; if (MethodRequiresMemberAccess(this.OnSerializing)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -631,7 +631,7 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) if (MethodRequiresMemberAccess(this.OnSerialized)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -643,13 +643,13 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) return true; } - if (this.Members != null) + if (this.Members is not null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForGet()) { - if (securityException != null) + if (securityException is not null) { if (this.Members[i].MemberInfo is FieldInfo) { @@ -732,12 +732,12 @@ internal ClassDataContractCriticalHelper(Type type) : base(type) { if (HasDataContract) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.ISerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); - if (baseType != null && !(baseType.IsSerializable && Globals.TypeOfISerializable.IsAssignableFrom(baseType))) + if (baseType is not null && !(baseType.IsSerializable && Globals.TypeOfISerializable.IsAssignableFrom(baseType))) baseType = null; } SetKeyValuePairAdapterFlags(type); this.IsValueType = type.IsValueType; - if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) + if (baseType is not null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) { // https://github.com/dotnet/corefx/pull/19629: // A DataContract created at runtime does not work with the base DataContract pre-generated by SG. @@ -761,7 +761,7 @@ internal ClassDataContractCriticalHelper(Type type) : base(type) this.BaseContract = baseContract as ClassDataContract; } - if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType) + if (this.BaseContract is not null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes, @@ -793,7 +793,7 @@ internal ClassDataContractCriticalHelper(Type type) : base(type) int baseMemberCount = 0; int baseContractCount = 0; - if (BaseContract == null) + if (BaseContract is null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; @@ -848,7 +848,7 @@ private void EnsureIsReferenceImported(Type type) bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); - if (BaseContract != null) + if (BaseContract is not null) { if (hasDataContractAttribute && dataContractAttribute!.IsReferenceSetExplicitly) { @@ -922,7 +922,7 @@ private void ImportDataMembers() if (HasDataContract) { object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray(); - if (memberAttributes != null && memberAttributes.Length > 0) + if (memberAttributes is not null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name)); @@ -934,14 +934,14 @@ private void ImportDataMembers() PropertyInfo property = (PropertyInfo)member; MethodInfo? getMethod = property.GetMethod; - if (getMethod != null && IsMethodOverriding(getMethod)) + if (getMethod is not null && IsMethodOverriding(getMethod)) continue; MethodInfo? setMethod = property.SetMethod; - if (setMethod != null && IsMethodOverriding(setMethod)) + if (setMethod is not null && IsMethodOverriding(setMethod)) continue; - if (getMethod == null) + if (getMethod is null) ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name)); - if (setMethod == null) + if (setMethod is null) { if (!SetIfGetOnlyCollection(memberContract)) { @@ -957,7 +957,7 @@ private void ImportDataMembers() DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { - if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) + if (memberAttribute.Name is null || memberAttribute.Name.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } @@ -983,11 +983,11 @@ private void ImportDataMembers() { FieldInfo? field = member as FieldInfo; PropertyInfo? property = member as PropertyInfo; - if ((field == null && property == null) || (field != null && field.IsInitOnly)) + if ((field is null && property is null) || (field is not null && field.IsInitOnly)) continue; object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray(); - if (memberAttributes != null && memberAttributes.Length > 0) + if (memberAttributes is not null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name)); @@ -995,14 +995,14 @@ private void ImportDataMembers() continue; } DataMember memberContract = new DataMember(member); - if (property != null) + if (property is not null) { MethodInfo? getMethod = property.GetGetMethod(); - if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) + if (getMethod is null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; MethodInfo? setMethod = property.SetMethod; - if (setMethod == null) + if (setMethod is null) { if (!SetIfGetOnlyCollection(memberContract)) continue; @@ -1035,7 +1035,7 @@ private void ImportDataMembers() } else { - canSerializeMember = field != null && !field.IsNotSerialized; + canSerializeMember = field is not null && !field.IsNotSerialized; } if (canSerializeMember) @@ -1044,7 +1044,7 @@ private void ImportDataMembers() memberContract.Name = DataContract.EncodeLocalName(member.Name); object[] optionalFields = field!.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); - if (optionalFields == null || optionalFields.Length == 0) + if (optionalFields is null || optionalFields.Length == 0) { if (this.IsReference) { @@ -1067,12 +1067,12 @@ private void ImportDataMembers() Interlocked.MemoryBarrier(); _members = tempMembers; - Debug.Assert(Members != null); + Debug.Assert(Members is not null); } private static bool CanSerializeMember(FieldInfo? field) { - return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType!, field.Name); + return field is not null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType!, field.Name); } private bool SetIfGetOnlyCollection(DataMember memberContract) @@ -1088,7 +1088,7 @@ private bool SetIfGetOnlyCollection(DataMember memberContract) private void SetIfMembersHaveConflict(List members) { - if (BaseContract == null) + if (BaseContract is null) return; int baseTypeIndex = 0; @@ -1098,7 +1098,7 @@ private void SetIfMembersHaveConflict(List members) membersInHierarchy.Add(new Member(member, this.StableName!.Namespace, baseTypeIndex)); } ClassDataContract? currContract = BaseContract; - while (currContract != null) + while (currContract is not null) { baseTypeIndex++; @@ -1172,7 +1172,7 @@ private static bool IsMethodOverriding(MethodInfo method) internal void EnsureMethodsImported() { - if (!_isMethodChecked && UnderlyingType != null) + if (!_isMethodChecked && UnderlyingType is not null) { lock (this) { @@ -1212,13 +1212,13 @@ private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] pa { if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod) { - Debug.Assert(method.DeclaringType != null); + Debug.Assert(method.DeclaringType is not null); - if (_extensionDataSetMethod != null) + if (_extensionDataSetMethod is not null) ThrowInvalidDataContractException(SR.Format(SR.DuplicateExtensionDataSetMethod, method, _extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); - if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) + if (parameters is null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfExtensionDataObject), method.DeclaringType); return true; } @@ -1229,11 +1229,11 @@ private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameter { if (method.IsDefined(attributeType, false)) { - Debug.Assert(method.DeclaringType != null); + Debug.Assert(method.DeclaringType is not null); - if (currentCallback != null) + if (currentCallback is not null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); - else if (prevAttributeType != null) + else if (prevAttributeType is not null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); else if (method.IsVirtual) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); @@ -1241,7 +1241,7 @@ private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameter { if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); - if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) + if (parameters is null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); prevAttributeType = attributeType; @@ -1257,7 +1257,7 @@ internal ClassDataContract? BaseContract set { _baseContract = value; - if (_baseContract != null && IsValueType) + if (_baseContract is not null && IsValueType) ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName!.Name, StableName.Namespace, _baseContract.StableName!.Name, _baseContract.StableName.Namespace)); } } @@ -1316,12 +1316,12 @@ internal override DataContractDictionary? KnownDataContracts { get { - if (_knownDataContracts != null) + if (_knownDataContracts is not null) { return _knownDataContracts; } - if (!_isKnownTypeAttributeChecked && UnderlyingType != null) + if (!_isKnownTypeAttributeChecked && UnderlyingType is not null) { lock (this) { @@ -1409,7 +1409,7 @@ internal MethodInfo? GetKeyValuePairMethodInfo return null; ConstructorInfo? ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); - if (ctor == null) + if (ctor is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType)))); return ctor; @@ -1426,7 +1426,7 @@ internal MethodInfo? GetKeyValuePairMethodInfo return null; ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Array.Empty(), null); - if (ctor == null) + if (ctor is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; @@ -1454,7 +1454,7 @@ private static Type[] SerInfoCtorArgs { get { - if (s_serInfoCtorArgs == null) + if (s_serInfoCtorArgs is null) s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; return s_serInfoCtorArgs; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 132a76b6da6a21..c8b6df591955a2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -22,10 +22,10 @@ private static MethodInfo GetTypeFromHandle { get { - if (s_getTypeFromHandle == null) + if (s_getTypeFromHandle is null) { s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle"); - Debug.Assert(s_getTypeFromHandle != null); + Debug.Assert(s_getTypeFromHandle is not null); } return s_getTypeFromHandle; } @@ -36,10 +36,10 @@ private static MethodInfo ObjectEquals { get { - if (s_objectEquals == null) + if (s_objectEquals is null) { s_objectEquals = typeof(object).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static); - Debug.Assert(s_objectEquals != null); + Debug.Assert(s_objectEquals is not null); } return s_objectEquals; } @@ -50,10 +50,10 @@ private static MethodInfo ArraySetValue { get { - if (s_arraySetValue == null) + if (s_arraySetValue is null) { s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }); - Debug.Assert(s_arraySetValue != null); + Debug.Assert(s_arraySetValue is not null); } return s_arraySetValue; } @@ -64,10 +64,10 @@ private static MethodInfo ObjectToString { get { - if (s_objectToString == null) + if (s_objectToString is null) { s_objectToString = typeof(object).GetMethod("ToString", Array.Empty()); - Debug.Assert(s_objectToString != null); + Debug.Assert(s_objectToString is not null); } return s_objectToString; } @@ -78,10 +78,10 @@ private static MethodInfo StringFormat { get { - if (s_stringFormat == null) + if (s_stringFormat is null) { s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) }); - Debug.Assert(s_stringFormat != null); + Debug.Assert(s_stringFormat is not null); } return s_stringFormat; } @@ -94,7 +94,7 @@ private static Module SerializationModule { get { - if (s_serializationModule == null) + if (s_serializationModule is null) { s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false } @@ -234,7 +234,7 @@ internal void Set(LocalBuilder local, object value) internal object For(LocalBuilder? local, object? start, object? end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); - if (forState.Index != null) + if (forState.Index is not null) { Load(start); Stloc(forState.Index); @@ -249,10 +249,10 @@ internal void EndFor() { object stackTop = _blockStack.Pop(); ForState? forState = stackTop as ForState; - if (forState == null) + if (forState is null) ThrowMismatchException(stackTop); - if (forState.Index != null) + if (forState.Index is not null) { Ldloc(forState.Index); Ldc(1); @@ -286,7 +286,7 @@ internal void InternalBreakFor(object userForState, OpCode branchInstruction) foreach (object block in _blockStack) { ForState? forState = block as ForState; - if (forState != null && (object)forState == userForState) + if (forState is not null && (object)forState == userForState) { if (!forState.RequiresEndLabel) { @@ -320,7 +320,7 @@ internal void EndForEach(MethodInfo moveNextMethod) { object stackTop = _blockStack.Pop(); ForState? forState = stackTop as ForState; - if (forState == null) + if (forState is null) ThrowMismatchException(stackTop); MarkLabel(forState.TestLabel); @@ -628,10 +628,10 @@ internal Type LoadMember(MemberInfo memberInfo) else if (memberInfo is PropertyInfo property) { memberType = property.PropertyType; - if (property != null) + if (property is not null) { MethodInfo? getMethod = property.GetMethod; - if (getMethod == null) + if (getMethod is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property))); Call(getMethod); } @@ -670,10 +670,10 @@ internal void StoreMember(MemberInfo memberInfo) else if (memberInfo is PropertyInfo) { PropertyInfo? property = memberInfo as PropertyInfo; - if (property != null) + if (property is not null) { MethodInfo? setMethod = property.SetMethod; - if (setMethod == null) + if (setMethod is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property))); Call(setMethod); } @@ -728,7 +728,7 @@ internal void LoadDefaultValue(Type type) internal void Load(object? obj) { - if (obj == null) + if (obj is null) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldnull"); @@ -1255,7 +1255,7 @@ internal void Dup() private void LoadThis(object? thisObj, MethodInfo methodInfo) { - if (thisObj != null && !methodInfo.IsStatic) + if (thisObj is not null && !methodInfo.IsStatic) { LoadAddress(thisObj); ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType!); @@ -1265,7 +1265,7 @@ private void LoadThis(object? thisObj, MethodInfo methodInfo) private void LoadParam(object? arg, int oneBasedArgIndex, MethodBase methodInfo) { Load(arg); - if (arg != null) + if (arg is not null) ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType); } @@ -1351,7 +1351,7 @@ private IfState PopIfState() { object stackTop = _blockStack.Pop(); IfState? ifState = stackTop as IfState; - if (ifState == null) + if (ifState is null) ThrowMismatchException(stackTop); return ifState; } @@ -1405,7 +1405,7 @@ internal void EndCase() { object stackTop = _blockStack.Peek(); SwitchState? switchState = stackTop as SwitchState; - if (switchState == null) + if (switchState is null) ThrowMismatchException(stackTop); Br(switchState.EndOfSwitchLabel); if (_codeGenTrace != CodeGenTrace.None) @@ -1416,7 +1416,7 @@ internal void EndSwitch() { object stackTop = _blockStack.Pop(); SwitchState? switchState = stackTop as SwitchState; - if (switchState == null) + if (switchState is null) ThrowMismatchException(stackTop); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end switch"); @@ -1472,7 +1472,7 @@ internal void EndWhile() internal void CallStringFormat(string msg, params object[] values) { NewArray(typeof(object), values.Length); - if (_stringFormatArray == null) + if (_stringFormatArray is null) _stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray"); Stloc(_stringFormatArray); for (int i = 0; i < values.Length; i++) 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 430e7ba45df9bd..b73662154e2080 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 @@ -249,20 +249,20 @@ public string? ValueName internal bool IsDictionary { - get { return KeyName != null; } + get { return KeyName is not null; } } public XmlDictionaryString? ChildElementNamespace { get { - if (_childElementNamespace == null) + if (_childElementNamespace is null) { lock (this) { - if (_childElementNamespace == null) + if (_childElementNamespace is null) { - if (_helper.ChildElementNamespace == null && !IsDictionary) + if (_helper.ChildElementNamespace is null && !IsDictionary) { XmlDictionaryString? tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Interlocked.MemoryBarrier(); @@ -331,7 +331,7 @@ internal string? DeserializationExceptionMessage internal bool IsReadOnlyContract { - get { return DeserializationExceptionMessage != null; } + get { return DeserializationExceptionMessage is not null; } } private XmlFormatCollectionWriterDelegate CreateXmlFormatWriterDelegate() @@ -343,11 +343,11 @@ internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { get { - if (_helper.XmlFormatWriterDelegate == null) + if (_helper.XmlFormatWriterDelegate is null) { lock (this) { - if (_helper.XmlFormatWriterDelegate == null) + if (_helper.XmlFormatWriterDelegate is null) { XmlFormatCollectionWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate(); Interlocked.MemoryBarrier(); @@ -371,11 +371,11 @@ internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { get { - if (_helper.XmlFormatReaderDelegate == null) + if (_helper.XmlFormatReaderDelegate is null) { lock (this) { - if (_helper.XmlFormatReaderDelegate == null) + if (_helper.XmlFormatReaderDelegate is null) { if (IsReadOnlyContract) { @@ -405,11 +405,11 @@ internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionRead { get { - if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) + if (_helper.XmlFormatGetOnlyCollectionReaderDelegate is null) { lock (this) { - if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) + if (_helper.XmlFormatGetOnlyCollectionReaderDelegate is null) { if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable)) { @@ -421,7 +421,7 @@ internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionRead ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null); } - if (Kind != CollectionKind.Array && AddMethod == null) + if (Kind != CollectionKind.Array && AddMethod is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } @@ -485,7 +485,7 @@ internal static Type[] KnownInterfaces { get { - if (s_knownInterfaces == null) + if (s_knownInterfaces is null) { // Listed in priority order s_knownInterfaces = new Type[] @@ -507,25 +507,25 @@ internal static Type[] KnownInterfaces private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAttribute? collectionContractAttribute) { _kind = kind; - if (itemType != null) + if (itemType is not null) { _itemType = itemType; _isItemTypeNullable = DataContract.IsTypeNullable(itemType); bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); string? itemName = null, keyName = null, valueName = null; - if (collectionContractAttribute != null) + if (collectionContractAttribute is not null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { - if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) + if (collectionContractAttribute.ItemName is null || collectionContractAttribute.ItemName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(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 (collectionContractAttribute.KeyName is null || collectionContractAttribute.KeyName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName))); @@ -533,7 +533,7 @@ private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAtt } if (collectionContractAttribute.IsValueNameSetExplicitly) { - if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) + if (collectionContractAttribute.ValueName is null || collectionContractAttribute.ValueName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName))); @@ -552,7 +552,7 @@ private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAtt _valueName = valueName ?? Globals.ValueLocalName; } } - if (collectionContractAttribute != null) + if (collectionContractAttribute is not null) { this.IsReference = collectionContractAttribute.IsReference; } @@ -573,9 +573,9 @@ internal CollectionDataContractCriticalHelper(Type type) : base(type) internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(type) { - if (getEnumeratorMethod == null) + if (getEnumeratorMethod is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, GetClrTypeFullName(type)))); - if (itemType == null) + if (itemType is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, GetClrTypeFullName(type)))); CollectionDataContractAttribute? collectionContractAttribute; @@ -589,11 +589,11 @@ internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Ty // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(type) { - if (getEnumeratorMethod == null) + if (getEnumeratorMethod is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); - if (addMethod == null && !type.IsInterface) + if (addMethod is null && !type.IsInterface) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type)))); - if (itemType == null) + if (itemType is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); CollectionDataContractAttribute? collectionContractAttribute; @@ -633,7 +633,7 @@ internal DataContract ItemContract { get { - if (_itemContract == null) + if (_itemContract is null) { if (IsDictionary) { @@ -643,8 +643,8 @@ internal DataContract ItemContract SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } - Debug.Assert(KeyName != null); - Debug.Assert(ValueName != null); + Debug.Assert(KeyName is not null); + Debug.Assert(ValueName is not null); _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); @@ -652,7 +652,7 @@ internal DataContract ItemContract else { _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType); - if (_itemContract == null) + if (_itemContract is null) { _itemContract = DataContract.GetDataContract(ItemType); } @@ -701,7 +701,7 @@ internal string? ValueName set { _valueName = value; } } - internal bool IsDictionary => KeyName != null; + internal bool IsDictionary => KeyName is not null; public string? DeserializationExceptionMessage => _deserializationExceptionMessage; @@ -727,7 +727,7 @@ internal override DataContractDictionary? KnownDataContracts { get { - if (!_isKnownTypeAttributeChecked && UnderlyingType != null) + if (!_isKnownTypeAttributeChecked && UnderlyingType is not null) { lock (this) { @@ -776,7 +776,7 @@ private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { - if (_incrementCollectionCountDelegate == null) + if (_incrementCollectionCountDelegate is null) { switch (Kind) { @@ -819,7 +819,7 @@ private static MethodInfo BuildIncrementCollectionCountDelegateMethod { get { - if (s_buildIncrementCollectionCountDelegateMethod == null) + if (s_buildIncrementCollectionCountDelegateMethod is null) { s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!; } @@ -846,7 +846,7 @@ internal IEnumerator GetEnumeratorForCollection(object obj) IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator(); if (Kind == CollectionKind.GenericDictionary) { - if (_createGenericDictionaryEnumeratorDelegate == null) + if (_createGenericDictionaryEnumeratorDelegate is null) { var keyValueTypes = ItemType.GetGenericArguments(); MethodInfo buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); @@ -866,7 +866,7 @@ internal IEnumerator GetEnumeratorForCollection(object obj) internal Type GetCollectionElementType() { Debug.Assert(Kind != CollectionKind.Array, "GetCollectionElementType should not be called on Arrays"); - Debug.Assert(GetEnumeratorMethod != null, "GetEnumeratorMethod should be non-null for non-Arrays"); + Debug.Assert(GetEnumeratorMethod is not null, "GetEnumeratorMethod should be non-null for non-Arrays"); Type? enumeratorType = null; if (Kind == CollectionKind.GenericDictionary) @@ -884,7 +884,7 @@ internal Type GetCollectionElementType() } MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null); - if (getCurrentMethod == null) + if (getCurrentMethod is null) { if (enumeratorType.IsInterface) { @@ -922,7 +922,7 @@ private static MethodInfo BuildCreateGenericDictionaryEnumerato { get { - if (s_buildCreateGenericDictionaryEnumerator == null) + if (s_buildCreateGenericDictionaryEnumerator is null) { s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!; } @@ -979,7 +979,7 @@ internal static bool IsCollection(Type type, bool constructorRequired) private static bool IsCollectionHelper(Type type, [NotNullWhen(true)] out Type? itemType, bool constructorRequired) { - if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) + if (type.IsArray && DataContract.GetBuiltInDataContract(type) is null) { itemType = type.GetElementType()!; return true; @@ -1011,7 +1011,7 @@ internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); - if (dataContract == null) + if (dataContract is null) { Type itemType; if (type.IsArray) @@ -1054,7 +1054,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC dataContract = null; itemType = Globals.TypeOfObject; - if (DataContract.GetBuiltInDataContract(type) != null) + if (DataContract.GetBuiltInDataContract(type) is not null) { return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/, SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); @@ -1065,7 +1065,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC bool isReadOnlyContract = false; string? deserializationExceptionMessage = null; Type? baseType = type.BaseType; - bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject + bool isBaseTypeCollection = (baseType is not null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; // Avoid creating an invalid collection contract for Serializable types since we can create a ClassDataContract instead @@ -1146,7 +1146,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC if (!type.IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Array.Empty(), null); - if (defaultCtor == null && constructorRequired) + if (defaultCtor is null && constructorRequired) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. @@ -1196,7 +1196,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } - Debug.Assert(knownInterfaceType != null); + Debug.Assert(knownInterfaceType is not null); if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) @@ -1206,9 +1206,9 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); - Debug.Assert(getEnumeratorMethod != null); + Debug.Assert(getEnumeratorMethod is not null); - if (addMethod == null) + if (addMethod is null) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. @@ -1265,12 +1265,12 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC if (tryCreate) { - Debug.Assert(addMethodTypeArray != null); + Debug.Assert(addMethodTypeArray is not null); GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); - Debug.Assert(getEnumeratorMethod != null); + Debug.Assert(getEnumeratorMethod is not null); dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) : @@ -1312,13 +1312,13 @@ private static void GetReadOnlyCollectionExceptionMessages(Type type, string mes private static string GetInvalidCollectionMessage(string message, string nestedMessage, string? param) { - return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); + return (param is null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); } private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo? addMethod, ref MethodInfo? getEnumeratorMethod) { Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); - if (t != null) + if (t is not null) { addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod; getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod; @@ -1332,10 +1332,10 @@ private static void GetCollectionMethods(Type type, Type interfaceType, Type[] a if (addMethodOnInterface) { addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, null, addMethodTypeArray, null); - if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) + if (addMethod is null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); - if (addMethod == null) + if (addMethod is null) { Type[] parentInterfaceTypes = interfaceType.GetInterfaces(); // The for loop below depeneds on the order for the items in parentInterfaceTypes, which @@ -1347,7 +1347,7 @@ private static void GetCollectionMethods(Type type, Type interfaceType, Type[] a if (IsKnownInterface(parentInterfaceType)) { FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod); - if (addMethod == null) + if (addMethod is null) { break; } @@ -1362,13 +1362,13 @@ private static void GetCollectionMethods(Type type, Type interfaceType, Type[] a addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, addMethodTypeArray, null); } - if (getEnumeratorMethod == null) + if (getEnumeratorMethod is null) { getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null); - if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) + if (getEnumeratorMethod is null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); - if (ienumerableInterface == null) + if (ienumerableInterface is null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); } @@ -1390,7 +1390,7 @@ private static bool IsKnownInterface(Type type) internal override DataContract GetValidContract(SerializationMode mode) { - if (InvalidCollectionInSharedContractMessage != null) + if (InvalidCollectionInSharedContractMessage is not null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); return this; @@ -1407,7 +1407,7 @@ internal override DataContract GetValidContract() private void CheckConstructor() { - if (this.Constructor == null) + if (this.Constructor is null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } @@ -1419,7 +1419,7 @@ private void CheckConstructor() internal override bool IsValidContract(SerializationMode mode) { - return (InvalidCollectionInSharedContractMessage == null); + return (InvalidCollectionInSharedContractMessage is null); } /// @@ -1431,7 +1431,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -1441,9 +1441,9 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) } return true; } - if (ItemType != null && !IsTypeVisible(ItemType)) + if (ItemType is not null && !IsTypeVisible(ItemType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -1455,7 +1455,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) } if (ConstructorRequiresMemberAccess(Constructor)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -1467,7 +1467,7 @@ internal bool RequiresMemberAccessForRead(SecurityException? securityException) } if (MethodRequiresMemberAccess(this.AddMethod)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -1491,7 +1491,7 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -1501,9 +1501,9 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) } return true; } - if (ItemType != null && !IsTypeVisible(ItemType)) + if (ItemType is not null && !IsTypeVisible(ItemType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( @@ -1519,7 +1519,7 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; @@ -1528,7 +1528,7 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); xmlReader.Read(); object? o = null; 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 2099fc9f3fb9fe..65eeebccffa000 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 @@ -52,7 +52,7 @@ internal DataContract(DataContractCriticalHelper helper) internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract? dataContract) { dataContract = GetGeneratedDataContract(type); - return dataContract != null; + return dataContract is not null; } internal static DataContract? GetDataContractFromGeneratedAssembly(Type? type) @@ -361,7 +361,7 @@ internal class DataContractCriticalHelper internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { dataContract = CreateDataContract(id, typeHandle, type); AssignDataContractToId(dataContract, id); @@ -376,7 +376,7 @@ internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHa internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { dataContract = CreateGetOnlyCollectionDataContract(id, typeHandle, type); s_dataContractCache[id] = dataContract; @@ -387,7 +387,7 @@ internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int internal static DataContract GetDataContractForInitialization(int id) { DataContract dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } @@ -414,7 +414,7 @@ internal static int GetIdForInitialization(ClassDataContract classContract) private static bool ContractMatches(DataContract contract, DataContract cachedContract) { - return (cachedContract != null && cachedContract.UnderlyingType == contract.UnderlyingType); + return (cachedContract is not null && cachedContract.UnderlyingType == contract.UnderlyingType); } internal static int GetId(RuntimeTypeHandle typeHandle) @@ -455,20 +455,20 @@ internal static int GetId(RuntimeTypeHandle typeHandle) private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract? dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { - if (type == null) + if (type is null) type = Type.GetTypeFromHandle(typeHandle); type = UnwrapNullableType(type); dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); - if (dataContract != null) + if (dataContract is not null) { AssignDataContractToId(dataContract, id); return dataContract; @@ -489,7 +489,7 @@ private static DataContract CreateDataContract(Type type) type = GetDataContractAdapterType(type); DataContract? dataContract = GetBuiltInDataContract(type); - if (dataContract == null) + if (dataContract is null) { if (type.IsArray) dataContract = new CollectionDataContract(type); @@ -542,9 +542,9 @@ private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeT lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { - if (type == null) + if (type is null) type = Type.GetTypeFromHandle(typeHandle); type = UnwrapNullableType(type); type = GetDataContractAdapterType(type); @@ -600,7 +600,7 @@ private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHan lock (s_initBuiltInContractsLock) { - if (s_typeToBuiltInContract == null) + if (s_typeToBuiltInContract is null) s_typeToBuiltInContract = new Dictionary(); DataContract? dataContract; @@ -617,7 +617,7 @@ private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHan { lock (s_initBuiltInContractsLock) { - if (s_nameToBuiltInContract == null) + if (s_nameToBuiltInContract is null) s_nameToBuiltInContract = new Dictionary(); DataContract? dataContract; @@ -638,7 +638,7 @@ private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHan lock (s_initBuiltInContractsLock) { - if (s_nameToBuiltInContract == null) + if (s_nameToBuiltInContract is null) s_nameToBuiltInContract = new Dictionary(); DataContract? dataContract; @@ -700,7 +700,7 @@ private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHan else if (name == "Xml.XmlNode[]") type = typeof(XmlNode[]); - if (type != null) + if (type is not null) TryCreateBuiltInDataContract(type, out dataContract); s_nameToBuiltInContract.Add(qname, dataContract); @@ -787,7 +787,7 @@ public static bool TryCreateBuiltInDataContract(Type type, [NotNullWhen(true)] o dataContract = new XmlDataContract(type); break; } - return dataContract != null; + return dataContract is not null; } public static bool TryCreateBuiltInDataContract(string name, string ns, [NotNullWhen(true)] out DataContract? dataContract) @@ -909,14 +909,14 @@ public static bool TryCreateBuiltInDataContract(string name, string ns, [NotNull else if (name == "ArrayOfXmlNode") dataContract = new XmlDataContract(typeof(XmlNode[])); } - return dataContract != null; + return dataContract is not null; } internal static string GetNamespace(string key) { lock (s_namespacesLock) { - if (s_namespaces == null) + if (s_namespaces is null) s_namespaces = new Dictionary(); string? value; if (s_namespaces.TryGetValue(key, out value)) @@ -937,7 +937,7 @@ internal static XmlDictionaryString GetClrTypeString(string key) { lock (s_clrTypeStringsLock) { - if (s_clrTypeStrings == null) + if (s_clrTypeStrings is null) { s_clrTypeStringsDictionary = new XmlDictionary(); s_clrTypeStrings = new Dictionary(); @@ -969,7 +969,7 @@ internal static XmlDictionaryString GetClrTypeString(string key) [DoesNotReturn] internal static void ThrowInvalidDataContractException(string? message, Type? type) { - if (type != null) + if (type is not null) { lock (s_cacheLock) { @@ -1005,7 +1005,7 @@ internal Type OriginalUnderlyingType { get { - if (_originalUnderlyingType == null) + if (_originalUnderlyingType is null) { _originalUnderlyingType = GetDataContractOriginalType(this._underlyingType); } @@ -1094,7 +1094,7 @@ internal virtual XmlDictionaryString? TopLevelElementName get { return _name; } set { - Debug.Assert(value != null); + Debug.Assert(value is not null); _name = value; } } @@ -1104,7 +1104,7 @@ internal virtual XmlDictionaryString? TopLevelElementNamespace get { return _ns; } set { - Debug.Assert(value != null); + Debug.Assert(value is not null); _ns = value; } } @@ -1127,7 +1127,7 @@ internal MethodInfo? ParseMethod { MethodInfo? method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null); - if (method != null && method.ReturnType == UnderlyingType) + if (method is not null && method.ReturnType == UnderlyingType) { _parseMethod = method; } @@ -1188,7 +1188,7 @@ private static bool IsTypeSerializable(Type type, HashSet previousCollecti return true; } } - return DataContract.GetBuiltInDataContract(type) != null || + return DataContract.GetBuiltInDataContract(type) is not null || ClassDataContract.IsNonAttributedTypeValidForSerialization(type); } @@ -1314,7 +1314,7 @@ private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttri if (dataContractAttribute.IsNameSetExplicitly) { name = dataContractAttribute.Name; - if (name == null || name.Length == 0) + if (name is null || name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidDataContractName, DataContract.GetClrTypeFullName(type)))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); @@ -1326,7 +1326,7 @@ private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttri if (dataContractAttribute.IsNamespaceSetExplicitly) { ns = dataContractAttribute.Namespace; - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidDataContractNamespace, DataContract.GetClrTypeFullName(type)))); CheckExplicitDataContractNamespaceUri(ns, type); } @@ -1363,7 +1363,7 @@ private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWh stableName = null; DataContract? builtInContract = GetBuiltInDataContract(type); - if (builtInContract != null) + if (builtInContract is not null) { stableName = builtInContract.StableName; } @@ -1380,7 +1380,7 @@ private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWh CollectionDataContractAttribute? collectionContractAttribute; stableName = GetCollectionStableName(type, type.GetElementType()!, out collectionContractAttribute); } - return stableName != null; + return stableName is not null; } internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataContractAttribute? dataContractAttribute) @@ -1388,7 +1388,7 @@ internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataCo dataContractAttribute = null; object[] dataContractAttributes = type.GetCustomAttributes(Globals.TypeOfDataContractAttribute, false).ToArray(); - if (dataContractAttributes != null && dataContractAttributes.Length > 0) + if (dataContractAttributes is not null && dataContractAttributes.Length > 0) { #if DEBUG if (dataContractAttributes.Length > 1) @@ -1397,14 +1397,14 @@ internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataCo dataContractAttribute = (DataContractAttribute)dataContractAttributes[0]; } - return dataContractAttribute != null; + return dataContractAttribute is not null; } internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute? collectionContractAttribute) { string? name, ns; object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false).ToArray(); - if (collectionContractAttributes != null && collectionContractAttributes.Length > 0) + if (collectionContractAttributes is not null && collectionContractAttributes.Length > 0) { #if DEBUG if (collectionContractAttributes.Length > 1) @@ -1414,7 +1414,7 @@ internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemTyp if (collectionContractAttribute.IsNameSetExplicitly) { name = collectionContractAttribute.Name; - if (name == null || name.Length == 0) + if (name is null || name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractName, DataContract.GetClrTypeFullName(type)))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); @@ -1426,7 +1426,7 @@ internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemTyp if (collectionContractAttribute.IsNamespaceSetExplicitly) { ns = collectionContractAttribute.Namespace; - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractNamespace, DataContract.GetClrTypeFullName(type)))); CheckExplicitDataContractNamespaceUri(ns, type); } @@ -1449,7 +1449,7 @@ private static string GetArrayPrefix(ref Type itemType) string arrayOfPrefix = string.Empty; while (itemType.IsArray) { - if (DataContract.GetBuiltInDataContract(itemType) != null) + if (DataContract.GetBuiltInDataContract(itemType) is not null) break; arrayOfPrefix += Globals.ArrayPrefix; itemType = itemType.GetElementType()!; @@ -1475,16 +1475,16 @@ private static string GetDefaultStableLocalName(Type type) string? arrayPrefix = null; if (type.IsArray) arrayPrefix = GetArrayPrefix(ref type); - if (type.DeclaringType == null) + if (type.DeclaringType is null) typeName = type.Name; else { - int nsLen = (type.Namespace == null) ? 0 : type.Namespace.Length; + int nsLen = (type.Namespace is null) ? 0 : type.Namespace.Length; if (nsLen > 0) nsLen++; //include the . following namespace typeName = DataContract.GetClrTypeFullName(type).Substring(nsLen).Replace('+', '.'); } - if (arrayPrefix != null) + if (arrayPrefix is not null) typeName = arrayPrefix + typeName; if (type.IsGenericType) { @@ -1527,13 +1527,13 @@ private static string GetDefaultStableLocalName(Type type) private static string GetDefaultDataContractNamespace(Type type) { string? clrNs = type.Namespace; - if (clrNs == null) + if (clrNs is null) clrNs = string.Empty; string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); - if (ns == null) + if (ns is null) ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); - if (ns == null) + if (ns is null) ns = GetDefaultStableNamespace(type); else CheckExplicitDataContractNamespaceUri(ns, type); @@ -1548,12 +1548,12 @@ internal static List GetDataContractNameForGenericName(string typeName, Str endIndex = typeName.IndexOf('`', startIndex); if (endIndex < 0) { - if (localName != null) + if (localName is not null) localName.Append(typeName.Substring(startIndex)); nestedParamCounts.Add(0); break; } - if (localName != null) + if (localName is not null) { string tempLocalName = typeName.Substring(startIndex, endIndex - startIndex); localName.Append((tempLocalName.Equals("KeyValuePairAdapter") ? "KeyValuePair" : tempLocalName)); @@ -1569,7 +1569,7 @@ internal static List GetDataContractNameForGenericName(string typeName, Str else nestedParamCounts.Add(int.Parse(typeName.AsSpan(endIndex + 1, startIndex - endIndex - 1), provider: CultureInfo.InvariantCulture)); } - if (localName != null) + if (localName is not null) localName.Append("Of"); return nestedParamCounts; } @@ -1593,7 +1593,7 @@ internal static XmlQualifiedName CreateQualifiedName(string localName, string ns internal static string GetDefaultStableNamespace(string? clrNs) { - if (clrNs == null) clrNs = string.Empty; + if (clrNs is null) clrNs = string.Empty; return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri; } @@ -1607,7 +1607,7 @@ private static void GetDefaultStableName(CodeTypeReference typeReference, out st { string fullTypeName = typeReference.BaseType; DataContract? dataContract = GetBuiltInDataContract(fullTypeName); - if (dataContract != null) + if (dataContract is not null) { localName = dataContract.StableName.Name; ns = dataContract.StableName.Namespace; @@ -1705,13 +1705,13 @@ internal static string GetDataContractNamespaceFromUri(string uriString) { ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i]; string? clrNsInAttribute = nsAttribute.ClrNamespace; - if (clrNsInAttribute == null) + if (clrNsInAttribute is null) clrNsInAttribute = string.Empty; if (clrNsInAttribute == clrNs) { - if (nsAttribute.ContractNamespace == null) + if (nsAttribute.ContractNamespace is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGlobalDataContractNamespace, clrNs))); - if (dataContractNs != null) + if (dataContractNs is not null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.DataContractNamespaceAlreadySet, dataContractNs, nsAttribute.ContractNamespace, clrNs))); dataContractNs = nsAttribute.ContractNamespace; } @@ -1895,7 +1895,7 @@ internal static string ExpandGenericParameters(string format, IGenericNameProvid { if (nestedParameterCounts.Count > 1 || !genericNameProvider.ParametersFromBuiltInNamespaces) { - if (digest == null) + if (digest is null) { StringBuilder namespaces = new StringBuilder(genericNameProvider.GetNamespaces()); foreach (int count in nestedParameterCounts) @@ -1938,21 +1938,21 @@ internal static bool IsTypeNullable(Type type) private static void ImportKnownTypeAttributes(Type? type, Dictionary typesChecked, ref DataContractDictionary? knownDataContracts) { - while (type != null && DataContract.IsTypeSerializable(type)) + while (type is not null && DataContract.IsTypeSerializable(type)) { if (typesChecked.ContainsKey(type)) return; typesChecked.Add(type, type); object[] knownTypeAttributes = type.GetCustomAttributes(Globals.TypeOfKnownTypeAttribute, false).ToArray(); - if (knownTypeAttributes != null) + if (knownTypeAttributes is not null) { KnownTypeAttribute kt; bool useMethod = false, useType = false; for (int i = 0; i < knownTypeAttributes.Length; ++i) { kt = (KnownTypeAttribute)knownTypeAttributes[i]; - if (kt.Type != null) + if (kt.Type is not null) { if (useMethod) { @@ -1970,7 +1970,7 @@ private static void ImportKnownTypeAttributes(Type? type, Dictionary } string? methodName = kt.MethodName; - if (methodName == null) + if (methodName is null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type); } @@ -1979,21 +1979,21 @@ private static void ImportKnownTypeAttributes(Type? type, Dictionary DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type); MethodInfo? method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, Array.Empty(), null); - if (method == null) + if (method is null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type); if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType)) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type); object? types = method.Invoke(null, Array.Empty()); - if (types == null) + if (types is null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type); } foreach (Type ty in (IEnumerable)types) { - if (ty == null) + if (ty is null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeValidMethodTypes, DataContract.GetClrTypeFullName(type)), type); CheckAndAdd(ty, typesChecked, ref knownDataContracts); @@ -2008,11 +2008,11 @@ private static void ImportKnownTypeAttributes(Type? type, Dictionary try { CollectionDataContract? collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract; - if (collectionDataContract != null && collectionDataContract.IsDictionary && + if (collectionDataContract is not null && collectionDataContract.IsDictionary && collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments())); - if (knownDataContracts == null) + if (knownDataContracts is null) { knownDataContracts = new DataContractDictionary(); } @@ -2037,7 +2037,7 @@ internal static void CheckAndAdd(Type type, Dictionary typesChecked, type = DataContract.UnwrapNullableType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContract? alreadyExistingContract; - if (nameToDataContractTable == null) + if (nameToDataContractTable is null) { nameToDataContractTable = new DataContractDictionary(); } @@ -2080,7 +2080,7 @@ internal static bool IsTypeVisible(Type t) /// internal static bool ConstructorRequiresMemberAccess(ConstructorInfo? ctor) { - return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor); + return ctor is not null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor); } /// @@ -2091,7 +2091,7 @@ internal static bool ConstructorRequiresMemberAccess(ConstructorInfo? ctor) /// internal static bool MethodRequiresMemberAccess(MethodInfo? method) { - return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method); + return method is not null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method); } /// @@ -2102,7 +2102,7 @@ internal static bool MethodRequiresMemberAccess(MethodInfo? method) /// internal static bool FieldRequiresMemberAccess(FieldInfo? field) { - return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field); + return field is not null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field); } /// @@ -2250,10 +2250,10 @@ private XmlQualifiedName GetStableName(int i) { object o = _genericParams[i]; XmlQualifiedName? qname = o as XmlQualifiedName; - if (qname == null) + if (qname is null) { Type? paramType = o as Type; - if (paramType != null) + if (paramType is not null) _genericParams[i] = qname = DataContract.GetStableName(paramType); else _genericParams[i] = qname = ((DataContract)o).StableName; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs index 53a1840c9cdc13..ab04c24efcf609 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs @@ -95,7 +95,7 @@ internal DataContractSerializer(Type type, IEnumerable knownTypes, int max public DataContractSerializer(Type type, DataContractSerializerSettings? settings) { - if (settings == null) + if (settings is null) { settings = new DataContractSerializerSettings(); } @@ -115,7 +115,7 @@ private void Initialize(Type type, CheckNull(type, nameof(type)); _rootType = type; - if (knownTypes != null) + if (knownTypes is not null) { this.knownTypeList = new List(); foreach (Type knownType in knownTypes) @@ -154,9 +154,9 @@ public ReadOnlyCollection KnownTypes { get { - if (_knownTypeCollection == null) + if (_knownTypeCollection is null) { - if (knownTypeList != null) + if (knownTypeList is not null) { _knownTypeCollection = new ReadOnlyCollection(knownTypeList); } @@ -173,7 +173,7 @@ internal override DataContractDictionary? KnownDataContracts { get { - if (this.knownDataContracts == null && this.knownTypeList != null) + if (this.knownDataContracts is null && this.knownTypeList is not null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of @@ -220,9 +220,9 @@ private DataContract RootContract { get { - if (_rootContract == null) + if (_rootContract is null) { - _rootContract = DataContract.GetDataContract((_serializationSurrogateProvider == null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType)); + _rootContract = DataContract.GetDataContract((_serializationSurrogateProvider is null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType)); _needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(_rootName, _rootNamespace, _rootContract); } return _rootContract; @@ -328,17 +328,17 @@ internal void InternalWriteObjectContent(XmlWriterDelegator writer, object? grap DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; - Type graphType = (graph == null) ? declaredType : graph.GetType(); + Type graphType = (graph is null) ? declaredType : graph.GetType(); - if (_serializationSurrogateProvider != null) + if (_serializationSurrogateProvider is not null) { graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType); } - if (dataContractResolver == null) + if (dataContractResolver is null) dataContractResolver = this.DataContractResolver; - if (graph == null) + if (graph is null) { if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeNull, declaredType))); @@ -411,7 +411,7 @@ internal override void InternalWriteEndObject(XmlWriterDelegator writer) if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); - if (dataContractResolver == null) + if (dataContractResolver is null) dataContractResolver = this.DataContractResolver; if (verifyObjectName) @@ -420,7 +420,7 @@ internal override void InternalWriteEndObject(XmlWriterDelegator writer) { XmlDictionaryString? expectedName; XmlDictionaryString? expectedNs; - if (_rootName == null) + if (_rootName is null) { expectedName = RootContract.TopLevelElementName; expectedNs = RootContract.TopLevelElementNamespace; @@ -461,7 +461,7 @@ internal override bool InternalIsStartObject(XmlReaderDelegator reader) internal override Type? GetSerializeType(object? graph) { - return (graph == null) ? _rootType : graph.GetType(); + return (graph is null) ? _rootType : graph.GetType(); } internal override Type? GetDeserializeType() @@ -475,7 +475,7 @@ internal override bool InternalIsStartObject(XmlReaderDelegator reader) object? obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType); if (obj != oldObj) { - objType = obj != null ? obj.GetType() : Globals.TypeOfObject; + objType = obj is not null ? obj.GetType() : Globals.TypeOfObject; } return obj; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 69f10044954474..bb0ef16fceaf59 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -32,7 +32,7 @@ internal DataContractSet(IDataContractSurrogate dataContractSurrogate, ICollecti internal DataContractSet(DataContractSet dataContractSet) { - if (dataContractSet == null) + if (dataContractSet is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(dataContractSet))); //this.dataContractSurrogate = dataContractSet.dataContractSurrogate; @@ -44,7 +44,7 @@ internal DataContractSet(DataContractSet dataContractSet) Add(pair.Key, pair.Value); } - if (dataContractSet._processedContracts != null) + if (dataContractSet._processedContracts is not null) { foreach (KeyValuePair pair in dataContractSet._processedContracts) { @@ -57,7 +57,7 @@ private Dictionary Contracts { get { - if (_contracts == null) + if (_contracts is null) { _contracts = new Dictionary(); } @@ -69,7 +69,7 @@ private Dictionary ProcessedContracts { get { - if (_processedContracts == null) + if (_processedContracts is null) { _processedContracts = new Dictionary(); } @@ -81,7 +81,7 @@ private Hashtable SurrogateDataTable { get { - if (_surrogateDataTable == null) + if (_surrogateDataTable is null) _surrogateDataTable = new Hashtable(); return _surrogateDataTable; } @@ -120,7 +120,7 @@ internal void InternalAdd(XmlQualifiedName name, DataContract dataContract) { if (!dataContractInSet.Equals(dataContract)) { - if (dataContract.UnderlyingType == null || dataContractInSet.UnderlyingType == null) + if (dataContract.UnderlyingType is null || dataContractInSet.UnderlyingType is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.DupContractInDataContractSet, dataContract.StableName.Name, dataContract.StableName.Namespace))); else { @@ -150,26 +150,26 @@ internal void InternalAdd(XmlQualifiedName name, DataContract dataContract) private void AddClassDataContract(ClassDataContract classDataContract) { - if (classDataContract.BaseContract != null) + if (classDataContract.BaseContract is not null) { Add(classDataContract.BaseContract.StableName, classDataContract.BaseContract); } if (!classDataContract.IsISerializable) { - if (classDataContract.Members != null) + if (classDataContract.Members is not null) { for (int i = 0; i < classDataContract.Members.Count; i++) { DataMember dataMember = classDataContract.Members[i]; DataContract memberDataContract = GetMemberTypeDataContract(dataMember); #if SUPPORT_SURROGATE - if (_dataContractSurrogate != null && dataMember.MemberInfo != null) + if (_dataContractSurrogate is not null && dataMember.MemberInfo is not null) { object customData = DataContractSurrogateCaller.GetCustomDataToExport( _dataContractSurrogate, dataMember.MemberInfo, memberDataContract.UnderlyingType); - if (customData != null) + if (customData is not null) SurrogateDataTable.Add(dataMember, customData); } #endif @@ -190,7 +190,7 @@ private void AddCollectionDataContract(CollectionDataContract collectionDataCont else { DataContract itemContract = GetItemTypeDataContract(collectionDataContract); - if (itemContract != null) + if (itemContract is not null) Add(itemContract.StableName, itemContract); } AddKnownDataContracts(collectionDataContract.KnownDataContracts); @@ -203,7 +203,7 @@ private void AddXmlDataContract(XmlDataContract xmlDataContract) private void AddKnownDataContracts(DataContractDictionary? knownDataContracts) { - if (knownDataContracts != null) + if (knownDataContracts is not null) { foreach (DataContract knownDataContract in knownDataContracts.Values) { @@ -215,11 +215,11 @@ private void AddKnownDataContracts(DataContractDictionary? knownDataContracts) internal DataContract GetDataContract(Type clrType) { #if SUPPORT_SURROGATE - if (_dataContractSurrogate == null) + if (_dataContractSurrogate is null) return DataContract.GetDataContract(clrType); #endif DataContract? dataContract = DataContract.GetBuiltInDataContract(clrType); - if (dataContract != null) + if (dataContract is not null) return dataContract; #if SUPPORT_SURROGATE @@ -234,7 +234,7 @@ internal DataContract GetDataContract(Type clrType) { object customData = DataContractSurrogateCaller.GetCustomDataToExport( _dataContractSurrogate, clrType, dcType); - if (customData != null) + if (customData is not null) SurrogateDataTable.Add(dataContract, customData); } #endif @@ -247,7 +247,7 @@ internal DataContract GetMemberTypeDataContract(DataMember dataMember) if (dataMember.IsGetOnlyCollection) { #if SUPPORT_SURROGATE - if (_dataContractSurrogate != null) + if (_dataContractSurrogate is not null) { Type dcType = DataContractSurrogateCaller.GetDataContractType(_dataContractSurrogate, dataMemberType); if (dcType != dataMemberType) @@ -267,7 +267,7 @@ internal DataContract GetMemberTypeDataContract(DataMember dataMember) internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract) { - if (collectionContract.ItemType != null) + if (collectionContract.ItemType is not null) return GetDataContract(collectionContract.ItemType); return collectionContract.ItemContract; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs index 2ef49f1e56ca69..a650adaff0d5ab 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs @@ -13,7 +13,7 @@ internal static class DataContractSurrogateCaller { internal static Type GetDataContractType(ISerializationSurrogateProvider surrogateProvider, Type type) { - if (DataContract.GetBuiltInDataContract(type) != null) + if (DataContract.GetBuiltInDataContract(type) is not null) return type; return surrogateProvider.GetSurrogateType(type) ?? type; } @@ -21,9 +21,9 @@ internal static Type GetDataContractType(ISerializationSurrogateProvider surroga [return: NotNullIfNotNull("obj")] internal static object? GetObjectToSerialize(ISerializationSurrogateProvider surrogateProvider, object? obj, Type objType, Type membertype) { - if (obj == null) + if (obj is null) return null; - if (DataContract.GetBuiltInDataContract(objType) != null) + if (DataContract.GetBuiltInDataContract(objType) is not null) return obj; return surrogateProvider.GetObjectToSerialize(obj, membertype); } @@ -31,9 +31,9 @@ internal static Type GetDataContractType(ISerializationSurrogateProvider surroga [return: NotNullIfNotNull("obj")] internal static object? GetDeserializedObject(ISerializationSurrogateProvider surrogateProvider, object? obj, Type objType, Type memberType) { - if (obj == null) + if (obj is null) return null; - if (DataContract.GetBuiltInDataContract(objType) != null) + if (DataContract.GetBuiltInDataContract(objType) is not null) return obj; return surrogateProvider.GetDeserializedObject(obj, memberType); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs index 7f475094c5d8bf..e6ad0c6ebe2e7e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs @@ -124,7 +124,7 @@ internal FastInvokerBuilder.Getter Getter { get { - if (_getter == null) + if (_getter is null) { _getter = FastInvokerBuilder.CreateGetter(MemberInfo); } @@ -138,7 +138,7 @@ internal FastInvokerBuilder.Setter Setter { get { - if (_setter == null) + if (_setter is null) { _setter = FastInvokerBuilder.CreateSetter(MemberInfo); } @@ -213,10 +213,10 @@ internal Type MemberType { get { - if (_memberType == null) + if (_memberType is null) { FieldInfo? field = MemberInfo as FieldInfo; - if (field != null) + if (field is not null) _memberType = field.FieldType; else _memberType = ((PropertyInfo)MemberInfo).PropertyType; @@ -230,7 +230,7 @@ internal DataContract MemberTypeContract { get { - if (_memberTypeContract == null) + if (_memberTypeContract is null) { if (this.IsGetOnlyCollection) { @@ -287,7 +287,7 @@ internal bool RequiresMemberAccessForGet() { MemberInfo memberInfo = MemberInfo; FieldInfo? field = memberInfo as FieldInfo; - if (field != null) + if (field is not null) { return DataContract.FieldRequiresMemberAccess(field); } @@ -295,7 +295,7 @@ internal bool RequiresMemberAccessForGet() { PropertyInfo property = (PropertyInfo)memberInfo; MethodInfo? getMethod = property.GetMethod; - if (getMethod != null) + if (getMethod is not null) { return DataContract.MethodRequiresMemberAccess(getMethod) || !DataContract.IsTypeVisible(property.PropertyType); } @@ -312,7 +312,7 @@ internal bool RequiresMemberAccessForSet() { MemberInfo memberInfo = MemberInfo; FieldInfo? field = memberInfo as FieldInfo; - if (field != null) + if (field is not null) { return DataContract.FieldRequiresMemberAccess(field); } @@ -320,7 +320,7 @@ internal bool RequiresMemberAccessForSet() { PropertyInfo property = (PropertyInfo)memberInfo; MethodInfo? setMethod = property.SetMethod; - if (setMethod != null) + if (setMethod is not null) { return DataContract.MethodRequiresMemberAccess(setMethod) || !DataContract.IsTypeVisible(property.PropertyType); } 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 e6d46aac89983d..633791a8ad58f2 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 @@ -175,7 +175,7 @@ private void ImportDataMembers() if (_hasDataContract) { object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false).ToArray(); - if (memberAttributes != null && memberAttributes.Length > 0) + if (memberAttributes is not null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType!), field.Name)); @@ -184,7 +184,7 @@ private void ImportDataMembers() DataMember memberContract = new DataMember(field); if (memberAttribute.IsValueSetExplicitly) { - if (memberAttribute.Value == null || memberAttribute.Value.Length == 0) + if (memberAttribute.Value is null || memberAttribute.Value.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Value; } @@ -195,7 +195,7 @@ private void ImportDataMembers() } object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray(); - if (dataMemberAttributes != null && dataMemberAttributes.Length > 0) + if (dataMemberAttributes is not null && dataMemberAttributes.Length > 0) ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType!), field.Name)); } else @@ -363,7 +363,7 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { object obj = ReadEnumValue(xmlReader); - if (context != null) + if (context is not null) context.AddNewObject(obj); return obj; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs index c1c60b53ae75a5..33aa3aba963d44 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs @@ -27,7 +27,7 @@ public Collection KnownTypes { get { - if (_knownTypes == null) + if (_knownTypes is null) { _knownTypes = new Collection(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs index b828cab0f81f38..fe77d22c59c2ea 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs @@ -154,11 +154,11 @@ public virtual void GetData(ElementData element) element.attributeCount = 0; element.childElementIndex = 0; - if (DataContractName != null) + if (DataContractName is not null) AddQualifiedNameAttribute(element, Globals.XsiPrefix, Globals.XsiTypeLocalName, Globals.SchemaInstanceNamespace, DataContractName, DataContractNamespace); - if (ClrTypeName != null) + if (ClrTypeName is not null) element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrTypeLocalName, ClrTypeName); - if (ClrAssemblyName != null) + if (ClrAssemblyName is not null) element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, ClrAssemblyName); } @@ -174,12 +174,12 @@ internal void AddQualifiedNameAttribute(ElementData element, string elementPrefi element.AddAttribute(elementPrefix, elementNs, elementName, prefix + ":" + valueName); bool prefixDeclaredOnElement = false; - if (element.attributes != null) + if (element.attributes is not null) { for (int i = 0; i < element.attributes.Length; i++) { AttributeData attribute = element.attributes[i]; - if (attribute != null && attribute.prefix == Globals.XmlnsPrefix && attribute.localName == prefix) + if (attribute is not null && attribute.prefix == Globals.XmlnsPrefix && attribute.localName == prefix) { prefixDeclaredOnElement = true; break; @@ -335,7 +335,7 @@ public override void GetData(ElementData element) { base.GetData(element); - if (FactoryTypeName != null) + if (FactoryTypeName is not null) AddQualifiedNameAttribute(element, Globals.SerPrefix, Globals.ISerializableFactoryTypeLocalName, Globals.SerializationNamespace, FactoryTypeName, FactoryTypeNamespace); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs index 6457f16b903798..19e09e6bdecb9f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs @@ -437,7 +437,7 @@ private void PushElement() { GrowElementsIfNeeded(); _elements[_depth++] = _element; - if (_nextElement == null) + if (_nextElement is null) _element = GetNextElement(); else { @@ -457,7 +457,7 @@ private void PopElement() _depth--; - if (_elements != null) + if (_elements is not null) { _element = _elements[_depth]; } @@ -466,7 +466,7 @@ private void PopElement() [MemberNotNull(nameof(_elements))] private void GrowElementsIfNeeded() { - if (_elements == null) + if (_elements is null) _elements = new ElementData[8]; else if (_elements.Length == _depth) { @@ -479,7 +479,7 @@ private void GrowElementsIfNeeded() private ElementData? GetNextElement() { int nextDepth = _depth + 1; - return (_elements == null || _elements.Length <= nextDepth || _elements[nextDepth] == null) + return (_elements is null || _elements.Length <= nextDepth || _elements[nextDepth] is null) ? new ElementData() : _elements[nextDepth]; } @@ -487,12 +487,12 @@ internal static string GetPrefix(string? ns) { ns = ns ?? string.Empty; string? prefix = (string?)s_nsToPrefixTable[ns]; - if (prefix == null) + if (prefix is null) { lock (s_prefixLock) { prefix = (string?)s_nsToPrefixTable[ns]; - if (prefix == null) + if (prefix is null) { prefix = (ns.Length == 0) ? string.Empty : "p" + s_nsToPrefixTable.Count; AddPrefix(prefix, ns); @@ -531,7 +531,7 @@ public void AddAttribute(string prefix, string ns, string name, string? value) { GrowAttributesIfNeeded(); AttributeData attribute = attributes[attributeCount]; - if (attribute == null) + if (attribute is null) attributes[attributeCount] = attribute = new AttributeData(); attribute.prefix = prefix; attribute.ns = ns; @@ -543,7 +543,7 @@ public void AddAttribute(string prefix, string ns, string name, string? value) [MemberNotNull(nameof(attributes))] private void GrowAttributesIfNeeded() { - if (attributes == null) + if (attributes is null) attributes = new AttributeData[4]; else if (attributes.Length == attributeCount) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs index eb24db27f6a771..449c696717721f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs @@ -27,7 +27,7 @@ internal static XmlQualifiedName IdQualifiedName { get { - if (s_idQualifiedName == null) + if (s_idQualifiedName is null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } @@ -38,7 +38,7 @@ internal static XmlQualifiedName RefQualifiedName { get { - if (s_refQualifiedName == null) + if (s_refQualifiedName is null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } @@ -49,7 +49,7 @@ internal static Type TypeOfObject { get { - if (s_typeOfObject == null) + if (s_typeOfObject is null) s_typeOfObject = typeof(object); return s_typeOfObject; } @@ -60,7 +60,7 @@ internal static Type TypeOfValueType { get { - if (s_typeOfValueType == null) + if (s_typeOfValueType is null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } @@ -71,7 +71,7 @@ internal static Type TypeOfArray { get { - if (s_typeOfArray == null) + if (s_typeOfArray is null) s_typeOfArray = typeof(Array); return s_typeOfArray; } @@ -82,7 +82,7 @@ internal static Type TypeOfString { get { - if (s_typeOfString == null) + if (s_typeOfString is null) s_typeOfString = typeof(string); return s_typeOfString; } @@ -93,7 +93,7 @@ internal static Type TypeOfInt { get { - if (s_typeOfInt == null) + if (s_typeOfInt is null) s_typeOfInt = typeof(int); return s_typeOfInt; } @@ -104,7 +104,7 @@ internal static Type TypeOfULong { get { - if (s_typeOfULong == null) + if (s_typeOfULong is null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } @@ -115,7 +115,7 @@ internal static Type TypeOfVoid { get { - if (s_typeOfVoid == null) + if (s_typeOfVoid is null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } @@ -126,7 +126,7 @@ internal static Type TypeOfByteArray { get { - if (s_typeOfByteArray == null) + if (s_typeOfByteArray is null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } @@ -137,7 +137,7 @@ internal static Type TypeOfTimeSpan { get { - if (s_typeOfTimeSpan == null) + if (s_typeOfTimeSpan is null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } @@ -148,7 +148,7 @@ internal static Type TypeOfGuid { get { - if (s_typeOfGuid == null) + if (s_typeOfGuid is null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } @@ -159,7 +159,7 @@ internal static Type TypeOfDateTimeOffset { get { - if (s_typeOfDateTimeOffset == null) + if (s_typeOfDateTimeOffset is null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } @@ -170,7 +170,7 @@ internal static Type TypeOfDateTimeOffsetAdapter { get { - if (s_typeOfDateTimeOffsetAdapter == null) + if (s_typeOfDateTimeOffsetAdapter is null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } @@ -181,7 +181,7 @@ internal static Type TypeOfUri { get { - if (s_typeOfUri == null) + if (s_typeOfUri is null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } @@ -192,7 +192,7 @@ internal static Type TypeOfTypeEnumerable { get { - if (s_typeOfTypeEnumerable == null) + if (s_typeOfTypeEnumerable is null) s_typeOfTypeEnumerable = typeof(IEnumerable); return s_typeOfTypeEnumerable; } @@ -203,7 +203,7 @@ internal static Type TypeOfStreamingContext { get { - if (s_typeOfStreamingContext == null) + if (s_typeOfStreamingContext is null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } @@ -214,7 +214,7 @@ internal static Type TypeOfISerializable { get { - if (s_typeOfISerializable == null) + if (s_typeOfISerializable is null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } @@ -225,7 +225,7 @@ internal static Type TypeOfIDeserializationCallback { get { - if (s_typeOfIDeserializationCallback == null) + if (s_typeOfIDeserializationCallback is null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } @@ -236,7 +236,7 @@ internal static Type TypeOfIObjectReference { get { - if (s_typeOfIObjectReference == null) + if (s_typeOfIObjectReference is null) s_typeOfIObjectReference = typeof(IObjectReference); return s_typeOfIObjectReference; } @@ -247,7 +247,7 @@ internal static Type TypeOfXmlFormatClassWriterDelegate { get { - if (s_typeOfXmlFormatClassWriterDelegate == null) + if (s_typeOfXmlFormatClassWriterDelegate is null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } @@ -258,7 +258,7 @@ internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { - if (s_typeOfXmlFormatCollectionWriterDelegate == null) + if (s_typeOfXmlFormatCollectionWriterDelegate is null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } @@ -269,7 +269,7 @@ internal static Type TypeOfXmlFormatClassReaderDelegate { get { - if (s_typeOfXmlFormatClassReaderDelegate == null) + if (s_typeOfXmlFormatClassReaderDelegate is null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } @@ -280,7 +280,7 @@ internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { - if (s_typeOfXmlFormatCollectionReaderDelegate == null) + if (s_typeOfXmlFormatCollectionReaderDelegate is null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } @@ -291,7 +291,7 @@ internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { - if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) + if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate is null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } @@ -302,7 +302,7 @@ internal static Type TypeOfKnownTypeAttribute { get { - if (s_typeOfKnownTypeAttribute == null) + if (s_typeOfKnownTypeAttribute is null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } @@ -313,7 +313,7 @@ internal static Type TypeOfDataContractAttribute { get { - if (s_typeOfDataContractAttribute == null) + if (s_typeOfDataContractAttribute is null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } @@ -324,7 +324,7 @@ internal static Type TypeOfDataMemberAttribute { get { - if (s_typeOfDataMemberAttribute == null) + if (s_typeOfDataMemberAttribute is null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } @@ -335,7 +335,7 @@ internal static Type TypeOfEnumMemberAttribute { get { - if (s_typeOfEnumMemberAttribute == null) + if (s_typeOfEnumMemberAttribute is null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } @@ -346,7 +346,7 @@ internal static Type TypeOfCollectionDataContractAttribute { get { - if (s_typeOfCollectionDataContractAttribute == null) + if (s_typeOfCollectionDataContractAttribute is null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } @@ -357,7 +357,7 @@ internal static Type TypeOfOptionalFieldAttribute { get { - if (s_typeOfOptionalFieldAttribute == null) + if (s_typeOfOptionalFieldAttribute is null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } @@ -371,7 +371,7 @@ internal static Type TypeOfObjectArray { get { - if (s_typeOfObjectArray == null) + if (s_typeOfObjectArray is null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } @@ -382,7 +382,7 @@ internal static Type TypeOfOnSerializingAttribute { get { - if (s_typeOfOnSerializingAttribute == null) + if (s_typeOfOnSerializingAttribute is null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } @@ -393,7 +393,7 @@ internal static Type TypeOfOnSerializedAttribute { get { - if (s_typeOfOnSerializedAttribute == null) + if (s_typeOfOnSerializedAttribute is null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } @@ -404,7 +404,7 @@ internal static Type TypeOfOnDeserializingAttribute { get { - if (s_typeOfOnDeserializingAttribute == null) + if (s_typeOfOnDeserializingAttribute is null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } @@ -415,7 +415,7 @@ internal static Type TypeOfOnDeserializedAttribute { get { - if (s_typeOfOnDeserializedAttribute == null) + if (s_typeOfOnDeserializedAttribute is null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } @@ -426,7 +426,7 @@ internal static Type TypeOfFlagsAttribute { get { - if (s_typeOfFlagsAttribute == null) + if (s_typeOfFlagsAttribute is null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } @@ -437,7 +437,7 @@ internal static Type TypeOfIXmlSerializable { get { - if (s_typeOfIXmlSerializable == null) + if (s_typeOfIXmlSerializable is null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } @@ -448,7 +448,7 @@ internal static Type TypeOfXmlSchemaProviderAttribute { get { - if (s_typeOfXmlSchemaProviderAttribute == null) + if (s_typeOfXmlSchemaProviderAttribute is null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } @@ -459,7 +459,7 @@ internal static Type TypeOfXmlRootAttribute { get { - if (s_typeOfXmlRootAttribute == null) + if (s_typeOfXmlRootAttribute is null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } @@ -470,7 +470,7 @@ internal static Type TypeOfXmlQualifiedName { get { - if (s_typeOfXmlQualifiedName == null) + if (s_typeOfXmlQualifiedName is null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } @@ -481,7 +481,7 @@ internal static Type TypeOfXmlSchemaType { get { - if (s_typeOfXmlSchemaType == null) + if (s_typeOfXmlSchemaType is null) { s_typeOfXmlSchemaType = typeof(XmlSchemaType); } @@ -501,7 +501,7 @@ internal static Type TypeOfISerializableDataNode { get { - if (s_typeOfISerializableDataNode == null) + if (s_typeOfISerializableDataNode is null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } @@ -512,7 +512,7 @@ internal static Type TypeOfClassDataNode { get { - if (s_typeOfClassDataNode == null) + if (s_typeOfClassDataNode is null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } @@ -523,7 +523,7 @@ internal static Type TypeOfCollectionDataNode { get { - if (s_typeOfCollectionDataNode == null) + if (s_typeOfCollectionDataNode is null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } @@ -537,7 +537,7 @@ internal static Type TypeOfNullable { get { - if (s_typeOfNullable == null) + if (s_typeOfNullable is null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } @@ -548,7 +548,7 @@ internal static Type TypeOfIDictionaryGeneric { get { - if (s_typeOfIDictionaryGeneric == null) + if (s_typeOfIDictionaryGeneric is null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } @@ -559,7 +559,7 @@ internal static Type TypeOfIDictionary { get { - if (s_typeOfIDictionary == null) + if (s_typeOfIDictionary is null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } @@ -570,7 +570,7 @@ internal static Type TypeOfIListGeneric { get { - if (s_typeOfIListGeneric == null) + if (s_typeOfIListGeneric is null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } @@ -581,7 +581,7 @@ internal static Type TypeOfIList { get { - if (s_typeOfIList == null) + if (s_typeOfIList is null) s_typeOfIList = typeof(IList); return s_typeOfIList; } @@ -592,7 +592,7 @@ internal static Type TypeOfICollectionGeneric { get { - if (s_typeOfICollectionGeneric == null) + if (s_typeOfICollectionGeneric is null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } @@ -603,7 +603,7 @@ internal static Type TypeOfICollection { get { - if (s_typeOfICollection == null) + if (s_typeOfICollection is null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } @@ -614,7 +614,7 @@ internal static Type TypeOfIEnumerableGeneric { get { - if (s_typeOfIEnumerableGeneric == null) + if (s_typeOfIEnumerableGeneric is null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } @@ -625,7 +625,7 @@ internal static Type TypeOfIEnumerable { get { - if (s_typeOfIEnumerable == null) + if (s_typeOfIEnumerable is null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } @@ -636,7 +636,7 @@ internal static Type TypeOfIEnumeratorGeneric { get { - if (s_typeOfIEnumeratorGeneric == null) + if (s_typeOfIEnumeratorGeneric is null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } @@ -647,7 +647,7 @@ internal static Type TypeOfIEnumerator { get { - if (s_typeOfIEnumerator == null) + if (s_typeOfIEnumerator is null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } @@ -658,7 +658,7 @@ internal static Type TypeOfKeyValuePair { get { - if (s_typeOfKeyValuePair == null) + if (s_typeOfKeyValuePair is null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } @@ -669,7 +669,7 @@ internal static Type TypeOfKeyValuePairAdapter { get { - if (s_typeOfKeyValuePairAdapter == null) + if (s_typeOfKeyValuePairAdapter is null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } @@ -680,7 +680,7 @@ internal static Type TypeOfKeyValue { get { - if (s_typeOfKeyValue == null) + if (s_typeOfKeyValue is null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } @@ -691,7 +691,7 @@ internal static Type TypeOfIDictionaryEnumerator { get { - if (s_typeOfIDictionaryEnumerator == null) + if (s_typeOfIDictionaryEnumerator is null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } @@ -702,7 +702,7 @@ internal static Type TypeOfDictionaryEnumerator { get { - if (s_typeOfDictionaryEnumerator == null) + if (s_typeOfDictionaryEnumerator is null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } @@ -713,7 +713,7 @@ internal static Type TypeOfGenericDictionaryEnumerator { get { - if (s_typeOfGenericDictionaryEnumerator == null) + if (s_typeOfGenericDictionaryEnumerator is null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } @@ -724,7 +724,7 @@ internal static Type TypeOfDictionaryGeneric { get { - if (s_typeOfDictionaryGeneric == null) + if (s_typeOfDictionaryGeneric is null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } @@ -735,7 +735,7 @@ internal static Type TypeOfHashtable { get { - if (s_typeOfHashtable == null) + if (s_typeOfHashtable is null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } @@ -746,7 +746,7 @@ internal static Type TypeOfXmlElement { get { - if (s_typeOfXmlElement == null) + if (s_typeOfXmlElement is null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } @@ -757,7 +757,7 @@ internal static Type TypeOfXmlNodeArray { get { - if (s_typeOfXmlNodeArray == null) + if (s_typeOfXmlNodeArray is null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } @@ -768,7 +768,7 @@ internal static Type TypeOfDBNull { get { - if (s_typeOfDBNull == null) + if (s_typeOfDBNull is null) s_typeOfDBNull = typeof(DBNull); return s_typeOfDBNull; } @@ -779,7 +779,7 @@ internal static Uri DataContractXsdBaseNamespaceUri { get { - if (s_dataContractXsdBaseNamespaceUri == null) + if (s_dataContractXsdBaseNamespaceUri is null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } @@ -789,13 +789,13 @@ internal static Uri DataContractXsdBaseNamespaceUri internal static ClassDataContract CreateScriptObjectClassDataContract() { - Debug.Assert(s_typeOfScriptObject != null); + Debug.Assert(s_typeOfScriptObject is not null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { - return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); + return s_typeOfScriptObject is not null && s_typeOfScriptObject.IsAssignableFrom(type); } public const bool DefaultIsRequired = false; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs index 035f1556b67a8b..1365089a01ead2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs @@ -19,7 +19,7 @@ internal HybridObjectCache() internal void Add(string id, object? obj) { - if (_objectDictionary == null) + if (_objectDictionary is null) _objectDictionary = new Dictionary(); object? existingObject; @@ -30,13 +30,13 @@ internal void Add(string id, object? obj) internal void Remove(string id) { - if (_objectDictionary != null) + if (_objectDictionary is not null) _objectDictionary.Remove(id); } internal object? GetObject(string id) { - if (_referencedObjectDictionary == null) + if (_referencedObjectDictionary is null) { _referencedObjectDictionary = new Dictionary(); _referencedObjectDictionary.Add(id, null); @@ -46,7 +46,7 @@ internal void Remove(string id) _referencedObjectDictionary.TryAdd(id, null); } - if (_objectDictionary != null) + if (_objectDictionary is not null) { object? obj; _objectDictionary.TryGetValue(id, out obj); @@ -58,7 +58,7 @@ internal void Remove(string id) internal bool IsObjectReferenced(string id) { - if (_referencedObjectDictionary != null) + if (_referencedObjectDictionary is not null) { return _referencedObjectDictionary.ContainsKey(id); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs index 604040e59e8db2..506dfab2ae0e25 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs @@ -84,9 +84,9 @@ public ReadOnlyCollection KnownTypes { get { - if (_knownTypeCollection == null) + if (_knownTypeCollection is null) { - if (knownTypeList != null) + if (knownTypeList is not null) { _knownTypeCollection = new ReadOnlyCollection(knownTypeList); } @@ -103,7 +103,7 @@ internal override DataContractDictionary? KnownDataContracts { get { - if (this.knownDataContracts == null && this.knownTypeList != null) + if (this.knownDataContracts is null && this.knownTypeList is not null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of @@ -210,16 +210,16 @@ public override void WriteObject(XmlDictionaryWriter writer, object? graph) private List GetKnownTypesFromContext(XmlObjectSerializerContext context, IList? serializerKnownTypeList) { List knownTypesList = new List(); - if (context != null) + if (context is not null) { List stableNames = new List(); Dictionary[] entries = context.scopedKnownTypes.dataContractDictionaries; - if (entries != null) + if (entries is not null) { for (int i = 0; i < entries.Length; i++) { Dictionary entry = entries[i]; - if (entry != null) + if (entry is not null) { foreach (KeyValuePair pair in entry) { @@ -232,7 +232,7 @@ private List GetKnownTypesFromContext(XmlObjectSerializerContext context, } } } - if (serializerKnownTypeList != null) + if (serializerKnownTypeList is not null) { knownTypesList.AddRange(serializerKnownTypeList); } @@ -244,9 +244,9 @@ internal static void InvokeOnSerializing(object value, DataContract contract, Xm { if (contract is ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerializing(value, classContract.BaseContract, context); - if (classContract.OnSerializing != null) + if (classContract.OnSerializing is not null) { bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try @@ -266,7 +266,7 @@ internal static void InvokeOnSerializing(object value, DataContract contract, Xm } catch (TargetInvocationException targetInvocationException) { - if (targetInvocationException.InnerException == null) + if (targetInvocationException.InnerException is null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers @@ -280,9 +280,9 @@ internal static void InvokeOnSerialized(object value, DataContract contract, Xml { if (contract is ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerialized(value, classContract.BaseContract, context); - if (classContract.OnSerialized != null) + if (classContract.OnSerialized is not null) { bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try @@ -302,7 +302,7 @@ internal static void InvokeOnSerialized(object value, DataContract contract, Xml } catch (TargetInvocationException targetInvocationException) { - if (targetInvocationException.InnerException == null) + if (targetInvocationException.InnerException is null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers @@ -316,9 +316,9 @@ internal static void InvokeOnDeserializing(object value, DataContract contract, { if (contract is ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserializing(value, classContract.BaseContract, context); - if (classContract.OnDeserializing != null) + if (classContract.OnDeserializing is not null) { bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try @@ -338,7 +338,7 @@ internal static void InvokeOnDeserializing(object value, DataContract contract, } catch (TargetInvocationException targetInvocationException) { - if (targetInvocationException.InnerException == null) + if (targetInvocationException.InnerException is null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers @@ -352,9 +352,9 @@ internal static void InvokeOnDeserialized(object value, DataContract contract, X { if (contract is ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserialized(value, classContract.BaseContract, context); - if (classContract.OnDeserialized != null) + if (classContract.OnDeserialized is not null) { bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try @@ -374,7 +374,7 @@ internal static void InvokeOnDeserialized(object value, DataContract contract, X } catch (TargetInvocationException targetInvocationException) { - if (targetInvocationException.InnerException == null) + if (targetInvocationException.InnerException is null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers @@ -392,7 +392,7 @@ internal static bool CharacterNeedsEscaping(char ch) internal static bool CheckIfJsonNameRequiresMapping(string jsonName) { - if (jsonName != null) + if (jsonName is not null) { if (!DataContract.IsValidNCName(jsonName)) { @@ -412,7 +412,7 @@ internal static bool CheckIfJsonNameRequiresMapping(string jsonName) internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) { - return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); + return (jsonName is null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } internal static string ConvertXmlNameToJsonName(string xmlName) @@ -422,7 +422,7 @@ internal static string ConvertXmlNameToJsonName(string xmlName) internal static XmlDictionaryString? ConvertXmlNameToJsonName(XmlDictionaryString? xmlName) { - return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); + return (xmlName is null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static object? ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) @@ -525,12 +525,12 @@ internal DataContractJsonSerializerImpl(Type type, public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings? settings) { - if (settings == null) + if (settings is null) { settings = new DataContractJsonSerializerSettings(); } - XmlDictionaryString? rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); + XmlDictionaryString? rootName = (settings.RootName is null) ? null : new XmlDictionary(1).Add(settings.RootName); Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat); } @@ -539,9 +539,9 @@ public ReadOnlyCollection KnownTypes { get { - if (_knownTypeCollection == null) + if (_knownTypeCollection is null) { - if (knownTypeList != null) + if (knownTypeList is not null) { _knownTypeCollection = new ReadOnlyCollection(knownTypeList); } @@ -558,7 +558,7 @@ internal override DataContractDictionary? KnownDataContracts { get { - if (this.knownDataContracts == null && this.knownTypeList != null) + if (this.knownDataContracts is null && this.knownTypeList is not null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of @@ -619,7 +619,7 @@ private DataContract RootContract { get { - if (_rootContract == null) + if (_rootContract is null) { _rootContract = DataContract.GetDataContract(_rootType); CheckIfTypeIsReference(_rootContract); @@ -729,7 +729,7 @@ public override void WriteStartObject(XmlDictionaryWriter writer, object? graph) internal static bool CheckIfJsonNameRequiresMapping(string? jsonName) { - if (jsonName != null) + if (jsonName is not null) { if (!DataContract.IsValidNCName(jsonName)) { @@ -749,17 +749,17 @@ internal static bool CheckIfJsonNameRequiresMapping(string? jsonName) internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString? jsonName) { - return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); + return (jsonName is null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } internal static bool CheckIfXmlNameRequiresMapping(string xmlName) { - return (xmlName == null) ? false : CheckIfJsonNameRequiresMapping(ConvertXmlNameToJsonName(xmlName)); + return (xmlName is null) ? false : CheckIfJsonNameRequiresMapping(ConvertXmlNameToJsonName(xmlName)); } internal static bool CheckIfXmlNameRequiresMapping(XmlDictionaryString xmlName) { - return (xmlName == null) ? false : CheckIfXmlNameRequiresMapping(xmlName.Value); + return (xmlName is null) ? false : CheckIfXmlNameRequiresMapping(xmlName.Value); } internal static string ConvertXmlNameToJsonName(string xmlName) @@ -770,7 +770,7 @@ internal static string ConvertXmlNameToJsonName(string xmlName) [return: NotNullIfNotNull("xmlName")] internal static XmlDictionaryString? ConvertXmlNameToJsonName(XmlDictionaryString? xmlName) { - return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); + return (xmlName is null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName) @@ -805,7 +805,7 @@ internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegato internal override Type? GetSerializeType(object? graph) { - return (graph == null) ? _rootType : graph.GetType(); + return (graph is null) ? _rootType : graph.GetType(); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) @@ -868,14 +868,14 @@ internal override void InternalWriteObjectContent(XmlWriterDelegator writer, obj DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; - Type graphType = (graph == null) ? declaredType : graph.GetType(); + Type graphType = (graph is null) ? declaredType : graph.GetType(); - //if (dataContractSurrogate != null) + //if (dataContractSurrogate is not null) //{ // graph = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, graph, declaredType, ref graphType); //} - if (graph == null) + if (graph is null) { WriteJsonNull(writer); } @@ -952,13 +952,13 @@ private void Initialize(Type type, CheckNull(type, nameof(type)); _rootType = type; - if (knownTypes != null) + if (knownTypes is not null) { this.knownTypeList = new List(); foreach (Type knownType in knownTypes) { this.knownTypeList.Add(knownType); - if (knownType != null) + if (knownType is not null) { AddCollectionItemTypeToKnownTypes(knownType); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs index 81057315deb584..f583464420c41e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs @@ -34,12 +34,12 @@ public DateTimeFormat(string formatString) : this(formatString, DateTimeFormatIn /// Specifies the formatProvider to be used. public DateTimeFormat(string formatString, IFormatProvider formatProvider) { - if (formatString == null) + if (formatString is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(formatString)); } - if (formatProvider == null) + if (formatProvider is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(formatProvider)); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs index 19ac60805082e0..6f9a771f24be69 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs @@ -18,7 +18,7 @@ public JsonByteArrayDataContract(ByteArrayDataContract traditionalByteArrayDataC public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsBase64(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs index 13e8a4031810fc..151261ac362b00 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs @@ -28,11 +28,11 @@ internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate { get { - if (_helper.JsonFormatReaderDelegate == null) + if (_helper.JsonFormatReaderDelegate is null) { lock (this) { - if (_helper.JsonFormatReaderDelegate == null) + if (_helper.JsonFormatReaderDelegate is null) { JsonFormatClassReaderDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) @@ -62,11 +62,11 @@ internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate { get { - if (_helper.JsonFormatWriterDelegate == null) + if (_helper.JsonFormatWriterDelegate is null) { lock (this) { - if (_helper.JsonFormatWriterDelegate == null) + if (_helper.JsonFormatWriterDelegate is null) { JsonFormatClassWriterDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) @@ -103,7 +103,7 @@ internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { - Debug.Assert(context != null); + Debug.Assert(context is not null); jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString); JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalClassDataContract, MemberNames); } @@ -148,7 +148,7 @@ internal ClassDataContract TraditionalClassDataContract private void CopyMembersAndCheckDuplicateNames() { - if (_traditionalClassDataContract.MemberNames != null) + if (_traditionalClassDataContract.MemberNames is not null) { int memberCount = _traditionalClassDataContract.MemberNames.Length; Dictionary memberTable = new Dictionary(memberCount); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs index 3374eb79c89eec..045ceba758408b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs @@ -28,11 +28,11 @@ internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate { get { - if (_helper.JsonFormatReaderDelegate == null) + if (_helper.JsonFormatReaderDelegate is null) { lock (this) { - if (_helper.JsonFormatReaderDelegate == null) + if (_helper.JsonFormatReaderDelegate is null) { JsonFormatCollectionReaderDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) @@ -62,11 +62,11 @@ internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelega { get { - if (_helper.JsonFormatGetOnlyReaderDelegate == null) + if (_helper.JsonFormatGetOnlyReaderDelegate is null) { lock (this) { - if (_helper.JsonFormatGetOnlyReaderDelegate == null) + if (_helper.JsonFormatGetOnlyReaderDelegate is null) { CollectionKind kind = this.TraditionalCollectionDataContract.Kind; if (this.TraditionalDataContract.UnderlyingType.IsInterface && (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)) @@ -103,11 +103,11 @@ internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate { get { - if (_helper.JsonFormatWriterDelegate == null) + if (_helper.JsonFormatWriterDelegate is null) { lock (this) { - if (_helper.JsonFormatWriterDelegate == null) + if (_helper.JsonFormatWriterDelegate is null) { JsonFormatCollectionWriterDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) @@ -132,7 +132,7 @@ internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); jsonReader.Read(); object? o = null; @@ -152,7 +152,7 @@ internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { - Debug.Assert(context != null); + Debug.Assert(context is not null); // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs index f0ad3d71763c14..c781d7e4801519 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs @@ -44,7 +44,7 @@ protected JsonDataContract(JsonDataContractCriticalHelper helper) internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); - if (result == null) + if (result is null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType)); } @@ -111,18 +111,18 @@ protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) protected void PopKnownDataContracts(XmlObjectSerializerContext? context) { - if (KnownDataContracts != null) + if (KnownDataContracts is not null) { - Debug.Assert(context != null); + Debug.Assert(context is not null); context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext? context) { - if (KnownDataContracts != null) + if (KnownDataContracts is not null) { - Debug.Assert(context != null); + Debug.Assert(context is not null); context.scopedKnownTypes.Push(KnownDataContracts); } } @@ -158,7 +158,7 @@ public static JsonDataContract GetJsonDataContract(DataContract traditionalDataC { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; @@ -204,7 +204,7 @@ private static JsonDataContract CreateJsonDataContract(int id, DataContract trad lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; - if (dataContract == null) + if (dataContract is null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) @@ -264,15 +264,15 @@ private static JsonDataContract CreateJsonDataContract(int id, DataContract trad private void AddCollectionItemContractsToKnownDataContracts() { - if (_traditionalDataContract.KnownDataContracts != null) + if (_traditionalDataContract.KnownDataContracts is not null) { foreach (KeyValuePair knownDataContract in _traditionalDataContract.KnownDataContracts) { CollectionDataContract? collectionDataContract = knownDataContract.Value as CollectionDataContract; - while (collectionDataContract != null) + while (collectionDataContract is not null) { DataContract itemContract = collectionDataContract.ItemContract; - if (_knownDataContracts == null) + if (_knownDataContracts is null) { _knownDataContracts = new Dictionary(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs index 939f83ba5b23e6..484ad8e03093ed 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs @@ -44,7 +44,7 @@ public JsonEncodingStreamWrapper(Stream stream, Encoding? encoding, bool isReade } else { - if (encoding == null) + if (encoding is null) { throw new ArgumentNullException(nameof(encoding)); } @@ -188,8 +188,8 @@ public override int Read(byte[] buffer, int offset, int count) return _stream.Read(buffer, offset, count); } - Debug.Assert(_bytes != null); - Debug.Assert(_chars != null); + Debug.Assert(_bytes is not null); + Debug.Assert(_chars is not null); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); @@ -257,8 +257,8 @@ public override void Write(byte[] buffer, int offset, int count) return; } - Debug.Assert(_bytes != null); - Debug.Assert(_chars != null); + Debug.Assert(_bytes is not null); + Debug.Assert(_chars is not null); while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; @@ -301,7 +301,7 @@ private static string GetEncodingName(SupportedEncoding enc) => private static SupportedEncoding GetSupportedEncoding(Encoding? encoding) { - if (encoding == null) + if (encoding is null) { return SupportedEncoding.None; } @@ -352,7 +352,7 @@ private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, Supp private void CleanupCharBreak() { - Debug.Assert(_bytes != null); + Debug.Assert(_bytes is not null); int max = _byteOffset + _byteCount; @@ -398,7 +398,7 @@ private void CleanupCharBreak() private void EnsureBuffers() { EnsureByteBuffer(); - if (_chars == null) + if (_chars is null) { _chars = new char[BufferLength]; } @@ -407,7 +407,7 @@ private void EnsureBuffers() [MemberNotNull(nameof(_bytes))] private void EnsureByteBuffer() { - if (_bytes != null) + if (_bytes is not null) { return; } @@ -419,7 +419,7 @@ private void EnsureByteBuffer() private void FillBuffer(int count) { - Debug.Assert(_bytes != null); + Debug.Assert(_bytes is not null); count -= _byteCount; while (count > 0) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs index f169cf1488ba59..b25a075bdbfd8c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs @@ -27,7 +27,7 @@ public JsonEnumDataContract(EnumDataContract traditionalDataContract) enumValue = Enum.ToObject(TraditionalDataContract.UnderlyingType, jsonReader.ReadElementContentAsLong()); } - if (context != null) + if (context is not null) { context.AddNewObject(enumValue); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs index 2ed0acc31cd188..a8521e7a019a0f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs @@ -84,10 +84,10 @@ public static PropertyInfo CollectionItemNameProperty { get { - if (s_collectionItemNameProperty == null) + if (s_collectionItemNameProperty is null) { s_collectionItemNameProperty = typeof(XmlObjectSerializerWriteContextComplexJson).GetProperty("CollectionItemName", Globals.ScanAllMembers); - Debug.Assert(s_collectionItemNameProperty != null); + Debug.Assert(s_collectionItemNameProperty is not null); } return s_collectionItemNameProperty; @@ -105,10 +105,10 @@ public static MethodInfo GetCurrentMethod { get { - if (s_ienumeratorGetCurrentMethod == null) + if (s_ienumeratorGetCurrentMethod is null) { s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current")!.GetGetMethod(); - Debug.Assert(s_ienumeratorGetCurrentMethod != null); + Debug.Assert(s_ienumeratorGetCurrentMethod is not null); } return s_ienumeratorGetCurrentMethod; } @@ -117,10 +117,10 @@ public static MethodInfo GetItemContractMethod { get { - if (s_getItemContractMethod == null) + if (s_getItemContractMethod is null) { s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers)!.GetGetMethod(nonPublic: true); - Debug.Assert(s_getItemContractMethod != null); + Debug.Assert(s_getItemContractMethod is not null); } return s_getItemContractMethod; } @@ -129,10 +129,10 @@ public static MethodInfo GetJsonDataContractMethod { get { - if (s_getJsonDataContractMethod == null) + if (s_getJsonDataContractMethod is null) { s_getJsonDataContractMethod = typeof(JsonDataContract).GetMethod("GetJsonDataContract", Globals.ScanAllMembers); - Debug.Assert(s_getJsonDataContractMethod != null); + Debug.Assert(s_getJsonDataContractMethod is not null); } return s_getJsonDataContractMethod; } @@ -141,10 +141,10 @@ public static MethodInfo GetJsonMemberIndexMethod { get { - if (s_getJsonMemberIndexMethod == null) + if (s_getJsonMemberIndexMethod is null) { s_getJsonMemberIndexMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("GetJsonMemberIndex", Globals.ScanAllMembers); - Debug.Assert(s_getJsonMemberIndexMethod != null); + Debug.Assert(s_getJsonMemberIndexMethod is not null); } return s_getJsonMemberIndexMethod; } @@ -153,10 +153,10 @@ public static MethodInfo GetRevisedItemContractMethod { get { - if (s_getRevisedItemContractMethod == null) + if (s_getRevisedItemContractMethod is null) { s_getRevisedItemContractMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("GetRevisedItemContract", Globals.ScanAllMembers); - Debug.Assert(s_getRevisedItemContractMethod != null); + Debug.Assert(s_getRevisedItemContractMethod is not null); } return s_getRevisedItemContractMethod; } @@ -165,10 +165,10 @@ public static MethodInfo GetUninitializedObjectMethod { get { - if (s_getUninitializedObjectMethod == null) + if (s_getUninitializedObjectMethod is null) { s_getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", Globals.ScanAllMembers, null, new Type[] { typeof(Type) }, null); - Debug.Assert(s_getUninitializedObjectMethod != null); + Debug.Assert(s_getUninitializedObjectMethod is not null); } return s_getUninitializedObjectMethod; } @@ -178,10 +178,10 @@ public static MethodInfo IsStartElementMethod0 { get { - if (s_isStartElementMethod0 == null) + if (s_isStartElementMethod0 is null) { s_isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, null, Array.Empty(), null); - Debug.Assert(s_isStartElementMethod0 != null); + Debug.Assert(s_isStartElementMethod0 is not null); } return s_isStartElementMethod0; } @@ -190,10 +190,10 @@ public static MethodInfo IsStartElementMethod2 { get { - if (s_isStartElementMethod2 == null) + if (s_isStartElementMethod2 is null) { s_isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, null, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); - Debug.Assert(s_isStartElementMethod2 != null); + Debug.Assert(s_isStartElementMethod2 is not null); } return s_isStartElementMethod2; } @@ -202,10 +202,10 @@ public static PropertyInfo LocalNameProperty { get { - if (s_localNameProperty == null) + if (s_localNameProperty is null) { s_localNameProperty = typeof(XmlReaderDelegator).GetProperty("LocalName", Globals.ScanAllMembers); - Debug.Assert(s_localNameProperty != null); + Debug.Assert(s_localNameProperty is not null); } return s_localNameProperty; } @@ -214,10 +214,10 @@ public static PropertyInfo NamespaceProperty { get { - if (s_namespaceProperty == null) + if (s_namespaceProperty is null) { s_namespaceProperty = typeof(XmlReaderDelegator).GetProperty("NamespaceProperty", Globals.ScanAllMembers); - Debug.Assert(s_namespaceProperty != null); + Debug.Assert(s_namespaceProperty is not null); } return s_namespaceProperty; } @@ -226,10 +226,10 @@ public static MethodInfo MoveNextMethod { get { - if (s_ienumeratorMoveNextMethod == null) + if (s_ienumeratorMoveNextMethod is null) { s_ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext"); - Debug.Assert(s_ienumeratorMoveNextMethod != null); + Debug.Assert(s_ienumeratorMoveNextMethod is not null); } return s_ienumeratorMoveNextMethod; } @@ -238,10 +238,10 @@ public static MethodInfo MoveToContentMethod { get { - if (s_moveToContentMethod == null) + if (s_moveToContentMethod is null) { s_moveToContentMethod = typeof(XmlReaderDelegator).GetMethod("MoveToContent", Globals.ScanAllMembers); - Debug.Assert(s_moveToContentMethod != null); + Debug.Assert(s_moveToContentMethod is not null); } return s_moveToContentMethod; } @@ -250,10 +250,10 @@ public static PropertyInfo NodeTypeProperty { get { - if (s_nodeTypeProperty == null) + if (s_nodeTypeProperty is null) { s_nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", Globals.ScanAllMembers); - Debug.Assert(s_nodeTypeProperty != null); + Debug.Assert(s_nodeTypeProperty is not null); } return s_nodeTypeProperty; } @@ -262,10 +262,10 @@ public static MethodInfo OnDeserializationMethod { get { - if (s_onDeserializationMethod == null) + if (s_onDeserializationMethod is null) { s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization"); - Debug.Assert(s_onDeserializationMethod != null); + Debug.Assert(s_onDeserializationMethod is not null); } return s_onDeserializationMethod; } @@ -274,10 +274,10 @@ public static MethodInfo ReadJsonValueMethod { get { - if (s_readJsonValueMethod == null) + if (s_readJsonValueMethod is null) { s_readJsonValueMethod = typeof(DataContractJsonSerializer).GetMethod("ReadJsonValue", Globals.ScanAllMembers); - Debug.Assert(s_readJsonValueMethod != null); + Debug.Assert(s_readJsonValueMethod is not null); } return s_readJsonValueMethod; } @@ -286,10 +286,10 @@ public static ConstructorInfo SerializationExceptionCtor { get { - if (s_serializationExceptionCtor == null) + if (s_serializationExceptionCtor is null) { s_serializationExceptionCtor = typeof(SerializationException).GetConstructor(new Type[] { typeof(string) }); - Debug.Assert(s_serializationExceptionCtor != null); + Debug.Assert(s_serializationExceptionCtor is not null); } return s_serializationExceptionCtor; } @@ -298,7 +298,7 @@ public static Type[] SerInfoCtorArgs { get { - if (s_serInfoCtorArgs == null) + if (s_serInfoCtorArgs is null) { s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; } @@ -309,10 +309,10 @@ public static MethodInfo ThrowDuplicateMemberExceptionMethod { get { - if (s_throwDuplicateMemberExceptionMethod == null) + if (s_throwDuplicateMemberExceptionMethod is null) { s_throwDuplicateMemberExceptionMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("ThrowDuplicateMemberException", Globals.ScanAllMembers); - Debug.Assert(s_throwDuplicateMemberExceptionMethod != null); + Debug.Assert(s_throwDuplicateMemberExceptionMethod is not null); } return s_throwDuplicateMemberExceptionMethod; } @@ -321,10 +321,10 @@ public static MethodInfo ThrowMissingRequiredMembersMethod { get { - if (s_throwMissingRequiredMembersMethod == null) + if (s_throwMissingRequiredMembersMethod is null) { s_throwMissingRequiredMembersMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("ThrowMissingRequiredMembers", Globals.ScanAllMembers); - Debug.Assert(s_throwMissingRequiredMembersMethod != null); + Debug.Assert(s_throwMissingRequiredMembersMethod is not null); } return s_throwMissingRequiredMembersMethod; } @@ -333,10 +333,10 @@ public static PropertyInfo TypeHandleProperty { get { - if (s_typeHandleProperty == null) + if (s_typeHandleProperty is null) { s_typeHandleProperty = typeof(Type).GetProperty("TypeHandle"); - Debug.Assert(s_typeHandleProperty != null); + Debug.Assert(s_typeHandleProperty is not null); } return s_typeHandleProperty; } @@ -345,10 +345,10 @@ public static PropertyInfo UseSimpleDictionaryFormatReadProperty { get { - if (s_useSimpleDictionaryFormatReadProperty == null) + if (s_useSimpleDictionaryFormatReadProperty is null) { s_useSimpleDictionaryFormatReadProperty = typeof(XmlObjectSerializerReadContextComplexJson).GetProperty("UseSimpleDictionaryFormat", Globals.ScanAllMembers); - Debug.Assert(s_useSimpleDictionaryFormatReadProperty != null); + Debug.Assert(s_useSimpleDictionaryFormatReadProperty is not null); } return s_useSimpleDictionaryFormatReadProperty; } @@ -357,10 +357,10 @@ public static PropertyInfo UseSimpleDictionaryFormatWriteProperty { get { - if (s_useSimpleDictionaryFormatWriteProperty == null) + if (s_useSimpleDictionaryFormatWriteProperty is null) { s_useSimpleDictionaryFormatWriteProperty = typeof(XmlObjectSerializerWriteContextComplexJson).GetProperty("UseSimpleDictionaryFormat", Globals.ScanAllMembers); - Debug.Assert(s_useSimpleDictionaryFormatWriteProperty != null); + Debug.Assert(s_useSimpleDictionaryFormatWriteProperty is not null); } return s_useSimpleDictionaryFormatWriteProperty; } @@ -369,10 +369,10 @@ public static MethodInfo WriteAttributeStringMethod { get { - if (s_writeAttributeStringMethod == null) + if (s_writeAttributeStringMethod is null) { s_writeAttributeStringMethod = typeof(XmlWriterDelegator).GetMethod("WriteAttributeString", Globals.ScanAllMembers, null, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string) }, null); - Debug.Assert(s_writeAttributeStringMethod != null); + Debug.Assert(s_writeAttributeStringMethod is not null); } return s_writeAttributeStringMethod; } @@ -381,10 +381,10 @@ public static MethodInfo WriteEndElementMethod { get { - if (s_writeEndElementMethod == null) + if (s_writeEndElementMethod is null) { s_writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", Globals.ScanAllMembers, null, Array.Empty(), null); - Debug.Assert(s_writeEndElementMethod != null); + Debug.Assert(s_writeEndElementMethod is not null); } return s_writeEndElementMethod; } @@ -393,10 +393,10 @@ public static MethodInfo WriteJsonISerializableMethod { get { - if (s_writeJsonISerializableMethod == null) + if (s_writeJsonISerializableMethod is null) { s_writeJsonISerializableMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("WriteJsonISerializable", Globals.ScanAllMembers); - Debug.Assert(s_writeJsonISerializableMethod != null); + Debug.Assert(s_writeJsonISerializableMethod is not null); } return s_writeJsonISerializableMethod; } @@ -405,10 +405,10 @@ public static MethodInfo WriteJsonNameWithMappingMethod { get { - if (s_writeJsonNameWithMappingMethod == null) + if (s_writeJsonNameWithMappingMethod is null) { s_writeJsonNameWithMappingMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("WriteJsonNameWithMapping", Globals.ScanAllMembers); - Debug.Assert(s_writeJsonNameWithMappingMethod != null); + Debug.Assert(s_writeJsonNameWithMappingMethod is not null); } return s_writeJsonNameWithMappingMethod; } @@ -417,10 +417,10 @@ public static MethodInfo WriteJsonValueMethod { get { - if (s_writeJsonValueMethod == null) + if (s_writeJsonValueMethod is null) { s_writeJsonValueMethod = typeof(DataContractJsonSerializer).GetMethod("WriteJsonValue", Globals.ScanAllMembers); - Debug.Assert(s_writeJsonValueMethod != null); + Debug.Assert(s_writeJsonValueMethod is not null); } return s_writeJsonValueMethod; } @@ -429,10 +429,10 @@ public static MethodInfo WriteStartElementMethod { get { - if (s_writeStartElementMethod == null) + if (s_writeStartElementMethod is null) { s_writeStartElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, null, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); - Debug.Assert(s_writeStartElementMethod != null); + Debug.Assert(s_writeStartElementMethod is not null); } return s_writeStartElementMethod; } @@ -442,10 +442,10 @@ public static MethodInfo WriteStartElementStringMethod { get { - if (s_writeStartElementStringMethod == null) + if (s_writeStartElementStringMethod is null) { s_writeStartElementStringMethod = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, null, new Type[] { typeof(string), typeof(string) }, null); - Debug.Assert(s_writeStartElementStringMethod != null); + Debug.Assert(s_writeStartElementStringMethod is not null); } return s_writeStartElementStringMethod; } @@ -455,10 +455,10 @@ public static MethodInfo ParseEnumMethod { get { - if (s_parseEnumMethod == null) + if (s_parseEnumMethod is null) { s_parseEnumMethod = typeof(Enum).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(Type), typeof(string) }, null); - Debug.Assert(s_parseEnumMethod != null); + Debug.Assert(s_parseEnumMethod is not null); } return s_parseEnumMethod; } @@ -468,10 +468,10 @@ public static MethodInfo GetJsonMemberNameMethod { get { - if (s_getJsonMemberNameMethod == null) + if (s_getJsonMemberNameMethod is null) { s_getJsonMemberNameMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("GetJsonMemberName", Globals.ScanAllMembers, null, new Type[] { typeof(XmlReaderDelegator) }, null); - Debug.Assert(s_getJsonMemberNameMethod != null); + Debug.Assert(s_getJsonMemberNameMethod is not null); } return s_getJsonMemberNameMethod; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs index 477ad9a7bb487a..707b837850e07a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs @@ -217,9 +217,9 @@ private void CreateObject(ClassDataContract classContract) private void InvokeOnDeserializing(ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserializing(classContract.BaseContract); - if (classContract.OnDeserializing != null) + if (classContract.OnDeserializing is not null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); @@ -231,9 +231,9 @@ private void InvokeOnDeserializing(ClassDataContract classContract) private void InvokeOnDeserialized(ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserialized(classContract.BaseContract); - if (classContract.OnDeserialized != null) + if (classContract.OnDeserialized is not null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); @@ -274,10 +274,10 @@ private void ReadClass(ClassDataContract classContract) ReadMembers(classContract, extensionDataLocal); ClassDataContract? currentContract = classContract; - while (currentContract != null) + while (currentContract is not null) { MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod; - if (extensionDataSetMethod != null) + if (extensionDataSetMethod is not null) _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; } @@ -338,7 +338,7 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensio private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expectedElements, Label[] memberLabels, Label throwDuplicateMemberLabel, LocalBuilder memberIndexLocal) { - int memberCount = (classContract.BaseContract == null) ? 0 : + int memberCount = (classContract.BaseContract is null) ? 0 : ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal); for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) @@ -401,7 +401,7 @@ private void LoadArray(byte[] array, string name) private int SetRequiredElements(ClassDataContract contract, byte[] requiredElements) { - int memberCount = (contract.BaseContract == null) ? 0 : + int memberCount = (contract.BaseContract is null) ? 0 : SetRequiredElements(contract.BaseContract, requiredElements); List members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) @@ -431,7 +431,7 @@ private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index private void ReadISerializable(ClassDataContract classContract) { ConstructorInfo? ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null); - if (ctor == null) + if (ctor is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType)))); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); @@ -453,7 +453,7 @@ private LocalBuilder ReadValue(Type type, string name) } PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); - if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) + if ((primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); @@ -492,7 +492,7 @@ private LocalBuilder ReadValue(Type type, string name) value = _ilg.DeclareLocal(type, "innerValueRead"); } - if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) + if (primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { _ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod); _ilg.Stloc(value); @@ -515,7 +515,7 @@ private LocalBuilder ReadValue(Type type, string name) } _ilg.EndIf(); - if (nullableValue != null) + if (nullableValue is not null) { _ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); @@ -647,7 +647,7 @@ private void ReadCollection(CollectionDataContract collectionContract) LocalBuilder value = ReadCollectionItem(collectionContract, itemType); if (isArray) { - Debug.Assert(growingCollection != null); + Debug.Assert(growingCollection is not null); MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); @@ -713,7 +713,7 @@ private void ReadSimpleDictionary(CollectionDataContract collectionContract, Typ { keyParseMode = KeyParseMode.UsingParseEnum; } - else if (keyDataContract.ParseMethod != null) + else if (keyDataContract.ParseMethod is not null) { keyParseMode = KeyParseMode.UsingCustomParse; } @@ -869,7 +869,7 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) private bool TryReadPrimitiveArray(Type itemType) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; string? readArrayMethod = null; @@ -899,7 +899,7 @@ private bool TryReadPrimitiveArray(Type itemType) default: break; } - if (readArrayMethod != null) + if (readArrayMethod is not null) { _ilg.Load(_xmlReaderArg); _ilg.ConvertValue(typeof(XmlReaderDelegator), typeof(JsonReaderDelegator)); @@ -943,7 +943,7 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; - if (keyValuePairContract == null) + if (keyValuePairContract is null) { Fx.Assert("Failed to create contract for KeyValuePair type"); } @@ -962,7 +962,7 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C } else { - Debug.Assert(collectionContract.AddMethod != null); + Debug.Assert(collectionContract.AddMethod is not null); _ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) @@ -972,7 +972,7 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C private void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue) { - Debug.Assert(collectionContract.AddMethod != null); + Debug.Assert(collectionContract.AddMethod is not null); _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) @@ -1016,7 +1016,7 @@ private void ThrowUnexpectedStateException(XmlNodeType expectedState) private void ThrowSerializationException(string msg, params object[] values) { - if (values != null && values.Length > 0) + if (values is not null && values.Length > 0) _ilg.CallStringFormat(msg, values); else _ilg.Load(msg); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs index 68eaefbc457516..af72f4a25e75c5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs @@ -146,9 +146,9 @@ private void InitArgs(Type objType) private void InvokeOnSerializing(ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerializing(classContract.BaseContract); - if (classContract.OnSerializing != null) + if (classContract.OnSerializing is not null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); @@ -159,9 +159,9 @@ private void InvokeOnSerializing(ClassDataContract classContract) private void InvokeOnSerialized(ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerialized(classContract.BaseContract); - if (classContract.OnSerialized != null) + if (classContract.OnSerialized is not null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); @@ -200,7 +200,7 @@ private void WriteClass(ClassDataContract classContract) private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal, ClassDataContract derivedMostClassContract) { - int memberCount = (classContract.BaseContract == null) ? 0 : + int memberCount = (classContract.BaseContract is null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); int classMemberCount = classContract.Members!.Count; @@ -236,7 +236,7 @@ private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensio { WriteStartElement(nameLocal: null, nameIndex: i + _childElementIndex); } - if (memberValue == null) + if (memberValue is null) memberValue = LoadMemberValue(member); WriteValue(memberValue); WriteEndElement(); @@ -304,7 +304,7 @@ private void WriteCollection(CollectionDataContract collectionContract) } else { - Debug.Assert(collectionContract.GetEnumeratorMethod != null); + Debug.Assert(collectionContract.GetEnumeratorMethod is not null); MethodInfo? incrementCollectionCountMethod = null; switch (collectionContract.Kind) @@ -322,7 +322,7 @@ private void WriteCollection(CollectionDataContract collectionContract) incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } - if (incrementCollectionCountMethod != null) + if (incrementCollectionCountMethod is not null) { _ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal); } @@ -348,13 +348,13 @@ private void WriteCollection(CollectionDataContract collectionContract) } MethodInfo? moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null); MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null); - if (moveNextMethod == null || getCurrentMethod == null) + if (moveNextMethod is null || getCurrentMethod is null) { if (enumeratorType.IsInterface) { - if (moveNextMethod == null) + if (moveNextMethod is null) moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod; - if (getCurrentMethod == null) + if (getCurrentMethod is null) getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod; } else @@ -375,9 +375,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } } - if (moveNextMethod == null) + if (moveNextMethod is null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; - if (getCurrentMethod == null) + if (getCurrentMethod is null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } @@ -394,7 +394,7 @@ private void WriteCollection(CollectionDataContract collectionContract) } else if (isGenericDictionary) { - Debug.Assert(keyValueTypes != null); + Debug.Assert(keyValueTypes is not null); Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null)!; _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); @@ -405,7 +405,7 @@ private void WriteCollection(CollectionDataContract collectionContract) bool canWriteSimpleDictionary = isDictionary || isGenericDictionary; if (canWriteSimpleDictionary) { - Debug.Assert(keyValueTypes != null); + Debug.Assert(keyValueTypes is not null); Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes); PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString)!; PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString)!; @@ -438,7 +438,7 @@ private void WriteCollection(CollectionDataContract collectionContract) WriteArrayAttribute(); _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); - if (incrementCollectionCountMethod == null) + if (incrementCollectionCountMethod is null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } @@ -477,7 +477,7 @@ private void WriteCollection(CollectionDataContract collectionContract) private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? memberInfo, LocalBuilder? arrayItemIndex, LocalBuilder? name, int nameIndex) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); - if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) + if (primitiveContract is null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load writer @@ -491,11 +491,11 @@ private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? membe _ilg.Load(_xmlWriterArg); } // load primitive value - if (value != null) + if (value is not null) { _ilg.Load(value); } - else if (memberInfo != null) + else if (memberInfo is not null) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(memberInfo); @@ -505,7 +505,7 @@ private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? membe _ilg.LoadArrayElement(_objectLocal, arrayItemIndex); } // load name - if (name != null) + if (name is not null) { _ilg.Load(name); } @@ -523,7 +523,7 @@ private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? membe private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; string? writeArrayMethod = null; @@ -553,7 +553,7 @@ private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value default: break; } - if (writeArrayMethod != null) + if (writeArrayMethod is not null) { WriteArrayAttribute(); @@ -595,7 +595,7 @@ private void WriteValue(LocalBuilder memberValue) if (memberType.IsValueType && !isNullableOfT) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); - if (primitiveContract != null) + if (primitiveContract is not null) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, false /* writeXsiType */); @@ -617,7 +617,7 @@ private void WriteValue(LocalBuilder memberValue) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); - if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) + if (primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { if (isNullableOfT) { @@ -705,7 +705,7 @@ private void WriteStartElement(LocalBuilder? nameLocal, int nameIndex) _ilg.Load(_xmlWriterArg); // localName - if (nameLocal == null) + if (nameLocal is null) _ilg.LoadArrayElement(_memberNamesArg!, nameIndex); else _ilg.Load(nameLocal); @@ -713,7 +713,7 @@ private void WriteStartElement(LocalBuilder? nameLocal, int nameIndex) // namespace _ilg.Load(null); - if (nameLocal != null && nameLocal.LocalType == Globals.TypeOfString) + if (nameLocal is not null && nameLocal.LocalType == Globals.TypeOfString) { _ilg.Call(JsonFormatGeneratorStatics.WriteStartElementStringMethod); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs index 601ddc1843198b..be8fc65be25013 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs @@ -46,7 +46,7 @@ public JsonObjectDataContract(DataContract traditionalDataContract) throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnexpectedAttributeValue, contentMode)); } - if (context != null) + if (context is not null) { context.AddNewObject(obj); } @@ -60,7 +60,7 @@ public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object ob internal static object ParseJsonNumber(string value, out TypeCode objectTypeCode) { - if (value == null) + if (value is null) { throw new XmlException(SR.Format(SR.XmlInvalidConversion, value, Globals.TypeOfInt)); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs index 7a9f805fee2996..cd78dc3e3d5553 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs @@ -18,7 +18,7 @@ public JsonQNameDataContract(QNameDataContract traditionalQNameDataContract) public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsQName(); } 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 083877a47b8c97..476d39873cca57 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 @@ -28,7 +28,7 @@ internal XmlDictionaryReaderQuotas? ReaderQuotas { get { - if (this.dictionaryReader == null) + if (this.dictionaryReader is null) { return null; } @@ -43,7 +43,7 @@ private DateTimeArrayJsonHelperWithString DateTimeArrayHelper { get { - if (_dateTimeArrayHelper == null) + if (_dateTimeArrayHelper is null) { _dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat); } @@ -98,7 +98,7 @@ public override byte[] ReadContentAsBase64() byte[] buffer; - if (dictionaryReader == null) + if (dictionaryReader is null) { XmlDictionaryReader tempDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader); buffer = ByteArrayHelperWithString.Instance.ReadArray(tempDictionaryReader, JsonGlobals.itemString, string.Empty, tempDictionaryReader.Quotas.MaxArrayLength); @@ -142,7 +142,7 @@ internal override DateTime ReadContentAsDateTime() internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat? dateTimeFormat) { - if (dateTimeFormat == null) + if (dateTimeFormat is null) { return ParseJsonDateInDefaultFormat(originalDateTimeValue); } @@ -247,7 +247,7 @@ internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out DateTime[]? array) { - if ((dictionaryReader == null) || (arrayLength != -1)) + if ((dictionaryReader is null) || (arrayLength != -1)) { array = null; return false; @@ -291,7 +291,7 @@ internal override ulong ReadContentAsUnsignedLong() { string value = reader.ReadContentAsString(); - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) { throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64"))); } @@ -324,7 +324,7 @@ internal override ulong ReadElementContentAsUnsignedLong() string value = reader.ReadElementContentAsString(); - if (value == null || value.Length == 0) + if (value is null || value.Length == 0) { throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64"))); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs index 888c613a188eed..91f623c747820d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs @@ -22,7 +22,7 @@ public static XmlDictionaryReader CreateJsonReader(Stream stream, XmlDictionaryR public static XmlDictionaryReader CreateJsonReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs index e9e1d3c5d77c45..7af9d676edd462 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs @@ -18,7 +18,7 @@ public JsonStringDataContract(StringDataContract traditionalStringDataContract) public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsString(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs index 5e5605931c44f9..e2ba4e4f5825e2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs @@ -18,7 +18,7 @@ public JsonUriDataContract(UriDataContract traditionalUriDataContract) public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsUri(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs index 0ed5f9f7d5a4c5..4560067b80dbfc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs @@ -28,7 +28,7 @@ internal override void WriteChar(char value) internal override void WriteBase64(byte[]? bytes) { - if (bytes == null) + if (bytes is null) { return; } @@ -160,7 +160,7 @@ internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, Xm internal override void WriteDateTime(DateTime value) { - if (_dateTimeFormat == null) + if (_dateTimeFormat is null) { WriteDateTimeInDefaultFormat(value); } @@ -235,7 +235,7 @@ internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, internal override void WriteStartElement(string? prefix, string localName, string? ns) { - if (localName != null && localName.Length == 0) + if (localName is not null && localName.Length == 0) { base.WriteStartElement(JsonGlobals.itemString, JsonGlobals.itemString); base.WriteAttributeString(null, JsonGlobals.itemString, null, localName); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs index 0dea02feddb5e6..9b45e83a67abcb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs @@ -20,12 +20,12 @@ public JsonXmlDataContract(XmlDataContract traditionalXmlDataContract) string xmlContent = jsonReader.ReadElementContentAsString(); DataContractSerializer dataContractSerializer = new DataContractSerializer(TraditionalDataContract.UnderlyingType, - GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); // maxItemsInObjectGraph // ignoreExtensionDataObject // preserveObjectReferences + GetKnownTypesFromContext(context, (context is null) ? null : context.SerializerKnownTypeList), 1, false, false); // maxItemsInObjectGraph // ignoreExtensionDataObject // preserveObjectReferences MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent)); object? xmlValue; XmlDictionaryReaderQuotas? quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas; - if (quotas == null) + if (quotas is null) { xmlValue = dataContractSerializer.ReadObject(memoryStream); } @@ -33,7 +33,7 @@ public JsonXmlDataContract(XmlDataContract traditionalXmlDataContract) { xmlValue = dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(memoryStream, quotas)); } - if (context != null) + if (context is not null) { context.AddNewObject(xmlValue); } @@ -43,7 +43,7 @@ public JsonXmlDataContract(XmlDataContract traditionalXmlDataContract) public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), - GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); // maxItemsInObjectGraph // ignoreExtensionDataObject // preserveObjectReferences + GetKnownTypesFromContext(context, (context is null) ? null : context.SerializerKnownTypeList), 1, false, false); // maxItemsInObjectGraph // ignoreExtensionDataObject // preserveObjectReferences MemoryStream memoryStream = new MemoryStream(); dataContractSerializer.WriteObject(memoryStream, obj); @@ -55,16 +55,16 @@ public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object ob private List GetKnownTypesFromContext(XmlObjectSerializerContext? context, IList? serializerKnownTypeList) { List knownTypesList = new List(); - if (context != null) + if (context is not null) { List stableNames = new List(); Dictionary[] entries = context.scopedKnownTypes.dataContractDictionaries; - if (entries != null) + if (entries is not null) { for (int i = 0; i < entries.Length; i++) { Dictionary entry = entries[i]; - if (entry != null) + if (entry is not null) { foreach (KeyValuePair pair in entry) { @@ -77,7 +77,7 @@ private List GetKnownTypesFromContext(XmlObjectSerializerContext? context, } } } - if (serializerKnownTypeList != null) + if (serializerKnownTypeList is not null) { knownTypesList.AddRange(serializerKnownTypeList); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs index dae0e1b19128f8..e0f44cba200885 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs @@ -20,14 +20,14 @@ internal sealed class ReflectionJsonClassReader public ReflectionJsonClassReader(ClassDataContract classDataContract) { - Debug.Assert(classDataContract != null); + Debug.Assert(classDataContract is not null); _classContract = classDataContract; _reflectionReader = new ReflectionJsonReader(); } public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames) { - Debug.Assert(_classContract != null); + Debug.Assert(_classContract is not null); return _reflectionReader.ReflectionReadClass(xmlReader, context, memberNames, null /*memberNamespaces*/, _classContract); } } @@ -52,7 +52,7 @@ internal sealed class ReflectionJsonReader : ReflectionReader protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj) { var jsonContext = context as XmlObjectSerializerReadContextComplexJson; - Debug.Assert(jsonContext != null); + Debug.Assert(jsonContext is not null); int memberCount = classContract.MemberNames!.Length; context.IncrementItemCount(memberCount); @@ -105,7 +105,7 @@ protected override string GetCollectionContractNamespace(CollectionDataContract protected override object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract) { var jsonContext = context as XmlObjectSerializerReadContextComplexJson; - Debug.Assert(jsonContext != null); + Debug.Assert(jsonContext is not null); Debug.Assert(collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary); context.ReadAttributes(xmlReader); @@ -116,7 +116,7 @@ protected override string GetCollectionContractNamespace(CollectionDataContract protected override bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object? resultCollection) { var jsonContext = context as XmlObjectSerializerReadContextComplexJson; - Debug.Assert(jsonContext != null); + Debug.Assert(jsonContext is not null); bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; @@ -154,7 +154,7 @@ private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSeriali { keyParseMode = KeyParseMode.UsingParseEnum; } - else if (keyDataContract.ParseMethod != null) + else if (keyDataContract.ParseMethod is not null) { keyParseMode = KeyParseMode.UsingCustomParse; } @@ -222,7 +222,7 @@ private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSeriali object? pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty); - Debug.Assert(dictionary != null); + Debug.Assert(dictionary is not null); ((IDictionary)dictionary).Add(pairKey, pairValue); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs index 3fd8d58bd346ef..c55df3b143c2b2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs @@ -25,7 +25,7 @@ public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlOb public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract) { JsonWriterDelegator? jsonWriter = xmlWriter as JsonWriterDelegator; - if (jsonWriter == null) + if (jsonWriter is null) { throw new ArgumentException(nameof(xmlWriter)); } @@ -82,7 +82,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, ReflectionWriteArrayAttribute(jsonWriter); PrimitiveDataContract? primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionContract.UnderlyingType); - if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject) + if (primitiveContractForType is not null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject) { while (enumerator.MoveNext()) { @@ -137,7 +137,7 @@ private void ReflectionWriteObjectAttribute(XmlWriterDelegator xmlWriter) private bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type underlyingType, Type itemType, XmlDictionaryString collectionItemName) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; XmlDictionaryString? itemNamespace = null; @@ -192,9 +192,9 @@ internal class ReflectionJsonClassWriter : ReflectionClassWriter { protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? memberNames) { - Debug.Assert(memberNames != null); + Debug.Assert(memberNames is not null); - int memberCount = (classContract.BaseContract == null) ? 0 : + int memberCount = (classContract.BaseContract is null) ? 0 : ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, memberNames); childElementIndex += memberCount; @@ -220,8 +220,8 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje { memberValue = ReflectionGetMemberValue(obj, member); object? defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType); - if ((memberValue == null && defaultValue == null) - || (memberValue != null && memberValue.Equals(defaultValue))) + if ((memberValue is null && defaultValue is null) + || (memberValue is not null && memberValue.Equals(defaultValue))) { shouldWriteValue = false; @@ -234,7 +234,7 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje if (shouldWriteValue) { - if (memberValue == null) + if (memberValue is null) { memberValue = ReflectionGetMemberValue(obj, member); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs index a035f951261d4c..796fce3dca0039 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs @@ -342,7 +342,7 @@ protected override void Dispose(bool disposing) OnXmlDictionaryReaderClose? onClose = _onReaderClose; _onReaderClose = null; ResetState(); - if (onClose != null) + if (onClose is not null) { try { @@ -414,7 +414,7 @@ public override bool Read() BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead); } - Debug.Assert(_charactersToSkipOnNextRead != null); + Debug.Assert(_charactersToSkipOnNextRead is not null); byte ch; // Skip whitespace before checking EOF @@ -731,7 +731,7 @@ public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { if (IsAttributeValue) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -762,7 +762,7 @@ public override int ReadValueChunk(char[] chars, int offset, int count) { if (IsAttributeValue) { - if (chars == null) + if (chars is null) { throw new ArgumentNullException(nameof(chars)); } @@ -807,7 +807,7 @@ public override int ReadValueChunk(char[] chars, int offset, int count) public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -838,7 +838,7 @@ public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, X public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -858,7 +858,7 @@ public override void StartCanonicalization(Stream stream, bool includeComments, internal static void CheckArray(Array array, int offset, int count) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -1063,7 +1063,7 @@ private void BufferElement() private void EnterJsonScope(JsonNodeType currentNodeType) { _scopeDepth++; - if (_scopes == null) + if (_scopes is null) { _scopes = new JsonNodeType[4]; } @@ -1549,7 +1549,7 @@ private void ResetState() _expectingFirstElementInNonPrimitiveChild = false; _charactersToSkipOnNextRead = new byte[2]; _scopeDepth = 0; - if ((_scopes != null) && (_scopes.Length > JsonGlobals.maxScopeSize)) + if ((_scopes is not null) && (_scopes.Length > JsonGlobals.maxScopeSize)) { _scopes = null; } @@ -1612,7 +1612,7 @@ private bool TryGetByte(out byte ch) [return: NotNullIfNotNull("val")] private string? UnescapeJsonString(string? val) { - if (val == null) + if (val is null) { return null; } @@ -1624,7 +1624,7 @@ private bool TryGetByte(out byte ch) if (val[i] == '\\') { i++; - if (sb == null) + if (sb is null) { sb = new StringBuilder(); } @@ -1675,7 +1675,7 @@ private bool TryGetByte(out byte ch) count++; } } - if (sb == null) + if (sb is null) { return val; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs index 31c8c2ffeaf9b7..bc374dca4c4c41 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs @@ -94,7 +94,7 @@ public XmlJsonWriter(bool indent, string? indentChars) _indent = indent; if (indent) { - if (indentChars == null) + if (indentChars is null) { throw new ArgumentNullException(nameof(indentChars)); } @@ -173,7 +173,7 @@ private static BinHexEncoding BinHexEncoding { get { - if (s_binHexEncoding == null) + if (s_binHexEncoding is null) { s_binHexEncoding = new BinHexEncoding(); } @@ -233,7 +233,7 @@ public override void Flush() public override string? LookupPrefix(string ns) { - if (ns == null) + if (ns is null) { throw new ArgumentNullException(nameof(ns)); } @@ -254,11 +254,11 @@ public override void Flush() public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } - if (encoding == null) + if (encoding is null) { throw new ArgumentNullException(nameof(encoding)); } @@ -271,7 +271,7 @@ public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { tempEncoding = null; } - if (_nodeWriter == null) + if (_nodeWriter is null) { _nodeWriter = new JsonNodeWriter(); } @@ -382,7 +382,7 @@ public override void WriteArray(string? prefix, XmlDictionaryString localName, X public override void WriteBase64(byte[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -408,7 +408,7 @@ public override void WriteBase64(byte[] buffer, int index, int count) public override void WriteBinHex(byte[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -444,7 +444,7 @@ public override void WriteCharEntity(char ch) public override void WriteChars(char[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -633,7 +633,7 @@ public override void WriteEndElement() } else if (_nodeType == JsonNodeType.Element) { - if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) + if ((_dataType == JsonDataType.None) && (_serverTypeValue is not null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } @@ -726,7 +726,7 @@ public override void WriteProcessingInstruction(string name, string? text) public override void WriteQualifiedName(string localName, string? ns) { - if (localName == null) + if (localName is null) { throw new ArgumentNullException(nameof(localName)); } @@ -734,7 +734,7 @@ public override void WriteQualifiedName(string localName, string? ns) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); } - if (ns == null) + if (ns is null) { ns = string.Empty; } @@ -749,7 +749,7 @@ public override void WriteRaw(string data) public override void WriteRaw(char[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -782,7 +782,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin { if (IsWritingNameWithMapping && prefix == JsonGlobals.xmlnsPrefix) { - if (ns != null && ns != xmlnsNamespace) + if (ns is not null && ns != xmlnsNamespace) { throw new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), nameof(ns)); } @@ -815,7 +815,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), nameof(ns)); } } - if (localName == null) + if (localName is null) { throw new ArgumentNullException(nameof(localName)); } @@ -846,7 +846,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin } else if (localName == JsonGlobals.serverTypeString) { - if (_serverTypeValue != null) + if (_serverTypeValue is not null) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.serverTypeString)); } @@ -902,7 +902,7 @@ public override void WriteStartDocument() public override void WriteStartElement(string? prefix, string localName, string? ns) { - if (localName == null) + if (localName is null) { throw new ArgumentNullException(nameof(localName)); } @@ -1013,13 +1013,13 @@ public override void WriteStartElement(string? prefix, string localName, string? public override void WriteString(string? text) { - if (HasOpenAttribute && (text != null)) + if (HasOpenAttribute && (text is not null)) { _attributeText += text; } else { - if (text == null) + if (text is null) { text = string.Empty; } @@ -1099,7 +1099,7 @@ public override void WriteValue(TimeSpan value) public override void WriteValue(UniqueId value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1115,7 +1115,7 @@ public override void WriteValue(object value) ThrowClosed(); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1140,7 +1140,7 @@ public override void WriteWhitespace(string? ws) { ThrowClosed(); } - if (ws == null) + if (ws is null) { throw new ArgumentNullException(nameof(ws)); } @@ -1219,7 +1219,7 @@ private void CheckText(JsonNodeType nextNodeType) private void EnterScope(JsonNodeType currentNodeType) { _depth++; - if (_scopes == null) + if (_scopes is null) { _scopes = new JsonNodeType[4]; } @@ -1254,7 +1254,7 @@ private void InitializeWriter() { _depth = 0; } - if ((_scopes != null) && (_scopes.Length > JsonGlobals.maxScopeSize)) + if ((_scopes is not null) && (_scopes.Length > JsonGlobals.maxScopeSize)) { _scopes = null; } @@ -1282,7 +1282,7 @@ private void StartText() throw new InvalidOperationException(SR.JsonMustUseWriteStringForWritingAttributeValues); } - if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) + if ((_dataType == JsonDataType.None) && (_serverTypeValue is not null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } @@ -1318,7 +1318,7 @@ private void StartText() private void ThrowIfServerTypeWritten(string dataTypeSpecified) { - if (_serverTypeValue != null) + if (_serverTypeValue is not null) { throw new XmlException(SR.Format(SR.JsonInvalidDataTypeSpecifiedForServerType, JsonGlobals.typeString, dataTypeSpecified, JsonGlobals.serverTypeString, JsonGlobals.objectString)); } @@ -1375,7 +1375,7 @@ private void WriteDataTypeServerType() break; } - if (_serverTypeValue != null) + if (_serverTypeValue is not null) { // dataType must be object because we throw in all other case. WriteServerTypeAttribute(); @@ -1469,7 +1469,7 @@ private void WritePrimitiveValue(object value) ThrowClosed(); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs index 39011d6f38b742..5f71e6a9c11d39 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs @@ -136,7 +136,7 @@ private IDataNode ReadNumericalPrimitiveExtensionDataValue(XmlReaderDelegator xm internal override void ReadAttributes(XmlReaderDelegator xmlReader) { - if (attributes == null) + if (attributes is null) attributes = new Attributes(); attributes.Reset(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs index 15d0335e7dbae6..d9c5ab4ed451f1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs @@ -260,7 +260,7 @@ internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, private void VerifyType(DataContract dataContract, Type declaredType) { bool knownTypesAddedInCurrentScope = false; - if (dataContract.KnownDataContracts != null) + if (dataContract.KnownDataContracts is not null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; @@ -301,7 +301,7 @@ internal override void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, { // Don't write type or __type for XML types because we serialize them to strings } - else if ((dataType == Globals.TypeOfObject) && (dataNode.Value != null)) + else if ((dataType == Globals.TypeOfObject) && (dataNode.Value is not null)) { DataContract dc = GetDataContract(dataNode.Value.GetType()); if (RequiresJsonTypeInfo(dc)) @@ -343,7 +343,7 @@ internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable [return: NotNullIfNotNull("oldItemContract")] internal static DataContract? GetRevisedItemContract(DataContract oldItemContract) { - if ((oldItemContract != null) && + if ((oldItemContract is not null) && oldItemContract.UnderlyingType.IsGenericType && (oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs index 5c5a9291036012..3bc8f625f2d2e8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs @@ -12,19 +12,19 @@ internal sealed class KnownTypeDataContractResolver : DataContractResolver internal KnownTypeDataContractResolver(XmlObjectSerializerContext context) { - Fx.Assert(context != null, "KnownTypeDataContractResolver should not be instantiated with a null context"); + Fx.Assert(context is not null, "KnownTypeDataContractResolver should not be instantiated with a null context"); _context = context; } public override bool TryResolveType(Type type, Type? declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString? typeName, out XmlDictionaryString? typeNamespace) { - if (type == null) + if (type is null) { typeName = null; typeNamespace = null; return false; } - if (declaredType != null && declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) + if (declaredType is not null && declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { typeName = null; typeNamespace = null; @@ -48,7 +48,7 @@ public override bool TryResolveType(Type type, Type? declaredType, DataContractR public override Type? ResolveName(string typeName, string? typeNamespace, Type? declaredType, DataContractResolver knownTypeResolver) { - if (typeName == null || typeNamespace == null) + if (typeName is null || typeNamespace is null) return null; return _context.ResolveNameFromKnownTypes(new XmlQualifiedName(typeName, typeNamespace)); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs index 7945a647a124d7..8bcae0de191e40 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs @@ -20,7 +20,7 @@ internal struct ObjectReferenceStack internal void Push(object obj) { - if (_objectArray == null) + if (_objectArray is null) { _objectArray = new object[InitialArraySize]; _objectArray[_count++] = obj; @@ -33,7 +33,7 @@ internal void Push(object obj) } else { - if (_objectDictionary == null) + if (_objectDictionary is null) _objectDictionary = new Dictionary(); _objectDictionary.Add(obj, null); @@ -47,7 +47,7 @@ internal void EnsureSetAsIsReference(object obj) return; if (_count > MaximumArraySize) { - if (_objectDictionary == null) + if (_objectDictionary is null) { DiagnosticUtility.DebugAssert("Object reference stack in invalid state"); } @@ -55,9 +55,9 @@ internal void EnsureSetAsIsReference(object obj) } else { - if ((_objectArray != null) && _objectArray[_count - 1] == obj) + if ((_objectArray is not null) && _objectArray[_count - 1] == obj) { - if (_isReferenceArray == null) + if (_isReferenceArray is null) { _isReferenceArray = new bool[_objectArray.Length]; } @@ -74,7 +74,7 @@ internal void Pop(object obj) { if (_count > MaximumArraySize) { - if (_objectDictionary == null) + if (_objectDictionary is null) { DiagnosticUtility.DebugAssert("Object reference stack in invalid state"); } @@ -89,13 +89,13 @@ internal bool Contains(object obj) int currentCount = _count; if (currentCount > MaximumArraySize) { - if (_objectDictionary != null && _objectDictionary.ContainsKey(obj)) + if (_objectDictionary is not null && _objectDictionary.ContainsKey(obj)) return true; currentCount = MaximumArraySize; } for (int i = (currentCount - 1); i >= 0; i--) { - if (object.ReferenceEquals(obj, _objectArray![i]) && _isReferenceArray != null && !_isReferenceArray[i]) + if (object.ReferenceEquals(obj, _objectArray![i]) && _isReferenceArray is not null && !_isReferenceArray[i]) return true; } return false; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs index dbe86840f9b9fb..5617117b8bec22 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs @@ -71,7 +71,7 @@ private int FindElement(object obj, out bool isEmpty, out bool isWrapped) int position = ComputeStartPosition(obj); for (int i = position; i != (position - 1); i++) { - if (m_objs[i] == null) + if (m_objs[i] is null) { isEmpty = true; return i; @@ -98,7 +98,7 @@ private void RemoveAt(int position) int lastVacantPosition = position; for (int next = (position == cacheSize - 1) ? 0 : position + 1; next != position; next++) { - if (m_objs[next] == null) + if (m_objs[next] is null) { m_objs[lastVacantPosition] = null; m_ids[lastVacantPosition] = 0; @@ -148,7 +148,7 @@ private void Rehash() for (int j = 0; j < oldObjs.Length; j++) { object? obj = oldObjs[j]; - if (obj != null) + if (obj is not null) { bool found, isWrapped; int position = FindElement(obj, out found, out isWrapped); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs index 8bc6d130f3596c..e3a9d45b2e419f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs @@ -53,7 +53,7 @@ internal MethodInfo XmlFormatWriterMethod { get { - if (_helper.XmlFormatWriterMethod == null) + if (_helper.XmlFormatWriterMethod is null) { if (UnderlyingType.IsValueType) _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, null, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null)!; @@ -68,7 +68,7 @@ internal MethodInfo XmlFormatContentWriterMethod { get { - if (_helper.XmlFormatContentWriterMethod == null) + if (_helper.XmlFormatContentWriterMethod is null) { if (UnderlyingType.IsValueType) _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, null, new Type[] { UnderlyingType }, null)!; @@ -83,7 +83,7 @@ internal MethodInfo XmlFormatReaderMethod { get { - if (_helper.XmlFormatReaderMethod == null) + if (_helper.XmlFormatReaderMethod is null) { _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!; } @@ -167,7 +167,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsChar() + return (context is null) ? reader.ReadElementContentAsChar() : HandleReadValue(reader.ReadElementContentAsChar(), context); } @@ -198,7 +198,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsBoolean() + return (context is null) ? reader.ReadElementContentAsBoolean() : HandleReadValue(reader.ReadElementContentAsBoolean(), context); } @@ -224,7 +224,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsSignedByte() + return (context is null) ? reader.ReadElementContentAsSignedByte() : HandleReadValue(reader.ReadElementContentAsSignedByte(), context); } @@ -250,7 +250,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsUnsignedByte() + return (context is null) ? reader.ReadElementContentAsUnsignedByte() : HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context); } @@ -276,7 +276,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsShort() + return (context is null) ? reader.ReadElementContentAsShort() : HandleReadValue(reader.ReadElementContentAsShort(), context); } @@ -302,7 +302,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsUnsignedShort() + return (context is null) ? reader.ReadElementContentAsUnsignedShort() : HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context); } @@ -367,7 +367,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsInt() + return (context is null) ? reader.ReadElementContentAsInt() : HandleReadValue(reader.ReadElementContentAsInt(), context); } @@ -393,7 +393,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsUnsignedInt() + return (context is null) ? reader.ReadElementContentAsUnsignedInt() : HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context); } @@ -423,7 +423,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsLong() + return (context is null) ? reader.ReadElementContentAsLong() : HandleReadValue(reader.ReadElementContentAsLong(), context); } @@ -474,7 +474,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsUnsignedLong() + return (context is null) ? reader.ReadElementContentAsUnsignedLong() : HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context); } @@ -500,7 +500,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsFloat() + return (context is null) ? reader.ReadElementContentAsFloat() : HandleReadValue(reader.ReadElementContentAsFloat(), context); } @@ -526,7 +526,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsDouble() + return (context is null) ? reader.ReadElementContentAsDouble() : HandleReadValue(reader.ReadElementContentAsDouble(), context); } @@ -552,7 +552,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsDecimal() + return (context is null) ? reader.ReadElementContentAsDecimal() : HandleReadValue(reader.ReadElementContentAsDecimal(), context); } @@ -578,7 +578,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsDateTime() + return (context is null) ? reader.ReadElementContentAsDateTime() : HandleReadValue(reader.ReadElementContentAsDateTime(), context); } @@ -608,7 +608,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsString(); } @@ -740,7 +740,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsBase64(); } @@ -795,7 +795,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlForObjectCannotHaveContent, localName, ns), xes)); } } - return (context == null) ? obj : HandleReadValue(obj, context); + return (context is null) ? obj : HandleReadValue(obj, context); } internal override bool CanContainReferences @@ -829,7 +829,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsTimeSpan() + return (context is null) ? reader.ReadElementContentAsTimeSpan() : HandleReadValue(reader.ReadElementContentAsTimeSpan(), context); } @@ -864,7 +864,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - return (context == null) ? reader.ReadElementContentAsGuid() + return (context is null) ? reader.ReadElementContentAsGuid() : HandleReadValue(reader.ReadElementContentAsGuid(), context); } @@ -895,7 +895,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsUri(); } @@ -932,7 +932,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { - if (context == null) + if (context is null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsQName(); } @@ -951,7 +951,7 @@ internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionary { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace)) writer.WriteStartElement(Globals.SerPrefix, name, ns); - else if (ns != null && ns.Value != null && ns.Value.Length > 0) + else if (ns is not null && ns.Value is not null && ns.Value.Length > 0) writer.WriteStartElement(Globals.ElementPrefix, name, ns); else writer.WriteStartElement(name, ns); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs index 6253555eadd3c5..d906f8cc998112 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs @@ -44,10 +44,10 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ bool originValueIsNullableOfT = (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !originValueIsNullableOfT) { - Debug.Assert(memberValue != null); + Debug.Assert(memberValue is not null); PrimitiveDataContract? primitiveContract = primitiveContractForParamType; - if (primitiveContract != null && !writeXsiType) + if (primitiveContract is not null && !writeXsiType) { primitiveContract.WriteXmlValue(xmlWriter, memberValue, context); } @@ -60,7 +60,7 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ { if (originValueIsNullableOfT) { - if (memberValue == null) + if (memberValue is null) { memberType = Nullable.GetUnderlyingType(memberType)!; } @@ -72,20 +72,20 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ } } - if (memberValue == null) + if (memberValue is null) { context.WriteNull(xmlWriter, memberType, DataContract.IsTypeSerializable(memberType)); } else { PrimitiveDataContract? primitiveContract = originValueIsNullableOfT ? PrimitiveDataContract.GetPrimitiveDataContract(memberType) : primitiveContractForParamType; - if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) + if (primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { primitiveContract.WriteXmlValue(xmlWriter, memberValue, context); } else { - if (memberValue == null && + if (memberValue is null && (memberType == Globals.TypeOfObject || (originValueIsNullableOfT && memberType.IsValueType))) { @@ -109,7 +109,7 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract) { - if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) + if (primitiveContract is null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; primitiveContract.WriteXmlElement(xmlWriter, value, context, name, ns); @@ -119,9 +119,9 @@ protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObje private void InvokeOnSerializing(object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerializing(obj, context, classContract.BaseContract); - if (classContract.OnSerializing != null) + if (classContract.OnSerializing is not null) { var contextArg = context.GetStreamingContext(); classContract.OnSerializing.Invoke(obj, new object[] { contextArg }); @@ -130,9 +130,9 @@ private void InvokeOnSerializing(object obj, XmlObjectSerializerWriteContext con private void InvokeOnSerialized(object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerialized(obj, context, classContract.BaseContract); - if (classContract.OnSerialized != null) + if (classContract.OnSerialized is not null) { var contextArg = context.GetStreamingContext(); classContract.OnSerialized.Invoke(obj, new object[] { contextArg }); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs index 284d45dc8dae40..3078bc79be18c5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs @@ -29,7 +29,7 @@ internal abstract class ReflectionReader public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract) { - Debug.Assert(context != null); + Debug.Assert(context is not null); object obj = CreateObject(classContract); context.AddNewObject(obj); @@ -41,7 +41,7 @@ public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSeriali } else { - Debug.Assert(memberNames != null); + Debug.Assert(memberNames is not null); ReflectionReadMembers(xmlReader, context, memberNames, memberNamespaces, classContract, ref obj); } @@ -68,7 +68,7 @@ public void ReflectionReadGetOnlyCollection(XmlReaderDelegator xmlReader, XmlObj if (xmlReader.IsStartElement(collectionItemName, collectionItemNamespace)) { - if (resultCollection == null) + if (resultCollection is null) { XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException(collectionContract.UnderlyingType); } @@ -183,7 +183,7 @@ protected virtual bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlRea protected int ReflectionGetMembers(ClassDataContract classContract, DataMember[] members) { - int memberCount = (classContract.BaseContract == null) ? 0 : ReflectionGetMembers(classContract.BaseContract, members); + int memberCount = (classContract.BaseContract is null) ? 0 : ReflectionGetMembers(classContract.BaseContract, members); int childElementIndex = memberCount; for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) { @@ -197,7 +197,7 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria { DataMember dataMember = members[memberIndex]; - Debug.Assert(dataMember != null); + Debug.Assert(dataMember is not null); if (dataMember.IsGetOnlyCollection) { var memberValue = ReflectionGetMemberValue(obj, dataMember); @@ -209,7 +209,7 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria context.ResetCollectionMemberInfo(); var value = ReflectionReadValue(xmlReader, context, dataMember, classContract.StableName.Namespace); MemberInfo memberInfo = dataMember.MemberInfo; - Debug.Assert(memberInfo != null); + Debug.Assert(memberInfo is not null); ReflectionSetMemberValue(ref obj, value, dataMember); } @@ -229,7 +229,7 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria PrimitiveDataContract.GetPrimitiveDataContract(type) : (primitiveContractForOriginalType ?? PrimitiveDataContract.GetPrimitiveDataContract(type)); - if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) + if ((primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { value = ReadItemOfPrimitiveType(xmlReader, context, type, name, ns, primitiveContract, nullables); } @@ -247,7 +247,7 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria context.ReadAttributes(xmlReader); string objectId = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type)); bool typeIsValueType = type.IsValueType; - if (objectId != null) + if (objectId is not null) { if (objectId.Length == 0) { @@ -258,7 +258,7 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria throw new SerializationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); } - if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) + if (primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { value = primitiveContract.ReadXmlValue(xmlReader, context); } @@ -315,7 +315,7 @@ private CollectionReadItemDelegate GetReflectionReadValueDelegate(Type type) } PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); - if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) + if ((primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { return (xmlReaderArg, contextArg, collectionContract, typeArg, nameArg, nsArg) => { @@ -353,9 +353,9 @@ private void ReflectionSetMemberValue(ref object obj, object? memberValue, DataM private void InvokeOnDeserializing(XmlObjectSerializerReadContext context, ClassDataContract classContract, object obj) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserializing(context, classContract.BaseContract, obj); - if (classContract.OnDeserializing != null) + if (classContract.OnDeserializing is not null) { var contextArg = context.GetStreamingContext(); classContract.OnDeserializing.Invoke(obj, new object[] { contextArg }); @@ -364,9 +364,9 @@ private void InvokeOnDeserializing(XmlObjectSerializerReadContext context, Class private void InvokeOnDeserialized(XmlObjectSerializerReadContext context, ClassDataContract classContract, object obj) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserialized(context, classContract.BaseContract, obj); - if (classContract.OnDeserialized != null) + if (classContract.OnDeserialized is not null) { var contextArg = context.GetStreamingContext(); classContract.OnDeserialized.Invoke(obj, new object[] { contextArg }); @@ -556,7 +556,7 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData else { MethodInfo? addMethod = collectionContract.AddMethod; - if (addMethod == null) + if (addMethod is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType)))); } @@ -575,7 +575,7 @@ private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlOb resultArray = null; PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; switch (itemType.GetTypeCode()) @@ -646,7 +646,7 @@ private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlOb default: return false; } - return resultArray != null; + return resultArray is not null; } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs index 9c45733bb2b4ec..5f6425b61f787d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs @@ -20,7 +20,7 @@ internal sealed class ReflectionXmlClassReader public ReflectionXmlClassReader(ClassDataContract classDataContract) { - Debug.Assert(classDataContract != null); + Debug.Assert(classDataContract is not null); _classContract = classDataContract; _reflectionReader = new ReflectionXmlReader(); } @@ -50,7 +50,7 @@ internal sealed class ReflectionXmlReader : ReflectionReader { protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj) { - Debug.Assert(memberNamespaces != null); + Debug.Assert(memberNamespaces is not null); int memberCount = classContract.MemberNames!.Length; context.IncrementItemCount(memberCount); @@ -129,7 +129,7 @@ private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequi private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { - int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); + int memberCount = (contract.BaseContract is null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); List members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs index 643f3a631001f9..cdc01617e76758 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs @@ -24,7 +24,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlDictionaryString ns = collectionDataContract.Namespace; XmlDictionaryString itemName = collectionDataContract.CollectionItemName; - if (collectionDataContract.ChildElementNamespace != null) + if (collectionDataContract.ChildElementNamespace is not null) { xmlWriter.WriteNamespaceDecl(collectionDataContract.ChildElementNamespace); } @@ -52,7 +52,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, IEnumerator enumerator = collectionDataContract.GetEnumeratorForCollection(obj); PrimitiveDataContract? primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionDataContract.UnderlyingType); - if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject) + if (primitiveContractForType is not null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject) { while (enumerator.MoveNext()) { @@ -88,7 +88,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, private bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type type, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; switch (itemType.GetTypeCode()) @@ -126,7 +126,7 @@ internal sealed class ReflectionXmlClassWriter : ReflectionClassWriter { protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? emptyStringArray) { - int memberCount = (classContract.BaseContract == null) ? 0 : + int memberCount = (classContract.BaseContract is null) ? 0 : ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, emptyStringArray); childElementIndex += memberCount; @@ -153,8 +153,8 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje { memberValue = ReflectionGetMemberValue(obj, member); object? defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType); - if ((memberValue == null && defaultValue == null) - || (memberValue != null && memberValue.Equals(defaultValue))) + if ((memberValue is null && defaultValue is null) + || (memberValue is not null && memberValue.Equals(defaultValue))) { shouldWriteValue = false; @@ -168,7 +168,7 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje if (shouldWriteValue) { bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); - if (memberValue == null) + if (memberValue is null) { memberValue = ReflectionGetMemberValue(obj, member); } @@ -177,7 +177,7 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract)) { ReflectionWriteStartElement(xmlWriter, memberType, ns, ns.Value, member.Name, 0); - if (classContract.ChildElementNamespaces![i + childElementIndex] != null) + if (classContract.ChildElementNamespaces![i + childElementIndex] is not null) { var nsChildElement = classContract.ChildElementNamespaces[i + childElementIndex]!; xmlWriter.WriteNamespaceDecl(nsChildElement); @@ -217,7 +217,7 @@ public void ReflectionWriteEndElement(XmlWriterDelegator xmlWriter) private bool NeedsPrefix(Type type, XmlDictionaryString? ns) { - return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); + return type == Globals.TypeOfXmlQualifiedName && (ns is not null && ns.Value is not null && ns.Value.Length > 0); } private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) @@ -230,7 +230,7 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class string? name = member.Name; string? ns = classContract.StableName.Namespace; ClassDataContract? currentContract = derivedMostClassContract; - while (currentContract != null && currentContract != classContract) + while (currentContract is not null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { @@ -249,7 +249,7 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { - while (member.ConflictingMember != null) + while (member.ConflictingMember is not null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; 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 d372854bf11594..a739a23d3acad2 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 @@ -37,7 +37,7 @@ private XmlDocument XmlDoc { get { - if (_xmlDoc == null) + if (_xmlDoc is null) _xmlDoc = new XmlDocument(); return _xmlDoc; } @@ -72,7 +72,7 @@ private void ExportSerializationSchema() { StringReader reader = new StringReader(Globals.SerializationSchema); XmlSchema? schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null); - if (schema == null) + if (schema is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CouldNotReadSerializationSchema, Globals.SerializationNamespace))); Schemas.Add(schema); } @@ -107,7 +107,7 @@ private void ExportDataContract(DataContract dataContract) private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema? schema) { - if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace!.Value) + if (schema is null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace!.Value) schema = GetSchema(dataContract.TopLevelElementNamespace!.Value); XmlSchemaElement topLevelElement = new XmlSchemaElement(); @@ -155,7 +155,7 @@ private void ExportClassDataContract(ClassDataContract classDataContract, XmlSch } XmlElement? isValueTypeElement = null; - if (classDataContract.BaseContract != null) + if (classDataContract.BaseContract is not null) { XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema); extension.Particle = rootSequence; @@ -186,7 +186,7 @@ private void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSch private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema) { XmlDataContract? xmlDataContract = dataContract as XmlDataContract; - if (xmlDataContract != null && xmlDataContract.IsAnonymous) + if (xmlDataContract is not null && xmlDataContract.IsAnonymous) { element.SchemaType = xmlDataContract.XsdType; } @@ -207,7 +207,7 @@ private bool CheckIfMemberHasConflict(DataMember dataMember) return true; DataMember? conflictingMember = dataMember.ConflictingMember; - while (conflictingMember != null) + while (conflictingMember is not null) { if (conflictingMember.HasConflictingNameAndType) return true; @@ -254,7 +254,7 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el int nestedCollectionLevel = 0; while (CollectionDataContract.IsCollection(clrType, out itemType)) { - if (DataContract.GetBuiltInDataContract(clrType) != null + if (DataContract.GetBuiltInDataContract(clrType) is not null || CollectionDataContract.IsCollectionDataContract(clrType)) { break; @@ -269,11 +269,11 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el { genericArguments = clrType.GetGenericArguments(); string typeName; - if (clrType.DeclaringType == null) + if (clrType.DeclaringType is null) typeName = clrType.Name; else { - int nsLen = (clrType.Namespace == null) ? 0 : clrType.Namespace.Length; + int nsLen = (clrType.Namespace is null) ? 0 : clrType.Namespace.Length; if (nsLen > 0) nsLen++; //include the . following namespace typeName = DataContract.GetClrTypeFullName(clrType).Substring(nsLen).Replace('+', '.'); @@ -295,7 +295,7 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el XmlElement typeElement = XmlDoc.CreateElement(elementName, elementNs); XmlAttribute nameAttribute = XmlDoc.CreateAttribute(Globals.GenericNameAttribute); - nameAttribute.Value = genericArguments != null ? XmlConvert.DecodeName(dcqname.Name) : dcqname.Name; + nameAttribute.Value = genericArguments is not null ? XmlConvert.DecodeName(dcqname.Name) : dcqname.Name; //nameAttribute.Value = dcqname.Name; typeElement.Attributes.Append(nameAttribute); @@ -303,11 +303,11 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el nsAttribute.Value = dcqname.Namespace; typeElement.Attributes.Append(nsAttribute); - if (genericArguments != null) + if (genericArguments is not null) { int argIndex = 0; int nestedLevel = 0; - Debug.Assert(genericArgumentCounts != null); + Debug.Assert(genericArgumentCounts is not null); foreach (int genericArgumentCount in genericArgumentCounts) { for (int i = 0; i < genericArgumentCount; i++, argIndex++) @@ -405,7 +405,7 @@ private void ExportEnumDataContract(EnumDataContract enumDataContract, XmlSchema XmlSchemaSimpleType type = new XmlSchemaSimpleType(); type.Name = enumDataContract.StableName.Name; // https://github.com/dotnet/runtime/issues/41448 - enumDataContract.BaseContractName is always null, but this method is not reachable - Debug.Assert(enumDataContract.BaseContractName != null, "BaseContractName is always null, but this method is not reachable. Suppressing compiler error."); + Debug.Assert(enumDataContract.BaseContractName is not null, "BaseContractName is always null, but this method is not reachable. Suppressing compiler error."); XmlElement? actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName); type.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(enumDataContract)); schema.Items.Add(type); @@ -413,7 +413,7 @@ private void ExportEnumDataContract(EnumDataContract enumDataContract, XmlSchema XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = StringQualifiedName; SchemaHelper.AddSchemaImport(enumDataContract.BaseContractName.Namespace, schema); - if (enumDataContract.Values != null) + if (enumDataContract.Values is not null) { for (int i = 0; i < enumDataContract.Values.Count; i++) { @@ -451,7 +451,7 @@ private void ExportISerializableDataContract(ClassDataContract dataContract, Xml genericInfoElement = ExportGenericInfo(dataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); XmlElement? isValueTypeElement = null; - if (dataContract.BaseContract != null) + if (dataContract.BaseContract is not null) { _ = CreateTypeContent(type, dataContract.BaseContract.StableName, schema); } @@ -501,7 +501,7 @@ private void ExportXmlDataContract(XmlDataContract dataContract) XmlSchema? schema; if (SchemaHelper.GetSchemaElement(Schemas, new XmlQualifiedName(dataContract.TopLevelElementName!.Value, dataContract.TopLevelElementNamespace!.Value), - out schema) == null) + out schema) is null) { XmlSchemaElement topLevelElement = ExportTopLevelElement(dataContract, schema); topLevelElement.IsNillable = dataContract.IsTopLevelElementNullable; @@ -510,11 +510,11 @@ private void ExportXmlDataContract(XmlDataContract dataContract) XmlSchemaType? anonymousType = xsdType; xsdType = SchemaHelper.GetSchemaType(_schemas, typeQName, out schema); - if (anonymousType == null && xsdType == null && typeQName.Namespace != XmlSchema.Namespace) + if (anonymousType is null && xsdType is null && typeQName.Namespace != XmlSchema.Namespace) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeQName, DataContract.GetClrTypeFullName(clrType)))); } - if (xsdType != null) + if (xsdType is not null) { xsdType.Annotation = GetSchemaAnnotation( ExportSurrogateData(dataContract), @@ -555,7 +555,7 @@ private static void ReprocessAll(XmlSchemaSet schemas)// and remove duplicate it else continue; object? otherItem = items[qname]; - if (otherItem != null) + if (otherItem is not null) { schema.Items.Remove(item); } @@ -573,7 +573,7 @@ internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = null; InvokeSchemaProviderMethod(type, schemas, out stableName, out xsdType, out hasRoot); - if (stableName.Name == null || stableName.Name.Length == 0) + if (stableName.Name is null || stableName.Name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type)))); } @@ -582,7 +582,7 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema xsdType = null; hasRoot = true; object[] attrs = clrType.GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, false); - if (attrs == null || attrs.Length == 0) + if (attrs is null || attrs.Length == 0) { stableName = DataContract.GetDefaultStableName(clrType); return false; @@ -595,7 +595,7 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema hasRoot = false; } string? methodName = provider.MethodName; - if (methodName == null || methodName.Length == 0) + if (methodName is null || methodName.Length == 0) { if (!provider.IsAny) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType)))); @@ -604,7 +604,7 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema else { MethodInfo? getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null); - if (getMethod == null) + if (getMethod is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName))); if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType))) @@ -614,11 +614,11 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema if (provider.IsAny) { - if (typeInfo != null) + if (typeInfo is not null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidNonNullReturnValueByIsAny, DataContract.GetClrTypeFullName(clrType), methodName))); stableName = DataContract.GetDefaultStableName(clrType); } - else if (typeInfo == null) + else if (typeInfo is null) { xsdType = CreateAnyElementType(); hasRoot = false; @@ -627,11 +627,11 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema else { XmlSchemaType? providerXsdType = typeInfo as XmlSchemaType; - if (providerXsdType != null) + if (providerXsdType is not null) { string? typeName = providerXsdType.Name; string? typeNs = null; - if (typeName == null || typeName.Length == 0) + if (typeName is null || typeName.Length == 0) { DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs); stableName = new XmlQualifiedName(typeName, typeNs); @@ -647,15 +647,15 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema if ((object)schemaItem == (object)providerXsdType) { typeNs = schema.TargetNamespace; - if (typeNs == null) + if (typeNs is null) typeNs = string.Empty; break; } } - if (typeNs != null) + if (typeNs is not null) break; } - if (typeNs == null) + if (typeNs is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeName, DataContract.GetClrTypeFullName(clrType)))); stableName = new XmlQualifiedName(typeName, typeNs); } @@ -671,13 +671,13 @@ private static void InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, Xm { IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType)!; XmlSchema? schema = ixmlSerializable.GetSchema(); - if (schema == null) + if (schema is null) { AddDefaultDatasetType(schemas, stableName.Name, stableName.Namespace); } else { - if (schema.Id == null || schema.Id.Length == 0) + if (schema.Id is null || schema.Id.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnSchemaOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType)))); AddDefaultTypedDatasetType(schemas, schema, stableName.Name, stableName.Namespace); } @@ -765,7 +765,7 @@ private static void AddDefaultTypedDatasetType(XmlSchemaSet schemas, XmlSchema d type.Name = localName; type.Particle = new XmlSchemaSequence(); XmlSchemaAny any = new XmlSchemaAny(); - any.Namespace = (datasetSchema.TargetNamespace == null) ? string.Empty : datasetSchema.TargetNamespace; + any.Namespace = (datasetSchema.TargetNamespace is null) ? string.Empty : datasetSchema.TargetNamespace; ((XmlSchemaSequence)type.Particle).Items.Add(any); schemas.Add(datasetSchema); XmlSchema schema = SchemaHelper.GetSchema(ns, schemas); @@ -786,11 +786,11 @@ private XmlSchemaAnnotation GetSchemaAnnotation(XmlQualifiedName annotationQuali private static XmlSchemaAnnotation? GetSchemaAnnotation(params XmlNode?[]? nodes) { - if (nodes == null || nodes.Length == 0) + if (nodes is null || nodes.Length == 0) return null; bool hasAnnotation = false; for (int i = 0; i < nodes.Length; i++) - if (nodes[i] != null) + if (nodes[i] is not null) { hasAnnotation = true; break; @@ -850,7 +850,7 @@ internal static XmlQualifiedName AnytypeQualifiedName { get { - if (s_anytypeQualifiedName == null) + if (s_anytypeQualifiedName is null) s_anytypeQualifiedName = new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace); return s_anytypeQualifiedName; } @@ -861,7 +861,7 @@ internal static XmlQualifiedName StringQualifiedName { get { - if (s_stringQualifiedName == null) + if (s_stringQualifiedName is null) s_stringQualifiedName = new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace); return s_stringQualifiedName; } @@ -872,7 +872,7 @@ internal static XmlQualifiedName DefaultEnumBaseTypeName { get { - if (s_defaultEnumBaseTypeName == null) + if (s_defaultEnumBaseTypeName is null) s_defaultEnumBaseTypeName = new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace); return s_defaultEnumBaseTypeName; } @@ -883,7 +883,7 @@ internal static XmlQualifiedName EnumerationValueAnnotationName { get { - if (s_enumerationValueAnnotationName == null) + if (s_enumerationValueAnnotationName is null) s_enumerationValueAnnotationName = new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace); return s_enumerationValueAnnotationName; } @@ -894,7 +894,7 @@ internal static XmlQualifiedName SurrogateDataAnnotationName { get { - if (s_surrogateDataAnnotationName == null) + if (s_surrogateDataAnnotationName is null) s_surrogateDataAnnotationName = new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace); return s_surrogateDataAnnotationName; } @@ -905,7 +905,7 @@ internal static XmlQualifiedName DefaultValueAnnotation { get { - if (s_defaultValueAnnotation == null) + if (s_defaultValueAnnotation is null) s_defaultValueAnnotation = new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace); return s_defaultValueAnnotation; } @@ -916,7 +916,7 @@ internal static XmlQualifiedName ActualTypeAnnotationName { get { - if (s_actualTypeAnnotationName == null) + if (s_actualTypeAnnotationName is null) s_actualTypeAnnotationName = new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace); return s_actualTypeAnnotationName; } @@ -927,7 +927,7 @@ internal static XmlQualifiedName IsDictionaryAnnotationName { get { - if (s_isDictionaryAnnotationName == null) + if (s_isDictionaryAnnotationName is null) s_isDictionaryAnnotationName = new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace); return s_isDictionaryAnnotationName; } @@ -938,7 +938,7 @@ internal static XmlQualifiedName IsValueTypeName { get { - if (s_isValueTypeName == null) + if (s_isValueTypeName is null) s_isValueTypeName = new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace); return s_isValueTypeName; } 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 8a07b0e2fc9910..e11deca50a4210 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 @@ -14,8 +14,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 (ns1 is null || ns1.Length == 0) + return (ns2 is null || ns2.Length == 0); else return ns1 == ns2; } @@ -33,7 +33,7 @@ internal static bool NamespacesEqual(string? ns1, string? ns2) foreach (XmlSchemaObject schemaObj in schema.Items) { XmlSchemaType? schemaType = schemaObj as XmlSchemaType; - if (schemaType != null && schemaType.Name == typeQName.Name) + if (schemaType is not null && schemaType.Name == typeQName.Name) { return schemaType; } @@ -56,7 +56,7 @@ internal static bool NamespacesEqual(string? ns1, string? ns2) foreach (XmlSchemaObject schemaObj in schema.Items) { XmlSchemaElement? schemaElement = schemaObj as XmlSchemaElement; - if (schemaElement != null && schemaElement.Name == elementQName.Name) + if (schemaElement is not null && schemaElement.Name == elementQName.Name) { return schemaElement; } @@ -68,12 +68,12 @@ internal static bool NamespacesEqual(string? ns1, string? ns2) internal static XmlSchema GetSchema(string ns, XmlSchemaSet schemas) { - if (ns == null) { ns = string.Empty; } + if (ns is null) { ns = string.Empty; } ICollection currentSchemas = schemas.Schemas(); foreach (XmlSchema schema in currentSchemas) { - if ((schema.TargetNamespace == null && ns.Length == 0) || ns.Equals(schema.TargetNamespace)) + if ((schema.TargetNamespace is null && ns.Length == 0) || ns.Equals(schema.TargetNamespace)) { return schema; } @@ -120,7 +120,7 @@ internal static void AddSchemaImport(string ns, XmlSchema schema) } XmlSchemaImport import = new XmlSchemaImport(); - if (ns != null && ns.Length > 0) + if (ns is not null && ns.Length > 0) import.Namespace = ns; schema.Includes.Add(import); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs index e9414b2a899d20..521272db40082a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs @@ -13,7 +13,7 @@ internal struct ScopedKnownTypes private int _count; internal void Push(DataContractDictionary dataContractDictionary) { - if (dataContractDictionaries == null) + if (dataContractDictionaries is null) dataContractDictionaries = new DataContractDictionary[4]; else if (_count == dataContractDictionaries.Length) Array.Resize(ref dataContractDictionaries, dataContractDictionaries.Length * 2); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs index ebf41ee91263c1..fa05451a6653eb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs @@ -25,7 +25,7 @@ internal ISerializationSurrogate SerializationSurrogate public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); SerializationInfo serInfo = new SerializationInfo(UnderlyingType, XmlObjectSerializer.FormatterConverter, !context.UnsafeTypeForwardingEnabled); SerializationSurrogateGetObjectData(obj, serInfo, context.GetStreamingContext()); @@ -58,7 +58,7 @@ private void SerializationSurrogateGetObjectData(object obj, SerializationInfo s public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); xmlReader.Read(); Type objType = UnderlyingType; @@ -67,7 +67,7 @@ private void SerializationSurrogateGetObjectData(object obj, SerializationInfo s string objectId = context.GetObjectId(); SerializationInfo serInfo = context.ReadSerializationInfo(xmlReader, objType); object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()); - if (newObj == null) + if (newObj is null) newObj = obj; if (newObj is IDeserializationCallback) ((IDeserializationCallback)newObj).OnDeserialization(null); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/TypeCode.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/TypeCode.cs index f9b2b9d4ca526d..34536e50f37b4a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/TypeCode.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/TypeCode.cs @@ -7,7 +7,7 @@ internal static class TypeExtensionMethods { public static TypeCode GetTypeCode(this Type type) { - if (type == null) + if (type is null) { return TypeCode.Empty; } 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 7c0a0a9bb53769..e7eab23bb47322 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 @@ -25,11 +25,11 @@ public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pa // Here you can provide your own root element Xpath which will replace the Xpath of the top level element public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder? rootElementXpath, out XmlNamespaceManager namespaces) { - if (type == null) + if (type is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); } - if (pathToMember == null) + if (pathToMember is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(pathToMember))); } @@ -37,7 +37,7 @@ public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pa DataContract currentContract = DataContract.GetDataContract(type); ExportContext context; - if (rootElementXpath == null) + if (rootElementXpath is null) { context = new ExportContext(currentContract); } @@ -81,14 +81,14 @@ private static DataContract ProcessClassDataContract(ClassDataContract contract, private static IEnumerable GetDataMembers(ClassDataContract contract) { - if (contract.BaseContract != null) + if (contract.BaseContract is not null) { foreach (DataMember baseClassMember in GetDataMembers(contract.BaseContract)) { yield return baseClassMember; } } - if (contract.Members != null) + if (contract.Members is not null) { foreach (DataMember member in contract.Members) { @@ -140,7 +140,7 @@ public string XPath public string SetNamespace(string ns) { string? prefix = _namespaces.LookupPrefix(ns); - if (prefix == null || prefix.Length == 0) + if (prefix is null || prefix.Length == 0) { 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 6dfadbd82d391d..f6e84738b03fa1 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 @@ -88,11 +88,11 @@ internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate // otherwise, we would create the delegate via reflection. if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { - if (_helper.CreateXmlSerializableDelegate == null) + if (_helper.CreateXmlSerializableDelegate is null) { lock (this) { - if (_helper.CreateXmlSerializableDelegate == null) + if (_helper.CreateXmlSerializableDelegate is null) { CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate(); Interlocked.MemoryBarrier(); @@ -137,8 +137,8 @@ internal XmlDataContractCriticalHelper(Type type) : base(type) XmlDictionary dictionary = new XmlDictionary(); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); - object[]? xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); - if (xmlRootAttributes == null || xmlRootAttributes.Length == 0) + object[]? xmlRootAttributes = (UnderlyingType is null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); + if (xmlRootAttributes is null || xmlRootAttributes.Length == 0) { if (hasRoot) { @@ -154,9 +154,9 @@ internal XmlDataContractCriticalHelper(Type type) : base(type) 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 = (elementName is null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); string? elementNs = xmlRootAttribute.Namespace; - _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); + _topLevelElementNamespace = (elementNs is null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); } else { @@ -169,7 +169,7 @@ internal override DataContractDictionary? KnownDataContracts { get { - if (!_isKnownTypeAttributeChecked && UnderlyingType != null) + if (!_isKnownTypeAttributeChecked && UnderlyingType is not null) { lock (this) { @@ -194,7 +194,7 @@ internal XmlSchemaType? XsdType set { _xsdType = value; } } - internal bool IsAnonymous => _xsdType != null; + internal bool IsAnonymous => _xsdType is not null; internal override bool HasRoot { @@ -242,7 +242,7 @@ internal CreateXmlSerializableDelegate? CreateXmlSerializableDelegate return null; ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Array.Empty(), null); - if (ctor == null) + if (ctor is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; @@ -283,7 +283,7 @@ internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement") { Type? xName = type.Assembly.GetType("System.Xml.Linq.XName"); - if (xName != null) + if (xName is not null) { MethodInfo? XName_op_Implicit = xName.GetMethod( "op_Implicit", @@ -298,7 +298,7 @@ internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() new Type[] { xName }, null ); - if (XName_op_Implicit != null && XElement_ctor != null) + if (XName_op_Implicit is not null && XElement_ctor is not null) { ilg.Ldstr("default"); ilg.Call(XName_op_Implicit); @@ -322,7 +322,7 @@ private bool RequiresMemberAccessForCreate(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), @@ -333,7 +333,7 @@ private bool RequiresMemberAccessForCreate(SecurityException? securityException) if (ConstructorRequiresMemberAccess(GetConstructor())) { - if (securityException != null) + if (securityException is not null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), @@ -370,7 +370,7 @@ internal IXmlSerializable ReflectionCreateXmlSerializable(Type type) public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { - if (context == null) + if (context is null) XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj); else context.WriteIXmlSerializable(xmlWriter, obj); @@ -379,7 +379,7 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { object? o; - if (context == null) + if (context is null) { o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs index 3cbcba6288fecd..79b8ba37e319c2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs @@ -15,10 +15,10 @@ internal static MethodInfo WriteStartElementMethod2 { get { - if (s_writeStartElementMethod2 == null) + if (s_writeStartElementMethod2 is null) { s_writeStartElementMethod2 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, null, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); - Debug.Assert(s_writeStartElementMethod2 != null); + Debug.Assert(s_writeStartElementMethod2 is not null); } return s_writeStartElementMethod2; } @@ -29,10 +29,10 @@ internal static MethodInfo WriteStartElementMethod3 { get { - if (s_writeStartElementMethod3 == null) + if (s_writeStartElementMethod3 is null) { s_writeStartElementMethod3 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, null, new Type[] { typeof(string), typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); - Debug.Assert(s_writeStartElementMethod3 != null); + Debug.Assert(s_writeStartElementMethod3 is not null); } return s_writeStartElementMethod3; } @@ -43,10 +43,10 @@ internal static MethodInfo WriteEndElementMethod { get { - if (s_writeEndElementMethod == null) + if (s_writeEndElementMethod is null) { s_writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", Globals.ScanAllMembers, null, Array.Empty(), null); - Debug.Assert(s_writeEndElementMethod != null); + Debug.Assert(s_writeEndElementMethod is not null); } return s_writeEndElementMethod; } @@ -57,10 +57,10 @@ internal static MethodInfo WriteNamespaceDeclMethod { get { - if (s_writeNamespaceDeclMethod == null) + if (s_writeNamespaceDeclMethod is null) { s_writeNamespaceDeclMethod = typeof(XmlWriterDelegator).GetMethod("WriteNamespaceDecl", Globals.ScanAllMembers, null, new Type[] { typeof(XmlDictionaryString) }, null); - Debug.Assert(s_writeNamespaceDeclMethod != null); + Debug.Assert(s_writeNamespaceDeclMethod is not null); } return s_writeNamespaceDeclMethod; } @@ -75,10 +75,10 @@ internal static ConstructorInfo DictionaryEnumeratorCtor { get { - if (s_dictionaryEnumeratorCtor == null) + if (s_dictionaryEnumeratorCtor is null) { s_dictionaryEnumeratorCtor = typeof(CollectionDataContract.DictionaryEnumerator).GetConstructor(Globals.ScanAllMembers, null, new Type[] { Globals.TypeOfIDictionaryEnumerator }, null); - Debug.Assert(s_dictionaryEnumeratorCtor != null); + Debug.Assert(s_dictionaryEnumeratorCtor is not null); } return s_dictionaryEnumeratorCtor; } @@ -89,10 +89,10 @@ internal static MethodInfo MoveNextMethod { get { - if (s_ienumeratorMoveNextMethod == null) + if (s_ienumeratorMoveNextMethod is null) { s_ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext"); - Debug.Assert(s_ienumeratorMoveNextMethod != null); + Debug.Assert(s_ienumeratorMoveNextMethod is not null); } return s_ienumeratorMoveNextMethod; } @@ -103,10 +103,10 @@ internal static MethodInfo GetCurrentMethod { get { - if (s_ienumeratorGetCurrentMethod == null) + if (s_ienumeratorGetCurrentMethod is null) { s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current")!.GetGetMethod(); - Debug.Assert(s_ienumeratorGetCurrentMethod != null); + Debug.Assert(s_ienumeratorGetCurrentMethod is not null); } return s_ienumeratorGetCurrentMethod; } @@ -117,10 +117,10 @@ internal static MethodInfo GetItemContractMethod { get { - if (s_getItemContractMethod == null) + if (s_getItemContractMethod is null) { s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers)!.GetMethod; - Debug.Assert(s_getItemContractMethod != null); + Debug.Assert(s_getItemContractMethod is not null); } return s_getItemContractMethod; } @@ -131,10 +131,10 @@ internal static MethodInfo IsStartElementMethod2 { get { - if (s_isStartElementMethod2 == null) + if (s_isStartElementMethod2 is null) { s_isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, null, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); - Debug.Assert(s_isStartElementMethod2 != null); + Debug.Assert(s_isStartElementMethod2 is not null); } return s_isStartElementMethod2; } @@ -145,10 +145,10 @@ internal static MethodInfo IsStartElementMethod0 { get { - if (s_isStartElementMethod0 == null) + if (s_isStartElementMethod0 is null) { s_isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, null, Array.Empty(), null); - Debug.Assert(s_isStartElementMethod0 != null); + Debug.Assert(s_isStartElementMethod0 is not null); } return s_isStartElementMethod0; } @@ -159,10 +159,10 @@ internal static MethodInfo GetUninitializedObjectMethod { get { - if (s_getUninitializedObjectMethod == null) + if (s_getUninitializedObjectMethod is null) { s_getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", Globals.ScanAllMembers, null, new Type[] { typeof(int) }, null); - Debug.Assert(s_getUninitializedObjectMethod != null); + Debug.Assert(s_getUninitializedObjectMethod is not null); } return s_getUninitializedObjectMethod; } @@ -173,10 +173,10 @@ internal static MethodInfo OnDeserializationMethod { get { - if (s_onDeserializationMethod == null) + if (s_onDeserializationMethod is null) { s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization"); - Debug.Assert(s_onDeserializationMethod != null); + Debug.Assert(s_onDeserializationMethod is not null); } return s_onDeserializationMethod; } @@ -187,10 +187,10 @@ internal static PropertyInfo NodeTypeProperty { get { - if (s_nodeTypeProperty == null) + if (s_nodeTypeProperty is null) { s_nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", Globals.ScanAllMembers); - Debug.Assert(s_nodeTypeProperty != null); + Debug.Assert(s_nodeTypeProperty is not null); } return s_nodeTypeProperty; } @@ -206,10 +206,10 @@ internal static ConstructorInfo HashtableCtor { get { - if (s_hashtableCtor == null) + if (s_hashtableCtor is null) { s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, null, Array.Empty(), null); - Debug.Assert(s_hashtableCtor != null); + Debug.Assert(s_hashtableCtor is not null); } return s_hashtableCtor; } @@ -220,10 +220,10 @@ internal static MethodInfo GetStreamingContextMethod { get { - if (s_getStreamingContextMethod == null) + if (s_getStreamingContextMethod is null) { s_getStreamingContextMethod = typeof(XmlObjectSerializerContext).GetMethod("GetStreamingContext", Globals.ScanAllMembers); - Debug.Assert(s_getStreamingContextMethod != null); + Debug.Assert(s_getStreamingContextMethod is not null); } return s_getStreamingContextMethod; } @@ -234,10 +234,10 @@ internal static MethodInfo GetCollectionMemberMethod { get { - if (s_getCollectionMemberMethod == null) + if (s_getCollectionMemberMethod is null) { s_getCollectionMemberMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetCollectionMember", Globals.ScanAllMembers); - Debug.Assert(s_getCollectionMemberMethod != null); + Debug.Assert(s_getCollectionMemberMethod is not null); } return s_getCollectionMemberMethod; } @@ -248,10 +248,10 @@ internal static MethodInfo StoreCollectionMemberInfoMethod { get { - if (s_storeCollectionMemberInfoMethod == null) + if (s_storeCollectionMemberInfoMethod is null) { s_storeCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("StoreCollectionMemberInfo", Globals.ScanAllMembers, null, new Type[] { typeof(object) }, null); - Debug.Assert(s_storeCollectionMemberInfoMethod != null); + Debug.Assert(s_storeCollectionMemberInfoMethod is not null); } return s_storeCollectionMemberInfoMethod; } @@ -262,10 +262,10 @@ internal static MethodInfo ResetCollectionMemberInfoMethod { get { - if (s_resetCollectionMemberInfoMethod == null) + if (s_resetCollectionMemberInfoMethod is null) { s_resetCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetCollectionMemberInfo", Globals.ScanAllMembers, null, Array.Empty(), null); - Debug.Assert(s_resetCollectionMemberInfoMethod != null); + Debug.Assert(s_resetCollectionMemberInfoMethod is not null); } return s_resetCollectionMemberInfoMethod; } @@ -276,10 +276,10 @@ internal static MethodInfo StoreIsGetOnlyCollectionMethod { get { - if (s_storeIsGetOnlyCollectionMethod == null) + if (s_storeIsGetOnlyCollectionMethod is null) { s_storeIsGetOnlyCollectionMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("StoreIsGetOnlyCollection", Globals.ScanAllMembers); - Debug.Assert(s_storeIsGetOnlyCollectionMethod != null); + Debug.Assert(s_storeIsGetOnlyCollectionMethod is not null); } return s_storeIsGetOnlyCollectionMethod; } @@ -290,10 +290,10 @@ internal static MethodInfo ResetIsGetOnlyCollectionMethod { get { - if (s_resetIsGetOnlyCollection == null) + if (s_resetIsGetOnlyCollection is null) { s_resetIsGetOnlyCollection = typeof(XmlObjectSerializerWriteContext).GetMethod("ResetIsGetOnlyCollection", Globals.ScanAllMembers); - Debug.Assert(s_resetIsGetOnlyCollection != null); + Debug.Assert(s_resetIsGetOnlyCollection is not null); } return s_resetIsGetOnlyCollection; } @@ -304,10 +304,10 @@ internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMe { get { - if (s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod == null) + if (s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod is null) { s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowNullValueReturnedForGetOnlyCollectionException", Globals.ScanAllMembers); - Debug.Assert(s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod != null); + Debug.Assert(s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod is not null); } return s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod; } @@ -318,10 +318,10 @@ internal static MethodInfo ThrowArrayExceededSizeExceptionMethod { get { - if (s_throwArrayExceededSizeExceptionMethod == null) + if (s_throwArrayExceededSizeExceptionMethod is null) { s_throwArrayExceededSizeExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowArrayExceededSizeException", Globals.ScanAllMembers); - Debug.Assert(s_throwArrayExceededSizeExceptionMethod != null); + Debug.Assert(s_throwArrayExceededSizeExceptionMethod is not null); } return s_throwArrayExceededSizeExceptionMethod; } @@ -332,10 +332,10 @@ internal static MethodInfo IncrementItemCountMethod { get { - if (s_incrementItemCountMethod == null) + if (s_incrementItemCountMethod is null) { s_incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", Globals.ScanAllMembers); - Debug.Assert(s_incrementItemCountMethod != null); + Debug.Assert(s_incrementItemCountMethod is not null); } return s_incrementItemCountMethod; } @@ -346,10 +346,10 @@ internal static MethodInfo InternalDeserializeMethod { get { - if (s_internalDeserializeMethod == null) + if (s_internalDeserializeMethod is null) { s_internalDeserializeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("InternalDeserialize", Globals.ScanAllMembers, null, new Type[] { typeof(XmlReaderDelegator), typeof(int), typeof(RuntimeTypeHandle), typeof(string), typeof(string) }, null); - Debug.Assert(s_internalDeserializeMethod != null); + Debug.Assert(s_internalDeserializeMethod is not null); } return s_internalDeserializeMethod; } @@ -360,10 +360,10 @@ internal static MethodInfo MoveToNextElementMethod { get { - if (s_moveToNextElementMethod == null) + if (s_moveToNextElementMethod is null) { s_moveToNextElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("MoveToNextElement", Globals.ScanAllMembers); - Debug.Assert(s_moveToNextElementMethod != null); + Debug.Assert(s_moveToNextElementMethod is not null); } return s_moveToNextElementMethod; } @@ -374,10 +374,10 @@ internal static MethodInfo GetMemberIndexMethod { get { - if (s_getMemberIndexMethod == null) + if (s_getMemberIndexMethod is null) { s_getMemberIndexMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndex", Globals.ScanAllMembers); - Debug.Assert(s_getMemberIndexMethod != null); + Debug.Assert(s_getMemberIndexMethod is not null); } return s_getMemberIndexMethod; } @@ -388,10 +388,10 @@ internal static MethodInfo GetMemberIndexWithRequiredMembersMethod { get { - if (s_getMemberIndexWithRequiredMembersMethod == null) + if (s_getMemberIndexWithRequiredMembersMethod is null) { s_getMemberIndexWithRequiredMembersMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndexWithRequiredMembers", Globals.ScanAllMembers); - Debug.Assert(s_getMemberIndexWithRequiredMembersMethod != null); + Debug.Assert(s_getMemberIndexWithRequiredMembersMethod is not null); } return s_getMemberIndexWithRequiredMembersMethod; } @@ -402,10 +402,10 @@ internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod { get { - if (s_throwRequiredMemberMissingExceptionMethod == null) + if (s_throwRequiredMemberMissingExceptionMethod is null) { s_throwRequiredMemberMissingExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowRequiredMemberMissingException", Globals.ScanAllMembers); - Debug.Assert(s_throwRequiredMemberMissingExceptionMethod != null); + Debug.Assert(s_throwRequiredMemberMissingExceptionMethod is not null); } return s_throwRequiredMemberMissingExceptionMethod; } @@ -416,10 +416,10 @@ internal static MethodInfo SkipUnknownElementMethod { get { - if (s_skipUnknownElementMethod == null) + if (s_skipUnknownElementMethod is null) { s_skipUnknownElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("SkipUnknownElement", Globals.ScanAllMembers); - Debug.Assert(s_skipUnknownElementMethod != null); + Debug.Assert(s_skipUnknownElementMethod is not null); } return s_skipUnknownElementMethod; } @@ -430,10 +430,10 @@ internal static MethodInfo ReadIfNullOrRefMethod { get { - if (s_readIfNullOrRefMethod == null) + if (s_readIfNullOrRefMethod is null) { s_readIfNullOrRefMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadIfNullOrRef", Globals.ScanAllMembers, null, new Type[] { typeof(XmlReaderDelegator), typeof(Type), typeof(bool) }, null); - Debug.Assert(s_readIfNullOrRefMethod != null); + Debug.Assert(s_readIfNullOrRefMethod is not null); } return s_readIfNullOrRefMethod; } @@ -444,10 +444,10 @@ internal static MethodInfo ReadAttributesMethod { get { - if (s_readAttributesMethod == null) + if (s_readAttributesMethod is null) { s_readAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadAttributes", Globals.ScanAllMembers); - Debug.Assert(s_readAttributesMethod != null); + Debug.Assert(s_readAttributesMethod is not null); } return s_readAttributesMethod; } @@ -458,10 +458,10 @@ internal static MethodInfo ResetAttributesMethod { get { - if (s_resetAttributesMethod == null) + if (s_resetAttributesMethod is null) { s_resetAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetAttributes", Globals.ScanAllMembers); - Debug.Assert(s_resetAttributesMethod != null); + Debug.Assert(s_resetAttributesMethod is not null); } return s_resetAttributesMethod; } @@ -472,10 +472,10 @@ internal static MethodInfo GetObjectIdMethod { get { - if (s_getObjectIdMethod == null) + if (s_getObjectIdMethod is null) { s_getObjectIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetObjectId", Globals.ScanAllMembers); - Debug.Assert(s_getObjectIdMethod != null); + Debug.Assert(s_getObjectIdMethod is not null); } return s_getObjectIdMethod; } @@ -486,10 +486,10 @@ internal static MethodInfo GetArraySizeMethod { get { - if (s_getArraySizeMethod == null) + if (s_getArraySizeMethod is null) { s_getArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetArraySize", Globals.ScanAllMembers); - Debug.Assert(s_getArraySizeMethod != null); + Debug.Assert(s_getArraySizeMethod is not null); } return s_getArraySizeMethod; } @@ -500,10 +500,10 @@ internal static MethodInfo AddNewObjectMethod { get { - if (s_addNewObjectMethod == null) + if (s_addNewObjectMethod is null) { s_addNewObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObject", Globals.ScanAllMembers); - Debug.Assert(s_addNewObjectMethod != null); + Debug.Assert(s_addNewObjectMethod is not null); } return s_addNewObjectMethod; } @@ -514,10 +514,10 @@ internal static MethodInfo AddNewObjectWithIdMethod { get { - if (s_addNewObjectWithIdMethod == null) + if (s_addNewObjectWithIdMethod is null) { s_addNewObjectWithIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObjectWithId", Globals.ScanAllMembers); - Debug.Assert(s_addNewObjectWithIdMethod != null); + Debug.Assert(s_addNewObjectWithIdMethod is not null); } return s_addNewObjectWithIdMethod; } @@ -528,10 +528,10 @@ internal static MethodInfo GetExistingObjectMethod { get { - if (s_getExistingObjectMethod == null) + if (s_getExistingObjectMethod is null) { s_getExistingObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetExistingObject", Globals.ScanAllMembers); - Debug.Assert(s_getExistingObjectMethod != null); + Debug.Assert(s_getExistingObjectMethod is not null); } return s_getExistingObjectMethod; } @@ -542,10 +542,10 @@ internal static MethodInfo GetRealObjectMethod { get { - if (s_getRealObjectMethod == null) + if (s_getRealObjectMethod is null) { s_getRealObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetRealObject", Globals.ScanAllMembers); - Debug.Assert(s_getRealObjectMethod != null); + Debug.Assert(s_getRealObjectMethod is not null); } return s_getRealObjectMethod; } @@ -556,10 +556,10 @@ internal static MethodInfo EnsureArraySizeMethod { get { - if (s_ensureArraySizeMethod == null) + if (s_ensureArraySizeMethod is null) { s_ensureArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("EnsureArraySize", Globals.ScanAllMembers); - Debug.Assert(s_ensureArraySizeMethod != null); + Debug.Assert(s_ensureArraySizeMethod is not null); } return s_ensureArraySizeMethod; } @@ -570,10 +570,10 @@ internal static MethodInfo TrimArraySizeMethod { get { - if (s_trimArraySizeMethod == null) + if (s_trimArraySizeMethod is null) { s_trimArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("TrimArraySize", Globals.ScanAllMembers); - Debug.Assert(s_trimArraySizeMethod != null); + Debug.Assert(s_trimArraySizeMethod is not null); } return s_trimArraySizeMethod; } @@ -584,10 +584,10 @@ internal static MethodInfo CheckEndOfArrayMethod { get { - if (s_checkEndOfArrayMethod == null) + if (s_checkEndOfArrayMethod is null) { s_checkEndOfArrayMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CheckEndOfArray", Globals.ScanAllMembers); - Debug.Assert(s_checkEndOfArrayMethod != null); + Debug.Assert(s_checkEndOfArrayMethod is not null); } return s_checkEndOfArrayMethod; } @@ -598,10 +598,10 @@ internal static MethodInfo GetArrayLengthMethod { get { - if (s_getArrayLengthMethod == null) + if (s_getArrayLengthMethod is null) { s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length")!.GetMethod; - Debug.Assert(s_getArrayLengthMethod != null); + Debug.Assert(s_getArrayLengthMethod is not null); } return s_getArrayLengthMethod; } @@ -612,10 +612,10 @@ internal static MethodInfo CreateSerializationExceptionMethod { get { - if (s_createSerializationExceptionMethod == null) + if (s_createSerializationExceptionMethod is null) { s_createSerializationExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateSerializationException", Globals.ScanAllMembers, null, new Type[] { typeof(string) }, null); - Debug.Assert(s_createSerializationExceptionMethod != null); + Debug.Assert(s_createSerializationExceptionMethod is not null); } return s_createSerializationExceptionMethod; } @@ -626,10 +626,10 @@ internal static MethodInfo ReadSerializationInfoMethod { get { - if (s_readSerializationInfoMethod == null) + if (s_readSerializationInfoMethod is null) { s_readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", Globals.ScanAllMembers); - Debug.Assert(s_readSerializationInfoMethod != null); + Debug.Assert(s_readSerializationInfoMethod is not null); } return s_readSerializationInfoMethod; } @@ -640,10 +640,10 @@ internal static MethodInfo CreateUnexpectedStateExceptionMethod { get { - if (s_createUnexpectedStateExceptionMethod == null) + if (s_createUnexpectedStateExceptionMethod is null) { s_createUnexpectedStateExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateUnexpectedStateException", Globals.ScanAllMembers, null, new Type[] { typeof(XmlNodeType), typeof(XmlReaderDelegator) }, null); - Debug.Assert(s_createUnexpectedStateExceptionMethod != null); + Debug.Assert(s_createUnexpectedStateExceptionMethod is not null); } return s_createUnexpectedStateExceptionMethod; } @@ -654,10 +654,10 @@ internal static MethodInfo InternalSerializeReferenceMethod { get { - if (s_internalSerializeReferenceMethod == null) + if (s_internalSerializeReferenceMethod is null) { s_internalSerializeReferenceMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerializeReference", Globals.ScanAllMembers); - Debug.Assert(s_internalSerializeReferenceMethod != null); + Debug.Assert(s_internalSerializeReferenceMethod is not null); } return s_internalSerializeReferenceMethod; } @@ -668,10 +668,10 @@ internal static MethodInfo InternalSerializeMethod { get { - if (s_internalSerializeMethod == null) + if (s_internalSerializeMethod is null) { s_internalSerializeMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerialize", Globals.ScanAllMembers); - Debug.Assert(s_internalSerializeMethod != null); + Debug.Assert(s_internalSerializeMethod is not null); } return s_internalSerializeMethod; } @@ -682,10 +682,10 @@ internal static MethodInfo WriteNullMethod { get { - if (s_writeNullMethod == null) + if (s_writeNullMethod is null) { s_writeNullMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteNull", Globals.ScanAllMembers, null, new Type[] { typeof(XmlWriterDelegator), typeof(Type), typeof(bool) }, null); - Debug.Assert(s_writeNullMethod != null); + Debug.Assert(s_writeNullMethod is not null); } return s_writeNullMethod; } @@ -696,10 +696,10 @@ internal static MethodInfo IncrementArrayCountMethod { get { - if (s_incrementArrayCountMethod == null) + if (s_incrementArrayCountMethod is null) { s_incrementArrayCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementArrayCount", Globals.ScanAllMembers); - Debug.Assert(s_incrementArrayCountMethod != null); + Debug.Assert(s_incrementArrayCountMethod is not null); } return s_incrementArrayCountMethod; } @@ -710,10 +710,10 @@ internal static MethodInfo IncrementCollectionCountMethod { get { - if (s_incrementCollectionCountMethod == null) + if (s_incrementCollectionCountMethod is null) { s_incrementCollectionCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCount", Globals.ScanAllMembers, null, new Type[] { typeof(XmlWriterDelegator), typeof(ICollection) }, null); - Debug.Assert(s_incrementCollectionCountMethod != null); + Debug.Assert(s_incrementCollectionCountMethod is not null); } return s_incrementCollectionCountMethod; } @@ -724,10 +724,10 @@ internal static MethodInfo IncrementCollectionCountGenericMethod { get { - if (s_incrementCollectionCountGenericMethod == null) + if (s_incrementCollectionCountGenericMethod is null) { s_incrementCollectionCountGenericMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCountGeneric", Globals.ScanAllMembers); - Debug.Assert(s_incrementCollectionCountGenericMethod != null); + Debug.Assert(s_incrementCollectionCountGenericMethod is not null); } return s_incrementCollectionCountGenericMethod; } @@ -738,10 +738,10 @@ internal static MethodInfo GetDefaultValueMethod { get { - if (s_getDefaultValueMethod == null) + if (s_getDefaultValueMethod is null) { s_getDefaultValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(nameof(XmlObjectSerializerWriteContext.GetDefaultValue), Globals.ScanAllMembers); - Debug.Assert(s_getDefaultValueMethod != null); + Debug.Assert(s_getDefaultValueMethod is not null); } return s_getDefaultValueMethod; } @@ -757,10 +757,10 @@ internal static MethodInfo GetNullableValueMethod { get { - if (s_getNullableValueMethod == null) + if (s_getNullableValueMethod is null) { s_getNullableValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetNullableValue", Globals.ScanAllMembers); - Debug.Assert(s_getNullableValueMethod != null); + Debug.Assert(s_getNullableValueMethod is not null); } return s_getNullableValueMethod; } @@ -771,10 +771,10 @@ internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod { get { - if (s_throwRequiredMemberMustBeEmittedMethod == null) + if (s_throwRequiredMemberMustBeEmittedMethod is null) { s_throwRequiredMemberMustBeEmittedMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("ThrowRequiredMemberMustBeEmitted", Globals.ScanAllMembers); - Debug.Assert(s_throwRequiredMemberMustBeEmittedMethod != null); + Debug.Assert(s_throwRequiredMemberMustBeEmittedMethod is not null); } return s_throwRequiredMemberMustBeEmittedMethod; } @@ -785,10 +785,10 @@ internal static MethodInfo GetHasValueMethod { get { - if (s_getHasValueMethod == null) + if (s_getHasValueMethod is null) { s_getHasValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetHasValue", Globals.ScanAllMembers); - Debug.Assert(s_getHasValueMethod != null); + Debug.Assert(s_getHasValueMethod is not null); } return s_getHasValueMethod; } @@ -799,10 +799,10 @@ internal static MethodInfo WriteISerializableMethod { get { - if (s_writeISerializableMethod == null) + if (s_writeISerializableMethod is null) { s_writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", Globals.ScanAllMembers); - Debug.Assert(s_writeISerializableMethod != null); + Debug.Assert(s_writeISerializableMethod is not null); } return s_writeISerializableMethod; } @@ -814,10 +814,10 @@ internal static MethodInfo IsMemberTypeSameAsMemberValue { get { - if (s_isMemberTypeSameAsMemberValue == null) + if (s_isMemberTypeSameAsMemberValue is null) { s_isMemberTypeSameAsMemberValue = typeof(XmlObjectSerializerWriteContext).GetMethod("IsMemberTypeSameAsMemberValue", Globals.ScanAllMembers, null, new Type[] { typeof(object), typeof(Type) }, null); - Debug.Assert(s_isMemberTypeSameAsMemberValue != null); + Debug.Assert(s_isMemberTypeSameAsMemberValue is not null); } return s_isMemberTypeSameAsMemberValue; } @@ -832,10 +832,10 @@ internal static MethodInfo WriteXmlValueMethod { get { - if (s_writeXmlValueMethod == null) + if (s_writeXmlValueMethod is null) { s_writeXmlValueMethod = typeof(DataContract).GetMethod("WriteXmlValue", Globals.ScanAllMembers); - Debug.Assert(s_writeXmlValueMethod != null); + Debug.Assert(s_writeXmlValueMethod is not null); } return s_writeXmlValueMethod; } @@ -846,10 +846,10 @@ internal static MethodInfo ReadXmlValueMethod { get { - if (s_readXmlValueMethod == null) + if (s_readXmlValueMethod is null) { s_readXmlValueMethod = typeof(DataContract).GetMethod("ReadXmlValue", Globals.ScanAllMembers); - Debug.Assert(s_readXmlValueMethod != null); + Debug.Assert(s_readXmlValueMethod is not null); } return s_readXmlValueMethod; } @@ -860,10 +860,10 @@ internal static PropertyInfo NamespaceProperty { get { - if (s_namespaceProperty == null) + if (s_namespaceProperty is null) { s_namespaceProperty = typeof(DataContract).GetProperty("Namespace", Globals.ScanAllMembers); - Debug.Assert(s_namespaceProperty != null); + Debug.Assert(s_namespaceProperty is not null); } return s_namespaceProperty; } @@ -874,10 +874,10 @@ internal static FieldInfo ContractNamespacesField { get { - if (s_contractNamespacesField == null) + if (s_contractNamespacesField is null) { s_contractNamespacesField = typeof(ClassDataContract).GetField("ContractNamespaces", Globals.ScanAllMembers); - Debug.Assert(s_contractNamespacesField != null); + Debug.Assert(s_contractNamespacesField is not null); } return s_contractNamespacesField; } @@ -888,10 +888,10 @@ internal static FieldInfo MemberNamesField { get { - if (s_memberNamesField == null) + if (s_memberNamesField is null) { s_memberNamesField = typeof(ClassDataContract).GetField("MemberNames", Globals.ScanAllMembers); - Debug.Assert(s_memberNamesField != null); + Debug.Assert(s_memberNamesField is not null); } return s_memberNamesField; } @@ -906,10 +906,10 @@ internal static PropertyInfo ChildElementNamespacesProperty { get { - if (s_childElementNamespacesProperty == null) + if (s_childElementNamespacesProperty is null) { s_childElementNamespacesProperty = typeof(ClassDataContract).GetProperty("ChildElementNamespaces", Globals.ScanAllMembers); - Debug.Assert(s_childElementNamespacesProperty != null); + Debug.Assert(s_childElementNamespacesProperty is not null); } return s_childElementNamespacesProperty; } @@ -920,10 +920,10 @@ internal static PropertyInfo CollectionItemNameProperty { get { - if (s_collectionItemNameProperty == null) + if (s_collectionItemNameProperty is null) { s_collectionItemNameProperty = typeof(CollectionDataContract).GetProperty("CollectionItemName", Globals.ScanAllMembers); - Debug.Assert(s_collectionItemNameProperty != null); + Debug.Assert(s_collectionItemNameProperty is not null); } return s_collectionItemNameProperty; } @@ -934,10 +934,10 @@ internal static PropertyInfo ChildElementNamespaceProperty { get { - if (s_childElementNamespaceProperty == null) + if (s_childElementNamespaceProperty is null) { s_childElementNamespaceProperty = typeof(CollectionDataContract).GetProperty("ChildElementNamespace", Globals.ScanAllMembers); - Debug.Assert(s_childElementNamespaceProperty != null); + Debug.Assert(s_childElementNamespaceProperty is not null); } return s_childElementNamespaceProperty; } @@ -948,10 +948,10 @@ internal static MethodInfo GetDateTimeOffsetMethod { get { - if (s_getDateTimeOffsetMethod == null) + if (s_getDateTimeOffsetMethod is null) { s_getDateTimeOffsetMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffset", Globals.ScanAllMembers); - Debug.Assert(s_getDateTimeOffsetMethod != null); + Debug.Assert(s_getDateTimeOffsetMethod is not null); } return s_getDateTimeOffsetMethod; } @@ -962,10 +962,10 @@ internal static MethodInfo GetDateTimeOffsetAdapterMethod { get { - if (s_getDateTimeOffsetAdapterMethod == null) + if (s_getDateTimeOffsetAdapterMethod is null) { s_getDateTimeOffsetAdapterMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffsetAdapter", Globals.ScanAllMembers); - Debug.Assert(s_getDateTimeOffsetAdapterMethod != null); + Debug.Assert(s_getDateTimeOffsetAdapterMethod is not null); } return s_getDateTimeOffsetAdapterMethod; } @@ -976,10 +976,10 @@ internal static MethodInfo GetTypeHandleMethod { get { - if (s_getTypeHandleMethod == null) + if (s_getTypeHandleMethod is null) { s_getTypeHandleMethod = typeof(Type).GetMethod("get_TypeHandle"); - Debug.Assert(s_getTypeHandleMethod != null); + Debug.Assert(s_getTypeHandleMethod is not null); } return s_getTypeHandleMethod; } @@ -990,10 +990,10 @@ internal static MethodInfo GetTypeMethod { get { - if (s_getTypeMethod == null) + if (s_getTypeMethod is null) { s_getTypeMethod = typeof(object).GetMethod("GetType"); - Debug.Assert(s_getTypeMethod != null); + Debug.Assert(s_getTypeMethod is not null); } return s_getTypeMethod; } @@ -1004,10 +1004,10 @@ internal static MethodInfo ThrowInvalidDataContractExceptionMethod { get { - if (s_throwInvalidDataContractExceptionMethod == null) + if (s_throwInvalidDataContractExceptionMethod is null) { s_throwInvalidDataContractExceptionMethod = typeof(DataContract).GetMethod("ThrowInvalidDataContractException", Globals.ScanAllMembers, null, new Type[] { typeof(string), typeof(Type) }, null); - Debug.Assert(s_throwInvalidDataContractExceptionMethod != null); + Debug.Assert(s_throwInvalidDataContractExceptionMethod is not null); } return s_throwInvalidDataContractExceptionMethod; } @@ -1018,10 +1018,10 @@ internal static PropertyInfo SerializeReadOnlyTypesProperty { get { - if (s_serializeReadOnlyTypesProperty == null) + if (s_serializeReadOnlyTypesProperty is null) { s_serializeReadOnlyTypesProperty = typeof(XmlObjectSerializerWriteContext).GetProperty("SerializeReadOnlyTypes", Globals.ScanAllMembers); - Debug.Assert(s_serializeReadOnlyTypesProperty != null); + Debug.Assert(s_serializeReadOnlyTypesProperty is not null); } return s_serializeReadOnlyTypesProperty; } @@ -1032,10 +1032,10 @@ internal static PropertyInfo ClassSerializationExceptionMessageProperty { get { - if (s_classSerializationExceptionMessageProperty == null) + if (s_classSerializationExceptionMessageProperty is null) { s_classSerializationExceptionMessageProperty = typeof(ClassDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers); - Debug.Assert(s_classSerializationExceptionMessageProperty != null); + Debug.Assert(s_classSerializationExceptionMessageProperty is not null); } return s_classSerializationExceptionMessageProperty; } @@ -1046,10 +1046,10 @@ internal static PropertyInfo CollectionSerializationExceptionMessageProperty { get { - if (s_collectionSerializationExceptionMessageProperty == null) + if (s_collectionSerializationExceptionMessageProperty is null) { s_collectionSerializationExceptionMessageProperty = typeof(CollectionDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers); - Debug.Assert(s_collectionSerializationExceptionMessageProperty != null); + Debug.Assert(s_collectionSerializationExceptionMessageProperty is not null); } return s_collectionSerializationExceptionMessageProperty; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs index 4e5ea78c3e34d7..a661f8886d7028 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs @@ -120,7 +120,7 @@ public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classC } InvokeOnDeserialized(classContract); - if (objectId == null) + if (objectId is null) { _ilg.Load(_objectLocal); @@ -266,12 +266,12 @@ private void CreateObject(ClassDataContract classContract) private void InvokeOnDeserializing(ClassDataContract classContract) { - Debug.Assert(_objectLocal != null); - Debug.Assert(_objectType != null); + Debug.Assert(_objectLocal is not null); + Debug.Assert(_objectType is not null); - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserializing(classContract.BaseContract); - if (classContract.OnDeserializing != null) + if (classContract.OnDeserializing is not null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); @@ -283,12 +283,12 @@ private void InvokeOnDeserializing(ClassDataContract classContract) private void InvokeOnDeserialized(ClassDataContract classContract) { - Debug.Assert(_objectLocal != null); - Debug.Assert(_objectType != null); + Debug.Assert(_objectLocal is not null); + Debug.Assert(_objectType is not null); - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnDeserialized(classContract.BaseContract); - if (classContract.OnDeserialized != null) + if (classContract.OnDeserialized is not null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); @@ -305,7 +305,7 @@ private bool HasFactoryMethod(ClassDataContract classContract) private bool InvokeFactoryMethod(ClassDataContract classContract, LocalBuilder? objectId) { - Debug.Assert(_objectLocal != null); + Debug.Assert(_objectLocal is not null); if (HasFactoryMethod(classContract)) { @@ -331,10 +331,10 @@ private void ReadClass(ClassDataContract classContract) ReadMembers(classContract, extensionDataLocal); ClassDataContract? currentContract = classContract; - while (currentContract != null) + while (currentContract is not null) { MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod; - if (extensionDataSetMethod != null) + if (extensionDataSetMethod is not null) _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; } @@ -378,10 +378,10 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensio private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder? requiredIndexLocal) { - Debug.Assert(_objectLocal != null); - Debug.Assert(_objectType != null); + Debug.Assert(_objectLocal is not null); + Debug.Assert(_objectType is not null); - int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers, + int memberCount = (classContract.BaseContract is null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) @@ -439,7 +439,7 @@ private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequi private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { - int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); + int memberCount = (contract.BaseContract is null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); List members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) { @@ -450,8 +450,8 @@ private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMember private void ReadISerializable(ClassDataContract classContract) { - Debug.Assert(_objectLocal != null); - Debug.Assert(_objectType != null); + Debug.Assert(_objectLocal is not null); + Debug.Assert(_objectType is not null); ConstructorInfo ctor = classContract.GetISerializableConstructor()!; _ilg.LoadAddress(_objectLocal); @@ -474,7 +474,7 @@ private LocalBuilder ReadValue(Type type, string name, string ns) } PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); - if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) + if ((primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); @@ -513,7 +513,7 @@ private LocalBuilder ReadValue(Type type, string name, string ns) value = _ilg.DeclareLocal(type, "innerValueRead"); } - if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) + if (primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { _ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod); _ilg.Stloc(value); @@ -536,7 +536,7 @@ private LocalBuilder ReadValue(Type type, string name, string ns) } _ilg.EndIf(); - if (nullableValue != null) + if (nullableValue is not null) { _ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); @@ -664,7 +664,7 @@ private void ReadCollection(CollectionDataContract collectionContract) LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { - Debug.Assert(growingCollection != null); + Debug.Assert(growingCollection is not null); MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); @@ -786,10 +786,10 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) { - Debug.Assert(_objectLocal != null); + Debug.Assert(_objectLocal is not null); PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; string? readArrayMethod = null; @@ -819,7 +819,7 @@ private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) default: break; } - if (readArrayMethod != null) + if (readArrayMethod is not null) { _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); @@ -856,12 +856,12 @@ private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContrac private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { - Debug.Assert(collectionContract.AddMethod != null); + Debug.Assert(collectionContract.AddMethod is not null); if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; - if (keyValuePairContract == null) + if (keyValuePairContract is null) { DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type"); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs index aa69ceb8e72e8e..1f66fb089d4d91 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs @@ -164,9 +164,9 @@ private void InitArgs(Type objType) private void InvokeOnSerializing(ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerializing(classContract.BaseContract); - if (classContract.OnSerializing != null) + if (classContract.OnSerializing is not null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); @@ -177,9 +177,9 @@ private void InvokeOnSerializing(ClassDataContract classContract) private void InvokeOnSerialized(ClassDataContract classContract) { - if (classContract.BaseContract != null) + if (classContract.BaseContract is not null) InvokeOnSerialized(classContract.BaseContract); - if (classContract.OnSerialized != null) + if (classContract.OnSerialized is not null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); @@ -213,7 +213,7 @@ private void WriteClass(ClassDataContract classContract) for (int i = 0; i < classContract.ChildElementNamespaces!.Length; i++) { - if (classContract.ChildElementNamespaces[i] != null) + if (classContract.ChildElementNamespaces[i] is not null) { _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); _ilg.Load(_dataContractArg); @@ -242,11 +242,11 @@ private void WriteClass(ClassDataContract classContract) private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal, ClassDataContract derivedMostClassContract) { - int memberCount = (classContract.BaseContract == null) ? 0 : + int memberCount = (classContract.BaseContract is null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); - if (_contractNamespacesLocal == null) + if (_contractNamespacesLocal is null) { _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); @@ -281,13 +281,13 @@ private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensio if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, ns: namespaceLocal, name: null, nameIndex: i + _childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, nameLocal: null, nameIndex: i + _childElementIndex); - if (classContract.ChildElementNamespaces![i + _childElementIndex] != null) + if (classContract.ChildElementNamespaces![i + _childElementIndex] is not null) { _ilg.Load(_xmlWriterArg); _ilg.LoadArrayElement(_childElementNamespacesLocal!, i + _childElementIndex); _ilg.Call(methodInfo: XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } - if (memberValue == null) + if (memberValue is null) memberValue = LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); @@ -335,7 +335,7 @@ private void WriteCollection(CollectionDataContract collectionContract) _ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); - if (collectionContract.ChildElementNamespace != null) + if (collectionContract.ChildElementNamespace is not null) { _ilg.Load(_xmlWriterArg); _ilg.Load(_dataContractArg); @@ -367,7 +367,7 @@ private void WriteCollection(CollectionDataContract collectionContract) } else { - Debug.Assert(collectionContract.GetEnumeratorMethod != null); + Debug.Assert(collectionContract.GetEnumeratorMethod is not null); MethodInfo? incrementCollectionCountMethod = null; switch (collectionContract.Kind) @@ -385,7 +385,7 @@ private void WriteCollection(CollectionDataContract collectionContract) incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } - if (incrementCollectionCountMethod != null) + if (incrementCollectionCountMethod is not null) { _ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal); } @@ -411,13 +411,13 @@ private void WriteCollection(CollectionDataContract collectionContract) } MethodInfo? moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null); MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null); - if (moveNextMethod == null || getCurrentMethod == null) + if (moveNextMethod is null || getCurrentMethod is null) { if (enumeratorType.IsInterface) { - if (moveNextMethod == null) + if (moveNextMethod is null) moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; - if (getCurrentMethod == null) + if (getCurrentMethod is null) getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else @@ -438,9 +438,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } } - if (moveNextMethod == null) + if (moveNextMethod is null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; - if (getCurrentMethod == null) + if (getCurrentMethod is null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } @@ -464,7 +464,7 @@ private void WriteCollection(CollectionDataContract collectionContract) _ilg.Stloc(enumerator); _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); - if (incrementCollectionCountMethod == null) + if (incrementCollectionCountMethod is null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } @@ -494,7 +494,7 @@ private void WriteCollection(CollectionDataContract collectionContract) private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? memberInfo, LocalBuilder? arrayItemIndex, LocalBuilder ns, LocalBuilder? name, int nameIndex) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); - if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) + if (primitiveContract is null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load xmlwriter @@ -508,11 +508,11 @@ private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? membe _ilg.Load(_xmlWriterArg); } // load primitive value - if (value != null) + if (value is not null) { _ilg.Load(value); } - else if (memberInfo != null) + else if (memberInfo is not null) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(memberInfo); @@ -522,7 +522,7 @@ private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? membe _ilg.LoadArrayElement(_objectLocal, arrayItemIndex); } // load name - if (name != null) + if (name is not null) { _ilg.Load(name); } @@ -540,7 +540,7 @@ private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? membe private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); - if (primitiveContract == null) + if (primitiveContract is null) return false; string? writeArrayMethod = null; @@ -570,7 +570,7 @@ private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value default: break; } - if (writeArrayMethod != null) + if (writeArrayMethod is not null) { _ilg.Load(_xmlWriterArg); _ilg.Load(value); @@ -590,7 +590,7 @@ private void WriteValue(LocalBuilder memberValue, bool writeXsiType) if (memberType.IsValueType && !isNullableOfT) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); - if (primitiveContract != null && !writeXsiType) + if (primitiveContract is not null && !writeXsiType) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType); @@ -612,7 +612,7 @@ private void WriteValue(LocalBuilder memberValue, bool writeXsiType) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); - if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) + if (primitiveContract is not null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) { @@ -695,7 +695,7 @@ private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !Ha private bool NeedsPrefix(Type type, XmlDictionaryString ns) { - return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); + return type == Globals.TypeOfXmlQualifiedName && (ns is not null && ns.Value is not null && ns.Value.Length > 0); } private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder? nameLocal, int nameIndex) @@ -707,7 +707,7 @@ private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder n _ilg.Load(Globals.ElementPrefix); // localName - if (nameLocal == null) + if (nameLocal is null) _ilg.LoadArrayElement(_memberNamesLocal!, nameIndex); else _ilg.Load(nameLocal); @@ -733,7 +733,7 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class string name = member.Name; string ns = classContract.StableName.Namespace; ClassDataContract? currentContract = derivedMostClassContract; - while (currentContract != null && currentContract != classContract) + while (currentContract is not null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { @@ -752,7 +752,7 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { - while (member.ConflictingMember != null) + while (member.ConflictingMember is not null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index 4d452bf64dc576..f62bb0dcaa70c5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -173,7 +173,7 @@ internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer) internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns, bool needsContractNsAtRoot) { - if (name == null) // root name not set explicitly + if (name is null) // root name not set explicitly { if (!contract.HasRoot) return; @@ -191,7 +191,7 @@ internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString? name, XmlDictionaryString? ns, DataContract contract) { - if (name == null) + if (name is null) return false; if (contract.IsBuiltInDataContract || !contract.CanContainReferences) @@ -307,7 +307,7 @@ internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader) internal bool IsRootXmlAny(XmlDictionaryString? rootName, DataContract contract) { - return (rootName == null) && !contract.HasRoot; + return (rootName is null) && !contract.HasRoot; } internal bool IsStartElement(XmlReaderDelegator reader) @@ -318,7 +318,7 @@ internal bool IsStartElement(XmlReaderDelegator reader) internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns) { reader.MoveToElement(); - if (name != null) // root name set explicitly + if (name is not null) // root name set explicitly { return reader.IsStartElement(name, ns!); // https://github.com/dotnet/runtime/issues/41395 } @@ -331,15 +331,15 @@ internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, Xm return true; ClassDataContract? classContract = contract as ClassDataContract; - if (classContract != null) + if (classContract is not null) classContract = classContract.BaseContract; - while (classContract != null) + while (classContract is not null) { if (reader.IsStartElement(classContract.TopLevelElementName!, classContract.TopLevelElementNamespace!)) return true; classContract = classContract.BaseContract; } - if (classContract == null) + if (classContract is null) { DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject)!; if (reader.IsStartElement(objectContract.TopLevelElementName!, objectContract.TopLevelElementNamespace!)) @@ -351,7 +351,7 @@ internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, Xm internal static void CheckNull(object obj, string name) { - if (obj == null) + if (obj is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(name)); } @@ -379,14 +379,14 @@ internal static SerializationException CreateSerializationException(string error } internal static string GetTypeInfoError(string errorMessage, Type? type, Exception innerException) { - string typeInfo = (type == null) ? string.Empty : SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type)); - string innerExceptionMessage = (innerException == null) ? string.Empty : innerException.Message; + string typeInfo = (type is null) ? string.Empty : SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type)); + string innerExceptionMessage = (innerException is null) ? string.Empty : innerException.Message; return SR.Format(errorMessage, typeInfo, innerExceptionMessage); } internal virtual Type? GetSerializeType(object? graph) { - return (graph == null) ? null : graph.GetType(); + return (graph is null) ? null : graph.GetType(); } internal virtual Type? GetDeserializeType() @@ -399,7 +399,7 @@ internal static IFormatterConverter FormatterConverter { get { - if (s_formatterConverter == null) + if (s_formatterConverter is null) { s_formatterConverter = new FormatterConverter(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs index 765f02b378b7b7..b839912f991152 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs @@ -98,7 +98,7 @@ protected KnownTypeDataContractResolver KnownTypeResolver { get { - if (_knownTypeResolver == null) + if (_knownTypeResolver is null) { _knownTypeResolver = new KnownTypeDataContractResolver(this); } @@ -175,7 +175,7 @@ internal virtual DataContractDictionary? SerializerKnownDataContracts private DataContract? GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname) { DataContractDictionary? serializerKnownDataContracts = this.SerializerKnownDataContracts; - if (serializerKnownDataContracts == null) + if (serializerKnownDataContracts is null) return null; DataContract? outDataContract; return serializerKnownDataContracts.TryGetValue(qname, out outDataContract) ? outDataContract : null; @@ -183,13 +183,13 @@ internal virtual DataContractDictionary? SerializerKnownDataContracts internal static DataContractDictionary? GetDataContractsForKnownTypes(IList knownTypeList) { - if (knownTypeList == null) return null; + if (knownTypeList is null) return null; DataContractDictionary dataContracts = new DataContractDictionary(); Dictionary typesChecked = new Dictionary(); for (int i = 0; i < knownTypeList.Count; i++) { Type knownType = knownTypeList[i]; - if (knownType == null) + if (knownType is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.NullKnownType, "knownTypes"))); DataContract.CheckAndAdd(knownType, typesChecked, ref dataContracts); @@ -200,7 +200,7 @@ internal virtual DataContractDictionary? SerializerKnownDataContracts internal bool IsKnownType(DataContract dataContract, DataContractDictionary? knownDataContracts, Type? declaredType) { bool knownTypesAddedInCurrentScope = false; - if (knownDataContracts != null) + if (knownDataContracts is not null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; @@ -218,22 +218,22 @@ internal bool IsKnownType(DataContract dataContract, DataContractDictionary? kno internal bool IsKnownType(DataContract dataContract, Type? declaredType) { DataContract? knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType); - return knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType; + return knownContract is not null && knownContract.UnderlyingType == dataContract.UnderlyingType; } internal Type? ResolveNameFromKnownTypes(XmlQualifiedName typeName) { DataContract? dataContract = ResolveDataContractFromKnownTypes(typeName); - return dataContract == null ? null : dataContract.UnderlyingType; + return dataContract is null ? null : dataContract.UnderlyingType; } private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) { DataContract? dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace); - if (dataContract == null) + if (dataContract is null) { dataContract = scopedKnownTypes.GetDataContract(typeName); - if (dataContract == null) + if (dataContract is null) { dataContract = GetDataContractFromSerializerKnownTypes(typeName); } @@ -245,31 +245,31 @@ internal bool IsKnownType(DataContract dataContract, Type? declaredType) { XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs); DataContract? dataContract; - if (_dataContractResolver == null) + if (_dataContractResolver is null) { dataContract = ResolveDataContractFromKnownTypes(qname); } else { Type? dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, declaredType, KnownTypeResolver); - dataContract = dataContractType == null ? null : GetDataContract(dataContractType); + dataContract = dataContractType is null ? null : GetDataContract(dataContractType); } - if (dataContract == null) + if (dataContract is null) { - if (memberTypeContract != null + if (memberTypeContract is not null && !memberTypeContract.UnderlyingType.IsInterface && memberTypeContract.StableName == qname) { dataContract = memberTypeContract; } - if (dataContract == null && rootTypeDataContract != null) + if (dataContract is null && rootTypeDataContract is not null) { if (rootTypeDataContract.StableName == qname) dataContract = rootTypeDataContract; else { CollectionDataContract? collectionContract = rootTypeDataContract as CollectionDataContract; - while (collectionContract != null) + while (collectionContract is not null) { DataContract itemContract = GetDataContract(GetSurrogatedType(collectionContract.ItemType)); if (itemContract.StableName == qname) @@ -287,7 +287,7 @@ internal bool IsKnownType(DataContract dataContract, Type? declaredType) internal void PushKnownTypes(DataContract dc) { - if (dc != null && dc.KnownDataContracts != null) + if (dc is not null && dc.KnownDataContracts is not null) { scopedKnownTypes.Push(dc.KnownDataContracts); } @@ -295,7 +295,7 @@ internal void PushKnownTypes(DataContract dc) internal void PopKnownTypes(DataContract dc) { - if (dc != null && dc.KnownDataContracts != null) + if (dc is not null && dc.KnownDataContracts is not null) { scopedKnownTypes.Pop(); } 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 e29728f553c0bf..6e8e219bbda30f 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 @@ -28,7 +28,7 @@ private HybridObjectCache DeserializedObjects { get { - if (_deserializedObjects == null) + if (_deserializedObjects is null) _deserializedObjects = new HybridObjectCache(); return _deserializedObjects; } @@ -74,7 +74,7 @@ internal static void ThrowArrayExceededSizeException(int arraySize, Type type) internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver) { - return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) + return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider is not null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } @@ -105,7 +105,7 @@ internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataC internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract? dataContract, string? name, string? ns) { - if (dataContract == null) + if (dataContract is null) dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } @@ -142,20 +142,20 @@ protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, return retObj; bool knownTypesAddedInCurrentScope = false; - if (dataContract.KnownDataContracts != null) + if (dataContract.KnownDataContracts is not null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); - if (attributes.XsiTypeName != null) + if (attributes.XsiTypeName is not null) { DataContract? tempDataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType); - if (tempDataContract == null) + if (tempDataContract is null) { - if (DataContractResolver == null) + if (DataContractResolver is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } @@ -165,10 +165,10 @@ protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } - if (dataContract.IsISerializable && attributes.FactoryTypeName != null) + if (dataContract.IsISerializable && attributes.FactoryTypeName is not null) { DataContract? factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType); - if (factoryDataContract != null) + if (factoryDataContract is not null) { if (factoryDataContract.IsISerializable) { @@ -201,7 +201,7 @@ private bool ReplaceScopedKnownTypesTop(DataContractDictionary? knownDataContrac scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } - if (knownDataContracts != null) + if (knownDataContracts is not null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; @@ -261,7 +261,7 @@ protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataO if (xmlReader.NodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); - if (IgnoreExtensionDataObject || extensionData == null) + if (IgnoreExtensionDataObject || extensionData is null) SkipUnknownElement(xmlReader); else HandleUnknownElement(xmlReader, extensionData, memberIndex); @@ -269,7 +269,7 @@ protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataO internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { - if (extensionData.Members == null) + if (extensionData.Members is null) extensionData.Members = new List(); extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex)); } @@ -282,7 +282,7 @@ internal void SkipUnknownElement(XmlReaderDelegator xmlReader) internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); if (attributes.Ref != Globals.NewObjectId) { @@ -302,20 +302,20 @@ internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, b [MemberNotNull(nameof(attributes))] internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) { - if (attributes == null) + if (attributes is null) attributes = new Attributes(); attributes.Read(xmlReader); } internal void ResetAttributes() { - if (attributes != null) + if (attributes is not null) attributes.Reset(); } internal string GetObjectId() { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); return attributes.Id; } @@ -327,7 +327,7 @@ internal virtual int GetArraySize() internal void AddNewObject(object? obj) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); AddNewObjectWithId(attributes.Id, obj); } @@ -354,7 +354,7 @@ public void ReplaceDeserializedObject(string id, object? oldObj, object? newObj) if (DeserializedObjects.IsObjectReferenced(id)) { // https://github.com/dotnet/runtime/issues/41465 - oldObj or newObj may be null below - suppress compiler error by asserting non-null - Debug.Assert(oldObj != null && newObj != null); + Debug.Assert(oldObj is not null && newObj is not null); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); } DeserializedObjects.Remove(id); @@ -365,7 +365,7 @@ public void ReplaceDeserializedObject(string id, object? oldObj, object? newObj) internal object GetExistingObject(string id, Type? type, string? name, string? ns) { object? retObj = DeserializedObjects.GetObject(id); - if (retObj == null) + if (retObj is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); return retObj; } @@ -373,7 +373,7 @@ internal object GetExistingObject(string id, Type? type, string? name, string? n private object GetExistingObjectOrExtensionData(string id) { object? retObj = DeserializedObjects.GetObject(id); - if (retObj == null) + if (retObj is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); @@ -391,7 +391,7 @@ public object GetRealObject(IObjectReference obj, string id) // XmlObjectSerializer implementations do not support fix-ups since the format does not contain // forward references. However, we throw for this case since it allows us to add fix-up support // in the future if we need to. - if (realObj == null) + if (realObj is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException("error")); ReplaceDeserializedObject(id, obj, realObj); return realObj; @@ -459,7 +459,7 @@ internal void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDi internal object? ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { - if (_xmlSerializableReader == null) + if (_xmlSerializableReader is null) _xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } @@ -544,9 +544,9 @@ public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Typ protected virtual DataContract? ResolveDataContractFromTypeName() { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); - return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/, null); + return (attributes.XsiTypeName is null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/, null); } private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex) @@ -556,7 +556,7 @@ private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader MemberIndex = memberIndex }; - member.Value = xmlReader.UnderlyingExtensionDataReader != null ? xmlReader.UnderlyingExtensionDataReader.GetCurrentNode() : ReadExtensionDataValue(xmlReader); + member.Value = xmlReader.UnderlyingExtensionDataReader is not null ? xmlReader.UnderlyingExtensionDataReader.GetCurrentNode() : ReadExtensionDataValue(xmlReader); return member; } @@ -581,7 +581,7 @@ private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader { string? dataContractName = null; string? dataContractNamespace = null; - if (attributes.XsiTypeName != null) + if (attributes.XsiTypeName is not null) { dataContractName = attributes.XsiTypeName; dataContractNamespace = attributes.XsiTypeNamespace; @@ -592,7 +592,7 @@ private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } - else if (attributes.FactoryTypeName != null) + else if (attributes.FactoryTypeName is not null) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); @@ -606,7 +606,7 @@ private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader { DataContract? dataContract = ResolveDataContractFromTypeName(); - if (dataContract == null) + if (dataContract is null) dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); else if (dataContract is XmlDataContract) dataNode = ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); @@ -659,7 +659,7 @@ protected virtual void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); StartReadExtensionDataValue(xmlReader); @@ -713,7 +713,7 @@ protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator x protected void InitializeExtensionDataNode(IDataNode dataNode, string? dataContractName, string? dataContractNamespace) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); dataNode.DataContractName = dataContractName; dataNode.DataContractNamespace = dataContractNamespace; @@ -742,7 +742,7 @@ private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string? if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); - if (dataNode.Members == null) + if (dataNode.Members is null) dataNode.Members = new List(); dataNode.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex++)); } @@ -752,7 +752,7 @@ private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string? private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); var dataNode = new CollectionDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); @@ -764,14 +764,14 @@ private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReade if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); - if (dataNode.ItemName == null) + if (dataNode.ItemName is null) { dataNode.ItemName = xmlReader.LocalName; dataNode.ItemNamespace = xmlReader.NamespaceURI; } if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace!)) { - if (dataNode.Items == null) + if (dataNode.Items is null) dataNode.Items = new List(); dataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } @@ -783,7 +783,7 @@ private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReade if (arraySize != -1) { dataNode.Size = arraySize; - if (dataNode.Items == null) + if (dataNode.Items is null) { if (dataNode.Size > 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, 0))); @@ -793,7 +793,7 @@ private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReade } else { - if (dataNode.Items != null) + if (dataNode.Items is not null) { dataNode.Size = dataNode.Items.Count; } @@ -808,7 +808,7 @@ private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReade private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); var dataNode = new ISerializableDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); @@ -830,7 +830,7 @@ private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xm var member = new ISerializableDataMember(xmlReader.LocalName); member.Value = ReadExtensionDataValue(xmlReader); - if (dataNode.Members == null) + if (dataNode.Members is null) dataNode.Members = new List(); dataNode.Members.Add(member); } @@ -858,7 +858,7 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string? dataC string ns = xmlReader.NamespaceURI; if (ns != Globals.SerializationNamespace && ns != Globals.SchemaInstanceNamespace) { - if (xmlAttributes == null) + if (xmlAttributes is null) xmlAttributes = new List(); xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)!); } @@ -871,7 +871,7 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string? dataC if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); - if (xmlChildNodes == null) + if (xmlChildNodes is null) xmlChildNodes = new List(); xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)!); } @@ -895,7 +895,7 @@ private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDi string? elementNs = null, elementName = null; var xmlChildNodes = new List(); IList? xmlAttributes = null; - if (namespaces != null) + if (namespaces is not null) { xmlAttributes = new List(); foreach (KeyValuePair prefixNsPair in namespaces) @@ -915,7 +915,7 @@ private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDi couldBeISerializableData = (ns.Length == 0); if (couldBeCollectionData) { - if (elementName == null) + if (elementName is null) { elementName = name; elementNs = ns; @@ -930,23 +930,23 @@ private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDi else if (IsContentNode(xmlReader.NodeType)) couldBeClassData = couldBeISerializableData = couldBeCollectionData = false; - if (_attributesInXmlData == null) _attributesInXmlData = new Attributes(); + if (_attributesInXmlData is null) _attributesInXmlData = new Attributes(); _attributesInXmlData.Read(xmlReader); XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader)!; xmlChildNodes.Add(childNode); - if (namespaces == null) + if (namespaces is null) { - if (_attributesInXmlData.XsiTypeName != null) + if (_attributesInXmlData.XsiTypeName is not null) childNode.Attributes!.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace)); - if (_attributesInXmlData.FactoryTypeName != null) + if (_attributesInXmlData.FactoryTypeName is not null) childNode.Attributes!.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace)); } } xmlReader.ReadEndElement(); - if (elementName != null && couldBeCollectionData) + if (elementName is not null && couldBeCollectionData) return ReadUnknownCollectionData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeISerializableData) return ReadUnknownISerializableData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); @@ -992,14 +992,14 @@ internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList 0) + if (ns is not null && ns.Value is not null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); @@ -425,7 +425,7 @@ internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size) internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) { - if (obj == null || memberType == null) + if (obj is null || memberType is null) return false; return obj.GetType().TypeHandle.Equals(memberType.TypeHandle); @@ -454,7 +454,7 @@ internal static bool GetHasValue(Nullable value) where T : struct internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { - if (_xmlSerializableWriter == null) + if (_xmlSerializableWriter is null) _xmlSerializableWriter = new XmlSerializableWriter(); WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter); } @@ -468,17 +468,17 @@ private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object o { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); IXmlSerializable? xmlSerializable = obj as IXmlSerializable; - if (xmlSerializable != null) + if (xmlSerializable is not null) xmlSerializable.WriteXml(xmlSerializableWriter); else { XmlElement? xmlElement = obj as XmlElement; - if (xmlElement != null) + if (xmlElement is not null) xmlElement.WriteTo(xmlSerializableWriter); else { XmlNode[]? xmlNodes = obj as XmlNode[]; - if (xmlNodes != null) + if (xmlNodes is not null) foreach (XmlNode xmlNode in xmlNodes) xmlNode.WriteTo(xmlSerializableWriter); else @@ -513,7 +513,7 @@ internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, { if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { - if (DataContractResolver != null) + if (DataContractResolver is not null) { XmlDictionaryString? typeName, typeNs; if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs)) @@ -536,7 +536,7 @@ internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name)); xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString); object? obj = serEntry.Value; - if (obj == null) + if (obj is null) { WriteNull(xmlWriter); } @@ -570,15 +570,15 @@ private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, T private bool ResolveType(Type objectType, Type declaredType, [NotNullWhen(true)] out XmlDictionaryString? typeName, [NotNullWhen(true)] out XmlDictionaryString? typeNamespace) { - Debug.Assert(DataContractResolver != null); + Debug.Assert(DataContractResolver is not null); if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } - if (typeName == null) + if (typeName is null) { - if (typeNamespace == null) + if (typeNamespace is null) { return false; } @@ -587,7 +587,7 @@ private bool ResolveType(Type objectType, Type declaredType, [NotNullWhen(true)] throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } } - if (typeNamespace == null) + if (typeNamespace is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } @@ -598,7 +598,7 @@ protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract con { if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract)) { - if (DataContractResolver == null) + if (DataContractResolver is null) { WriteTypeInfo(writer, contract.Name, contract.Namespace); return true; @@ -624,11 +624,11 @@ protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryStr public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject? extensionData, int memberIndex) { - if (IgnoreExtensionDataObject || extensionData == null) + if (IgnoreExtensionDataObject || extensionData is null) return; IList? members = extensionData.Members; - if (members != null) + if (members is not null) { for (int i = 0; i < members.Count; i++) { @@ -651,7 +651,7 @@ private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDat internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { - if (dataNode.DataContractName != null) + if (dataNode.DataContractName is not null) WriteTypeInfo(xmlWriter, dataNode.DataContractName, dataNode.DataContractNamespace); WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName); @@ -660,14 +660,14 @@ internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, I internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode? dataNode) { IncrementItemCount(1); - if (dataNode == null) + if (dataNode is null) { WriteNull(xmlWriter); return; } if (dataNode.PreservesReferences - && OnHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/)) + && OnHandleReference(xmlWriter, (dataNode.Value is null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/)) return; Type dataType = dataNode.DataType; @@ -688,23 +688,23 @@ internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode? d // NOTE: serialize value in DataNode since it may contain non-primitive // deserialized object (ex. empty class) object? o = dataNode.Value; - if (o != null) + if (o is not null) InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle); } else xmlWriter.WriteExtensionData(dataNode); } if (dataNode.PreservesReferences) - OnEndHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/); + OnEndHandleReference(xmlWriter, (dataNode.Value is null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/); } internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode) { object? o = dataNode.Value; - if (o == null) + if (o is null) return false; - Type declaredType = (dataNode.DataContractName == null) ? o.GetType() : Globals.TypeOfObject; + Type declaredType = (dataNode.DataContractName is null) ? o.GetType() : Globals.TypeOfObject; InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, declaredType.TypeHandle); return true; } @@ -716,7 +716,7 @@ private void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList? members = dataNode.Members; - if (members != null) + if (members is not null) { for (int i = 0; i < members.Count; i++) { @@ -735,7 +735,7 @@ private void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, Collecti WriteArraySize(xmlWriter, dataNode.Size); IList? items = dataNode.Items; - if (items != null) + if (items is not null) { for (int i = 0; i < items.Count; i++) { @@ -753,11 +753,11 @@ private void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISeri { WriteExtensionDataTypeInfo(xmlWriter, dataNode); - if (dataNode.FactoryTypeName != null) + if (dataNode.FactoryTypeName is not null) xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace); IList? members = dataNode.Members; - if (members != null) + if (members is not null) { for (int i = 0; i < members.Count; i++) { @@ -775,7 +775,7 @@ private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dat if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { IList? xmlAttributes = dataNode.XmlAttributes; - if (xmlAttributes != null) + if (xmlAttributes is not null) { foreach (XmlAttribute attribute in xmlAttributes) attribute.WriteTo(xmlWriter.Writer); @@ -783,7 +783,7 @@ private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dat WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList? xmlChildNodes = dataNode.XmlChildNodes; - if (xmlChildNodes != null) + if (xmlChildNodes is not null) { foreach (XmlNode node in xmlChildNodes) node.WriteTo(xmlWriter.Writer); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs index be3223aa661337..66fc5393da6639 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs @@ -62,7 +62,7 @@ internal override void WriteString(XmlWriterDelegator xmlWriter, string value) internal override void WriteString(XmlWriterDelegator xmlWriter, string? value, XmlDictionaryString name, XmlDictionaryString? ns) { - if (value == null) + if (value is null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { @@ -81,7 +81,7 @@ internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) { - if (value == null) + if (value is null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { @@ -100,7 +100,7 @@ internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) { - if (value == null) + if (value is null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { @@ -119,11 +119,11 @@ internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName? value, XmlDictionaryString name, XmlDictionaryString? ns) { - if (value == null) + if (value is null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { - if (ns != null && ns.Value != null && ns.Value.Length > 0) + if (ns is not null && ns.Value is not null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); @@ -135,7 +135,7 @@ internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName internal override void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { - if (_serializationSurrogateProvider == null) + if (_serializationSurrogateProvider is null) { base.InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } @@ -172,7 +172,7 @@ internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { - if (_serializationSurrogateProvider != null) + if (_serializationSurrogateProvider is not null) { while (memberType.IsArray) memberType = memberType.GetElementType()!; @@ -187,7 +187,7 @@ internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTyp internal override Type GetSurrogatedType(Type type) { - if (_serializationSurrogateProvider == null) + if (_serializationSurrogateProvider is null) { return base.GetSurrogatedType(type); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs index 8d21ec419b04b3..5cfc83acab9a22 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs @@ -61,7 +61,7 @@ internal bool IsEmptyElement internal bool IsNamespaceURI(string ns) { - if (dictionaryReader == null) + if (dictionaryReader is null) return ns == reader.NamespaceURI; else return dictionaryReader.IsNamespaceUri(ns); @@ -69,7 +69,7 @@ internal bool IsNamespaceURI(string ns) internal bool IsLocalName(string localName) { - if (dictionaryReader == null) + if (dictionaryReader is null) return localName == reader.LocalName; else return dictionaryReader.IsLocalName(localName); @@ -77,7 +77,7 @@ internal bool IsLocalName(string localName) internal bool IsNamespaceUri(XmlDictionaryString ns) { - if (dictionaryReader == null) + if (dictionaryReader is null) return ns.Value == reader.NamespaceURI; else return dictionaryReader.IsNamespaceUri(ns); @@ -85,7 +85,7 @@ internal bool IsNamespaceUri(XmlDictionaryString ns) internal bool IsLocalName(XmlDictionaryString localName) { - if (dictionaryReader == null) + if (dictionaryReader is null) return localName.Value == reader.LocalName; else return dictionaryReader.IsLocalName(localName); @@ -93,7 +93,7 @@ internal bool IsLocalName(XmlDictionaryString localName) internal int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString ns) { - if (dictionaryReader != null) + if (dictionaryReader is not null) return dictionaryReader.IndexOfLocalName(localNames, ns); if (reader.NamespaceURI == ns.Value) @@ -123,7 +123,7 @@ internal bool IsStartElement(string localname, string ns) internal bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns) { - if (dictionaryReader == null) + if (dictionaryReader is null) return !isEndOfEmptyElement && reader.IsStartElement(localname.Value, ns.Value); else return !isEndOfEmptyElement && dictionaryReader.IsStartElement(localname, ns); @@ -442,7 +442,7 @@ internal virtual byte[] ReadElementContentAsBase64() if (isEndOfEmptyElement) ThrowNotAtElement(); - if (dictionaryReader == null) + if (dictionaryReader is null) { return ReadContentAsBase64(reader.ReadElementContentAsString()); } @@ -457,7 +457,7 @@ public virtual byte[] ReadContentAsBase64() if (isEndOfEmptyElement) return Array.Empty(); - if (dictionaryReader == null) + if (dictionaryReader is null) { return ReadContentAsBase64(reader.ReadContentAsString()); } @@ -470,7 +470,7 @@ public virtual byte[] ReadContentAsBase64() [return: NotNullIfNotNull("str")] internal byte[]? ReadContentAsBase64(string? str) { - if (str == null) + if (str is null) return null; str = str.Trim(); if (str.Length == 0) @@ -621,7 +621,7 @@ internal virtual ulong ReadElementContentAsUnsignedLong() string str = reader.ReadElementContentAsString(); - if (str == null || str.Length == 0) + if (str is null || str.Length == 0) ThrowConversionException(string.Empty, "UInt64"); return XmlConverter.ToUInt64(str); @@ -631,7 +631,7 @@ internal virtual ulong ReadContentAsUnsignedLong() { string str = reader.ReadContentAsString(); - if (str == null || str.Length == 0) + if (str is null || str.Length == 0) ThrowConversionException(string.Empty, "UInt64"); return XmlConverter.ToUInt64(str); @@ -770,7 +770,7 @@ private XmlQualifiedName ParseQualifiedName(string str) { string name, prefix; string? ns; - if (str == null || str.Length == 0) + if (str is null || str.Length == 0) name = ns = string.Empty; else XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out prefix); @@ -797,7 +797,7 @@ internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out bool[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -827,7 +827,7 @@ internal virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext contex XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out DateTime[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -857,7 +857,7 @@ internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out decimal[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -887,7 +887,7 @@ internal bool TryReadInt32Array(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out int[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -917,7 +917,7 @@ internal bool TryReadInt64Array(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out long[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -947,7 +947,7 @@ internal bool TryReadSingleArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out float[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -977,7 +977,7 @@ internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, [NotNullWhen(true)] out double[]? array) { - if (dictionaryReader == null) + if (dictionaryReader is null) { array = null; return false; @@ -1012,7 +1012,7 @@ internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, internal bool HasLineInfo() { IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo; - return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo(); + return (iXmlLineInfo is null) ? false : iXmlLineInfo.HasLineInfo(); } internal int LineNumber @@ -1020,7 +1020,7 @@ internal int LineNumber get { IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo; - return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber; + return (iXmlLineInfo is null) ? 0 : iXmlLineInfo.LineNumber; } } @@ -1029,7 +1029,7 @@ internal int LinePosition get { IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo; - return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition; + return (iXmlLineInfo is null) ? 0 : iXmlLineInfo.LinePosition; } } @@ -1039,10 +1039,10 @@ internal bool Normalized get { XmlTextReader? xmlTextReader = reader as XmlTextReader; - if (xmlTextReader == null) + if (xmlTextReader is null) { IXmlTextParser? xmlTextParser = reader as IXmlTextParser; - return (xmlTextParser == null) ? false : xmlTextParser.Normalized; + return (xmlTextParser is null) ? false : xmlTextParser.Normalized; } else return xmlTextReader.Normalization; @@ -1050,10 +1050,10 @@ internal bool Normalized set { XmlTextReader? xmlTextReader = reader as XmlTextReader; - if (xmlTextReader == null) + if (xmlTextReader is null) { IXmlTextParser? xmlTextParser = reader as IXmlTextParser; - if (xmlTextParser != null) + if (xmlTextParser is not null) xmlTextParser.Normalized = value; } else @@ -1066,10 +1066,10 @@ internal WhitespaceHandling WhitespaceHandling get { XmlTextReader? xmlTextReader = reader as XmlTextReader; - if (xmlTextReader == null) + if (xmlTextReader is null) { IXmlTextParser? xmlTextParser = reader as IXmlTextParser; - return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; + return (xmlTextParser is null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; } else return xmlTextReader.WhitespaceHandling; @@ -1077,10 +1077,10 @@ internal WhitespaceHandling WhitespaceHandling set { XmlTextReader? xmlTextReader = reader as XmlTextReader; - if (xmlTextReader == null) + if (xmlTextReader is null) { IXmlTextParser? xmlTextParser = reader as IXmlTextParser; - if (xmlTextParser != null) + if (xmlTextParser is not null) xmlTextParser.WhitespaceHandling = value; } else diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs index a8a259e0b32795..a117faca56039d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs @@ -127,7 +127,7 @@ public override void Close() bool IXmlLineInfo.HasLineInfo() { IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo; - return (xmlLineInfo == null) ? _xmlReader.HasLineInfo() : xmlLineInfo.HasLineInfo(); + return (xmlLineInfo is null) ? _xmlReader.HasLineInfo() : xmlLineInfo.HasLineInfo(); } int IXmlLineInfo.LineNumber @@ -135,7 +135,7 @@ int IXmlLineInfo.LineNumber get { IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo; - return (xmlLineInfo == null) ? _xmlReader.LineNumber : xmlLineInfo.LineNumber; + return (xmlLineInfo is null) ? _xmlReader.LineNumber : xmlLineInfo.LineNumber; } } @@ -144,7 +144,7 @@ int IXmlLineInfo.LinePosition get { IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo; - return (xmlLineInfo == null) ? _xmlReader.LinePosition : xmlLineInfo.LinePosition; + return (xmlLineInfo is null) ? _xmlReader.LinePosition : xmlLineInfo.LinePosition; } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs index 3746d5dafdcbcf..657afa491c62e6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs @@ -11,7 +11,7 @@ public static class XmlSerializableServices { public static XmlNode[] ReadNodes(XmlReader xmlReader) { - if (xmlReader == null) + if (xmlReader is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(xmlReader)); XmlDocument doc = new XmlDocument(); List nodeList = new List(); @@ -22,7 +22,7 @@ public static XmlNode[] ReadNodes(XmlReader xmlReader) if (IsValidAttribute(xmlReader)) { XmlNode? node = doc.ReadNode(xmlReader); - if (node == null) + if (node is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); nodeList.Add(node); } @@ -36,7 +36,7 @@ public static XmlNode[] ReadNodes(XmlReader xmlReader) while (xmlReader.Depth > startDepth && xmlReader.NodeType != XmlNodeType.EndElement) { XmlNode? node = doc.ReadNode(xmlReader); - if (node == null) + if (node is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); nodeList.Add(node); } @@ -54,20 +54,20 @@ private static bool IsValidAttribute(XmlReader xmlReader) public static void WriteNodes(XmlWriter xmlWriter, XmlNode?[]? nodes) { - if (xmlWriter == null) + if (xmlWriter is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(xmlWriter)); - if (nodes != null) + if (nodes is not null) for (int i = 0; i < nodes.Length; i++) - if (nodes[i] != null) + if (nodes[i] is not null) nodes[i]!.WriteTo(xmlWriter); } internal static string AddDefaultSchemaMethodName = "AddDefaultSchema"; public static void AddDefaultSchema(XmlSchemaSet schemas, XmlQualifiedName typeQName) { - if (schemas == null) + if (schemas is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(schemas)); - if (typeQName == null) + if (typeQName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(typeQName)); SchemaExporter.AddDefaultXmlType(schemas, typeQName.Name, typeQName.Namespace); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs index f127737dfa132f..0c5b0471285ceb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs @@ -23,7 +23,7 @@ internal void BeginWrite(XmlWriter xmlWriter, object obj) internal void EndWrite() { if (_depth != 0) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableMissingEndElements, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableMissingEndElements, (_obj is null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); _obj = null; } @@ -52,7 +52,7 @@ public override void WriteStartElement(string? prefix, string localName, string? public override void WriteEndElement() { if (_depth == 0) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj is null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); _xmlWriter.WriteEndElement(); _depth--; } @@ -60,7 +60,7 @@ public override void WriteEndElement() public override void WriteFullEndElement() { if (_depth == 0) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj is null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); _xmlWriter.WriteFullEndElement(); _depth--; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs index 50f78a1dd4a48b..79eadcd862fbb9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs @@ -60,9 +60,9 @@ internal void WriteRaw(string data) internal void WriteXmlnsAttribute(XmlDictionaryString ns) { - if (dictionaryWriter != null) + if (dictionaryWriter is not null) { - if (ns != null) + if (ns is not null) dictionaryWriter.WriteXmlnsAttribute(null, ns); } else @@ -71,18 +71,18 @@ internal void WriteXmlnsAttribute(XmlDictionaryString ns) internal void WriteXmlnsAttribute(string? ns) { - if (ns != null) + if (ns is not null) { if (ns.Length == 0) writer.WriteAttributeString("xmlns", string.Empty, null, ns); else { - if (dictionaryWriter != null) + if (dictionaryWriter is not null) dictionaryWriter.WriteXmlnsAttribute(null, ns); else { string? prefix = writer.LookupPrefix(ns); - if (prefix == null) + if (prefix is null) { prefix = string.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes); _prefixes++; @@ -95,7 +95,7 @@ internal void WriteXmlnsAttribute(string? ns) internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { - if (dictionaryWriter != null) + if (dictionaryWriter is not null) { dictionaryWriter.WriteXmlnsAttribute(prefix, ns); } @@ -112,12 +112,12 @@ private void WriteStartAttribute(string? prefix, string localName, string? ns) private void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { - if (dictionaryWriter != null) + if (dictionaryWriter is not null) dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri); else writer.WriteStartAttribute(prefix, - (localName == null ? null : localName.Value)!, - (namespaceUri == null ? null : namespaceUri.Value)); + (localName is null ? null : localName.Value)!, + (namespaceUri is null ? null : namespaceUri.Value)); } internal void WriteAttributeString(string? prefix, string localName, string? ns, string value) @@ -148,7 +148,7 @@ internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, private void WriteAttributeStringValue(XmlDictionaryString value) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) writer.WriteString(value.Value); else dictionaryWriter.WriteString(value); @@ -201,7 +201,7 @@ internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString private void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDictionaryString ns) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) writer.WriteQualifiedName(name.Value, ns.Value); else dictionaryWriter.WriteQualifiedName(name, ns); @@ -226,20 +226,20 @@ internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryStri internal void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - if (dictionaryWriter != null) + if (dictionaryWriter is not null) dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri); else - writer.WriteStartElement(prefix, (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value)); + writer.WriteStartElement(prefix, (localName is null ? null : localName.Value)!, (namespaceUri is null ? null : namespaceUri.Value)); depth++; _prefixes = 1; } internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - if (dictionaryWriter != null) + if (dictionaryWriter is not null) dictionaryWriter.WriteStartElement(null, localName, namespaceUri); else - writer.WriteStartElement(null, (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value)); + writer.WriteStartElement(null, (localName is null ? null : localName.Value)!, (namespaceUri is null ? null : namespaceUri.Value)); } internal void WriteEndElementPrimitive() @@ -412,7 +412,7 @@ internal void WriteExtensionData(IDataNode dataNode) else if (valueType == Globals.TypeOfObject) { object? obj = dataNode.Value; - if (obj != null) + if (obj is not null) WriteAnyType(obj); } else if (valueType == Globals.TypeOfTimeSpan) @@ -523,7 +523,7 @@ internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryStr internal virtual void WriteBase64(byte[]? bytes) { - if (bytes == null) + if (bytes is null) return; writer.WriteBase64(bytes, 0, bytes.Length); @@ -671,7 +671,7 @@ internal void WriteQualifiedName(string localName, string ns) internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString ns) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) writer.WriteQualifiedName(localName.Value, ns.Value); else dictionaryWriter.WriteQualifiedName(localName, ns); @@ -679,7 +679,7 @@ internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryStr internal void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { @@ -694,7 +694,7 @@ internal void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlD internal void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { @@ -709,7 +709,7 @@ internal void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, internal void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { @@ -724,7 +724,7 @@ internal void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, X internal void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { @@ -739,7 +739,7 @@ internal void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDict internal void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { @@ -754,7 +754,7 @@ internal void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDic internal void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { @@ -769,7 +769,7 @@ internal void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlD internal void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { - if (dictionaryWriter == null) + if (dictionaryWriter is null) { for (int i = 0; i < value.Length; i++) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs index 2ff80082ec9dce..818c849a41bfaa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs @@ -41,7 +41,7 @@ public XmlSchemaSet Schemas private XmlSchemaSet GetSchemaSet() { - if (_schemas == null) + if (_schemas is null) { _schemas = new XmlSchemaSet(); _schemas.XmlResolver = null; @@ -74,17 +74,17 @@ private void TraceExportError(Exception exception) public void Export(ICollection assemblies) { - if (assemblies == null) + if (assemblies is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies))); TraceExportBegin(); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet is null) ? null : new DataContractSet(_dataContractSet); try { foreach (Assembly assembly in assemblies) { - if (assembly == null) + if (assembly is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, nameof(assemblies)))); Type[] types = assembly.GetTypes(); @@ -105,17 +105,17 @@ public void Export(ICollection assemblies) public void Export(ICollection types) { - if (types == null) + if (types is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types))); TraceExportBegin(); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet is null) ? null : new DataContractSet(_dataContractSet); try { foreach (Type type in types) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullType, nameof(types)))); AddType(type); } @@ -133,12 +133,12 @@ public void Export(ICollection types) public void Export(Type type) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); TraceExportBegin(); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet is null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); @@ -155,33 +155,33 @@ public void Export(Type type) public XmlQualifiedName GetSchemaTypeName(Type type) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); XmlDataContract? xmlDataContract = dataContract as XmlDataContract; - if (xmlDataContract != null && xmlDataContract.IsAnonymous) + if (xmlDataContract is not null && xmlDataContract.IsAnonymous) return XmlQualifiedName.Empty; return dataContract.StableName; } public XmlSchemaType? GetSchemaType(Type type) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); XmlDataContract? xmlDataContract = dataContract as XmlDataContract; - if (xmlDataContract != null && xmlDataContract.IsAnonymous) + if (xmlDataContract is not null && xmlDataContract.IsAnonymous) return xmlDataContract.XsdType; return null; } public XmlQualifiedName? GetRootElementName(Type type) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); @@ -200,7 +200,7 @@ private Type GetSurrogatedType(Type type) { #if SUPPORT_SURROGATE IDataContractSurrogate dataContractSurrogate; - if (options != null && (dataContractSurrogate = Options.GetSurrogate()) != null) + if (options is not null && (dataContractSurrogate = Options.GetSurrogate()) is not null) type = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, type); #endif return type; @@ -227,16 +227,16 @@ private void Export() private void AddKnownTypes() { - if (Options != null) + if (Options is not null) { Collection knownTypes = Options.KnownTypes; - if (knownTypes != null) + if (knownTypes is not null) { for (int i = 0; i < knownTypes.Count; i++) { Type type = knownTypes[i]; - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.CannotExportNullKnownType)); AddType(type); } @@ -246,15 +246,15 @@ private void AddKnownTypes() public bool CanExport(ICollection assemblies) { - if (assemblies == null) + if (assemblies is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies))); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet is null) ? null : new DataContractSet(_dataContractSet); try { foreach (Assembly assembly in assemblies) { - if (assembly == null) + if (assembly is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, nameof(assemblies)))); Type[] types = assembly.GetTypes(); @@ -279,15 +279,15 @@ public bool CanExport(ICollection assemblies) public bool CanExport(ICollection types) { - if (types == null) + if (types is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types))); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet is null) ? null : new DataContractSet(_dataContractSet); try { foreach (Type type in types) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullType, nameof(types)))); AddType(type); } @@ -309,10 +309,10 @@ public bool CanExport(ICollection types) public bool CanExport(Type type) { - if (type == null) + if (type is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet is null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs index c6d617d4e89d86..608e1d601f3393 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs @@ -55,7 +55,7 @@ private bool IsValidTailBytes(int v3, int v4) public unsafe override int GetByteCount(char[] chars, int index, int count) { - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (index < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative)); @@ -109,7 +109,7 @@ public unsafe override int GetByteCount(char[] chars, int index, int count) public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) @@ -122,7 +122,7 @@ public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, if (charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); - if (bytes == null) + if (bytes is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative)); @@ -188,7 +188,7 @@ public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, public unsafe virtual int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative)); @@ -200,7 +200,7 @@ public unsafe virtual int GetBytes(byte[] chars, int charIndex, int charCount, b if (charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); - if (bytes == null) + if (bytes is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative)); @@ -276,7 +276,7 @@ public override int GetCharCount(byte[] bytes, int index, int count) public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - if (bytes == null) + if (bytes is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative)); @@ -288,7 +288,7 @@ public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); int charCount = GetCharCount(bytes, byteIndex, byteCount); - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative)); @@ -365,7 +365,7 @@ public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, public unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex) { - if (bytes == null) + if (bytes is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative)); @@ -377,7 +377,7 @@ public unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] ch throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); int charCount = GetCharCount(bytes, byteIndex, byteCount); - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs index 959f916fcfaa24..c50150ee3e6e88 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs @@ -24,7 +24,7 @@ public override int GetByteCount(char[] chars, int index, int count) public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars)); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); @@ -34,7 +34,7 @@ public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative); if (charCount > chars.Length - charIndex) throw new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)); - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); @@ -68,7 +68,7 @@ public override int GetCharCount(byte[] bytes, int index, int count) public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); @@ -79,7 +79,7 @@ public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, if (byteCount > bytes.Length - byteIndex) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)); int charCount = GetCharCount(bytes, byteIndex, byteCount); - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars)); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs index 76e7640138cff9..57f88822555391 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs @@ -38,7 +38,7 @@ public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgu totalRead += read; if (read < array.Length || reader.NodeType == XmlNodeType.EndElement) break; - if (arrays == null) + if (arrays is null) arrays = new TArray[32][]; arrays[arrayCount++] = array; count = count * 2; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs index 08416bf4ef91f6..0293e5e862bdcb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs @@ -64,7 +64,7 @@ public EncodingStreamWrapper(Stream stream, Encoding? encoding) // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM - SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); + SupportedEncoding declEnc = ReadBOMEncoding(encoding is null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) @@ -150,7 +150,7 @@ private static string GetEncodingName(SupportedEncoding enc) => private static SupportedEncoding GetSupportedEncoding(Encoding? encoding) { - if (encoding == null) + if (encoding is null) return SupportedEncoding.None; else if (encoding.WebName == s_validatingUTF8.WebName) return SupportedEncoding.UTF8; @@ -297,14 +297,14 @@ private void FillBuffer(int count) private void EnsureBuffers() { EnsureByteBuffer(); - if (_chars == null) + if (_chars is null) _chars = new char[BufferLength]; } [MemberNotNull(nameof(_bytes))] private void EnsureByteBuffer() { - if (_bytes != null) + if (_bytes is not null) return; _bytes = new byte[BufferLength * 4]; @@ -457,7 +457,7 @@ internal static ArraySegment ProcessBuffer(byte[] buffer, int offset, int ArraySegment seg; SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); - SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); + SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding is null, out preserve); if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); @@ -607,8 +607,8 @@ public override int Read(byte[] buffer, int offset, int count) if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); - Debug.Assert(_bytes != null); - Debug.Assert(_chars != null); + Debug.Assert(_bytes is not null); + Debug.Assert(_chars is not null); // No more bytes than can be turned into characters _byteOffset = 0; @@ -642,7 +642,7 @@ public override int Read(byte[] buffer, int offset, int count) private void CleanupCharBreak() { - Debug.Assert(_bytes != null); + Debug.Assert(_bytes is not null); int max = _byteOffset + _byteCount; @@ -704,8 +704,8 @@ public override void Write(byte[] buffer, int offset, int count) return; } - Debug.Assert(_bytes != null); - Debug.Assert(_chars != null); + Debug.Assert(_bytes is not null); + Debug.Assert(_chars is not null); while (count > 0) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs index 662f2454c51465..aa69548653c4aa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs @@ -62,7 +62,7 @@ public UniqueId(byte[] guid) : this(guid, 0) public unsafe UniqueId(byte[] guid, int offset) { - if (guid == null) + if (guid is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(guid))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -79,7 +79,7 @@ public unsafe UniqueId(byte[] guid, int offset) public unsafe UniqueId(string value) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); if (value.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.XmlInvalidUniqueId)); @@ -92,7 +92,7 @@ public unsafe UniqueId(string value) public unsafe UniqueId(char[] chars, int offset, int count) { - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -119,7 +119,7 @@ public int CharArrayLength { get { - if (_s != null) + if (_s is not null) return _s.Length; return uuidLength; @@ -200,7 +200,7 @@ public unsafe int ToCharArray(char[] chars, int offset) { int count = CharArrayLength; - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (offset < 0) @@ -211,7 +211,7 @@ public unsafe int ToCharArray(char[] chars, int offset) if (count > chars.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(chars), SR.Format(SR.XmlArrayTooSmallOutput, count))); - if (_s != null) + if (_s is not null) { _s.CopyTo(0, chars, offset, count); } @@ -278,7 +278,7 @@ public unsafe bool TryGetGuid(byte[] buffer, int offset) if (!IsGuid) return false; - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); if (offset < 0) @@ -300,7 +300,7 @@ public unsafe bool TryGetGuid(byte[] buffer, int offset) public unsafe override string ToString() { - if (_s == null) + if (_s is null) { int length = CharArrayLength; char[] chars = new char[length]; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs index 94a4908b414ca7..ebc7f45dd08b4d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs @@ -510,7 +510,7 @@ public string GetString() return GetDictionaryString().Value; case ValueHandleType.Base64: byte[] bytes = ToByteArray(); - DiagnosticUtility.DebugAssert(bytes != null, ""); + DiagnosticUtility.DebugAssert(bytes is not null, ""); return Base64Encoding.GetString(bytes, 0, bytes.Length); case ValueHandleType.List: return XmlConverter.ToString(ToList()); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index bc1dceaad4490e..d17a0f5faa3e2e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -81,7 +81,7 @@ private static Base64Encoding Base64Encoding { get { - if (s_base64Encoding == null) + if (s_base64Encoding is null) s_base64Encoding = new Base64Encoding(); return s_base64Encoding; } @@ -91,7 +91,7 @@ private static BinHexEncoding BinHexEncoding { get { - if (s_binHexEncoding == null) + if (s_binHexEncoding is null) s_binHexEncoding = new BinHexEncoding(); return s_binHexEncoding; } @@ -132,7 +132,7 @@ protected void MoveToNode(XmlNode node) protected void MoveToInitial(XmlDictionaryReaderQuotas quotas) { - if (quotas == null) + if (quotas is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(quotas)); quotas.InternalCopyTo(_quotas); @@ -174,7 +174,7 @@ protected XmlDeclarationNode MoveToDeclaration() } } - if (_declarationNode == null) + if (_declarationNode is null) { _declarationNode = new XmlDeclarationNode(_bufferReader); } @@ -206,14 +206,14 @@ private bool CheckDeclAttribute(int index, string localName, string? value, bool if (node.LocalName != localName) return false; - if (value != null && !node.Value.Equals2(value, checkLower)) + if (value is not null && !node.Value.Equals2(value, checkLower)) XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(valueSR))); return true; } protected XmlCommentNode MoveToComment() { - if (_commentNode == null) + if (_commentNode is null) { _commentNode = new XmlCommentNode(_bufferReader); } @@ -223,7 +223,7 @@ protected XmlCommentNode MoveToComment() protected XmlCDataNode MoveToCData() { - if (_cdataNode == null) + if (_cdataNode is null) { _cdataNode = new XmlCDataNode(_bufferReader); } @@ -240,7 +240,7 @@ protected XmlAtomicTextNode MoveToAtomicText() protected XmlComplexTextNode MoveToComplexText() { - if (_complexTextNode == null) + if (_complexTextNode is null) { _complexTextNode = new XmlComplexTextNode(_bufferReader); } @@ -250,7 +250,7 @@ protected XmlComplexTextNode MoveToComplexText() protected XmlTextNode MoveToWhitespaceText() { - if (_whitespaceTextNode == null) + if (_whitespaceTextNode is null) { _whitespaceTextNode = new XmlWhitespaceTextNode(_bufferReader); } @@ -301,7 +301,7 @@ protected XmlElementNode EnterScope() _depth++; if (_depth > _quotas.MaxDepth) XmlExceptionHelper.ThrowMaxDepthExceeded(this, _quotas.MaxDepth); - if (_elementNodes == null) + if (_elementNodes is null) { _elementNodes = new XmlElementNode[4]; } @@ -312,7 +312,7 @@ protected XmlElementNode EnterScope() _elementNodes = newElementNodes; } XmlElementNode elementNode = _elementNodes[_depth]; - if (elementNode == null) + if (elementNode is null) { elementNode = new XmlElementNode(_bufferReader); _elementNodes[_depth] = elementNode; @@ -335,7 +335,7 @@ protected void ExitScope() private XmlAttributeNode AddAttribute(QNameType qnameType, bool isAtomicValue) { int attributeIndex = _attributeCount; - if (_attributeNodes == null) + if (_attributeNodes is null) { _attributeNodes = new XmlAttributeNode[4]; } @@ -346,7 +346,7 @@ private XmlAttributeNode AddAttribute(QNameType qnameType, bool isAtomicValue) _attributeNodes = newAttributeNodes; } XmlAttributeNode attributeNode = _attributeNodes[attributeIndex]; - if (attributeNode == null) + if (attributeNode is null) { attributeNode = new XmlAttributeNode(_bufferReader); _attributeNodes[attributeIndex] = attributeNode; @@ -496,15 +496,15 @@ public override void Close() { MoveToNode(s_closedNode); _nameTable = null; - if (_attributeNodes != null && _attributeNodes.Length > 16) + if (_attributeNodes is not null && _attributeNodes.Length > 16) _attributeNodes = null; - if (_elementNodes != null && _elementNodes.Length > 16) + if (_elementNodes is not null && _elementNodes.Length > 16) _elementNodes = null; _nsMgr.Close(); _bufferReader.Close(); - if (_signingWriter != null) + if (_signingWriter is not null) _signingWriter.Close(); - if (_attributeSorter != null) + if (_attributeSorter is not null) _attributeSorter.Close(); } @@ -544,7 +544,7 @@ private XmlAttributeNode GetAttributeNode(int index) private XmlAttributeNode? GetAttributeNode(string name) { - if (name == null) + if (name is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(name))); if (!_node.CanGetAttribute) return null; @@ -592,9 +592,9 @@ private XmlAttributeNode GetAttributeNode(int index) private XmlAttributeNode? GetAttributeNode(string localName, string? namespaceUri) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); - if (namespaceUri == null) + if (namespaceUri is null) namespaceUri = string.Empty; if (!_node.CanGetAttribute) return null; @@ -619,9 +619,9 @@ private XmlAttributeNode GetAttributeNode(int index) private XmlAttributeNode? GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); - if (namespaceUri == null) + if (namespaceUri is null) namespaceUri = XmlDictionaryString.Empty; if (!_node.CanGetAttribute) return null; @@ -653,7 +653,7 @@ public override string GetAttribute(int index) public override string? GetAttribute(string name) { XmlAttributeNode? attributeNode = GetAttributeNode(name); - if (attributeNode == null) + if (attributeNode is null) return null; return attributeNode.ValueAsString; } @@ -661,7 +661,7 @@ public override string GetAttribute(int index) public override string? GetAttribute(string localName, string? namespaceUri) { XmlAttributeNode? attributeNode = GetAttributeNode(localName, namespaceUri); - if (attributeNode == null) + if (attributeNode is null) return null; return attributeNode.ValueAsString; } @@ -669,7 +669,7 @@ public override string GetAttribute(int index) public override string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { XmlAttributeNode? attributeNode = GetAttributeNode(localName, namespaceUri); - if (attributeNode == null) + if (attributeNode is null) return null; return attributeNode.ValueAsString; } @@ -685,7 +685,7 @@ public override string LocalName { get { - if (_localName == null) + if (_localName is null) { QNameType qnameType = _node.QNameType; if (qnameType == QNameType.Normal) @@ -709,7 +709,7 @@ public override string LocalName public override string? LookupNamespace(string prefix) { Namespace? ns = _nsMgr.LookupNamespace(prefix); - if (ns != null) + if (ns is not null) return ns.Uri.GetString(NameTable); if (prefix == xmlns) return xmlnsNamespace; @@ -719,7 +719,7 @@ public override string LocalName protected Namespace LookupNamespace(PrefixHandleType prefix) { Namespace? ns = _nsMgr.LookupNamespace(prefix); - if (ns == null) + if (ns is null) XmlExceptionHelper.ThrowUndefinedPrefix(this, PrefixHandle.GetString(prefix)); return ns; } @@ -727,7 +727,7 @@ protected Namespace LookupNamespace(PrefixHandleType prefix) protected Namespace LookupNamespace(PrefixHandle prefix) { Namespace? ns = _nsMgr.LookupNamespace(prefix); - if (ns == null) + if (ns is null) XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix.GetString()); return ns; } @@ -802,7 +802,7 @@ private void ProcessAttributes(XmlAttributeNode[] attributeNodes, int attributeC private void CheckAttributes(XmlAttributeNode[] attributeNodes, int attributeCount) { // For large numbers of attributes, sorting the attributes (n * lg(n)) is faster - if (_attributeSorter == null) + if (_attributeSorter is null) _attributeSorter = new AttributeSorter(); if (!_attributeSorter.Sort(attributeNodes, attributeCount)) @@ -824,7 +824,7 @@ public override void MoveToAttribute(int index) public override bool MoveToAttribute(string name) { XmlNode? attributeNode = GetAttributeNode(name); - if (attributeNode == null) + if (attributeNode is null) return false; MoveToNode(attributeNode); return true; @@ -833,7 +833,7 @@ public override bool MoveToAttribute(string name) public override bool MoveToAttribute(string localName, string? namespaceUri) { XmlNode? attributeNode = GetAttributeNode(localName, namespaceUri); - if (attributeNode == null) + if (attributeNode is null) return false; MoveToNode(attributeNode); return true; @@ -865,7 +865,7 @@ public override XmlNodeType MoveToContent() break; } - if (_value == null) + if (_value is null) { if (!_node.Value.IsWhitespace()) break; @@ -914,7 +914,7 @@ public override string NamespaceURI { get { - if (_ns == null) + if (_ns is null) { QNameType qnameType = _node.QNameType; if (qnameType == QNameType.Normal) @@ -935,7 +935,7 @@ public override XmlNameTable NameTable { get { - if (_nameTable == null) + if (_nameTable is null) { _nameTable = new NameTable(); _nameTable.Add(xml); @@ -964,7 +964,7 @@ public override string Prefix { get { - if (_prefix == null) + if (_prefix is null) { QNameType qnameType = _node.QNameType; if (qnameType == QNameType.Normal) @@ -991,27 +991,27 @@ public override string Prefix public override bool IsLocalName(string localName) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); return _node.IsLocalName(localName); } public override bool IsLocalName(XmlDictionaryString localName) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); return _node.IsLocalName(localName); } public override bool IsNamespaceUri(string namespaceUri) { - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); return _node.IsNamespaceUri(namespaceUri); } public override bool IsNamespaceUri(XmlDictionaryString namespaceUri) { - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); return _node.IsNamespaceUri(namespaceUri); } @@ -1033,7 +1033,7 @@ public override sealed bool IsStartElement() public override bool IsStartElement(string name) { - if (name == null) + if (name is null) return false; int index = name.IndexOf(':'); string prefix; @@ -1053,27 +1053,27 @@ public override bool IsStartElement(string name) public override bool IsStartElement(string localName, string namespaceUri) { - if (localName == null) + if (localName is null) return false; - if (namespaceUri == null) + if (namespaceUri is null) return false; return (_node.NodeType == XmlNodeType.Element || IsStartElement()) && _node.LocalName == localName && _node.IsNamespaceUri(namespaceUri); } public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); return (_node.NodeType == XmlNodeType.Element || IsStartElement()) && _node.LocalName == localName && _node.IsNamespaceUri(namespaceUri); } public override int IndexOfLocalName(string[] localNames, string namespaceUri) { - if (localNames == null) + if (localNames is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames)); - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); QNameType qnameType = _node.QNameType; if (_node.IsNamespaceUri(namespaceUri)) @@ -1084,7 +1084,7 @@ public override int IndexOfLocalName(string[] localNames, string namespaceUri) for (int i = 0; i < localNames.Length; i++) { string value = localNames[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); if (localName == value) { @@ -1099,7 +1099,7 @@ public override int IndexOfLocalName(string[] localNames, string namespaceUri) for (int i = 0; i < localNames.Length; i++) { string value = localNames[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); if (prefix == value) { @@ -1113,9 +1113,9 @@ public override int IndexOfLocalName(string[] localNames, string namespaceUri) public override int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri) { - if (localNames == null) + if (localNames is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames)); - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); QNameType qnameType = _node.QNameType; if (_node.IsNamespaceUri(namespaceUri)) @@ -1126,7 +1126,7 @@ public override int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictio for (int i = 0; i < localNames.Length; i++) { XmlDictionaryString value = localNames[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); if (localName == value) { @@ -1141,7 +1141,7 @@ public override int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictio for (int i = 0; i < localNames.Length; i++) { XmlDictionaryString value = localNames[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); if (prefix == value) { @@ -1155,7 +1155,7 @@ public override int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictio public override int ReadValueChunk(char[] chars, int offset, int count) { - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -1167,7 +1167,7 @@ public override int ReadValueChunk(char[] chars, int offset, int count) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset))); int actual; - if (_value == null) + if (_value is null) { if (_node.QNameType == QNameType.Normal) { @@ -1185,7 +1185,7 @@ public override int ReadValueChunk(char[] chars, int offset, int count) public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -1198,7 +1198,7 @@ public override int ReadValueAsBase64(byte[] buffer, int offset, int count) if (count == 0) return 0; int actual; - if (_value == null) + if (_value is null) { if (_trailByteCount == 0 && _trailCharCount == 0) { @@ -1266,7 +1266,7 @@ public override void ReadEndElement() public override bool ReadAttributeValue() { XmlAttributeTextNode? attributeTextNode = _node.AttributeText; - if (attributeTextNode == null) + if (attributeTextNode is null) return false; MoveToNode(attributeTextNode); return true; @@ -1288,7 +1288,7 @@ private void SkipValue(XmlNode node) public override bool TryGetBase64ContentLength(out int length) { - if (_trailByteCount == 0 && _trailCharCount == 0 && _value == null) + if (_trailByteCount == 0 && _trailCharCount == 0 && _value is null) { XmlNode node = this.Node; if (node.IsAtomicValue) @@ -1299,7 +1299,7 @@ public override bool TryGetBase64ContentLength(out int length) public override byte[] ReadContentAsBase64() { - if (_trailByteCount == 0 && _trailCharCount == 0 && _value == null) + if (_trailByteCount == 0 && _trailCharCount == 0 && _value is null) { XmlNode node = this.Node; if (node.IsAtomicValue) @@ -1345,7 +1345,7 @@ public override int ReadElementContentAsBase64(byte[] buffer, int offset, int co public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -1358,7 +1358,7 @@ public override int ReadContentAsBase64(byte[] buffer, int offset, int count) if (count == 0) return 0; int actual; - if (_trailByteCount == 0 && _trailCharCount == 0 && _value == null) + if (_trailByteCount == 0 && _trailCharCount == 0 && _value is null) { if (_node.QNameType == QNameType.Normal) { @@ -1383,7 +1383,7 @@ public override byte[] ReadContentAsBinHex() public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -1428,7 +1428,7 @@ private int ReadBytes(Encoding encoding, int byteBlock, int charBlock, byte[] bu // If there are any trailing buffer return them. if (_trailByteCount > 0) { - Debug.Assert(_trailBytes != null); + Debug.Assert(_trailBytes is not null); int actual = Math.Min(_trailByteCount, byteCount); Buffer.BlockCopy(_trailBytes, 0, buffer, offset, actual); @@ -1487,7 +1487,7 @@ private int ReadBytes(Encoding encoding, int byteBlock, int charBlock, byte[] bu _trailCharCount = (charCount % charBlock); if (_trailCharCount > 0) { - if (_trailChars == null) + if (_trailChars is null) _trailChars = new char[4]; charCount = charCount - _trailCharCount; Array.Copy(chars, charCount, _trailChars, 0, _trailCharCount); @@ -1497,7 +1497,7 @@ private int ReadBytes(Encoding encoding, int byteBlock, int charBlock, byte[] bu { if (byteCount < byteBlock) { - if (_trailBytes == null) + if (_trailBytes is null) _trailBytes = new byte[3]; _trailByteCount = encoding.GetBytes(chars, 0, charCount, _trailBytes, 0); int actual = Math.Min(_trailByteCount, byteCount); @@ -1539,10 +1539,10 @@ public override string ReadContentAsString() XmlNode node = this.Node; if (node.IsAtomicValue) { - if (_value != null) + if (_value is not null) { value = _value; - if (node.AttributeText == null) + if (node.AttributeText is null) _value = string.Empty; } else @@ -1560,7 +1560,7 @@ public override string ReadContentAsString() public override bool ReadContentAsBoolean() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { bool value = node.Value.ToBoolean(); SkipValue(node); @@ -1572,7 +1572,7 @@ public override bool ReadContentAsBoolean() public override long ReadContentAsLong() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { long value = node.Value.ToLong(); SkipValue(node); @@ -1584,7 +1584,7 @@ public override long ReadContentAsLong() public override int ReadContentAsInt() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { int value = node.Value.ToInt(); SkipValue(node); @@ -1596,7 +1596,7 @@ public override int ReadContentAsInt() public override DateTime ReadContentAsDateTime() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { DateTime value = node.Value.ToDateTime(); SkipValue(node); @@ -1608,7 +1608,7 @@ public override DateTime ReadContentAsDateTime() public override double ReadContentAsDouble() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { double value = node.Value.ToDouble(); SkipValue(node); @@ -1620,7 +1620,7 @@ public override double ReadContentAsDouble() public override float ReadContentAsFloat() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { float value = node.Value.ToSingle(); SkipValue(node); @@ -1632,7 +1632,7 @@ public override float ReadContentAsFloat() public override decimal ReadContentAsDecimal() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { decimal value = node.Value.ToDecimal(); SkipValue(node); @@ -1644,7 +1644,7 @@ public override decimal ReadContentAsDecimal() public override UniqueId ReadContentAsUniqueId() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { UniqueId value = node.Value.ToUniqueId(); SkipValue(node); @@ -1656,7 +1656,7 @@ public override UniqueId ReadContentAsUniqueId() public override TimeSpan ReadContentAsTimeSpan() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { TimeSpan value = node.Value.ToTimeSpan(); SkipValue(node); @@ -1668,7 +1668,7 @@ public override TimeSpan ReadContentAsTimeSpan() public override Guid ReadContentAsGuid() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { Guid value = node.Value.ToGuid(); SkipValue(node); @@ -1680,7 +1680,7 @@ public override Guid ReadContentAsGuid() public override object ReadContentAsObject() { XmlNode node = this.Node; - if (_value == null && node.IsAtomicValue) + if (_value is null && node.IsAtomicValue) { object obj = node.Value.ToObject(); SkipValue(node); @@ -1693,7 +1693,7 @@ public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespace { if (type == typeof(ulong)) { - if (_value == null && _node.IsAtomicValue) + if (_value is null && _node.IsAtomicValue) { ulong value = _node.Value.ToULong(); SkipValue(_node); @@ -1760,7 +1760,7 @@ public override string Value { get { - if (_value == null) + if (_value is null) { _value = _node.ValueAsString; } @@ -1773,7 +1773,7 @@ public override Type ValueType { get { - if (_value == null && _node.QNameType == QNameType.Normal) + if (_value is null && _node.QNameType == QNameType.Normal) { Type type = _node.Value.ToType(); if (_node.IsAtomicValue) @@ -1924,7 +1924,7 @@ private char[] GetCharBuffer(int count) if (count > 1024) return new char[count]; - if (_chars == null || _chars.Length < count) + if (_chars is null || _chars.Length < count) _chars = new char[count]; return _chars; @@ -2033,7 +2033,7 @@ public override void StartCanonicalization(Stream stream, bool includeComments, if (_signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted)); - if (_signingWriter == null) + if (_signingWriter is null) _signingWriter = CreateSigningNodeWriter(); _signingWriter.SetOutput(XmlNodeWriter.Null, stream, includeComments, inclusivePrefixes); @@ -2649,7 +2649,7 @@ public void GetIndeces(out int attributeIndex1, out int attributeIndex2) public void Close() { - if (_indeces != null && _indeces.Length > 32) + if (_indeces is not null && _indeces.Length > 32) { _indeces = null; } @@ -2659,7 +2659,7 @@ private bool Sort() { // Optimistically use the last sort order and check to see if that works. This helps the case // where elements with large numbers of attributes are repeated. - if (_indeces != null && _indeces.Length == _attributeCount && IsSorted()) + if (_indeces is not null && _indeces.Length == _attributeCount && IsSorted()) return true; object[] newIndeces = new object[_attributeCount]; @@ -2749,9 +2749,9 @@ public NamespaceManager(XmlBufferReader bufferReader) public void Close() { - if (_namespaces != null && _namespaces.Length > 32) + if (_namespaces is not null && _namespaces.Length > 32) _namespaces = null; - if (_attributes != null && _attributes.Length > 4) + if (_attributes is not null && _attributes.Length > 4) _attributes = null; _lang = string.Empty; } @@ -2760,7 +2760,7 @@ public static Namespace XmlNamespace { get { - if (s_xmlNamespace == null) + if (s_xmlNamespace is null) { byte[] xmlBuffer = { @@ -2891,7 +2891,7 @@ public void AddSpaceAttribute(XmlSpace space) private void AddAttribute() { - if (_attributes == null) + if (_attributes is null) { _attributes = new XmlAttribute[1]; } @@ -2902,7 +2902,7 @@ private void AddAttribute() _attributes = newAttributes; } XmlAttribute attribute = _attributes[_attributeCount]; - if (attribute == null) + if (attribute is null) { attribute = new XmlAttribute(); _attributes[_attributeCount] = attribute; @@ -2929,7 +2929,7 @@ public void Register(Namespace nameSpace) public Namespace AddNamespace() { - if (_namespaces == null) + if (_namespaces is null) { _namespaces = new Namespace[4]; } @@ -2940,7 +2940,7 @@ public Namespace AddNamespace() _namespaces = newNamespaces; } Namespace nameSpace = _namespaces[_nsCount]; - if (nameSpace == null) + if (nameSpace is null) { nameSpace = new Namespace(_bufferReader); _namespaces[_nsCount] = nameSpace; @@ -3098,7 +3098,7 @@ public PrefixHandle Prefix public bool IsUri(string s) { - DiagnosticUtility.DebugAssert(s != null, ""); + DiagnosticUtility.DebugAssert(s is not null, ""); if (object.ReferenceEquals(s, _uriString)) return true; if (_uri == s) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index a16eade973bf44..6bedac9612aef6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -97,7 +97,7 @@ public override void Close() _attributeValue = null; _attributeLocalName = null; _nodeWriter.Close(); - if (_signingWriter != null) + if (_signingWriter is not null) { _signingWriter.Close(); } @@ -119,7 +119,7 @@ private static BinHexEncoding BinHexEncoding { get { - if (_binhexEncoding == null) + if (_binhexEncoding is null) _binhexEncoding = new BinHexEncoding(); return _binhexEncoding; } @@ -154,16 +154,16 @@ public override void WriteXmlnsAttribute(string? prefix, string ns) if (IsClosed) ThrowClosed(); - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ns)); if (_writeState != WriteState.Element) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteXmlnsAttribute", WriteState.ToString()))); - if (prefix == null) + if (prefix is null) { prefix = _nsMgr.LookupPrefix(ns); - if (prefix == null) + if (prefix is null) { GeneratePrefix(ns, null); } @@ -179,16 +179,16 @@ public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) if (IsClosed) ThrowClosed(); - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ns)); if (_writeState != WriteState.Element) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteXmlnsAttribute", WriteState.ToString()))); - if (prefix == null) + if (prefix is null) { prefix = _nsMgr.LookupPrefix(ns.Value); - if (prefix == null) + if (prefix is null) { GeneratePrefix(ns.Value, ns); } @@ -207,13 +207,13 @@ private void StartAttribute([AllowNull] ref string prefix, string localName, str if (_writeState == WriteState.Attribute) WriteEndAttribute(); - if (localName == null || (localName.Length == 0 && prefix != "xmlns")) + if (localName is null || (localName.Length == 0 && prefix != "xmlns")) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); if (_writeState != WriteState.Element) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartAttribute", WriteState.ToString()))); - if (prefix == null) + if (prefix is null) { if (ns == xmlnsNamespace && localName != "xmlns") prefix = "xmlns"; @@ -234,7 +234,7 @@ private void StartAttribute([AllowNull] ref string prefix, string localName, str _isXmlAttribute = false; if (prefix == "xml") { - if (ns != null && ns != xmlNamespace) + if (ns is not null && ns != xmlNamespace) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xml", xmlNamespace, ns), nameof(ns))); _isXmlAttribute = true; _attributeValue = string.Empty; @@ -242,13 +242,13 @@ private void StartAttribute([AllowNull] ref string prefix, string localName, str } else if (prefix == "xmlns") { - if (ns != null && ns != xmlnsNamespace) + if (ns is not null && ns != xmlnsNamespace) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), nameof(ns))); _isXmlnsAttribute = true; _attributeValue = string.Empty; _attributeLocalName = localName; } - else if (ns == null) + else if (ns is null) { // A null namespace means the namespace of the given prefix. if (prefix.Length == 0) @@ -260,7 +260,7 @@ private void StartAttribute([AllowNull] ref string prefix, string localName, str { ns = _nsMgr.LookupNamespace(prefix); - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlUndefinedPrefix, prefix), nameof(prefix))); } } @@ -276,7 +276,7 @@ private void StartAttribute([AllowNull] ref string prefix, string localName, str string? tempPrefix = _nsMgr.LookupAttributePrefix(ns); // If we didn't find anything with the right namespace, generate one. - if (tempPrefix == null) + if (tempPrefix is null) { // Watch for special values if (ns.Length == xmlnsNamespace.Length && ns == xmlnsNamespace) @@ -306,7 +306,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin public override void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - StartAttribute(ref prefix, (localName != null ? localName.Value : null)!, (namespaceUri != null ? namespaceUri.Value : null), namespaceUri); + StartAttribute(ref prefix, (localName is not null ? localName.Value : null)!, (namespaceUri is not null ? namespaceUri.Value : null), namespaceUri); if (!_isXmlnsAttribute) { _writer.WriteStartAttribute(prefix, localName!); @@ -444,7 +444,7 @@ public override void WriteComment(string? text) if (_writeState == WriteState.Attribute) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteComment", WriteState.ToString()))); - if (text == null) + if (text is null) { text = string.Empty; } @@ -482,7 +482,7 @@ public override void WriteCData(string? text) if (_writeState == WriteState.Attribute) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteCData", WriteState.ToString()))); - if (text == null) + if (text is null) text = string.Empty; if (text.Length > 0) @@ -506,7 +506,7 @@ private void StartElement(ref string? prefix, string localName, string? ns, XmlD if (_documentState == DocumentState.Epilog) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlyOneRoot)); - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); if (localName.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName))); @@ -516,21 +516,21 @@ private void StartElement(ref string? prefix, string localName, string? ns, XmlD FlushBase64(); AutoComplete(WriteState.Element); Element element = EnterScope(); - if (ns == null) + if (ns is null) { - if (prefix == null) + if (prefix is null) prefix = string.Empty; ns = _nsMgr.LookupNamespace(prefix); - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlUndefinedPrefix, prefix), nameof(prefix))); } - else if (prefix == null) + else if (prefix is null) { prefix = _nsMgr.LookupPrefix(ns); - if (prefix == null) + if (prefix is null) { prefix = string.Empty; _nsMgr.AddNamespace(string.Empty, ns, xNs); @@ -551,7 +551,7 @@ private void PreStartElementAsyncCheck(string? prefix, string localName, string? if (_documentState == DocumentState.Epilog) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlyOneRoot)); - if (localName == null) + if (localName is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); if (localName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName))); @@ -570,21 +570,21 @@ private async Task StartElementAsync(string? prefix, string localName, s await FlushBase64Async().ConfigureAwait(false); await AutoCompleteAsync(WriteState.Element).ConfigureAwait(false); Element element = EnterScope(); - if (ns == null) + if (ns is null) { - if (prefix == null) + if (prefix is null) prefix = string.Empty; ns = _nsMgr.LookupNamespace(prefix); - if (ns == null) + if (ns is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlUndefinedPrefix, prefix), nameof(prefix))); } - else if (prefix == null) + else if (prefix is null) { prefix = _nsMgr.LookupPrefix(ns); - if (prefix == null) + if (prefix is null) { prefix = string.Empty; _nsMgr.AddNamespace(string.Empty, ns, xNs); @@ -614,7 +614,7 @@ public override Task WriteStartElementAsync(string? prefix, string localName, st public override void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - StartElement(ref prefix, localName.Value, (namespaceUri != null ? namespaceUri.Value : null), namespaceUri); + StartElement(ref prefix, localName.Value, (namespaceUri is not null ? namespaceUri.Value : null), namespaceUri); _writer.WriteStartElement(prefix, localName); } @@ -681,7 +681,7 @@ private Element EnterScope() { _nsMgr.EnterScope(); _depth++; - if (_elements == null) + if (_elements is null) { _elements = new Element[4]; } @@ -692,7 +692,7 @@ private Element EnterScope() _elements = newElementNodes; } Element element = _elements[_depth]; - if (element == null) + if (element is null) { element = new Element(); _elements[_depth] = element; @@ -827,7 +827,7 @@ private Task EndStartElementAsync() public override string? LookupPrefix(string ns) { - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(ns))); if (IsClosed) @@ -839,7 +839,7 @@ private Task EndStartElementAsync() private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString? xNs) { string? prefix = _nsMgr.LookupPrefix(namespaceUri); - if (prefix == null) + if (prefix is null) { if (_writeState != WriteState.Attribute) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlNamespaceNotFound, namespaceUri), nameof(namespaceUri))); @@ -853,11 +853,11 @@ public override void WriteQualifiedName(string localName, string? namespaceUri) { if (IsClosed) ThrowClosed(); - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); if (localName.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName))); - if (namespaceUri == null) + if (namespaceUri is null) namespaceUri = string.Empty; string prefix = GetQualifiedNamePrefix(namespaceUri, null); if (prefix.Length != 0) @@ -872,16 +872,16 @@ public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictio { if (IsClosed) ThrowClosed(); - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); if (localName.Value.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName))); - if (namespaceUri == null) + if (namespaceUri is null) namespaceUri = XmlDictionaryString.Empty; string prefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(string.Concat(prefix, ":", namespaceUri.Value)); if (!_isXmlnsAttribute) @@ -980,7 +980,7 @@ public override void WriteWhitespace(string? whitespace) if (IsClosed) ThrowClosed(); - if (whitespace == null) + if (whitespace is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(whitespace)); for (int i = 0; i < whitespace.Length; ++i) @@ -1001,14 +1001,14 @@ public override void WriteString(string? value) if (IsClosed) ThrowClosed(); - if (value == null) + if (value is null) value = string.Empty; if (value.Length > 0 || _inList) { FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(value); if (!_isXmlnsAttribute) @@ -1025,14 +1025,14 @@ public override void WriteString(XmlDictionaryString? value) if (IsClosed) ThrowClosed(); - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); if (value.Value.Length > 0) { FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(value.Value); if (!_isXmlnsAttribute) @@ -1049,7 +1049,7 @@ public override void WriteChars(char[] chars, int offset, int count) if (IsClosed) ThrowClosed(); - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. @@ -1065,7 +1065,7 @@ public override void WriteChars(char[] chars, int offset, int count) { FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(new string(chars, offset, count)); if (!_isXmlnsAttribute) @@ -1082,14 +1082,14 @@ public override void WriteRaw(string value) if (IsClosed) ThrowClosed(); - if (value == null) + if (value is null) value = string.Empty; if (value.Length > 0) { FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(value); if (!_isXmlnsAttribute) @@ -1106,7 +1106,7 @@ public override void WriteRaw(char[] chars, int offset, int count) if (IsClosed) ThrowClosed(); - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. @@ -1122,7 +1122,7 @@ public override void WriteRaw(char[] chars, int offset, int count) { FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(new string(chars, offset, count)); if (!_isXmlnsAttribute) @@ -1142,7 +1142,7 @@ public override void WriteCharEntity(char ch) if (ch >= 0xd800 && ch <= 0xdfff) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlMissingLowSurrogate, nameof(ch))); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(ch.ToString()); if (!_isXmlnsAttribute) @@ -1161,7 +1161,7 @@ public override void WriteSurrogateCharEntity(char lowChar, char highChar) SurrogateChar ch = new SurrogateChar(lowChar, highChar); - if (_attributeValue != null) + if (_attributeValue is not null) { Span chars = stackalloc char[2] { highChar, lowChar }; WriteAttributeText(new string(chars)); @@ -1181,7 +1181,7 @@ public override void WriteValue(object value) if (IsClosed) ThrowClosed(); - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); else if (value is object[]) @@ -1203,7 +1203,7 @@ protected void WritePrimitiveValue(object value) if (IsClosed) ThrowClosed(); - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); if (value is ulong) @@ -1282,7 +1282,7 @@ public override void WriteValue(int value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1299,7 +1299,7 @@ public override void WriteValue(long value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1316,7 +1316,7 @@ private void WriteValue(ulong value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1333,7 +1333,7 @@ public override void WriteValue(bool value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1350,7 +1350,7 @@ public override void WriteValue(decimal value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1367,7 +1367,7 @@ public override void WriteValue(float value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1384,7 +1384,7 @@ public override void WriteValue(double value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1406,7 +1406,7 @@ public override void WriteValue(DateTime value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1422,11 +1422,11 @@ public override void WriteValue(UniqueId value) if (IsClosed) ThrowClosed(); - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1443,7 +1443,7 @@ public override void WriteValue(Guid value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1460,7 +1460,7 @@ public override void WriteValue(TimeSpan value) ThrowClosed(); FlushBase64(); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.ToString(value)); if (!_isXmlnsAttribute) @@ -1484,7 +1484,7 @@ public override void WriteBase64(byte[] buffer, int offset, int count) if (IsClosed) ThrowClosed(); - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. @@ -1510,14 +1510,14 @@ public override void WriteBase64(byte[] buffer, int offset, int count) int totalByteCount = _trailByteCount + count; int actualByteCount = totalByteCount - (totalByteCount % 3); - if (_trailBytes == null) + if (_trailBytes is null) { _trailBytes = new byte[3]; } if (actualByteCount >= 3) { - if (_attributeValue != null) + if (_attributeValue is not null) { WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount)); WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, offset, actualByteCount - _trailByteCount)); @@ -1549,7 +1549,7 @@ public override Task WriteBase64Async(byte[] buffer, int offset, int count) if (IsClosed) ThrowClosed(); - if (buffer == null) + if (buffer is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. @@ -1580,14 +1580,14 @@ private async Task WriteBase64AsyncImpl(byte[] buffer, int offset, int count) int totalByteCount = _trailByteCount + count; int actualByteCount = totalByteCount - (totalByteCount % 3); - if (_trailBytes == null) + if (_trailBytes is null) { _trailBytes = new byte[3]; } if (actualByteCount >= 3) { - if (_attributeValue != null) + if (_attributeValue is not null) { WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount)); WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, offset, actualByteCount - _trailByteCount)); @@ -1638,7 +1638,7 @@ public override void StartCanonicalization(Stream stream, bool includeComments, if (Signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted)); FlushElement(); - if (_signingWriter == null) + if (_signingWriter is null) _signingWriter = CreateSigningNodeWriter(); _signingWriter.SetOutput(_writer, stream, includeComments, inclusivePrefixes); _writer = _signingWriter; @@ -1672,9 +1672,9 @@ private Task FlushBase64Async() private void FlushTrailBytes() { - Debug.Assert(_trailBytes != null); + Debug.Assert(_trailBytes is not null); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount)); if (!_isXmlnsAttribute) @@ -1688,9 +1688,9 @@ private void FlushTrailBytes() private async Task FlushTrailBytesAsync() { - Debug.Assert(_trailBytes != null); + Debug.Assert(_trailBytes is not null); - if (_attributeValue != null) + if (_attributeValue is not null) WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount)); if (!_isXmlnsAttribute) @@ -1763,7 +1763,7 @@ private string GeneratePrefix(string ns, XmlDictionaryString? xNs) string? prefix = _nsMgr.AddNamespace(ns, xNs); - if (prefix != null) + if (prefix is not null) return prefix; while (true) @@ -1771,7 +1771,7 @@ private string GeneratePrefix(string ns, XmlDictionaryString? xNs) int prefixId = _elements![_depth].PrefixId++; prefix = string.Concat("d", _depth.ToString(CultureInfo.InvariantCulture), "p", prefixId.ToString(CultureInfo.InvariantCulture)); - if (_nsMgr.LookupNamespace(prefix) == null) + if (_nsMgr.LookupNamespace(prefix) is null) { _nsMgr.AddNamespace(prefix, ns, xNs); return prefix; @@ -1890,7 +1890,7 @@ public XmlSpace XmlSpace public void Clear() { - if (_namespaces == null) + if (_namespaces is null) { _namespaces = new Namespace[4]; _namespaces[0] = _defaultNamespace; @@ -1908,9 +1908,9 @@ public void Close() { if (_depth == 0) { - if (_namespaces != null && _namespaces.Length > 32) + if (_namespaces is not null && _namespaces.Length > 32) _namespaces = null; - if (_attributes != null && _attributes.Length > 4) + if (_attributes is not null && _attributes.Length > 4) _attributes = null; } else @@ -1934,7 +1934,7 @@ public void DeclareNamespaces(XmlNodeWriter writer) while (i < _nsCount) { Namespace nameSpace = _namespaces![i]; - if (nameSpace.UriDictionaryString != null) + if (nameSpace.UriDictionaryString is not null) writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.UriDictionaryString); else writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri!); @@ -1986,7 +1986,7 @@ public void AddSpaceAttribute(XmlSpace space) private void AddAttribute() { - if (_attributes == null) + if (_attributes is null) { _attributes = new XmlAttribute[1]; } @@ -1997,7 +1997,7 @@ private void AddAttribute() _attributes = newAttributes; } XmlAttribute attribute = _attributes[_attributeCount]; - if (attribute == null) + if (attribute is null) { attribute = new XmlAttribute(); _attributes[_attributeCount] = attribute; @@ -2091,7 +2091,7 @@ public void AddNamespace(string prefix, string uri, XmlDictionaryString? uriDict _namespaces = newNamespaces; } nameSpace = _namespaces[_nsCount]; - if (nameSpace == null) + if (nameSpace is null) { nameSpace = new Namespace(); _namespaces[_nsCount] = nameSpace; @@ -2106,7 +2106,7 @@ public void AddNamespace(string prefix, string uri, XmlDictionaryString? uriDict public string? LookupPrefix(string ns) { - if (_lastNameSpace != null && _lastNameSpace.Uri == ns) + if (_lastNameSpace is not null && _lastNameSpace.Uri == ns) return _lastNameSpace.Prefix; int nsCount = _nsCount; for (int i = nsCount - 1; i >= _nsTop; i--) @@ -2181,7 +2181,7 @@ public void AddNamespace(string prefix, string uri, XmlDictionaryString? uriDict public string? LookupAttributePrefix(string ns) { - if (_lastNameSpace != null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix!.Length != 0) + if (_lastNameSpace is not null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix!.Length != 0) return _lastNameSpace.Prefix; int nsCount = _nsCount; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs index 7f7e0e38ab3e72..faade494a8578b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs @@ -40,7 +40,7 @@ public void SetInput(byte[] buffer, int offset, int count, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer)); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -61,7 +61,7 @@ public void SetInput(Stream stream, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { - if (stream == null) + if (stream is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); MoveToInitial(quotas, session, null); BufferReader.SetBuffer(stream, dictionary, session); @@ -1216,7 +1216,7 @@ private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString nam private void CheckArray(Array array, int offset, int count) { - if (array == null) + if (array is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs index db7c46cd4c5a96..1d0e80890e3f30 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs @@ -24,7 +24,7 @@ public XmlDictionaryString Add(int id, string value) { if (id < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(id), SR.XmlInvalidID)); - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); XmlDictionaryString? xmlString; if (TryLookup(id, out xmlString)) @@ -33,14 +33,14 @@ public XmlDictionaryString Add(int id, string value) xmlString = new XmlDictionaryString(this, value, id); if (id >= MaxArrayEntries) { - if (_stringDict == null) + if (_stringDict is null) _stringDict = new Dictionary(); _stringDict.Add(id, xmlString); } else { - if (_strings == null) + if (_strings is null) { _strings = new XmlDictionaryString[Math.Max(id + 1, 16)]; } @@ -57,14 +57,14 @@ public XmlDictionaryString Add(int id, string value) public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result) { - if (_strings != null && key >= 0 && key < _strings.Length) + if (_strings is not null && key >= 0 && key < _strings.Length) { result = _strings[key]; - return result != null; + return result is not null; } else if (key >= MaxArrayEntries) { - if (_stringDict != null) + if (_stringDict is not null) return _stringDict.TryGetValue(key, out result); } result = null; @@ -73,15 +73,15 @@ public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? resu public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); - if (_strings != null) + if (_strings is not null) { for (int i = 0; i < _strings.Length; i++) { XmlDictionaryString s = _strings[i]; - if (s != null && s.Value == value) + if (s is not null && s.Value == value) { result = s; return true; @@ -89,7 +89,7 @@ public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? } } - if (_stringDict != null) + if (_stringDict is not null) { foreach (XmlDictionaryString s in _stringDict.Values) { @@ -107,7 +107,7 @@ public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); if (value.Dictionary != this) { @@ -120,10 +120,10 @@ public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDict public void Clear() { - if (_strings != null) + if (_strings is not null) Array.Clear(_strings, 0, _strings.Length); - if (_stringDict != null) + if (_stringDict is not null) _stringDict.Clear(); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs index c353ce30366a87..cbbfff3e153d72 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs @@ -350,14 +350,14 @@ private bool TryGetKey(XmlDictionaryString s, out int key) return true; } XmlDictionaryString? t; - if (_dictionary != null && _dictionary.TryLookup(s, out t)) + if (_dictionary is not null && _dictionary.TryLookup(s, out t)) { DiagnosticUtility.DebugAssert(t.Dictionary == _dictionary, ""); key = t.Key * 2; return true; } - if (_session == null) + if (_session is null) return false; int sessionKey; if (!_session.TryLookup(s, out sessionKey)) @@ -981,7 +981,7 @@ public void Clear() public void WriteText(string s) { - if (_captureStream != null) + if (_captureStream is not null) { ArraySegment arraySegment; bool result = _captureStream.TryGetBuffer(out arraySegment); @@ -990,13 +990,13 @@ public void WriteText(string s) _captureStream = null; } - if (_captureXText != null) + if (_captureXText is not null) { _captureText = _captureXText.Value; _captureXText = null; } - if (_captureText == null || _captureText.Length == 0) + if (_captureText is null || _captureText.Length == 0) { _captureText = s; } @@ -1008,7 +1008,7 @@ public void WriteText(string s) public void WriteText(XmlDictionaryString s) { - if (_captureText != null || _captureStream != null) + if (_captureText is not null || _captureStream is not null) { WriteText(s.Value); } @@ -1020,7 +1020,7 @@ public void WriteText(XmlDictionaryString s) public void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { - if (_captureText != null || _captureXText != null) + if (_captureText is not null || _captureXText is not null) { if (trailByteCount > 0) { @@ -1030,7 +1030,7 @@ public void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] buffe } else { - if (_captureStream == null) + if (_captureStream is null) _captureStream = new MemoryStream(); if (trailByteCount > 0) @@ -1042,17 +1042,17 @@ public void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] buffe public void WriteTo(XmlBinaryNodeWriter writer) { - if (_captureText != null) + if (_captureText is not null) { writer.WriteText(_captureText); _captureText = null; } - else if (_captureXText != null) + else if (_captureXText is not null) { writer.WriteText(_captureXText); _captureXText = null; } - else if (_captureStream != null) + else if (_captureStream is not null) { ArraySegment arraySegment; bool result = _captureStream.TryGetBuffer(out arraySegment); @@ -1077,9 +1077,9 @@ internal class XmlBinaryWriter : XmlBaseWriter, IXmlBinaryWriterInitializer public void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream) { - if (stream == null) + if (stream is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(stream))); - if (_writer == null) + if (_writer is null) _writer = new XmlBinaryNodeWriter(); _writer.SetOutput(stream, dictionary, session, ownsStream); SetOutput(_writer); @@ -1104,7 +1104,7 @@ protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute { if (reader.CanReadValueChunk) { - if (_chars == null) + if (_chars is null) { _chars = new char[256]; } @@ -1129,7 +1129,7 @@ protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute if (reader.CanReadBinaryContent) { // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text - if (_bytes == null) + if (_bytes is null) { _bytes = new byte[384]; } @@ -1211,7 +1211,7 @@ private unsafe void UnsafeWriteArray(string? prefix, XmlDictionaryString localNa private void CheckArray(Array array, int offset, int count) { - if (array == null) + if (array is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs index 1f2078d5bd79e0..8de9ff1c7f33fc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs @@ -28,7 +28,7 @@ public XmlBinaryWriterSession() public virtual bool TryAdd(XmlDictionaryString value, out int key) { IntArray? keys; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); if (_maps.TryGetValue(value.Dictionary, out keys)) @@ -88,7 +88,7 @@ internal bool TryLookup(XmlDictionaryString s, out int key) if (_strings.TryGetValue(s.Value, out key)) { - if (keys == null) + if (keys is null) { keys = AddKeys(s.Dictionary, s.Key + 1); } @@ -118,7 +118,7 @@ public void Clear() _now = 0; _listCount = 0; Array.Clear(_list, 0, _list.Length); - if (_dictionary != null) + if (_dictionary is not null) _dictionary.Clear(); } @@ -144,7 +144,7 @@ public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) } } - if (_dictionary == null) + if (_dictionary is null) { value = default(V); return false; @@ -182,7 +182,7 @@ public void Add(K key, V value) } else { - if (_dictionary == null) + if (_dictionary is null) { _dictionary = new Dictionary(); for (int i = 0; i < _listCount; i++) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs index 20956f5a1c56d6..92deb43016515f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs @@ -65,14 +65,14 @@ public bool IsStreamed { get { - return _stream != null; + return _stream is not null; } } public void SetBuffer(Stream stream, IXmlDictionary? dictionary, XmlBinaryReaderSession? session) { - if (_streamBuffer == null) + if (_streamBuffer is null) { _streamBuffer = new byte[128]; } @@ -99,11 +99,11 @@ private void SetBuffer(Stream? stream, byte[] buffer, int offset, int count, IXm public void Close() { - if (_streamBuffer != null && _streamBuffer.Length > 4096) + if (_streamBuffer is not null && _streamBuffer.Length > 4096) { _streamBuffer = null; } - if (_stream != null) + if (_stream is not null) { _stream.Dispose(); _stream = null; @@ -190,7 +190,7 @@ private void EnsureByte() private bool TryEnsureByte() { - if (_stream == null) + if (_stream is null) return false; DiagnosticUtility.DebugAssert(_offsetMax < _windowOffsetMax, ""); if (_offsetMax >= _buffer.Length) @@ -210,7 +210,7 @@ private void EnsureBytes(int count) private bool TryEnsureBytes(int count) { - if (_stream == null) + if (_stream is null) return false; // The data could be coming from an untrusted source, so we use a standard @@ -253,7 +253,7 @@ public void Advance(int count) public void InsertBytes(byte[] buffer, int offset, int count) { - DiagnosticUtility.DebugAssert(_stream != null, ""); + DiagnosticUtility.DebugAssert(_stream is not null, ""); if (_offsetMax > buffer.Length - count) { byte[] newBuffer = new byte[_offsetMax + count]; @@ -523,7 +523,7 @@ public unsafe void UnsafeReadArray(byte* dst, byte* dstMax) private unsafe void UnsafeReadArray(byte* dst, int length) { - if (_stream != null) + if (_stream is not null) { const int chunk = 256; while (length >= chunk) @@ -560,7 +560,7 @@ private char[] GetCharBuffer(int count) { if (count > 1024) return new char[count]; - if (_chars == null || _chars.Length < count) + if (_chars is null || _chars.Length < count) _chars = new char[count]; return _chars; } @@ -1080,7 +1080,7 @@ public UniqueId GetUniqueId(int offset) public Guid GetGuid(int offset) { - if (_guid == null) + if (_guid is null) _guid = new byte[16]; System.Buffer.BlockCopy(_buffer, offset, _guid, 0, _guid.Length); return new Guid(_guid); @@ -1148,7 +1148,7 @@ public int ReadDictionaryKey() int key = ReadMultiByteUInt31(); if ((key & 1) != 0) { - if (_session == null) + if (_session is null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int sessionKey = (key >> 1); XmlDictionaryString? xmlString; @@ -1161,7 +1161,7 @@ public int ReadDictionaryKey() } else { - if (_dictionary == null) + if (_dictionary is null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int staticKey = (key >> 1); XmlDictionaryString? xmlString; @@ -1290,7 +1290,7 @@ private void ReadUnicodeValue(ValueHandle value, int length) private void ReadList(ValueHandle value) { - if (_listValue == null) + if (_listValue is null) { _listValue = new ValueHandle(this); } @@ -1322,7 +1322,7 @@ public void ReadQName(ValueHandle value) public int[] GetRows() { - if (_buffer == null) + if (_buffer is null) { return new int[1] { 0 }; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index b7c740ae5c974d..88f7ebc243f75b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -56,27 +56,27 @@ public XmlCanonicalWriter() public void SetOutput(Stream stream, bool includeComments, string[]? inclusivePrefixes) { - if (stream == null) + if (stream is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); - if (_writer == null) + if (_writer is null) { _writer = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); } _writer.SetOutput(stream, false, null); - if (_elementStream == null) + if (_elementStream is null) { _elementStream = new MemoryStream(); } - if (_elementWriter == null) + if (_elementWriter is null) { _elementWriter = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); } _elementWriter.SetOutput(_elementStream, false, null); - if (_xmlnsAttributes == null) + if (_xmlnsAttributes is null) { _xmlnsAttributeCount = 0; _xmlnsOffset = 0; @@ -99,12 +99,12 @@ public void SetOutput(Stream stream, bool includeComments, string[]? inclusivePr _inStartElement = false; _includeComments = includeComments; _inclusivePrefixes = null; - if (inclusivePrefixes != null) + if (inclusivePrefixes is not null) { _inclusivePrefixes = new string[inclusivePrefixes.Length]; for (int i = 0; i < inclusivePrefixes.Length; ++i) { - if (inclusivePrefixes[i] == null) + if (inclusivePrefixes[i] is null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.InvalidInclusivePrefixListCollection); } @@ -121,18 +121,18 @@ public void Flush() public void Close() { - if (_writer != null) + if (_writer is not null) _writer.Close(); - if (_elementWriter != null) + if (_elementWriter is not null) _elementWriter.Close(); - if (_elementStream != null && _elementStream.Length > 512) + if (_elementStream is not null && _elementStream.Length > 512) _elementStream = null!; _elementBuffer = null; - if (_scopes != null && _scopes.Length > 16) + if (_scopes is not null && _scopes.Length > 16) _scopes = null; - if (_attributes != null && _attributes.Length > 16) + if (_attributes is not null && _attributes.Length > 16) _attributes = null; - if (_xmlnsBuffer != null && _xmlnsBuffer.Length > 1024) + if (_xmlnsBuffer is not null && _xmlnsBuffer.Length > 1024) { _xmlnsAttributes = null; _xmlnsBuffer = null; @@ -146,7 +146,7 @@ public void WriteDeclaration() public void WriteComment(string value) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); ThrowIfClosed(); if (_includeComments) @@ -158,7 +158,7 @@ public void WriteComment(string value) [MemberNotNull(nameof(_scopes))] private void StartElement() { - if (_scopes == null) + if (_scopes is null) { _scopes = new Scope[4]; } @@ -185,9 +185,9 @@ private void EndElement() public void WriteStartElement(string prefix, string localName) { - if (prefix == null) + if (prefix is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(prefix)); - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); ThrowIfClosed(); bool isRootElement = (_depth == 0); @@ -201,7 +201,7 @@ public void WriteStartElement(string prefix, string localName) // If we have a inclusivenamespace prefix list and the namespace declaration is in the // outer context, then Add it to the root element. - if (isRootElement && (_inclusivePrefixes != null)) + if (isRootElement && (_inclusivePrefixes is not null)) { // Scan through all the namespace declarations in the outer scope. for (int i = 0; i < _scopes[0].xmlnsAttributeCount; ++i) @@ -217,7 +217,7 @@ public void WriteStartElement(string prefix, string localName) public void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { - if (prefixBuffer == null) + if (prefixBuffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(prefixBuffer))); if (prefixOffset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.ValueMustBeNonNegative)); @@ -228,7 +228,7 @@ public void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixL if (prefixLength > prefixBuffer.Length - prefixOffset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, prefixBuffer.Length - prefixOffset))); - if (localNameBuffer == null) + if (localNameBuffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localNameBuffer))); if (localNameOffset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.ValueMustBeNonNegative)); @@ -250,7 +250,7 @@ public void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixL // If we have a inclusivenamespace prefix list and the namespace declaration is in the // outer context, then Add it to the root element. - if (isRootElement && (_inclusivePrefixes != null)) + if (isRootElement && (_inclusivePrefixes is not null)) { // Scan through all the namespace declarations in the outer scope. for (int i = 0; i < _scopes[0].xmlnsAttributeCount; ++i) @@ -295,7 +295,7 @@ public void WriteEndStartElement(bool isEmpty) bool alreadyReferred = false; while (j >= 0) { - Debug.Assert(_xmlnsBuffer != null); + Debug.Assert(_xmlnsBuffer is not null); if (Equals(_xmlnsBuffer, _xmlnsAttributes![i].prefixOffset, _xmlnsAttributes[i].prefixLength, _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength)) { // Check if the namespace is also equal. @@ -349,9 +349,9 @@ public void WriteEndStartElement(bool isEmpty) public void WriteEndElement(string prefix, string localName) { - if (prefix == null) + if (prefix is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(prefix)); - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); ThrowIfClosed(); _writer.WriteEndElement(prefix, localName); @@ -361,7 +361,7 @@ public void WriteEndElement(string prefix, string localName) [MemberNotNull(nameof(_xmlnsBuffer))] private void EnsureXmlnsBuffer(int byteCount) { - if (_xmlnsBuffer == null) + if (_xmlnsBuffer is null) { _xmlnsBuffer = new byte[Math.Max(byteCount, 128)]; } @@ -376,9 +376,9 @@ private void EnsureXmlnsBuffer(int byteCount) [MemberNotNull(nameof(_xmlnsAttributes))] public void WriteXmlnsAttribute(string prefix, string ns) { - if (prefix == null) + if (prefix is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(prefix)); - if (ns == null) + if (ns is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ns)); ThrowIfClosed(); if (prefix.Length > int.MaxValue - ns.Length) @@ -401,7 +401,7 @@ public void WriteXmlnsAttribute(string prefix, string ns) [MemberNotNull(nameof(_xmlnsAttributes))] public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { - if (prefixBuffer == null) + if (prefixBuffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(prefixBuffer))); if (prefixOffset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.ValueMustBeNonNegative)); @@ -412,7 +412,7 @@ public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefi if (prefixLength > prefixBuffer.Length - prefixOffset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, prefixBuffer.Length - prefixOffset))); - if (nsBuffer == null) + if (nsBuffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(nsBuffer))); if (nsOffset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsOffset), SR.ValueMustBeNonNegative)); @@ -441,9 +441,9 @@ public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefi public void WriteStartAttribute(string prefix, string localName) { - if (prefix == null) + if (prefix is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(prefix)); - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); ThrowIfClosed(); _attribute.offset = _elementWriter.Position; @@ -459,7 +459,7 @@ public void WriteStartAttribute(string prefix, string localName) public void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { - if (prefixBuffer == null) + if (prefixBuffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(prefixBuffer))); if (prefixOffset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.ValueMustBeNonNegative)); @@ -470,7 +470,7 @@ public void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefi if (prefixLength > prefixBuffer.Length - prefixOffset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, prefixBuffer.Length - prefixOffset))); - if (localNameBuffer == null) + if (localNameBuffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localNameBuffer))); if (localNameOffset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.ValueMustBeNonNegative)); @@ -516,7 +516,7 @@ public void WriteCharEntity(int ch) public void WriteEscapedText(string value) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); ThrowIfClosed(); // Skip all white spaces before the start of root element. @@ -535,7 +535,7 @@ public void WriteEscapedText(string value) public void WriteEscapedText(byte[] chars, int offset, int count) { - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -593,7 +593,7 @@ public void WriteText(int ch) public void WriteText(byte[] chars, int offset, int count) { ThrowIfClosed(); - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -615,7 +615,7 @@ public void WriteText(byte[] chars, int offset, int count) public void WriteText(string value) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); if (value.Length > 0) { @@ -633,7 +633,7 @@ public void WriteText(string value) public void WriteText(char[] chars, int offset, int count) { ThrowIfClosed(); - if (chars == null) + if (chars is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -655,7 +655,7 @@ public void WriteText(char[] chars, int offset, int count) private void ThrowIfClosed() { - if (_writer == null) + if (_writer is null) ThrowClosed(); } @@ -668,7 +668,7 @@ private void WriteXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) { if (xmlnsAttribute.referred) { - Debug.Assert(_xmlnsBuffer != null); + Debug.Assert(_xmlnsBuffer is not null); _writer.WriteXmlnsAttribute(_xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength, _xmlnsBuffer, xmlnsAttribute.nsOffset, xmlnsAttribute.nsLength); } } @@ -704,7 +704,7 @@ private void SortAttributes() private void AddAttribute(ref Attribute attribute) { - if (_attributes == null) + if (_attributes is null) { _attributes = new Attribute[4]; } @@ -725,7 +725,7 @@ private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) // Console.WriteLine("{0}={1}", Encoding.UTF8.GetString(xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), // Encoding.UTF8.GetString(xmlnsBuffer, xmlnsAttribute.nsOffset, xmlnsAttribute.nsLength)); - if (_xmlnsAttributes == null) + if (_xmlnsAttributes is null) { _xmlnsAttributes = new XmlnsAttribute[4]; } @@ -739,7 +739,7 @@ private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) // If the prefix is in the inclusive prefix list, then mark it as // to be rendered. Depth 0 is outer context and those can be ignored // for now. - if ((_depth > 0) && (_inclusivePrefixes != null)) + if ((_depth > 0) && (_inclusivePrefixes is not null)) { if (IsInclusivePrefix(ref xmlnsAttribute)) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs index f58260cb559a80..b47946903f8532 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs @@ -39,7 +39,7 @@ public static Base64Encoding Base64Encoding { get { - if (s_base64Encoding == null) + if (s_base64Encoding is null) s_base64Encoding = new Base64Encoding(); return s_base64Encoding; } @@ -49,7 +49,7 @@ private static UTF8Encoding UTF8Encoding { get { - if (s_utf8Encoding == null) + if (s_utf8Encoding is null) s_utf8Encoding = new UTF8Encoding(false, true); return s_utf8Encoding; } @@ -59,7 +59,7 @@ private static UnicodeEncoding UnicodeEncoding { get { - if (s_unicodeEncoding == null) + if (s_unicodeEncoding is null) s_unicodeEncoding = new UnicodeEncoding(false, false, true); return s_unicodeEncoding; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs index 49d54b8691fcaa..e882c3bab95444 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs @@ -24,7 +24,7 @@ public static IXmlDictionary Empty { get { - if (s_empty == null) + if (s_empty is null) s_empty = new EmptyDictionary(); return s_empty; } @@ -49,7 +49,7 @@ public virtual XmlDictionaryString Add(string value) XmlDictionaryString? str; if (!_lookup.TryGetValue(value, out str)) { - if (_strings == null) + if (_strings is null) { _strings = new XmlDictionaryString[4]; } @@ -86,7 +86,7 @@ public virtual bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryStri public virtual bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); if (value.Dictionary != this) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs index bf8e1bc8eb6836..555a2053a82b92 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs @@ -32,7 +32,7 @@ internal XmlDictionaryWriter CoreWriter [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckAsync() { - if (_lastTask != null && !_lastTask.IsCompleted) + if (_lastTask is not null && !_lastTask.IsCompleted) { throw new InvalidOperationException(SR.XmlAsyncIsRunningException); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs index 79922c417deb3f..5ae7069d060d19 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs @@ -21,12 +21,12 @@ public abstract class XmlDictionaryReader : XmlReader public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader) { - if (reader == null) + if (reader is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader)); XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; - if (dictionaryReader == null) + if (dictionaryReader is null) { dictionaryReader = new XmlWrappedReader(reader, null); } @@ -36,7 +36,7 @@ public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader) public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer)); return CreateBinaryReader(buffer, 0, buffer.Length, quotas); } @@ -95,7 +95,7 @@ public static XmlDictionaryReader CreateBinaryReader(Stream stream, public static XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer)); return CreateTextReader(buffer, 0, buffer.Length, quotas); } @@ -131,7 +131,7 @@ public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding? enco public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas) { - if (encoding == null) + if (encoding is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(encoding)); return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas); @@ -155,7 +155,7 @@ public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] enc public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas) { - if (encoding == null) + if (encoding is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(encoding)); return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas); @@ -234,7 +234,7 @@ public virtual bool IsLocalName(string localName) public virtual bool IsLocalName(XmlDictionaryString localName) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); return IsLocalName(localName.Value); @@ -242,14 +242,14 @@ public virtual bool IsLocalName(XmlDictionaryString localName) public virtual bool IsNamespaceUri(string namespaceUri) { - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); return this.NamespaceURI == namespaceUri; } public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri) { - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); return IsNamespaceUri(namespaceUri.Value); } @@ -299,10 +299,10 @@ public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryS public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { - if (localNames == null) + if (localNames is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames)); - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); if (this.NamespaceURI == namespaceUri) @@ -311,7 +311,7 @@ public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) for (int i = 0; i < localNames.Length; i++) { string value = localNames[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); if (localName == value) { @@ -325,10 +325,10 @@ public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri) { - if (localNames == null) + if (localNames is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames)); - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); if (this.NamespaceURI == namespaceUri.Value) @@ -337,7 +337,7 @@ public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDiction for (int i = 0; i < localNames.Length; i++) { XmlDictionaryString value = localNames[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); if (localName == value.Value) { @@ -421,7 +421,7 @@ protected string ReadContentAsString(int maxStringContentLength) } else { - if (sb == null) + if (sb is null) sb = new StringBuilder(result); if (sb.Length > maxStringContentLength - value.Length) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); @@ -453,7 +453,7 @@ protected string ReadContentAsString(int maxStringContentLength) else Read(); } - if (sb != null) + if (sb is not null) result = sb.ToString(); if (result.Length > maxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); @@ -491,7 +491,7 @@ protected string ReadString(int maxStringContentLength) } else { - if (sb == null) + if (sb is null) sb = new StringBuilder(result); if (sb.Length > maxStringContentLength - value.Length) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); @@ -500,7 +500,7 @@ protected string ReadString(int maxStringContentLength) if (!Read()) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation)); } - if (sb != null) + if (sb is not null) result = sb.ToString(); if (result.Length > maxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); @@ -622,14 +622,14 @@ public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespace public virtual string ReadContentAsString(string[] strings, out int index) { - if (strings == null) + if (strings is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(strings)); string s = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) { string value = strings[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i)); if (value == s) { @@ -642,14 +642,14 @@ public virtual string ReadContentAsString(string[] strings, out int index) public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index) { - if (strings == null) + if (strings is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(strings)); string s = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) { XmlDictionaryString value = strings[i]; - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i)); if (value.Value == s) { @@ -690,7 +690,7 @@ public virtual void ReadContentAsQualifiedName(out string localName, out string string prefix; XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName); namespaceUri = LookupNamespace(prefix)!; - if (namespaceUri == null) + if (namespaceUri is null) XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix); } @@ -1018,7 +1018,7 @@ public virtual bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDic private void CheckArray(Array array, int offset, int count) { - if (array == null) + if (array is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -1794,7 +1794,7 @@ public bool HasLineInfo() { IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; - if (lineInfo == null) + if (lineInfo is null) return false; return lineInfo.HasLineInfo(); @@ -1806,7 +1806,7 @@ public int LineNumber { IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; - if (lineInfo == null) + if (lineInfo is null) return 1; return lineInfo.LineNumber; @@ -1819,7 +1819,7 @@ public int LinePosition { IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; - if (lineInfo == null) + if (lineInfo is null) return 1; return lineInfo.LinePosition; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs index fa7730c82797e6..3c4ab61bed62ff 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs @@ -64,7 +64,7 @@ public static XmlDictionaryReaderQuotas Max public void CopyTo(XmlDictionaryReaderQuotas quotas) { - if (quotas == null) + if (quotas is null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(quotas))); if (quotas._readOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.QuotaCopyReadOnly)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs index 9adecff2542485..384e39adb7d2b3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs @@ -23,9 +23,9 @@ public class XmlDictionaryString public XmlDictionaryString(IXmlDictionary dictionary, string value, int key) { - if (dictionary == null) + if (dictionary is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(dictionary))); - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); if (key < MinKey || key > MaxKey) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(key), SR.Format(SR.ValueMustBeInRange, MinKey, MaxKey))); @@ -37,7 +37,7 @@ public XmlDictionaryString(IXmlDictionary dictionary, string value, int key) [return: NotNullIfNotNull("s")] internal static string? GetString(XmlDictionaryString? s) { - if (s == null) + if (s is null) return null; return s.Value; } @@ -76,7 +76,7 @@ public string Value internal byte[] ToUTF8() { - if (_buffer == null) + if (_buffer is null) _buffer = System.Text.Encoding.UTF8.GetBytes(_value); return _buffer; } @@ -105,7 +105,7 @@ public XmlDictionaryString EmptyString public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); if (value.Length == 0) { @@ -129,7 +129,7 @@ public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? resu public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); if (value.Dictionary != this) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs index 6d2fb2d345e8c2..0d1bc60425a9c3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs @@ -70,12 +70,12 @@ public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encod public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer) { - if (writer == null) + if (writer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer)); XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter; - if (dictionaryWriter == null) + if (dictionaryWriter is null) { dictionaryWriter = new XmlWrappedWriter(writer); } @@ -116,11 +116,11 @@ public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryStr public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri) { - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); - if (prefix == null) + if (prefix is null) { - if (LookupPrefix(namespaceUri) != null) + if (LookupPrefix(namespaceUri) is not null) return; #pragma warning suppress 56506 // Microsoft, namespaceUri is already checked prefix = namespaceUri.Length == 0 ? string.Empty : string.Concat("d", namespaceUri.Length.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); @@ -169,9 +169,9 @@ public virtual void WriteString(XmlDictionaryString? value) public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - if (localName == null) + if (localName is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); - if (namespaceUri == null) + if (namespaceUri is null) namespaceUri = XmlDictionaryString.Empty; #pragma warning suppress 56506 // Microsoft, XmlDictionaryString.Empty is never null WriteQualifiedName(localName.Value, namespaceUri.Value); @@ -185,7 +185,7 @@ public virtual void WriteValue(XmlDictionaryString? value) public virtual void WriteValue(UniqueId value) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); WriteString(value.ToString()); @@ -203,11 +203,11 @@ public virtual void WriteValue(TimeSpan value) public virtual void WriteValue(IStreamProvider value) { - if (value == null) + if (value is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); Stream stream = value.GetStream(); - if (stream == null) + if (stream is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.XmlInvalidStream)); int blockSize = 256; int bytesRead = 0; @@ -389,7 +389,7 @@ protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribut public override void WriteNode(XmlReader reader, bool defattr) { XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; - if (dictionaryReader != null) + if (dictionaryReader is not null) WriteNode(dictionaryReader, defattr); else base.WriteNode(reader, defattr); @@ -397,7 +397,7 @@ public override void WriteNode(XmlReader reader, bool defattr) public virtual void WriteNode(XmlDictionaryReader reader, bool defattr) { - if (reader == null) + if (reader is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(reader))); int d = (reader.NodeType == XmlNodeType.None ? -1 : reader.Depth); do @@ -450,7 +450,7 @@ public virtual void WriteNode(XmlDictionaryReader reader, bool defattr) private void CheckArray(Array array, int offset, int count) { - if (array == null) + if (array is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -853,11 +853,11 @@ public override void WriteValue(long value) public override void WriteXmlnsAttribute(string? prefix, string namespaceUri) { - if (namespaceUri == null) + if (namespaceUri is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); - if (prefix == null) + if (prefix is null) { - if (LookupPrefix(namespaceUri) != null) + if (LookupPrefix(namespaceUri) is not null) return; if (namespaceUri.Length == 0) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs index 3d6cc5cb606550..529f1b94d2d593 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs @@ -32,7 +32,7 @@ private static void ThrowXmlException(XmlDictionaryReader reader, string res, st { string s = SR.Format(res, arg1, arg2, arg3); IXmlLineInfo? lineInfo = reader as IXmlLineInfo; - if (lineInfo != null && lineInfo.HasLineInfo()) + if (lineInfo is not null && lineInfo.HasLineInfo()) { s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition); } @@ -45,7 +45,7 @@ public static void ThrowXmlException(XmlDictionaryReader reader, XmlException ex { string s = exception.Message; IXmlLineInfo? lineInfo = reader as IXmlLineInfo; - if (lineInfo != null && lineInfo.HasLineInfo()) + if (lineInfo is not null && lineInfo.HasLineInfo()) { s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs index 8cdf0455382f8d..6ea2782d4554b8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs @@ -20,7 +20,7 @@ public static XmlNodeWriter Null { get { - if (s_nullNodeWriter == null) + if (s_nullNodeWriter is null) s_nullNodeWriter = new XmlNullNodeWriter(); return s_nullNodeWriter; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs index fb539d2ac2ba10..6c352b10906851 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs @@ -23,7 +23,7 @@ public XmlSigningNodeWriter(bool text) public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[]? inclusivePrefixes) { _writer = writer; - if (_signingWriter == null) + if (_signingWriter is null) _signingWriter = new XmlCanonicalWriter(); _signingWriter.SetOutput(stream, includeComments, inclusivePrefixes); _chars = new byte[XmlConverter.MaxPrimitiveChars]; @@ -82,7 +82,7 @@ public override void WriteCData(string text) public override void WriteStartElement(string? prefix, string localName) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); _writer.WriteStartElement(prefix, localName); _signingWriter.WriteStartElement(prefix, localName); } @@ -96,7 +96,7 @@ public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, in public override void WriteStartElement(string? prefix, XmlDictionaryString localName) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); _writer.WriteStartElement(prefix, localName); _signingWriter.WriteStartElement(prefix, localName.Value); } @@ -109,14 +109,14 @@ public override void WriteEndStartElement(bool isEmpty) public override void WriteEndElement(string? prefix, string localName) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); _writer.WriteEndElement(prefix, localName); _signingWriter.WriteEndElement(prefix, localName); } public override void WriteXmlnsAttribute(string? prefix, string ns) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); _writer.WriteXmlnsAttribute(prefix, ns); _signingWriter.WriteXmlnsAttribute(prefix, ns); } @@ -130,7 +130,7 @@ public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); _writer.WriteXmlnsAttribute(prefix, ns); _signingWriter.WriteXmlnsAttribute(prefix, ns.Value); } @@ -353,7 +353,7 @@ public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte private void WriteBase64Text(byte[] buffer, int offset, int count) { - if (_base64Chars == null) + if (_base64Chars is null) _base64Chars = new byte[512]; Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs index 6075d0a9c608e6..c5d2fd5a6190c9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs @@ -58,7 +58,7 @@ public int Position private int GetByteCount(char[] chars) { - if (_encoding == null) + if (_encoding is null) { return s_UTF8Encoding.GetByteCount(chars); } @@ -456,7 +456,7 @@ public override async Task FlushAsync() public override void Close() { - if (_stream != null) + if (_stream is not null) { if (_ownsStream) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs index bfa8557cee4b8c..38a1951c776467 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs @@ -555,7 +555,7 @@ public XmlUTF8TextReader() public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { - if (buffer == null) + if (buffer is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -573,7 +573,7 @@ public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, X public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { - if (stream == null) + if (stream is null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); MoveToInitial(quotas, onClose); stream = new EncodingStreamWrapper(stream, encoding); @@ -594,7 +594,7 @@ public override void Close() base.Close(); OnXmlDictionaryReaderClose? onClose = _onClose; _onClose = null; - if (onClose != null) + if (onClose is not null) { try { @@ -1429,7 +1429,7 @@ public int LinePosition private void GetPosition(out int row, out int column) { - if (_rowOffsets == null) + if (_rowOffsets is null) { _rowOffsets = BufferReader.GetRows(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs index 22e4d66296e80c..347d855d4b7a58 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs @@ -18,16 +18,16 @@ internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); - if (encoding == null) + if (encoding is null) throw new ArgumentNullException(nameof(encoding)); if (encoding.WebName != Encoding.UTF8.WebName) { stream = new EncodingStreamWrapper(stream, encoding, true); } - if (_writer == null) + if (_writer is null) { _writer = new XmlUTF8NodeWriter(); } @@ -104,7 +104,7 @@ public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementC public new void SetOutput(Stream stream, bool ownsStream, Encoding? encoding) { Encoding? utf8Encoding = null; - if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage) + if (encoding is not null && encoding.CodePage == Encoding.UTF8.CodePage) { utf8Encoding = encoding; encoding = null; @@ -116,7 +116,7 @@ public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementC private byte[] GetCharEntityBuffer() { - if (_entityChars == null) + if (_entityChars is null) { _entityChars = new byte[maxEntityLength]; } @@ -127,14 +127,14 @@ private char[] GetCharBuffer(int charCount) { if (charCount >= 256) return new char[charCount]; - if (_chars == null || _chars.Length < charCount) + if (_chars is null || _chars.Length < charCount) _chars = new char[charCount]; return _chars; } public override void WriteDeclaration() { - if (_encoding == null) + if (_encoding is null) { WriteUTF8Chars(s_utf8Decl, 0, s_utf8Decl.Length); } diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs index 79dfe01d9e487b..cfb0af4144509e 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs @@ -221,7 +221,7 @@ internal DataView(IntPtr jsHandle, bool ownsHandle) : base(jsHandle, ownsHandle) private U UnBoxValue(object jsValue) where U : struct { - if (jsValue == null) + if (jsValue is null) { throw new InvalidCastException($"Unable to cast null to type {typeof(U)}."); } diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs index 536274d89b3095..ca3f0a5ec88f73 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs @@ -121,7 +121,7 @@ public void SetObjectProperty(string name, object value, bool createIfNotExists { object setPropResult = Interop.Runtime.SetObjectProperty(JSHandle, name, value, createIfNotExists, hasOwnProperty, out int exception); if (exception != 0) - throw new JSException($"Error setting {name} on (js-obj js '{JSHandle}' .NET '{Int32Handle} raw '{RawObject != null})"); + throw new JSException($"Error setting {name} on (js-obj js '{JSHandle}' .NET '{Int32Handle} raw '{RawObject is not null})"); } /// @@ -148,7 +148,7 @@ public int Length /// The String name or Symbol of the property to test. public bool PropertyIsEnumerable(string prop) => (bool)Invoke("propertyIsEnumerable", prop); - internal bool IsWeakWrapper => WeakRawObject?.Target != null; + internal bool IsWeakWrapper => WeakRawObject?.Target is not null; internal object? GetWrappedObject() { @@ -201,7 +201,7 @@ protected override bool ReleaseHandle() public override string ToString() { - return $"(js-obj js '{Int32Handle}' raw '{RawObject != null}' weak_raw '{WeakRawObject != null}')"; + return $"(js-obj js '{Int32Handle}' raw '{RawObject is not null}' weak_raw '{WeakRawObject is not null}')"; } } } diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs index 41a9e5f7ab9343..462d1017ad1c9c 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs @@ -106,14 +106,14 @@ public MapEnumerator(Map map) // Advance to the next item. public bool MoveNext() { - if (_mapIterator == null) + if (_mapIterator is null) _mapIterator = (JSObject)_map.Invoke("entries"); using (var result = (JSObject)_mapIterator.Invoke("next")) { using (var resultValue = (Array)result.GetObjectProperty("value")) { - if (resultValue != null) + if (resultValue is not null) { Key = resultValue[0]; Value = resultValue[1]; @@ -204,7 +204,7 @@ public MapItemEnumerator(MapItemCollection mapCollection) public bool MoveNext() { - if (_mapItemIterator == null) + if (_mapItemIterator is null) _mapItemIterator = (JSObject)_mapItemCollection._map.Invoke(_mapItemCollection._iterator); var done = false; diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs index 93d24cce4fe2a4..cfb391598c0608 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs @@ -130,7 +130,7 @@ internal static bool ReleaseJSObject(JSObject objToRelease) { Interop.Runtime.ReleaseHandle(objToRelease.JSHandle, out int exception); if (exception != 0) - throw new JSException($"Error releasing handle on (js-obj js '{objToRelease.JSHandle}' mono '{objToRelease.Int32Handle} raw '{objToRelease.RawObject != null}' weak raw '{objToRelease.IsWeakWrapper}' )"); + throw new JSException($"Error releasing handle on (js-obj js '{objToRelease.JSHandle}' mono '{objToRelease.Int32Handle} raw '{objToRelease.RawObject is not null}' weak raw '{objToRelease.IsWeakWrapper}' )"); lock (_boundObjects) { @@ -145,7 +145,7 @@ private static void UnBindRawJSObjectAndFree(int gcHandle) JSObject? obj = h.Target as JSObject; lock (_rawToJS) { - if (obj?.RawObject != null) + if (obj?.RawObject is not null) { _rawToJS.Remove(obj.RawObject); obj.FreeHandle(); @@ -265,7 +265,7 @@ private static string GetCallSignature(IntPtr methodHandle) tmp.ptr = methodHandle; MethodBase? mb = MethodBase.GetMethodFromHandle(tmp.handle); - if (mb == null) + if (mb is null) return string.Empty; ParameterInfo[] parms = mb.GetParameters(); @@ -346,7 +346,7 @@ void Complete() { try { - if (task.Exception == null) + if (task.Exception is null) { object? result; Type task_type = task.GetType(); @@ -384,7 +384,7 @@ private static string ObjectToString(object o) private static double GetDateValue(object dtv) { - if (dtv == null) + if (dtv is null) throw new ArgumentNullException(nameof(dtv)); if (!(dtv is DateTime dt)) throw new InvalidCastException($"Unable to cast object of type {dtv.GetType()} to type DateTime."); @@ -416,7 +416,7 @@ private static bool SafeHandleAddRef(SafeHandle safeHandle) { safeHandle.DangerousAddRef(ref _addRefSucceeded); #if DEBUG_HANDLE - if (_addRefSucceeded && _anyref != null) + if (_addRefSucceeded && _anyref is not null) _anyref.AddRef(); #endif } @@ -426,14 +426,14 @@ private static bool SafeHandleAddRef(SafeHandle safeHandle) { safeHandle.DangerousRelease(); #if DEBUG_HANDLE - if (_anyref != null) + if (_anyref is not null) _anyref.Release(); #endif _addRefSucceeded = false; } } #if DEBUG_HANDLE - Debug.WriteLine($"\tSafeHandleAddRef: {safeHandle.DangerousGetHandle()} / RefCount: {((_anyref == null) ? 0 : _anyref.RefCount)}"); + Debug.WriteLine($"\tSafeHandleAddRef: {safeHandle.DangerousGetHandle()} / RefCount: {((_anyref is null) ? 0 : _anyref.RefCount)}"); #endif return _addRefSucceeded; } @@ -443,7 +443,7 @@ private static void SafeHandleRelease(SafeHandle safeHandle) safeHandle.DangerousRelease(); #if DEBUG_HANDLE var _anyref = safeHandle as AnyRef; - if (_anyref != null) + if (_anyref is not null) { _anyref.Release(); Debug.WriteLine($"\tSafeHandleRelease: {safeHandle.DangerousGetHandle()} / RefCount: {_anyref.RefCount}"); @@ -460,7 +460,7 @@ private static void SafeHandleReleaseByHandle(int jsId) { if (_boundObjects.TryGetValue(jsId, out WeakReference? reference)) { - Debug.Assert(reference.Target != null, $"\tSafeHandleReleaseByHandle: did not find active target {jsId} / target: {reference.Target}"); + Debug.Assert(reference.Target is not null, $"\tSafeHandleReleaseByHandle: did not find active target {jsId} / target: {reference.Target}"); SafeHandleRelease((AnyRef)reference.Target); } else diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs index 453dd8eaafa096..d2636789b7bbcc 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs @@ -151,7 +151,7 @@ public U? this[int i] private U? UnBoxValue(object jsValue) { - if (jsValue == null) + if (jsValue is null) return null; Type type = jsValue.GetType(); @@ -169,12 +169,6 @@ public U[] ToArray() public static unsafe T From(ReadOnlySpan span) { - // source has to be instantiated. - if (span == null) - { - throw new System.ArgumentException($"Invalid argument: {nameof(span)} can not be null."); - } - TypedArrayTypeCode type = (TypedArrayTypeCode)Type.GetTypeCode(typeof(U)); // Special case for Uint8ClampedArray, a clamped array which represents an array of 8-bit unsigned integers clamped to 0-255; if (type == TypedArrayTypeCode.Uint8Array && typeof(T) == typeof(Uint8ClampedArray)) @@ -206,7 +200,7 @@ public unsafe int CopyTo(Span span) public unsafe int CopyFrom(ReadOnlySpan span) { // source has to be instantiated. - if (span == null || span.Length == 0) + if (span.Length == 0) { throw new System.ArgumentException($"Invalid argument: {nameof(span)} can not be null and must have a length"); } diff --git a/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs b/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs index d44168e2f36e2b..e410fd4f50c091 100644 --- a/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs +++ b/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs @@ -30,7 +30,7 @@ internal static string ParseCanonicalName(string str, int start, int end, ref bo end = i; } - if (res == null) + if (res is null) { res = str.Substring(start, end - start); } diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index f804daf360dfad..748eb0fd1a0671 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -189,7 +189,7 @@ private class MoreInfo private void InterlockedSetFlags(Flags flags) { - Debug.Assert(_syntax != null); + Debug.Assert(_syntax is not null); if (_syntax.IsSimple) { @@ -311,7 +311,7 @@ private UriInfo EnsureUriInfo() { CreateUriInfo(cF); } - Debug.Assert(_info != null && (_flags & Flags.MinimalUriInfoSet) != 0); + Debug.Assert(_info is not null && (_flags & Flags.MinimalUriInfoSet) != 0); return _info; } @@ -366,7 +366,7 @@ public Uri(string uriString) [Obsolete("The constructor has been deprecated. Please use new Uri(string). The dontEscape parameter is deprecated and is always false. https://go.microsoft.com/fwlink/?linkid=14202")] public Uri(string uriString, bool dontEscape) { - if (uriString == null) + if (uriString is null) throw new ArgumentNullException(nameof(uriString)); CreateThis(uriString, dontEscape, UriKind.Absolute); @@ -485,7 +485,7 @@ private void CreateUri(Uri baseUri, string? relativeUri, bool dontEscape) Uri? uriResult = ResolveHelper(baseUri, this, ref relativeUri, ref dontEscape); // If resolved into a Uri then we build from that Uri - if (uriResult != null) + if (uriResult is not null) { if (!ReferenceEquals(this, uriResult)) CreateThisFromUri(uriResult); @@ -497,7 +497,7 @@ private void CreateUri(Uri baseUri, string? relativeUri, bool dontEscape) { dontEscape = false; relativeUri = baseUri.Syntax.InternalResolve(baseUri, this, out UriFormatException? e); - if (e != null) + if (e is not null) throw e; } @@ -531,7 +531,7 @@ public Uri(Uri baseUri, Uri relativeUri) dontEscape = InFact(Flags.UserEscaped); Uri? resolvedRelativeUri = ResolveHelper(baseUri, this, ref newUriString, ref dontEscape); - if (resolvedRelativeUri != null) + if (resolvedRelativeUri is not null) { if (!ReferenceEquals(this, resolvedRelativeUri)) CreateThisFromUri(resolvedRelativeUri); @@ -544,7 +544,7 @@ public Uri(Uri baseUri, Uri relativeUri) { dontEscape = false; newUriString = baseUri.Syntax.InternalResolve(baseUri, this, out UriFormatException? e); - if (e != null) + if (e is not null) throw e; } @@ -696,7 +696,7 @@ public string AbsoluteUri { get { - if (_syntax == null) + if (_syntax is null) { throw new InvalidOperationException(SR.net_uri_NotAbsolute); } @@ -936,8 +936,8 @@ private string GetLocalPath() if (IsUncOrDosPath) { EnsureHostString(false); - Debug.Assert(_info != null); - Debug.Assert(_info.Host != null); + Debug.Assert(_info is not null); + Debug.Assert(_info.Host is not null); int start; // Do we have a valid local path right in _string? @@ -1170,7 +1170,7 @@ public string IdnHost } else if (hostType == Flags.IPv6HostType) { - host = _info.ScopeId != null ? + host = _info.ScopeId is not null ? string.Concat(host.AsSpan(1, host.Length - 2), _info.ScopeId) : host.Substring(1, host.Length - 2); } @@ -1205,7 +1205,7 @@ public bool IsAbsoluteUri { get { - return _syntax != null; + return _syntax is not null; } } @@ -1554,7 +1554,7 @@ public override int GetHashCode() public override string ToString() { - if (_syntax == null) + if (_syntax is null) { return _string; } @@ -1840,7 +1840,7 @@ private static unsafe ParsingError ParseScheme(string uriString, ref Flags flags // internal UriFormatException? ParseMinimal() { - Debug.Assert(_syntax != null && !_syntax.IsSimple); + Debug.Assert(_syntax is not null && !_syntax.IsSimple); Debug.Assert((_flags & Flags.CustomParser_ParseMinimalAlreadyCalled) != 0); DebugAssertInCtor(); @@ -1867,7 +1867,7 @@ private static unsafe ParsingError ParseScheme(string uriString, ref Flags flags // private unsafe ParsingError PrivateParseMinimal() { - Debug.Assert(_syntax != null); + Debug.Assert(_syntax is not null); DebugAssertInCtor(); int idx = (int)(_flags & Flags.IndexMask); @@ -2083,7 +2083,7 @@ private unsafe ParsingError PrivateParseMinimal() // is not created/canonicalized at this point. } - if (IriParsing && newHost != null) + if (IriParsing && newHost is not null) { // we have a new host! _string = newHost; @@ -2462,7 +2462,7 @@ private static string CreateHostStringHelper(string str, int idx, int end, ref F private unsafe void GetHostViaCustomSyntax() { // A multithreading check - if (_info.Host != null) + if (_info.Host is not null) return; string host = _syntax.InternalGetComponents(this, UriComponents.Host, UriFormat.UriEscaped); @@ -2552,7 +2552,7 @@ internal string GetParts(UriComponents uriParts, UriFormat formatAs) private string GetEscapedParts(UriComponents uriParts) { - Debug.Assert(_info != null && (_flags & Flags.MinimalUriInfoSet) != 0); + Debug.Assert(_info is not null && (_flags & Flags.MinimalUriInfoSet) != 0); // Which Uri parts are not escaped canonically ? // Notice that public UriPart and private Flags must be in Sync so below code can work @@ -2591,7 +2591,7 @@ private string GetEscapedParts(UriComponents uriParts) private string GetUnescapedParts(UriComponents uriParts, UriFormat formatAs) { - Debug.Assert(_info != null && (_flags & Flags.MinimalUriInfoSet) != 0); + Debug.Assert(_info is not null && (_flags & Flags.MinimalUriInfoSet) != 0); // Which Uri parts are not escaped canonically ? // Notice that public UriComponents and private Uri.Flags must me in Sync so below code can work @@ -4325,14 +4325,14 @@ private unsafe Check CheckCanonical(char* str, ref int idx, int end, char delim) { break; } - else if (delim == '?' && c == '#' && (_syntax != null && _syntax.InFact(UriSyntaxFlags.MayHaveFragment))) + else if (delim == '?' && c == '#' && (_syntax is not null && _syntax.InFact(UriSyntaxFlags.MayHaveFragment))) { // this is a special case when deciding on Query/Fragment break; } else if (c == '?') { - if (IsImplicitFile || (_syntax != null && !_syntax.InFact(UriSyntaxFlags.MayHaveQuery) + if (IsImplicitFile || (_syntax is not null && !_syntax.InFact(UriSyntaxFlags.MayHaveQuery) && delim != c_EOL)) { // If found as reserved this char is not suitable for safe unescaped display @@ -4345,7 +4345,7 @@ private unsafe Check CheckCanonical(char* str, ref int idx, int end, char delim) else if (c == '#') { needsEscaping = true; - if (IsImplicitFile || (_syntax != null && !_syntax.InFact(UriSyntaxFlags.MayHaveFragment))) + if (IsImplicitFile || (_syntax is not null && !_syntax.InFact(UriSyntaxFlags.MayHaveFragment))) { // If found as reserved this char is not suitable for safe unescaped display // Will need to escape it when both escaping and unescaping the string @@ -4651,7 +4651,7 @@ private static unsafe void UnescapeOnly(char* pch, int start, ref int end, char done: pend += 2; - if (pnew == null) + if (pnew is null) { //nothing was found return; @@ -5127,7 +5127,7 @@ private static string PathDifference(string path1, string path2, bool compareCas [Obsolete("The method has been deprecated. Please use MakeRelativeUri(Uri uri). https://go.microsoft.com/fwlink/?linkid=14202")] public string MakeRelative(Uri toUri) { - if (toUri == null) + if (toUri is null) throw new ArgumentNullException(nameof(toUri)); if (IsNotAbsoluteUri || toUri.IsNotAbsoluteUri) diff --git a/src/libraries/System.Private.Uri/src/System/UriBuilder.cs b/src/libraries/System.Private.Uri/src/System/UriBuilder.cs index 049d5d44f84ee4..b17383cadf55b3 100644 --- a/src/libraries/System.Private.Uri/src/System/UriBuilder.cs +++ b/src/libraries/System.Private.Uri/src/System/UriBuilder.cs @@ -128,7 +128,7 @@ private string? Extra { set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -173,7 +173,7 @@ public string Fragment } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -195,7 +195,7 @@ public string Host } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -220,7 +220,7 @@ public string Password } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -271,7 +271,7 @@ public string Query } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -293,7 +293,7 @@ public string Scheme } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -340,7 +340,7 @@ public string UserName } set { - if (value == null) + if (value is null) { value = string.Empty; } @@ -353,7 +353,7 @@ public string UserName public override bool Equals(object? rparam) { - if (rparam == null) + if (rparam is null) { return false; } @@ -403,7 +403,7 @@ public override string ToString() if (_scheme.Length != 0) { UriParser? syntax = UriParser.GetSyntax(_scheme); - if (syntax != null) + if (syntax is not null) _schemeDelimiter = syntax.InFact(UriSyntaxFlags.MustHaveAuthority) || (_host.Length != 0 && syntax.NotAny(UriSyntaxFlags.MailToLikeUri) && syntax.InFact(UriSyntaxFlags.OptionalAuthority)) ? Uri.SchemeDelimiter diff --git a/src/libraries/System.Private.Uri/src/System/UriExt.cs b/src/libraries/System.Private.Uri/src/System/UriExt.cs index 66552d086da08c..ece6073954cc3c 100644 --- a/src/libraries/System.Private.Uri/src/System/UriExt.cs +++ b/src/libraries/System.Private.Uri/src/System/UriExt.cs @@ -34,7 +34,7 @@ private void CreateThis(string? uri, bool dontEscape, UriKind uriKind) ParsingError err = ParseScheme(_string, ref _flags, ref _syntax!); InitializeUri(err, uriKind, out UriFormatException? e); - if (e != null) + if (e is not null) throw e; } @@ -93,7 +93,7 @@ private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatExcep _originalUnicodeString = _string; // original string location changed } - if (_syntax != null) + if (_syntax is not null) { if (_syntax.IsSimple) { @@ -144,7 +144,7 @@ private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatExcep // Ask a registered type to validate this uri _syntax.InternalValidate(this, out e); - if (e != null) + if (e is not null) { // Can we still take it as a relative Uri? if (uriKind != UriKind.Absolute && err != ParsingError.None @@ -155,7 +155,7 @@ private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatExcep _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } } - else // e == null + else // e is null { if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion)) { @@ -256,7 +256,7 @@ public static bool TryCreate(string? uriString, UriKind uriKind, [NotNullWhen(tr UriFormatException? e = null; result = CreateHelper(uriString, false, uriKind, ref e); result?.DebugSetLeftCtor(); - return e is null && result != null; + return e is null && result is not null; } public static bool TryCreate(Uri? baseUri, string? relativeUri, [NotNullWhen(true)] out Uri? result) @@ -297,7 +297,7 @@ public static bool TryCreate(Uri? baseUri, Uri? relativeUri, [NotNullWhen(true)] dontEscape = false; newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e); - if (e != null) + if (e is not null) return false; } @@ -305,7 +305,7 @@ public static bool TryCreate(Uri? baseUri, Uri? relativeUri, [NotNullWhen(true)] result = CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e); result?.DebugSetLeftCtor(); - return e is null && result != null && result.IsAbsoluteUri; + return e is null && result is not null && result.IsAbsoluteUri; } public string GetComponents(UriComponents components, UriFormat format) @@ -617,7 +617,7 @@ private Uri(Flags flags, UriParser? uriParser, string uri) } // Cannot be relative Uri if came here - Debug.Assert(syntax != null); + Debug.Assert(syntax is not null); Uri result = new Uri(flags, syntax, uriString); // Validate instance using ether built in or a user Parser @@ -625,7 +625,7 @@ private Uri(Flags flags, UriParser? uriParser, string uri) { result.InitializeUri(err, uriKind, out e); - if (e == null) + if (e is null) { result.DebugSetLeftCtor(); return result; @@ -645,7 +645,7 @@ private Uri(Flags flags, UriParser? uriParser, string uri) // // Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString // to return combined URI strings from both Uris - // otherwise if e != null on output the operation has failed + // otherwise if e is not null on output the operation has failed // internal static Uri? ResolveHelper(Uri baseUri, Uri? relativeUri, ref string? newUriString, ref bool userEscaped) { @@ -856,7 +856,7 @@ internal bool IsBaseOfHelper(Uri uriLink) uriLink = CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e)!; - if (e != null) + if (e is not null) return false; } } diff --git a/src/libraries/System.Private.Uri/src/System/UriHelper.cs b/src/libraries/System.Private.Uri/src/System/UriHelper.cs index 669ac56f6a8814..1ac4e903a661b5 100644 --- a/src/libraries/System.Private.Uri/src/System/UriHelper.cs +++ b/src/libraries/System.Private.Uri/src/System/UriHelper.cs @@ -192,7 +192,7 @@ internal static string EscapeString( for (; i < stringToEscape.Length && (c = stringToEscape[i]) <= 0x7F && noEscape[c]; i++) ; if (i == stringToEscape.Length) { - if (dest != null) + if (dest is not null) { EnsureCapacity(dest, destPos, stringToEscape.Length); stringToEscape.CopyTo(dest.AsSpan(destPos)); @@ -217,7 +217,7 @@ internal static string EscapeString( static void EnsureCapacity(char[]? dest, int destSize, int requiredSize) { - if (dest == null || dest.Length - destSize < requiredSize) + if (dest is null || dest.Length - destSize < requiredSize) { Array.Resize(ref dest, destSize + requiredSize + 120); // 120 == arbitrary minimum-empty space copied from previous implementation } @@ -524,7 +524,7 @@ internal static unsafe void UnescapeString(char* pStr, int start, int end, ref V } } - if (unescapedChars == null || unescapedChars.Length < bytes.Length) + if (unescapedChars is null || unescapedChars.Length < bytes.Length) { unescapedChars = new char[bytes.Length]; } diff --git a/src/libraries/System.Private.Uri/src/System/UriScheme.cs b/src/libraries/System.Private.Uri/src/System/UriScheme.cs index d9d96ab59ea3cb..7cc96eb712638f 100644 --- a/src/libraries/System.Private.Uri/src/System/UriScheme.cs +++ b/src/libraries/System.Private.Uri/src/System/UriScheme.cs @@ -109,7 +109,7 @@ protected virtual void InitializeAndValidate(Uri uri, out UriFormatException? pa Uri? result = Uri.ResolveHelper(baseUri, relativeUri, ref newUriString, ref userEscaped); - if (result != null) + if (result is not null) return result.OriginalString; return newUriString; @@ -162,10 +162,10 @@ protected virtual bool IsWellFormedOriginalString(Uri uri) // public static void Register(UriParser uriParser, string schemeName, int defaultPort) { - if (uriParser == null) + if (uriParser is null) throw new ArgumentNullException(nameof(uriParser)); - if (schemeName == null) + if (schemeName is null) throw new ArgumentNullException(nameof(schemeName)); if (schemeName.Length == 1) @@ -186,14 +186,14 @@ public static void Register(UriParser uriParser, string schemeName, int defaultP // public static bool IsKnownScheme(string schemeName) { - if (schemeName == null) + if (schemeName is null) throw new ArgumentNullException(nameof(schemeName)); if (!Uri.CheckSchemeName(schemeName)) throw new ArgumentOutOfRangeException(nameof(schemeName)); UriParser? syntax = UriParser.GetSyntax(schemeName.ToLowerInvariant()); - return syntax != null && syntax.NotAny(UriSyntaxFlags.V1_UnknownUri); + return syntax is not null && syntax.NotAny(UriSyntaxFlags.V1_UnknownUri); } } } diff --git a/src/libraries/System.Private.Uri/src/System/UriSyntax.cs b/src/libraries/System.Private.Uri/src/System/UriSyntax.cs index 1e5b70c0622d25..27e2bcedd8a6e3 100644 --- a/src/libraries/System.Private.Uri/src/System/UriSyntax.cs +++ b/src/libraries/System.Private.Uri/src/System/UriSyntax.cs @@ -170,11 +170,11 @@ private static void FetchSyntax(UriParser syntax, string lwrCaseSchemeName, int { syntax._flags &= ~UriSyntaxFlags.V1_UnknownUri; UriParser? oldSyntax = (UriParser?)s_table[lwrCaseSchemeName]; - if (oldSyntax != null) + if (oldSyntax is not null) throw new InvalidOperationException(SR.Format(SR.net_uri_AlreadyRegistered, oldSyntax.SchemeName)); oldSyntax = (UriParser?)s_tempTable[syntax.SchemeName]; - if (oldSyntax != null) + if (oldSyntax is not null) { // optimization on schemeName, will try to keep the first reference lwrCaseSchemeName = oldSyntax._scheme; @@ -196,12 +196,12 @@ internal static UriParser FindOrFetchAsUnknownV1Syntax(string lwrCaseScheme) { // check may be other thread just added one UriParser? syntax = (UriParser?)s_table[lwrCaseScheme]; - if (syntax != null) + if (syntax is not null) { return syntax; } syntax = (UriParser?)s_tempTable[lwrCaseScheme]; - if (syntax != null) + if (syntax is not null) { return syntax; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs index 96375e646f2744..ead55e6938b825 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs @@ -44,7 +44,7 @@ internal override bool IsFull internal override unsafe int Decode(char[] chars, int startPos, int len) { - if (chars == null) + if (chars is null) { throw new ArgumentNullException(nameof(chars)); } @@ -79,7 +79,7 @@ internal override unsafe int Decode(char[] chars, int startPos, int len) internal override unsafe int Decode(string str, int startPos, int len) { - if (str == null) + if (str is null) { throw new ArgumentNullException(nameof(str)); } @@ -122,11 +122,11 @@ internal override void Reset() internal override void SetNextOutputBuffer(Array buffer, int index, int count) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(count >= 0); Debug.Assert(index >= 0); Debug.Assert(buffer.Length - index >= count); - Debug.Assert((buffer as byte[]) != null); + Debug.Assert((buffer as byte[]) is not null); _buffer = (byte[])buffer; _startIndex = index; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs index 3c7f28c78a9dde..135cb2ac683014 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs @@ -14,7 +14,7 @@ internal abstract partial class Base64Encoder internal async Task EncodeAsync(byte[] buffer, int index, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -58,7 +58,7 @@ internal async Task EncodeAsync(byte[] buffer, int index, int count) if (_leftOverBytesCount > 0) { count -= _leftOverBytesCount; - if (_leftOverBytes == null) + if (_leftOverBytes is null) { _leftOverBytes = new byte[3]; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs index 058621d26563d6..45c836236ddd4d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs @@ -39,7 +39,7 @@ internal override bool IsFull internal override unsafe int Decode(char[] chars, int startPos, int len) { - if (chars == null) + if (chars is null) { throw new ArgumentNullException(nameof(chars)); } @@ -76,7 +76,7 @@ internal override unsafe int Decode(char[] chars, int startPos, int len) internal override unsafe int Decode(string str, int startPos, int len) { - if (str == null) + if (str is null) { throw new ArgumentNullException(nameof(str)); } @@ -120,11 +120,11 @@ internal override void Reset() internal override void SetNextOutputBuffer(Array buffer, int index, int count) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(count >= 0); Debug.Assert(index >= 0); Debug.Assert(buffer.Length - index >= count); - Debug.Assert((buffer as byte[]) != null); + Debug.Assert((buffer as byte[]) is not null); _buffer = (byte[])buffer; _startIndex = index; @@ -137,7 +137,7 @@ internal override void SetNextOutputBuffer(Array buffer, int index, int count) // public static unsafe byte[] Decode(char[] chars, bool allowOddChars) { - if (chars == null) + if (chars is null) { throw new ArgumentNullException(nameof(chars)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs index 397b48adc6111e..557b48f8e4ad55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs @@ -9,7 +9,7 @@ internal static partial class BinHexEncoder internal static void Encode(byte[] buffer, int index, int count, XmlWriter writer) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index 0215d5b243e614..6bb15d238075ff 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -620,7 +620,7 @@ public override string XmlLang for (int i = _elemDepth; i >= 0; i--) { string? xl = _elementStack[i].xmlLang; - if (null != xl) + if (xl is not null) return xl; } return string.Empty; @@ -676,9 +676,9 @@ public override int AttributeCount } else { - if (null == name) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (null == ns) + if (ns is null) ns = string.Empty; int index = LocateAttribute(name, ns); if (-1 == index) @@ -727,9 +727,9 @@ public override bool MoveToAttribute(string name, string? ns) } else { - if (null == name) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (null == ns) + if (ns is null) ns = string.Empty; int index = LocateAttribute(name, ns); if ((-1 != index) && (_state < ScanState.Init)) @@ -1847,7 +1847,7 @@ System.Collections.Generic.IDictionary IXmlNamespaceResolver.Get if (_elemDepth > 0) { NamespaceDecl? nsdecl = _elementStack[_elemDepth].nsdecls; - while (null != nsdecl) + while (nsdecl is not null) { nstable.Add(nsdecl.prefix, nsdecl.uri); nsdecl = nsdecl.scopeLink; @@ -1881,17 +1881,17 @@ System.Collections.Generic.IDictionary IXmlNamespaceResolver.Get } else { - if (null == namespaceName) + if (namespaceName is null) return null; string? atomizedNamespaceName = _xnt.Get(namespaceName); - if (null == atomizedNamespaceName) + if (atomizedNamespaceName is null) return null; for (int i = _elemDepth; i >= 0; i--) { NamespaceDecl? nsdecl = _elementStack[i].nsdecls; - while (null != nsdecl) + while (nsdecl is not null) { if ((object)nsdecl.uri == (object?)atomizedNamespaceName) return nsdecl.prefix; @@ -2377,7 +2377,7 @@ private string GetAttributeText(int i) { string? val = _attributes[i].val; - if (null != val) + if (val is not null) return val; else { @@ -2473,7 +2473,7 @@ private void PushNamespace(string prefix, string ns, bool implied) int elemDepth = _elemDepth; NamespaceDecl? curDecl; _namespaces.TryGetValue(prefix, out curDecl); - if (null != curDecl) + if (curDecl is not null) { if (curDecl.uri == ns) { @@ -2508,9 +2508,9 @@ private void PushNamespace(string prefix, string ns, bool implied) private void PopNamespaces(NamespaceDecl? firstInScopeChain) { NamespaceDecl? decl = firstInScopeChain; - while (null != decl) + while (decl is not null) { - if (null == decl.prevLink) + if (decl.prevLink is null) _namespaces.Remove(decl.prefix); else _namespaces[decl.prefix] = decl.prevLink; @@ -2526,7 +2526,7 @@ private void GenerateImpliedXmlnsAttrs() { QName name; NamespaceDecl? decl = _elementStack[_elemDepth].nsdecls; - while (null != decl) + while (decl is not null) { if (decl.implied) { @@ -2631,7 +2631,7 @@ private void ScanAttributes() if (BinXmlToken.Attr == token) { // watch out for nsdecl with no actual content - if (null != curDeclPrefix) + if (curDeclPrefix is not null) { PushNamespace(curDeclPrefix, string.Empty, false); curDeclPrefix = null; @@ -2688,7 +2688,7 @@ private void ScanAttributes() // might as well store the saved string for quick attr value access string? val = _stringValue; - if (null != val) + if (val is not null) { _attributes[_attrCount - 1].val = val; _stringValue = null; @@ -2696,7 +2696,7 @@ private void ScanAttributes() // namespace decls can only have text values, and should only // have a single value, so we just grab it here... - if (null != curDeclPrefix) + if (curDeclPrefix is not null) { string nsuri = _xnt.Add(ValueAsString(token)); PushNamespace(curDeclPrefix, nsuri, false); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs index 0efb592b204d55..ad3fbad08886dd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs @@ -127,7 +127,7 @@ public XmlSchemaElement XmlSchemaElement { public IList Particles { get { - if (null == this.particles) + if (this is null.particles) return emptyIList; return this.particles; } @@ -135,7 +135,7 @@ public IList Particles { public IList SubShapes { get { - if (null == this.subShapes) + if (this is null.subShapes) return emptyIList; return this.subShapes; } @@ -175,7 +175,7 @@ public void Clear() { } public void AddParticle(XmlSchemaElement elem) { - if (null == this.particles) + if (this is null.particles) this.particles = new ArrayList(); Debug.Assert(this.bindingType != BindingType.Attribute); this.particles.Add(elem); @@ -189,18 +189,18 @@ public void AddParticle(XmlSchemaAttribute elem) { } public void AddSubShape(Shape shape) { - if (null == this.subShapes) + if (this is null.subShapes) this.subShapes = new ArrayList(); this.subShapes.Add(shape); foreach (object p in shape.Particles) { XmlSchemaElement xse = p as XmlSchemaElement; - if (null != xse) + if (xse is not null) AddParticle(xse); } } public void AddAttrShapeAt(Shape shape, int pos) { - if (null == this.subShapes) + if (this is null.subShapes) this.subShapes = new ArrayList(); this.subShapes.Insert(pos, shape); } @@ -214,7 +214,7 @@ public string[] SubShapeNames() { public PropertyDescriptor[] PropertyDescriptors { get { - if (null == this.propertyDescriptors) { + if (this is null.propertyDescriptors) { PropertyDescriptor[] descs; switch (this.BindingType) { case BindingType.Element: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs index 62389914fc5caa..cb4445ce2c0275 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs @@ -27,7 +27,7 @@ public Shape GenerateFromSchema(XmlSchemaElement xse) { XmlQualifiedName xseName = xse.QualifiedName; XmlSchemaType schemaType = xse.ElementSchemaType; XmlSchemaComplexType complexType = schemaType as XmlSchemaComplexType; - if (null != complexType) { + if (complexType is not null) { XmlSchemaParticle particle = null; Shape rootShape = null; @@ -124,7 +124,7 @@ Shape ProcessParticle(XmlSchemaParticle xsp, Shape parent) { Shape ProcessParticleElement(XmlSchemaElement xse) { // watch out for recursive schema Shape s = (Shape)this.elementTypesProcessed[xse]; - if (null != s) + if (s is not null) return s; bool complex = xse.ElementSchemaType is XmlSchemaComplexType; @@ -173,7 +173,7 @@ string GenName(XmlQualifiedName xqn) { string GenAttrName(XmlQualifiedName xqn, string[] names) { string name = GenName(xqn); - if (null != names) { + if (names is not null) { for (int i=0; i")) + if (text is not null && text.Contains("]]>")) { throw new ArgumentException(SR.Xml_InvalidCDataChars); } _textWriter.Write("")) + if (text is not null && text.Contains("?>")) { throw new ArgumentException(SR.Xml_InvalidPiChars); } @@ -843,7 +843,7 @@ public override void WriteWhitespace(string? ws) { try { - if (null == ws) + if (ws is null) { ws = string.Empty; } @@ -867,7 +867,7 @@ public override void WriteString(string? text) { try { - if (null != text && text.Length != 0) + if (text is not null && text.Length != 0) { AutoComplete(Token.Content); _xmlEncoder.Write(text); @@ -1603,7 +1603,7 @@ private void InternalWriteProcessingInstruction(string name, string? text) _textWriter.Write(name); _textWriter.Write(' '); - if (null != text) + if (text is not null) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs index 866f25c4ea61e5..11fc958f21ba50 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs @@ -94,7 +94,7 @@ internal void Set(string prefix, string namespaceUri, NamespaceKind kind) internal void WriteDecl(XmlWriter writer, XmlRawWriter? rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); - if (null != rawWriter) + if (rawWriter is not null) { rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs index 36b337574fb38f..0ef5a3c4921de1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs @@ -30,7 +30,7 @@ private partial struct Namespace internal async Task WriteDeclAsync(XmlWriter writer, XmlRawWriter? rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); - if (null != rawWriter) + if (rawWriter is not null) { await rawWriter.WriteNamespaceDeclarationAsync(prefix, namespaceUri).ConfigureAwait(false); } 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 222b6e7c74d638..719b5cf8bf0c0f 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 @@ -347,7 +347,7 @@ public virtual void WriteValue(long value) // Writes out all the attributes found at the current position in the specified XmlReader. public virtual void WriteAttributes(XmlReader reader, bool defattr) { - if (null == reader) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -395,7 +395,7 @@ public virtual void WriteAttributes(XmlReader reader, bool defattr) // to the corresponding end element. public virtual void WriteNode(XmlReader reader, bool defattr) { - if (null == reader) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -599,7 +599,7 @@ public void WriteElementString(string localName, string? value) public void WriteElementString(string localName, string? ns, string? value) { WriteStartElement(localName, ns); - if (null != value && 0 != value.Length) + if (value is not null && 0 != value.Length) { WriteString(value); } @@ -611,7 +611,7 @@ public void WriteElementString(string localName, string? ns, string? value) public void WriteElementString(string? prefix, string localName, string? ns, string? value) { WriteStartElement(prefix, localName, ns); - if (null != value && 0 != value.Length) + if (value is not null && 0 != value.Length) { WriteString(value); } 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 d88d1123fcbcb0..7cd16163e95841 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 @@ -242,7 +242,7 @@ public virtual async Task WriteQualifiedNameAsync(string localName, string? ns) // Writes out all the attributes found at the current position in the specified XmlReader. public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr) { - if (null == reader) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -290,7 +290,7 @@ public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr) // to the corresponding end element. public virtual Task WriteNodeAsync(XmlReader reader, bool defattr) { - if (null == reader) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -569,7 +569,7 @@ public virtual async Task WriteNodeAsync(XPathNavigator navigator, bool defattr) public async Task WriteElementStringAsync(string? prefix, string localName, string? ns, string value) { await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false); - if (null != value && 0 != value.Length) + if (value is not null && 0 != value.Length) { await WriteStringAsync(value).ConfigureAwait(false); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index 68085baec44656..dec1c6c6c6c63b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -64,7 +64,7 @@ public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, _nameTable = _document.NameTable; _nsManager = new XmlNamespaceManager(_nameTable); - Debug.Assert(schemas != null && schemas.Count > 0); + Debug.Assert(schemas is not null && schemas.Count > 0); _nodeValueGetter = new XmlValueGetter(GetNodeValue); _psviAugmentation = true; @@ -86,7 +86,7 @@ public bool Validate(XmlNode nodeToValidate) { XmlSchemaObject? partialValidationType = null; XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes; - Debug.Assert(nodeToValidate.SchemaInfo != null); + Debug.Assert(nodeToValidate.SchemaInfo is not null); _startNode = nodeToValidate; switch (nodeToValidate.NodeType) @@ -101,7 +101,7 @@ public bool Validate(XmlNode nodeToValidate) case XmlNodeType.Element: //Validate children of this element IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo; XmlSchemaElement? schemaElement = schemaInfo.SchemaElement; - if (schemaElement != null) + if (schemaElement is not null) { if (!schemaElement.RefName.IsEmpty) { //If it is element ref, @@ -118,7 +118,7 @@ public bool Validate(XmlNode nodeToValidate) { //Can be an element that matched xs:any and had xsi:type partialValidationType = schemaInfo.SchemaType; - if (partialValidationType == null) + if (partialValidationType is null) { //Validated against xs:any with pc= lax or skip or undeclared / not validated element if (nodeToValidate.ParentNode!.NodeType == XmlNodeType.Document) { @@ -128,7 +128,7 @@ public bool Validate(XmlNode nodeToValidate) else { partialValidationType = FindSchemaInfo((nodeToValidate as XmlElement)!); - if (partialValidationType == null) + if (partialValidationType is null) { throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate); } @@ -140,10 +140,10 @@ public bool Validate(XmlNode nodeToValidate) case XmlNodeType.Attribute: if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) goto default; partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute; - if (partialValidationType == null) + if (partialValidationType is null) { //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute partialValidationType = FindSchemaInfo((nodeToValidate as XmlAttribute)!); - if (partialValidationType == null) + if (partialValidationType is null) { throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate); } @@ -157,7 +157,7 @@ public bool Validate(XmlNode nodeToValidate) CreateValidator(partialValidationType, validationFlags); if (_psviAugmentation) { - if (_schemaInfo == null) + if (_schemaInfo is null) { //Might have created it during FindSchemaInfo _schemaInfo = new XmlSchemaInfo(); } @@ -174,7 +174,7 @@ public IDictionary GetNamespacesInScope(XmlNamespaceScope scope) if (scope != XmlNamespaceScope.Local) { XmlNode? node = _startNode; - while (node != null) + while (node is not null) { switch (node.NodeType) { @@ -224,7 +224,7 @@ public IDictionary GetNamespacesInScope(XmlNamespaceScope scope) public string? LookupNamespace(string prefix) { string? namespaceName = _nsManager.LookupNamespace(prefix); - if (namespaceName == null) + if (namespaceName is null) { namespaceName = _startNode!.GetNamespaceOfPrefixStrict(prefix); } @@ -235,7 +235,7 @@ public IDictionary GetNamespacesInScope(XmlNamespaceScope scope) public string? LookupPrefix(string namespaceName) { string? prefix = _nsManager.LookupPrefix(namespaceName); - if (prefix == null) + if (prefix is null) { prefix = _startNode!.GetPrefixOfNamespaceStrict(namespaceName); } @@ -264,7 +264,7 @@ private void CreateValidator(XmlSchemaObject? partialValidationType, XmlSchemaVa _validator.ValidationEventHandler += _internalEventHandler; _validator.ValidationEventSender = this; - if (partialValidationType != null) + if (partialValidationType is not null) { _validator.Initialize(partialValidationType); } @@ -281,7 +281,7 @@ private void ValidateNode(XmlNode node) { case XmlNodeType.Document: XmlElement? docElem = ((XmlDocument)node).DocumentElement; - if (docElem == null) + if (docElem is null) { throw new InvalidOperationException(SR.Format(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle)); } @@ -291,7 +291,7 @@ private void ValidateNode(XmlNode node) case XmlNodeType.DocumentFragment: case XmlNodeType.EntityReference: - for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child is not null; child = child.NextSibling) { ValidateNode(child); } @@ -337,7 +337,7 @@ private void ValidateElement() { _nsManager.PushScope(); XmlElement? elementNode = _currentNode as XmlElement; - Debug.Assert(elementNode != null); + Debug.Assert(elementNode is not null); XmlAttributeCollection attributes = elementNode.Attributes; XmlAttribute? attr = null; @@ -351,8 +351,8 @@ private void ValidateElement() attr = attributes[i]; string objectNs = attr.NamespaceURI; string objectName = attr.LocalName; - Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null); - Debug.Assert(_nameTable.Get(attr.LocalName) != null); + Debug.Assert(_nameTable.Get(attr.NamespaceURI) is not null); + Debug.Assert(_nameTable.Get(attr.LocalName) is not null); if (Ref.Equal(objectNs, _nsXsi)) { @@ -376,7 +376,7 @@ private void ValidateElement() _validator!.ValidateEndOfAttributes(_schemaInfo); //If element has children, drill down - for (XmlNode? child = elementNode.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = elementNode.FirstChild; child is not null; child = child.NextSibling) { ValidateNode(child); } @@ -421,7 +421,7 @@ private void ValidateAttributes(XmlElement elementNode) if (_psviAugmentation) { //Add default attributes to the attributes collection - if (_defaultAttributes == null) + if (_defaultAttributes is null) { _defaultAttributes = new ArrayList(); } @@ -436,14 +436,14 @@ private void ValidateAttributes(XmlElement elementNode) { XmlSchemaAttribute schemaAttribute = (_defaultAttributes[i] as XmlSchemaAttribute)!; attrQName = schemaAttribute.QualifiedName; - Debug.Assert(schemaAttribute != null); + Debug.Assert(schemaAttribute is not null); attr = _document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace); SetDefaultAttributeSchemaInfo(schemaAttribute); attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo); attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef!.DefaultValueRaw)); attributes.Append(attr); XmlUnspecifiedAttribute? defAttr = attr as XmlUnspecifiedAttribute; - if (defAttr != null) + if (defAttr is not null) { defAttr.SetSpecified(false); } @@ -453,7 +453,7 @@ private void ValidateAttributes(XmlElement elementNode) private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) { - Debug.Assert(_attributeSchemaInfo != null); + Debug.Assert(_attributeSchemaInfo is not null); _attributeSchemaInfo.Clear(); _attributeSchemaInfo.IsDefault = true; _attributeSchemaInfo.IsNil = false; @@ -465,7 +465,7 @@ private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union) { XsdSimpleValue? simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue; - Debug.Assert(simpleValue != null); + Debug.Assert(simpleValue is not null); _attributeSchemaInfo.MemberType = simpleValue.XmlType; } _attributeSchemaInfo.Validity = XmlSchemaValidity.Valid; @@ -515,16 +515,16 @@ private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) do { parentSchemaInfo = parentNode!.SchemaInfo; - if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null) + if (parentSchemaInfo.SchemaElement is not null || parentSchemaInfo.SchemaType is not null) { break; //Found ancestor with schemaInfo } CheckNodeSequenceCapacity(nodeIndex); _nodeSequenceToValidate![nodeIndex++] = parentNode; parentNode = parentNode.ParentNode; - } while (parentNode != null); + } while (parentNode is not null); - if (parentNode == null) + if (parentNode is null) { //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null _nodeSequenceToValidate![nodeIndex] = null; @@ -537,7 +537,7 @@ private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) CheckNodeSequenceCapacity(nodeIndex); _nodeSequenceToValidate![nodeIndex++] = parentNode; XmlSchemaObject? ancestorSchemaObject = parentSchemaInfo.SchemaElement; - if (ancestorSchemaObject == null) + if (ancestorSchemaObject is null) { ancestorSchemaObject = parentSchemaInfo.SchemaType; } @@ -548,17 +548,17 @@ private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) /*private XmlSchemaElement GetTypeFromParent(XmlElement elementToValidate, XmlSchemaComplexType parentSchemaType) { XmlQualifiedName elementName = new XmlQualifiedName(elementToValidate.LocalName, elementToValidate.NamespaceURI); XmlSchemaElement elem = parentSchemaType.LocalElements[elementName] as XmlSchemaElement; - if (elem == null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member + if (elem is null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member SchemaInfo compiledSchemaInfo = schemas.CompiledInfo; XmlSchemaElement memberElem = compiledSchemaInfo.GetElement(elementName); - if (memberElem != null) { + if (memberElem is not null) { } } }*/ private void CheckNodeSequenceCapacity(int currentIndex) { - if (_nodeSequenceToValidate == null) + if (_nodeSequenceToValidate is null) { //Normally users would call Validate one level down, this allows for 4 _nodeSequenceToValidate = new XmlNode[4]; } @@ -575,17 +575,17 @@ private void CheckNodeSequenceCapacity(int currentIndex) XmlElement parentElement = attributeToValidate.OwnerElement!; XmlSchemaObject? schemaObject = FindSchemaInfo(parentElement); XmlSchemaComplexType? elementSchemaType = GetComplexType(schemaObject); - if (elementSchemaType == null) + if (elementSchemaType is null) { return null; } XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI); XmlSchemaAttribute? schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute; - if (schemaAttribute == null) + if (schemaAttribute is null) { XmlSchemaAnyAttribute? anyAttribute = elementSchemaType.AttributeWildcard; - if (anyAttribute != null) + if (anyAttribute is not null) { if (anyAttribute.NamespaceList!.Allows(attName)) { //Match wildcard against global attribute @@ -634,7 +634,7 @@ private void CheckNodeSequenceCapacity(int currentIndex) ValidateSingleElement(elementToValidate, false, _schemaInfo); XmlSchemaObject? schemaInfoFound = null; - if (_schemaInfo.SchemaElement != null) + if (_schemaInfo.SchemaElement is not null) { schemaInfoFound = _schemaInfo.SchemaElement; } @@ -642,7 +642,7 @@ private void CheckNodeSequenceCapacity(int currentIndex) { schemaInfoFound = _schemaInfo.SchemaType; } - if (schemaInfoFound == null) + if (schemaInfoFound is null) { //Detect if the node was validated lax or skip if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Skip) { @@ -662,7 +662,7 @@ private void CheckNodeSequenceCapacity(int currentIndex) private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) { XmlSchemaComplexType? ancestorSchemaType = GetComplexType(ancestorType); - if (ancestorType != null) + if (ancestorType is not null) { return ancestorSchemaType!.HasWildCard; } @@ -672,14 +672,14 @@ private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) private XmlSchemaComplexType? GetComplexType(XmlSchemaObject? schemaObject) { - if (schemaObject == null) + if (schemaObject is null) { return null; } XmlSchemaElement? schemaElement = schemaObject as XmlSchemaElement; XmlSchemaComplexType? complexType = null; - if (schemaElement != null) + if (schemaElement is not null) { complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType; } @@ -694,7 +694,7 @@ private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo? newSchemaInfo) { _nsManager.PushScope(); - Debug.Assert(elementNode != null); + Debug.Assert(elementNode is not null); XmlAttributeCollection attributes = elementNode.Attributes; XmlAttribute? attr = null; @@ -708,8 +708,8 @@ private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSc attr = attributes[i]; string objectNs = attr.NamespaceURI; string objectName = attr.LocalName; - Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null); - Debug.Assert(_nameTable.Get(attr.LocalName) != null); + Debug.Assert(_nameTable.Get(attr.NamespaceURI) is not null); + Debug.Assert(_nameTable.Get(attr.LocalName) is not null); if (Ref.Equal(objectNs, _nsXsi)) { @@ -742,7 +742,7 @@ private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childT { XmlNode? child; - for (child = parentNode.FirstChild; child != null; child = child.NextSibling) + for (child = parentNode.FirstChild; child is not null; child = child.NextSibling) { if (child == childToStopAt) { @@ -785,7 +785,7 @@ private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject? partialVal { XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(_document.NameTable, _document.Schemas, _nsManager, XmlSchemaValidationFlags.None); findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack); - if (partialValidationType != null) + if (partialValidationType is not null) { findTypeValidator.Initialize(partialValidationType); } @@ -812,9 +812,9 @@ private void InternalValidationCallBack(object? sender, ValidationEventArgs arg) _isValid = false; } XmlSchemaValidationException? ex = arg.Exception as XmlSchemaValidationException; - Debug.Assert(ex != null); + Debug.Assert(ex is not null); ex.SetSourceObject(_currentNode); - if (_eventHandler != null) + if (_eventHandler is not null) { //Invoke user's event handler _eventHandler(sender, arg); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs index 166c50fa0f7934..00284557eb4635 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs @@ -40,7 +40,7 @@ public override XPathNavigator Clone() public override void SetValue(string value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -179,7 +179,7 @@ public override string Value case XmlNodeType.SignificantWhitespace: return ValueText; default: - Debug.Assert(_source.Value != null); + Debug.Assert(_source.Value is not null); // TODO-NULLABLE: Consider switching this.Value to nullable even if that implies switching it in the base type. // Also consider the following: // * this.SetValue() does not accept null. @@ -194,7 +194,7 @@ private string ValueDocument get { XmlElement? element = _document.DocumentElement; - if (element != null) + if (element is not null) { return element.InnerText; } @@ -210,7 +210,7 @@ private string ValueText string? value = _source.Value; XmlNode? nextSibling = NextSibling(_source); - if (nextSibling != null + if (nextSibling is not null && nextSibling.IsText) { StringBuilder builder = new StringBuilder(value); @@ -219,13 +219,13 @@ private string ValueText builder.Append(nextSibling.Value); nextSibling = NextSibling(nextSibling); } - while (nextSibling != null + while (nextSibling is not null && nextSibling.IsText); value = builder.ToString(); } // TODO-NULLABLE: Consider making this nullable given that _source.Value is nullable, - // OR we could change this getter to return string.Empty if _source.Value == null. - Debug.Assert(value != null); + // OR we could change this getter to return string.Empty if _source.Value is null. + Debug.Assert(value is not null); return value; } } @@ -371,7 +371,7 @@ public override bool MoveToNextAttribute() public override string GetNamespace(string name) { XmlNode? node = _source; - while (node != null + while (node is not null && node.NodeType != XmlNodeType.Element) { if (node is XmlAttribute attribute) @@ -385,10 +385,10 @@ public override string GetNamespace(string name) } XmlElement? element = node as XmlElement; - if (element != null) + if (element is not null) { string localName; - if (name != null + if (name is not null && name.Length != 0) { localName = name; @@ -402,13 +402,13 @@ public override string GetNamespace(string name) do { XmlAttribute? attribute = element.GetAttributeNode(localName, namespaceUri); - if (attribute != null) + if (attribute is not null) { return attribute.Value; } element = element.ParentNode as XmlElement; } - while (element != null); + while (element is not null); } if (name == _document.strXml) @@ -429,10 +429,10 @@ public override bool MoveToNamespace(string name) return false; } XmlElement? element = _source as XmlElement; - if (element != null) + if (element is not null) { string localName; - if (name != null + if (name is not null && name.Length != 0) { localName = name; @@ -446,7 +446,7 @@ public override bool MoveToNamespace(string name) do { XmlAttribute? attribute = element.GetAttributeNode(localName, namespaceUri); - if (attribute != null) + if (attribute is not null) { _namespaceParent = (XmlElement)_source; _source = attribute; @@ -454,7 +454,7 @@ public override bool MoveToNamespace(string name) } element = element.ParentNode as XmlElement; } - while (element != null); + while (element is not null); if (name == _document.strXml) { @@ -532,7 +532,7 @@ public override bool MoveToFirstNamespace(XPathNamespaceScope scope) private static bool MoveToFirstNamespaceLocal(XmlAttributeCollection attributes, ref int index) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); for (int i = attributes.Count - 1; i >= 0; i--) { XmlAttribute attribute = attributes[i]; @@ -552,9 +552,9 @@ private static bool MoveToFirstNamespaceGlobal(ref XmlAttributeCollection attrib return true; } - Debug.Assert(attributes != null && attributes.parent != null); + Debug.Assert(attributes is not null && attributes.parent is not null); XmlElement? element = attributes.parent.ParentNode as XmlElement; - while (element != null) + while (element is not null) { if (element.HasAttributes) { @@ -583,7 +583,7 @@ public override bool MoveToNextNamespace(XPathNamespaceScope scope) { return false; } - Debug.Assert(_namespaceParent != null); + Debug.Assert(_namespaceParent is not null); switch (scope) { case XPathNamespaceScope.Local: @@ -645,7 +645,7 @@ public override bool MoveToNextNamespace(XPathNamespaceScope scope) private static bool MoveToNextNamespaceLocal(XmlAttributeCollection attributes, ref int index) { - Debug.Assert(attributes != null); + Debug.Assert(attributes is not null); Debug.Assert(0 <= index && index < attributes.Count); for (int i = index - 1; i >= 0; i--) { @@ -666,9 +666,9 @@ private static bool MoveToNextNamespaceGlobal(ref XmlAttributeCollection attribu return true; } - Debug.Assert(attributes != null && attributes.parent != null); + Debug.Assert(attributes is not null && attributes.parent is not null); XmlElement? element = attributes.parent.ParentNode as XmlElement; - while (element != null) + while (element is not null) { if (element.HasAttributes) { @@ -687,11 +687,11 @@ private bool PathHasDuplicateNamespace(XmlElement? top, XmlElement bottom, strin { XmlElement? current = bottom; string namespaceUri = _document.strReservedXmlns; - while (current != null + while (current is not null && current != top) { XmlAttribute? attribute = current.GetAttributeNode(localName, namespaceUri); - if (attribute != null) + if (attribute is not null) { return true; } @@ -703,7 +703,7 @@ private bool PathHasDuplicateNamespace(XmlElement? top, XmlElement bottom, strin public override string? LookupNamespace(string prefix) { string? ns = base.LookupNamespace(prefix); - if (ns != null) + if (ns is not null) { ns = this.NameTable.Add(ns); } @@ -713,7 +713,7 @@ private bool PathHasDuplicateNamespace(XmlElement? top, XmlElement bottom, strin public override bool MoveToNext() { XmlNode? sibling = NextSibling(_source); - if (sibling == null) + if (sibling is null) { return false; } @@ -722,18 +722,18 @@ public override bool MoveToNext() if (_source.IsText) { sibling = NextSibling(TextEnd(sibling)); - if (sibling == null) + if (sibling is null) { return false; } } } XmlNode? parent = ParentNode(sibling); - Debug.Assert(parent != null); + Debug.Assert(parent is not null); while (!IsValidChild(parent, sibling)) { sibling = NextSibling(sibling); - if (sibling == null) + if (sibling is null) { return false; } @@ -745,7 +745,7 @@ public override bool MoveToNext() public override bool MoveToPrevious() { XmlNode? sibling = PreviousSibling(_source); - if (sibling == null) + if (sibling is null) { return false; } @@ -754,7 +754,7 @@ public override bool MoveToPrevious() if (_source.IsText) { sibling = PreviousSibling(TextStart(sibling)); - if (sibling == null) + if (sibling is null) { return false; } @@ -765,11 +765,11 @@ public override bool MoveToPrevious() } } XmlNode? parent = ParentNode(sibling); - Debug.Assert(parent != null); + Debug.Assert(parent is not null); while (!IsValidChild(parent, sibling)) { sibling = PreviousSibling(sibling); - if (sibling == null) + if (sibling is null) { return false; } @@ -788,16 +788,16 @@ public override bool MoveToFirst() return false; } XmlNode? parent = ParentNode(_source); - if (parent == null) + if (parent is null) { return false; } XmlNode? sibling = FirstChild(parent); - Debug.Assert(sibling != null); + Debug.Assert(sibling is not null); while (!IsValidChild(parent, sibling)) { sibling = NextSibling(sibling); - if (sibling == null) + if (sibling is null) { return false; } @@ -813,7 +813,7 @@ public override bool MoveToFirstChild() { case XmlNodeType.Element: child = FirstChild(_source); - if (child == null) + if (child is null) { return false; } @@ -821,14 +821,14 @@ public override bool MoveToFirstChild() case XmlNodeType.DocumentFragment: case XmlNodeType.Document: child = FirstChild(_source); - if (child == null) + if (child is null) { return false; } while (!IsValidChild(_source, child)) { child = NextSibling(child); - if (child == null) + if (child is null) { return false; } @@ -844,7 +844,7 @@ public override bool MoveToFirstChild() public override bool MoveToParent() { XmlNode? parent = ParentNode(_source); - if (parent != null) + if (parent is not null) { _source = parent; return true; @@ -852,7 +852,7 @@ public override bool MoveToParent() if (_source is XmlAttribute attribute) { parent = attribute.IsNamespace ? _namespaceParent : attribute.OwnerElement; - if (parent != null) + if (parent is not null) { _source = parent; _namespaceParent = null; @@ -867,14 +867,14 @@ public override void MoveToRoot() while (true) { XmlNode? parent = _source.ParentNode; - if (parent == null) + if (parent is null) { if (!(_source is XmlAttribute attribute)) { break; } parent = attribute.IsNamespace ? _namespaceParent : attribute.OwnerElement; - if (parent == null) + if (parent is null) { break; } @@ -900,7 +900,7 @@ public override bool MoveTo(XPathNavigator other) public override bool MoveToId(string id) { XmlElement? element = _document.GetElementById(id); - if (element != null) + if (element is not null) { _source = element; _namespaceParent = null; @@ -917,7 +917,7 @@ public override bool MoveToChild(string localName, string namespaceUri) } XmlNode? child = FirstChild(_source); - if (child != null) + if (child is not null) { do { @@ -930,7 +930,7 @@ public override bool MoveToChild(string localName, string namespaceUri) } child = NextSibling(child); } - while (child != null); + while (child is not null); } return false; } @@ -943,7 +943,7 @@ public override bool MoveToChild(XPathNodeType type) } XmlNode? child = FirstChild(_source); - if (child != null) + if (child is not null) { int mask = GetContentKindMask(type); if (mask == 0) @@ -959,7 +959,7 @@ public override bool MoveToChild(XPathNodeType type) } child = NextSibling(child); } - while (child != null); + while (child is not null); } return false; } @@ -990,7 +990,7 @@ public override bool MoveToFollowing(string localName, string namespaceUri, XPat if (following.NodeType == XmlNodeType.Attribute) { following = ((XmlAttribute)following).OwnerElement; - if (following == null) + if (following is null) { return false; } @@ -998,7 +998,7 @@ public override bool MoveToFollowing(string localName, string namespaceUri, XPat do { XmlNode? firstChild = following.FirstChild; - if (firstChild != null) + if (firstChild is not null) { following = firstChild; } @@ -1007,7 +1007,7 @@ public override bool MoveToFollowing(string localName, string namespaceUri, XPat while (true) { XmlNode? nextSibling = following.NextSibling; - if (nextSibling != null) + if (nextSibling is not null) { following = nextSibling; break; @@ -1015,7 +1015,7 @@ public override bool MoveToFollowing(string localName, string namespaceUri, XPat else { XmlNode? parent = following.ParentNode; - if (parent != null) + if (parent is not null) { following = parent; } @@ -1071,7 +1071,7 @@ public override bool MoveToFollowing(XPathNodeType type, XPathNavigator? end) { case XmlNodeType.Attribute: following = ((XmlAttribute)following).OwnerElement; - if (following == null) + if (following is null) { return false; } @@ -1086,7 +1086,7 @@ public override bool MoveToFollowing(XPathNodeType type, XPathNavigator? end) do { XmlNode? firstChild = following.FirstChild; - if (firstChild != null) + if (firstChild is not null) { following = firstChild; } @@ -1095,7 +1095,7 @@ public override bool MoveToFollowing(XPathNodeType type, XPathNavigator? end) while (true) { XmlNode? nextSibling = following.NextSibling; - if (nextSibling != null) + if (nextSibling is not null) { following = nextSibling; break; @@ -1103,7 +1103,7 @@ public override bool MoveToFollowing(XPathNodeType type, XPathNavigator? end) else { XmlNode? parent = following.ParentNode; - if (parent != null) + if (parent is not null) { following = parent; } @@ -1128,7 +1128,7 @@ public override bool MoveToFollowing(XPathNodeType type, XPathNavigator? end) public override bool MoveToNext(string localName, string namespaceUri) { XmlNode? sibling = NextSibling(_source); - if (sibling == null) + if (sibling is null) { return false; } @@ -1143,14 +1143,14 @@ public override bool MoveToNext(string localName, string namespaceUri) } sibling = NextSibling(sibling); } - while (sibling != null); + while (sibling is not null); return false; } public override bool MoveToNext(XPathNodeType type) { XmlNode? sibling = NextSibling(_source); - if (sibling == null) + if (sibling is null) { return false; } @@ -1158,7 +1158,7 @@ public override bool MoveToNext(XPathNodeType type) && _source.IsText) { sibling = NextSibling(TextEnd(sibling)); - if (sibling == null) + if (sibling is null) { return false; } @@ -1178,7 +1178,7 @@ public override bool MoveToNext(XPathNodeType type) } sibling = NextSibling(sibling); } - while (sibling != null); + while (sibling is not null); return false; } @@ -1191,7 +1191,7 @@ public override bool HasChildren { case XmlNodeType.Element: child = FirstChild(_source); - if (child == null) + if (child is null) { return false; } @@ -1199,14 +1199,14 @@ public override bool HasChildren case XmlNodeType.DocumentFragment: case XmlNodeType.Document: child = FirstChild(_source); - if (child == null) + if (child is null) { return false; } while (!IsValidChild(_source, child)) { child = NextSibling(child); - if (child == null) + if (child is null) { return false; } @@ -1260,23 +1260,23 @@ public override bool CheckValidity(XmlSchemaSet schemas, ValidationEventHandler { ownerDocument = _source.OwnerDocument; - if (schemas != null) + if (schemas is not null) { throw new ArgumentException(SR.Format(SR.XPathDocument_SchemaSetNotAllowed, null)); } } - if (schemas == null && ownerDocument != null) + if (schemas is null && ownerDocument is not null) { schemas = ownerDocument.Schemas; } - if (schemas == null || schemas.Count == 0) + if (schemas is null || schemas.Count == 0) { throw new InvalidOperationException(SR.XmlDocument_NoSchemaInfo); } // DocumentSchemaValidator assumes that ownedDocument can never be null. - Debug.Assert(ownerDocument != null); + Debug.Assert(ownerDocument is not null); DocumentSchemaValidator validator = new DocumentSchemaValidator(ownerDocument, schemas, validationEventHandler); validator.PsviAugmentation = false; return validator.Validate(_source); @@ -1285,7 +1285,7 @@ public override bool CheckValidity(XmlSchemaSet schemas, ValidationEventHandler private static XmlNode? OwnerNode(XmlNode node) { XmlNode? parent = node.ParentNode; - if (parent != null) + if (parent is not null) { return parent; } @@ -1300,7 +1300,7 @@ private static int GetDepth(XmlNode node) { int depth = 0; XmlNode? owner = OwnerNode(node); - while (owner != null) + while (owner is not null) { depth++; owner = OwnerNode(owner); @@ -1312,8 +1312,8 @@ private static int GetDepth(XmlNode node) //the returned value is node2's position corresponding to node1 private XmlNodeOrder Compare(XmlNode node1, XmlNode node2) { - Debug.Assert(node1 != null); - Debug.Assert(node2 != null); + Debug.Assert(node1 is not null); + Debug.Assert(node2 is not null); Debug.Assert(node1 != node2, "Should be handled by ComparePosition()"); //Attribute nodes come before other children nodes except namespace nodes Debug.Assert(OwnerNode(node1) == OwnerNode(node2)); @@ -1322,7 +1322,7 @@ private XmlNodeOrder Compare(XmlNode node1, XmlNode node2) if (node2.XPNodeType == XPathNodeType.Attribute) { XmlElement? element = ((XmlAttribute)node1).OwnerElement; - Debug.Assert(element != null); + Debug.Assert(element is not null); if (element.HasAttributes) { XmlAttributeCollection attributes = element.Attributes; @@ -1353,9 +1353,9 @@ private XmlNodeOrder Compare(XmlNode node1, XmlNode node2) //neither of the node is Namespace node or Attribute node XmlNode? nextNode = node1.NextSibling; - while (nextNode != null && nextNode != node2) + while (nextNode is not null && nextNode != node2) nextNode = nextNode.NextSibling; - if (nextNode == null) + if (nextNode is null) //didn't meet node2 in the path to the end, thus it has to be in the front of node1 return XmlNodeOrder.After; else @@ -1379,8 +1379,8 @@ public override XmlNodeOrder ComparePosition(XPathNavigator? other) return XmlNodeOrder.Same; } - if (_namespaceParent != null - || that._namespaceParent != null) + if (_namespaceParent is not null + || that._namespaceParent is not null) { return base.ComparePosition(other); } @@ -1392,7 +1392,7 @@ public override XmlNodeOrder ComparePosition(XPathNavigator? other) XmlNode? parent2 = OwnerNode(node2); if (parent1 == parent2) { - if (parent1 == null) + if (parent1 is null) { return XmlNodeOrder.Unknown; } @@ -1407,7 +1407,7 @@ public override XmlNodeOrder ComparePosition(XPathNavigator? other) int depth2 = GetDepth(node2); if (depth2 > depth1) { - while (node2 != null + while (node2 is not null && depth2 > depth1) { node2 = OwnerNode(node2); @@ -1417,12 +1417,12 @@ public override XmlNodeOrder ComparePosition(XPathNavigator? other) { return XmlNodeOrder.Before; } - Debug.Assert(node2 != null); + Debug.Assert(node2 is not null); parent2 = OwnerNode(node2); } else if (depth1 > depth2) { - while (node1 != null + while (node1 is not null && depth1 > depth2) { node1 = OwnerNode(node1); @@ -1432,12 +1432,12 @@ public override XmlNodeOrder ComparePosition(XPathNavigator? other) { return XmlNodeOrder.After; } - Debug.Assert(node1 != null); + Debug.Assert(node1 is not null); parent1 = OwnerNode(node1); } - while (parent1 != null - && parent2 != null) + while (parent1 is not null + && parent2 is not null) { if (parent1 == parent2) { @@ -1458,13 +1458,13 @@ public override XmlNodeOrder ComparePosition(XPathNavigator? other) public override XPathNodeIterator SelectDescendants(string localName, string namespaceURI, bool matchSelf) { string? nsAtom = _document.NameTable.Get(namespaceURI); - if (nsAtom == null || _source.NodeType == XmlNodeType.Attribute) + if (nsAtom is null || _source.NodeType == XmlNodeType.Attribute) return new DocumentXPathNodeIterator_Empty(this); Debug.Assert(this.NodeType != XPathNodeType.Attribute && this.NodeType != XPathNodeType.Namespace && this.NodeType != XPathNodeType.All); string? localNameAtom = _document.NameTable.Get(localName); - if (localNameAtom == null) + if (localNameAtom is null) return new DocumentXPathNodeIterator_Empty(this); if (localNameAtom.Length == 0) @@ -1604,7 +1604,7 @@ public override XmlWriter ReplaceRange(XPathNavigator lastSiblingToReplace) { if (!(lastSiblingToReplace is DocumentXPathNavigator that)) { - if (lastSiblingToReplace == null) + if (lastSiblingToReplace is null) { throw new ArgumentNullException(nameof(lastSiblingToReplace)); } @@ -1661,7 +1661,7 @@ public override void DeleteRange(XPathNavigator lastSiblingToDelete) { if (!(lastSiblingToDelete is DocumentXPathNavigator that)) { - if (lastSiblingToDelete == null) + if (lastSiblingToDelete is null) { throw new ArgumentNullException(nameof(lastSiblingToDelete)); } @@ -1689,7 +1689,7 @@ public override void DeleteRange(XPathNavigator lastSiblingToDelete) } XmlNode? parent = OwnerNode(attribute); DeleteAttribute(attribute, _attributeIndex); - if (parent != null) + if (parent is not null) { ResetPosition(parent); } @@ -1705,7 +1705,7 @@ public override void DeleteRange(XPathNavigator lastSiblingToDelete) case XmlNodeType.Comment: parent = OwnerNode(node); DeleteToFollowingSibling(node, end); - if (parent != null) + if (parent is not null) { ResetPosition(parent); } @@ -1726,7 +1726,7 @@ public override void DeleteRange(XPathNavigator lastSiblingToDelete) } XmlNode? parent = OwnerNode(node); DeleteToFollowingSibling(node, end); - if (parent != null) + if (parent is not null) { ResetPosition(parent); } @@ -1748,7 +1748,7 @@ public override void DeleteSelf() } XmlNode? parent = OwnerNode(attribute); DeleteAttribute(attribute, _attributeIndex); - if (parent != null) + if (parent is not null) { ResetPosition(parent); } @@ -1767,7 +1767,7 @@ public override void DeleteSelf() case XmlNodeType.Comment: parent = OwnerNode(node); DeleteToFollowingSibling(node, end); - if (parent != null) + if (parent is not null) { ResetPosition(parent); } @@ -1797,7 +1797,7 @@ internal static void DeleteToFollowingSibling(XmlNode node, XmlNode end) { XmlNode? parent = node.ParentNode; - if (parent == null) + if (parent is null) { throw new InvalidOperationException(SR.Xpn_MissingParent); } @@ -1808,7 +1808,7 @@ internal static void DeleteToFollowingSibling(XmlNode node, XmlNode end) } while (node != end) { - Debug.Assert(node != null, "This method needs to be called with the beforehand check of NextSibling being not null from node to end"); + Debug.Assert(node is not null, "This method needs to be called with the beforehand check of NextSibling being not null from node to end"); XmlNode temp = node; node = node.NextSibling!; parent.RemoveChild(temp); @@ -1821,7 +1821,7 @@ private static XmlNamespaceManager GetNamespaceManager(XmlNode? node, XmlDocumen XmlNamespaceManager namespaceManager = new XmlNamespaceManager(document.NameTable); List elements = new List(); - while (node != null) + while (node is not null) { if (node is XmlElement element && element.HasAttributes) @@ -1850,13 +1850,13 @@ private static XmlNamespaceManager GetNamespaceManager(XmlNode? node, XmlDocumen [MemberNotNull(nameof(_source))] internal void ResetPosition(XmlNode node) { - Debug.Assert(node != null, "Undefined navigator position"); + Debug.Assert(node is not null, "Undefined navigator position"); Debug.Assert(node == _document || node.OwnerDocument == _document, "Navigator switched documents"); _source = node; if (node is XmlAttribute attribute) { XmlElement? element = attribute.OwnerElement; - if (element != null) + if (element is not null) { ResetAttributePosition(attribute, element.Attributes, out _attributeIndex); if (attribute.IsNamespace) @@ -1869,7 +1869,7 @@ internal void ResetPosition(XmlNode node) private static bool ResetAttributePosition(XmlAttribute attribute, [NotNullWhen(true)] XmlAttributeCollection? attributes, out int index) { - if (attributes != null) + if (attributes is not null) { for (int i = 0; i < attributes.Count; i++) { @@ -1887,7 +1887,7 @@ private static bool ResetAttributePosition(XmlAttribute attribute, [NotNullWhen( private static bool CheckAttributePosition(XmlAttribute attribute, [NotNullWhen(true)] out XmlAttributeCollection? attributes, int index) { XmlElement? element = attribute.OwnerElement; - if (element != null) + if (element is not null) { attributes = element.Attributes; if (index >= 0 @@ -1907,7 +1907,7 @@ private static bool CheckAttributePosition(XmlAttribute attribute, [NotNullWhen( private void CalibrateText() { XmlNode? text = PreviousText(_source); - while (text != null) + while (text is not null) { ResetPosition(text); text = PreviousText(text); @@ -1927,7 +1927,7 @@ private void CalibrateText() private XmlNode? ParentNodeTail(XmlNode? parent) { - while (parent != null + while (parent is not null && parent.NodeType == XmlNodeType.EntityReference) { parent = parent.ParentNode; @@ -1948,7 +1948,7 @@ private void CalibrateText() private XmlNode? FirstChildTail(XmlNode? child) { - while (child != null + while (child is not null && child.NodeType == XmlNodeType.EntityReference) { child = child.FirstChild; @@ -1970,17 +1970,17 @@ private void CalibrateText() private XmlNode? NextSiblingTail(XmlNode node, XmlNode? sibling) { XmlNode? current = node; - while (sibling == null) + while (sibling is null) { current = current.ParentNode; - if (current == null + if (current is null || current.NodeType != XmlNodeType.EntityReference) { return null; } sibling = current.NextSibling; } - while (sibling != null + while (sibling is not null && sibling.NodeType == XmlNodeType.EntityReference) { sibling = sibling.FirstChild; @@ -2002,17 +2002,17 @@ private void CalibrateText() private XmlNode? PreviousSiblingTail(XmlNode node, XmlNode? sibling) { XmlNode? current = node; - while (sibling == null) + while (sibling is null) { current = current.ParentNode; - if (current == null + if (current is null || current.NodeType != XmlNodeType.EntityReference) { return null; } sibling = current.PreviousSibling; } - while (sibling != null + while (sibling is not null && sibling.NodeType == XmlNodeType.EntityReference) { sibling = sibling.LastChild; @@ -2033,7 +2033,7 @@ private void CalibrateText() private XmlNode? PreviousTextTail(XmlNode node, XmlNode? text) { - if (text != null) + if (text is not null) { return text; } @@ -2043,17 +2043,17 @@ private void CalibrateText() } XmlNode? sibling = node.PreviousSibling; XmlNode? current = node; - while (sibling == null) + while (sibling is null) { current = current.ParentNode; - if (current == null + if (current is null || current.NodeType != XmlNodeType.EntityReference) { return null; } sibling = current.PreviousSibling; } - while (sibling != null) + while (sibling is not null) { switch (sibling.NodeType) { @@ -2078,7 +2078,7 @@ internal static bool IsFollowingSibling(XmlNode left, [NotNullWhen(true)] XmlNod while (true) { currentLeft = currentLeft.NextSibling; - if (currentLeft == null) + if (currentLeft is null) { break; } @@ -2095,14 +2095,14 @@ private static bool IsDescendant(XmlNode top, XmlNode bottom) while (true) { XmlNode? parent = bottom.ParentNode; - if (parent == null) + if (parent is null) { if (!(bottom is XmlAttribute attribute)) { break; } parent = attribute.OwnerElement; - if (parent == null) + if (parent is null) { break; } @@ -2160,7 +2160,7 @@ private XmlNode TextStart(XmlNode node) start = current; current = PreviousSibling(current); } - while (current != null + while (current is not null && current.IsText); return start; } @@ -2175,7 +2175,7 @@ private XmlNode TextEnd(XmlNode node) end = current; current = NextSibling(current); } - while (current != null + while (current is not null && current.IsText); return end; } @@ -2287,7 +2287,7 @@ public override XPathNodeIterator Clone() protected override bool Match(XmlNode node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); return (node.NodeType == XmlNodeType.Element); } } @@ -2343,7 +2343,7 @@ public override XPathNodeIterator Clone() protected override bool Match(XmlNode node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); Debug.Assert(node.NodeType == XmlNodeType.Element); return Ref.Equal(node.NamespaceURI, _nsAtom); } @@ -2408,7 +2408,7 @@ public override XPathNodeIterator Clone() protected override bool Match(XmlNode node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); Debug.Assert(node.NodeType == XmlNodeType.Element); return Ref.Equal(node.LocalName, localNameAtom) && Ref.Equal(node.NamespaceURI, nsAtom); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs index 3bcd7a3e0069b5..e7fb718300b3b3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs @@ -165,7 +165,7 @@ public override void WriteStartElement(string? prefix, string localName, string? public override void WriteEndElement() { VerifyState(Method.WriteEndElement); - if (_write == null) + if (_write is null) { throw new InvalidOperationException(); } @@ -182,7 +182,7 @@ public override void WriteFullEndElement() { VerifyState(Method.WriteFullEndElement); XmlElement? elem = _write as XmlElement; - if (elem == null) + if (elem is null) { throw new InvalidOperationException(); } @@ -213,7 +213,7 @@ public override void WriteEndAttribute() { VerifyState(Method.WriteEndAttribute); XmlAttribute? attr = _write as XmlAttribute; - if (attr == null) + if (attr is null) { throw new InvalidOperationException(); } @@ -263,7 +263,7 @@ internal override void WriteEndNamespaceDeclaration() { VerifyState(Method.WriteEndNamespaceDeclaration); XmlAttribute? attr = _write as XmlAttribute; - if (attr == null) + if (attr is null) { throw new InvalidOperationException(); } @@ -306,7 +306,7 @@ public override void WriteEntityRef(string name) VerifyState(Method.WriteEntityRef); XmlNode node = _document.CreateEntityReference(name); AddChild(node, _write); - // REVIEW: the namespace scope is incorrect(?) unless write == null + // REVIEW: the namespace scope is incorrect(?) unless write is null } public override void WriteCharEntity(char ch) @@ -371,7 +371,7 @@ internal override void Close(WriteState currentState) { case DocumentXmlWriterType.InsertSiblingAfter: XmlNode? parent = _start.ParentNode; - if (parent == null) + if (parent is null) { throw new InvalidOperationException(SR.Xpn_MissingParent); } @@ -384,7 +384,7 @@ internal override void Close(WriteState currentState) break; case DocumentXmlWriterType.InsertSiblingBefore: parent = _start.ParentNode; - if (parent == null) + if (parent is null) { throw new InvalidOperationException(SR.Xpn_MissingParent); } @@ -431,12 +431,12 @@ internal override void Close(WriteState currentState) private void CloseWithAppendAttribute() { XmlElement? elem = _start as XmlElement; - Debug.Assert(elem != null); + Debug.Assert(elem is not null); XmlAttributeCollection attrs = elem.Attributes; for (int i = 0; i < _fragment.Count; i++) { XmlAttribute? attr = _fragment[i] as XmlAttribute; - Debug.Assert(attr != null); + Debug.Assert(attr is not null); int offset = attrs.FindNodeOffsetNS(attr); if (offset != -1 && ((XmlAttribute)attrs.nodes[offset]).Specified) @@ -447,7 +447,7 @@ private void CloseWithAppendAttribute() for (int i = 0; i < _fragment.Count; i++) { XmlAttribute? attr = _fragment[i] as XmlAttribute; - Debug.Assert(attr != null); + Debug.Assert(attr is not null); attrs.Append(attr); } } @@ -455,7 +455,7 @@ private void CloseWithAppendAttribute() private void CloseWithReplaceToFollowingSibling() { XmlNode? parent = _start.ParentNode; - if (parent == null) + if (parent is null) { throw new InvalidOperationException(SR.Xpn_MissingParent); } @@ -506,14 +506,14 @@ IDictionary IXmlNamespaceResolver.GetNamespacesInScope(XmlNamesp private void AddAttribute(XmlAttribute attr, XmlNode? parent) { - if (parent == null) + if (parent is null) { _fragment.Add(attr); } else { XmlElement? elem = parent as XmlElement; - if (elem == null) + if (elem is null) { throw new InvalidOperationException(); } @@ -524,7 +524,7 @@ private void AddAttribute(XmlAttribute attr, XmlNode? parent) private void AddChild(XmlNode node, XmlNode? parent) { - if (parent == null) + if (parent is null) { _fragment.Add(node); } @@ -543,7 +543,7 @@ private State StartState() case DocumentXmlWriterType.InsertSiblingAfter: case DocumentXmlWriterType.InsertSiblingBefore: XmlNode? parent = _start.ParentNode; - if (parent != null) + if (parent is not null) { nodeType = parent.NodeType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs index 748f0c3d0b2788..d4a4cc55f49ebc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs @@ -28,18 +28,18 @@ public DomNameTable(XmlDocument document) public XmlName? GetName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo) { - if (prefix == null) + if (prefix is null) { prefix = string.Empty; } - if (ns == null) + if (ns is null) { ns = string.Empty; } int hashCode = XmlName.GetHashCode(localName); - for (XmlName e = _entries[hashCode & _mask]; e != null; e = e.next) + for (XmlName e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.HashCode == hashCode && ((object)e.LocalName == (object)localName @@ -58,18 +58,18 @@ public DomNameTable(XmlDocument document) public XmlName AddName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo) { - if (prefix == null) + if (prefix is null) { prefix = string.Empty; } - if (ns == null) + if (ns is null) { ns = string.Empty; } int hashCode = XmlName.GetHashCode(localName); - for (XmlName e = _entries[hashCode & _mask]; e != null; e = e.next) + for (XmlName e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.HashCode == hashCode && ((object)e.LocalName == (object)localName @@ -109,7 +109,7 @@ private void Grow() for (int i = 0; i < oldEntries.Length; i++) { XmlName name = oldEntries[i]; - while (name != null) + while (name is not null) { int newIndex = name.HashCode & newMask; XmlName tmp = name.next; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs index 11c01d42464f16..f72de13fa97165 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs @@ -46,9 +46,9 @@ internal int ReadUntil(int index) { if (_nodeIterator.MoveNext()) { - Debug.Assert(_nodeIterator.Current != null); + Debug.Assert(_nodeIterator.Current is not null); XmlNode? n = GetNode(_nodeIterator.Current); - if (n != null) + if (n is not null) { _list.Add(n); count++; @@ -109,7 +109,7 @@ public bool MoveNext() { return false; } - _valid = (_list[_index] != null); + _valid = (_list[_index] is not null); return _valid; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs index b29fea07407c14..d3ab028de0d8e0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs @@ -18,8 +18,8 @@ public class XmlAttribute : XmlNode internal XmlAttribute(XmlName name, XmlDocument doc) : base(doc) { - Debug.Assert(name != null); - Debug.Assert(doc != null); + Debug.Assert(name is not null); + Debug.Assert(doc is not null); this.parentNode = null; if (!doc.IsLoading) { @@ -51,7 +51,7 @@ internal XmlName XmlName public override XmlNode CloneNode(bool deep) { // CloneNode for attributes is deep irrespective of parameter 'deep' value - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); XmlDocument doc = OwnerDocument; XmlAttribute attr = doc.CreateAttribute(Prefix, LocalName, NamespaceURI); attr.CopyChildren(doc, this, true); @@ -140,10 +140,10 @@ public override string InnerText internal bool PrepareOwnerElementInElementIdAttrMap() { XmlDocument ownerDocument = OwnerDocument; - if (ownerDocument.DtdSchemaInfo != null) + if (ownerDocument.DtdSchemaInfo is not null) { // DTD exists XmlElement? ownerElement = OwnerElement; - if (ownerElement != null) + if (ownerElement is not null) { return ownerElement.Attributes.PrepareParentInElementIdAttrMap(Prefix, LocalName); } @@ -155,7 +155,7 @@ internal bool PrepareOwnerElementInElementIdAttrMap() internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText) { XmlElement? ownerElement = OwnerElement; - if (ownerElement != null) + if (ownerElement is not null) { ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText); } @@ -171,13 +171,13 @@ internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); - if (args != null) + if (args is not null) doc.BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; - if (_lastChild == null) - { // if LastNode == null + if (_lastChild is null) + { // if LastNode is null newNode.next = newNode; _lastChild = newNode; newNode.SetParentForLoad(this); @@ -199,7 +199,7 @@ internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) } } - if (args != null) + if (args is not null) doc.AfterEvent(args); return newNode; @@ -355,7 +355,7 @@ public override void WriteTo(XmlWriter w) // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { - for (XmlNode? node = FirstChild; node != null; node = node.NextSibling) + for (XmlNode? node = FirstChild; node is not null; node = node.NextSibling) { node.WriteTo(w); } @@ -365,7 +365,7 @@ public override string BaseURI { get { - if (OwnerElement != null) + if (OwnerElement is not null) return OwnerElement.BaseURI; return string.Empty; } @@ -380,7 +380,7 @@ internal override XmlSpace XmlSpace { get { - if (OwnerElement != null) + if (OwnerElement is not null) return OwnerElement.XmlSpace; return XmlSpace.None; } @@ -390,7 +390,7 @@ internal override string XmlLang { get { - if (OwnerElement != null) + if (OwnerElement is not null) return OwnerElement.XmlLang; return string.Empty; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs index fa5ab070b21025..587c8731ba2009 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs @@ -114,7 +114,7 @@ internal int FindNodeOffsetNS(XmlAttribute node) [return: NotNullIfNotNull("node")] public override XmlNode? SetNamedItem(XmlNode? node) { - if (node == null) + if (node is null) return null; if (!(node is XmlAttribute)) @@ -136,10 +136,10 @@ internal int FindNodeOffsetNS(XmlAttribute node) // Inserts the specified node as the first node in the collection. public XmlAttribute Prepend(XmlAttribute node) { - if (node.OwnerDocument != null && node.OwnerDocument != parent.OwnerDocument) + if (node.OwnerDocument is not null && node.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); - if (node.OwnerElement != null) + if (node.OwnerElement is not null) Detach(node); RemoveDuplicateAttribute(node); @@ -152,13 +152,13 @@ public XmlAttribute Prepend(XmlAttribute node) public XmlAttribute Append(XmlAttribute node) { XmlDocument doc = node.OwnerDocument; - if (doc == null || doc.IsLoading == false) + if (doc is null || doc.IsLoading == false) { - if (doc != null && doc != parent.OwnerDocument) + if (doc is not null && doc != parent.OwnerDocument) { throw new ArgumentException(SR.Xdom_NamedNode_Context); } - if (node.OwnerElement != null) + if (node.OwnerElement is not null) { Detach(node); } @@ -178,16 +178,16 @@ public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute? refNode) if (newNode == refNode) return newNode; - if (refNode == null) + if (refNode is null) return Append(newNode); if (refNode.OwnerElement != parent) throw new ArgumentException(SR.Xdom_AttrCol_Insert); - if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument) + if (newNode.OwnerDocument is not null && newNode.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); - if (newNode.OwnerElement != null) + if (newNode.OwnerElement is not null) Detach(newNode); int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI); @@ -207,16 +207,16 @@ public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute? refNode) if (newNode == refNode) return newNode; - if (refNode == null) + if (refNode is null) return Prepend(newNode); if (refNode.OwnerElement != parent) throw new ArgumentException(SR.Xdom_AttrCol_Insert); - if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument) + if (newNode.OwnerDocument is not null && newNode.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); - if (newNode.OwnerElement != null) + if (newNode.OwnerElement is not null) Detach(newNode); int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI); @@ -320,7 +320,7 @@ internal override XmlNode RemoveNodeAt(int i) RemoveParentFromElementIdAttrMap((XmlAttribute)retNode); // after remove the attribute, we need to check if a default attribute node should be created and inserted into the tree XmlAttribute? defattr = parent.OwnerDocument!.GetDefaultAttribute((XmlElement)parent, retNode.Prefix, retNode.LocalName, retNode.NamespaceURI); - if (defattr != null) + if (defattr is not null) InsertNodeAt(i, defattr); return retNode; @@ -335,13 +335,13 @@ internal void Detach(XmlAttribute attr) internal void InsertParentIntoElementIdAttrMap(XmlAttribute attr) { XmlElement? parentElem = parent as XmlElement; - if (parentElem != null) + if (parentElem is not null) { - if (parent.OwnerDocument == null) + if (parent.OwnerDocument is null) return; XmlName? attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); - if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) + if (attrname is not null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.AddElementWithId(attr.Value, parentElem); //add the element into the hashtable } @@ -352,13 +352,13 @@ internal void InsertParentIntoElementIdAttrMap(XmlAttribute attr) internal void RemoveParentFromElementIdAttrMap(XmlAttribute attr) { XmlElement? parentElem = parent as XmlElement; - if (parentElem != null) + if (parentElem is not null) { - if (parent.OwnerDocument == null) + if (parent.OwnerDocument is null) return; XmlName? attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); - if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) + if (attrname is not null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.RemoveElementWithId(attr.Value, parentElem); //remove the element from the hashtable } @@ -383,13 +383,13 @@ internal int RemoveDuplicateAttribute(XmlAttribute attr) internal bool PrepareParentInElementIdAttrMap(string attrPrefix, string attrLocalName) { XmlElement? parentElem = parent as XmlElement; - Debug.Assert(parentElem != null); + Debug.Assert(parentElem is not null); XmlDocument? doc = parent.OwnerDocument; - Debug.Assert(doc != null); + Debug.Assert(doc is not null); //The returned attrname if not null is the name with namespaceURI being set to string.Empty //Because DTD doesn't support namespaceURI so all comparisons are based on no namespaceURI (string.Empty); XmlName? attrname = doc.GetIDInfoByElement(parentElem.XmlName); - if (attrname != null && attrname.Prefix == attrPrefix && attrname.LocalName == attrLocalName) + if (attrname is not null && attrname.Prefix == attrPrefix && attrname.LocalName == attrLocalName) { return true; } @@ -400,9 +400,9 @@ internal bool PrepareParentInElementIdAttrMap(string attrPrefix, string attrLoca internal void ResetParentInElementIdAttrMap(string oldVal, string newVal) { XmlElement? parentElem = parent as XmlElement; - Debug.Assert(parentElem != null); + Debug.Assert(parentElem is not null); XmlDocument? doc = parent.OwnerDocument; - Debug.Assert(doc != null); + Debug.Assert(doc is not null); doc.RemoveElementWithId(oldVal, parentElem); //add the element into the hashtable doc.AddElementWithId(newVal, parentElem); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs index 41c1e6d29f4aed..9230069aef026d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs @@ -69,7 +69,7 @@ public override XmlNode? ParentNode // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateCDataSection(Data); } @@ -105,7 +105,7 @@ public override XmlNode? PreviousText { get { - if (parentNode != null && parentNode.IsText) + if (parentNode is not null && parentNode.IsText) { return parentNode; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs index 6e3ecb472011c2..9fea43fe1bf7c3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs @@ -40,7 +40,7 @@ public virtual string Data { get { - if (_data != null) + if (_data is not null) { return _data; } @@ -55,12 +55,12 @@ public virtual string Data XmlNode? parent = ParentNode; XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); - if (args != null) + if (args is not null) BeforeEvent(args); _data = value; - if (args != null) + if (args is not null) AfterEvent(args); } } @@ -70,7 +70,7 @@ public virtual int Length { get { - if (_data != null) + if (_data is not null) { return _data.Length; } @@ -81,7 +81,7 @@ public virtual int Length // Retrieves a substring of the full string from the specified range. public virtual string Substring(int offset, int count) { - int len = _data != null ? _data.Length : 0; + int len = _data is not null ? _data.Length : 0; if (len > 0) { if (len < (offset + count)) @@ -99,17 +99,17 @@ public virtual string Substring(int offset, int count) public virtual void AppendData(string? strData) { XmlNode? parent = ParentNode; - int capacity = _data != null ? _data.Length : 0; - if (strData != null) capacity += strData.Length; + int capacity = _data is not null ? _data.Length : 0; + if (strData is not null) capacity += strData.Length; string newValue = new StringBuilder(capacity).Append(_data).Append(strData).ToString(); XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); - if (args != null) + if (args is not null) BeforeEvent(args); _data = newValue; - if (args != null) + if (args is not null) AfterEvent(args); } @@ -117,16 +117,16 @@ public virtual void AppendData(string? strData) public virtual void InsertData(int offset, string? strData) { XmlNode? parent = ParentNode; - int capacity = _data != null ? _data.Length : 0; - if (strData != null) capacity += strData.Length; + int capacity = _data is not null ? _data.Length : 0; + if (strData is not null) capacity += strData.Length; string newValue = new StringBuilder(capacity).Append(_data).Insert(offset, strData).ToString(); XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); - if (args != null) + if (args is not null) BeforeEvent(args); _data = newValue; - if (args != null) + if (args is not null) AfterEvent(args); } @@ -135,7 +135,7 @@ public virtual void DeleteData(int offset, int count) { //Debug.Assert(offset >= 0 && offset <= Length); - int len = _data != null ? _data.Length : 0; + int len = _data is not null ? _data.Length : 0; if (len > 0) { if (len < (offset + count)) @@ -148,12 +148,12 @@ public virtual void DeleteData(int offset, int count) XmlNode? parent = ParentNode; XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); - if (args != null) + if (args is not null) BeforeEvent(args); _data = newValue; - if (args != null) + if (args is not null) AfterEvent(args); } @@ -161,7 +161,7 @@ public virtual void DeleteData(int offset, int count) // specified string. public virtual void ReplaceData(int offset, int count, string? strData) { - int len = _data != null ? _data.Length : 0; + int len = _data is not null ? _data.Length : 0; if (len > 0) { if (len < (offset + count)) @@ -176,12 +176,12 @@ public virtual void ReplaceData(int offset, int count, string? strData) XmlNode? parent = ParentNode; XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); - if (args != null) + if (args is not null) BeforeEvent(args); _data = newValue; - if (args != null) + if (args is not null) AfterEvent(args); } @@ -198,8 +198,8 @@ internal bool DecideXPNodeTypeForTextNodes(XmlNode node, ref XPathNodeType xnt) //nodetype when it returns. XmlNode? n = node; - Debug.Assert(XmlDocument.IsTextNode(n.NodeType) || (n.ParentNode != null && n.ParentNode.NodeType == XmlNodeType.EntityReference)); - while (n != null) + Debug.Assert(XmlDocument.IsTextNode(n.NodeType) || (n.ParentNode is not null && n.ParentNode.NodeType == XmlNodeType.EntityReference)); + while (n is not null) { switch (n.NodeType) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs index fc211c121b1614..1825073f76547f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs @@ -30,12 +30,12 @@ internal bool MoveNext() child = container.FirstChild; isFirst = false; } - else if (child != null) + else if (child is not null) { child = child.NextSibling; } - return child != null; + return child is not null; } void IEnumerator.Reset() @@ -56,7 +56,7 @@ internal XmlNode Current { get { - if (isFirst || child == null) + if (isFirst || child is null) throw new InvalidOperationException(SR.Xml_InvalidOperation); return child; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs index d696646e9540e8..1a255db034f587 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs @@ -20,7 +20,7 @@ public XmlChildNodes(XmlNode container) if (i < 0) return null; - for (XmlNode? n = _container.FirstChild; n != null; n = n.NextSibling, i--) + for (XmlNode? n = _container.FirstChild; n is not null; n = n.NextSibling, i--) { if (i == 0) return n; @@ -34,7 +34,7 @@ public override int Count get { int c = 0; - for (XmlNode? n = _container.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = _container.FirstChild; n is not null; n = n.NextSibling) { c++; } @@ -45,7 +45,7 @@ public override int Count public override IEnumerator GetEnumerator() { - if (_container.FirstChild == null) + if (_container.FirstChild is null) { return XmlDocument.EmptyEnumerator; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs index ae34a6e9fc3125..38c0eaa81563c2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs @@ -34,7 +34,7 @@ public override XmlNodeType NodeType // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateComment(Data); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs index dc21a3fd364b4c..e5c4c06bbc6249 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs @@ -22,7 +22,7 @@ protected internal XmlDeclaration(string version, string? encoding, string? stan { if (!IsValidXmlVersion(version)) throw new ArgumentException(SR.Xdom_Version); - if ((standalone != null) && (standalone.Length > 0)) + if ((standalone is not null) && (standalone.Length > 0)) if ((standalone != YES) && (standalone != NO)) throw new ArgumentException(SR.Format(SR.Xdom_standalone, standalone)); this.Encoding = encoding; @@ -46,7 +46,7 @@ public string Encoding { get { return _encoding; } [MemberNotNull(nameof(_encoding))] - set { _encoding = ((value == null) ? string.Empty : value); } + set { _encoding = ((value is null) ? string.Empty : value); } } // Specifies the value of the standalone attribute. @@ -57,7 +57,7 @@ public string Standalone [MemberNotNull(nameof(_standalone))] set { - if (value == null) + if (value is null) _standalone = string.Empty; else if (value.Length == 0 || value == YES || value == NO) _standalone = value; @@ -112,13 +112,13 @@ public override string InnerText try { - if (tempVersion != null && !IsValidXmlVersion(tempVersion)) + if (tempVersion is not null && !IsValidXmlVersion(tempVersion)) throw new ArgumentException(SR.Xdom_Version); Version = tempVersion!; - if (tempEncoding != null) + if (tempEncoding is not null) Encoding = tempEncoding; - if (tempStandalone != null) + if (tempStandalone is not null) Standalone = tempStandalone; } catch @@ -157,7 +157,7 @@ public override XmlNodeType NodeType // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateXmlDeclaration(Version, Encoding, Standalone); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index 34b22cce873fed..d062a131b210be 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -214,27 +214,27 @@ internal static void CheckName(string name) internal XmlName AddXmlName(string? prefix, string localName, string? namespaceURI, IXmlSchemaInfo? schemaInfo) { XmlName n = _domNameTable.AddName(prefix, localName, namespaceURI, schemaInfo); - Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)); + Debug.Assert((prefix is null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)); Debug.Assert(n.LocalName == localName); - Debug.Assert((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)); + Debug.Assert((namespaceURI is null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)); return n; } internal XmlName? GetXmlName(string? prefix, string localName, string? namespaceURI, IXmlSchemaInfo? schemaInfo) { XmlName? n = _domNameTable.GetName(prefix, localName, namespaceURI, schemaInfo); - Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix))); - Debug.Assert(n == null || n.LocalName == localName); - Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI))); + Debug.Assert(n is null || ((prefix is null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix))); + Debug.Assert(n is null || n.LocalName == localName); + Debug.Assert(n is null || ((namespaceURI is null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI))); return n; } internal XmlName AddAttrXmlName(string? prefix, string localName, string? namespaceURI, IXmlSchemaInfo? schemaInfo) { XmlName xmlName = AddXmlName(prefix, localName, namespaceURI, schemaInfo); - Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix)); + Debug.Assert((prefix is null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix)); Debug.Assert(xmlName.LocalName == localName); - Debug.Assert((namespaceURI == null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI)); + Debug.Assert((namespaceURI is null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI)); if (!this.IsLoading) { @@ -253,9 +253,9 @@ internal bool AddIdInfo(XmlName eleName, XmlName attrName) //when XmlLoader call XmlDocument.AddInfo, the element.XmlName and attr.XmlName //have already been replaced with the ones that don't have namespace values (or just //string.Empty) because in DTD, the namespace is not supported - if (_htElementIDAttrDecl == null || _htElementIDAttrDecl[eleName] == null) + if (_htElementIDAttrDecl is null || _htElementIDAttrDecl[eleName] is null) { - if (_htElementIDAttrDecl == null) + if (_htElementIDAttrDecl is null) _htElementIDAttrDecl = new Hashtable(); _htElementIDAttrDecl.Add(eleName, attrName); return true; @@ -269,7 +269,7 @@ internal bool AddIdInfo(XmlName eleName, XmlName attrName) //we need only compare the prefix and localname of element.XmlName with //the registered htElementIDAttrDecl. XmlName? newName = GetXmlName(eleName.Prefix, eleName.LocalName, string.Empty, null); - if (newName != null) + if (newName is not null) { return (XmlName?)(_htElementIDAttrDecl![newName]); } @@ -278,7 +278,7 @@ internal bool AddIdInfo(XmlName eleName, XmlName attrName) internal XmlName? GetIDInfoByElement(XmlName eleName) { - if (_htElementIDAttrDecl == null) + if (_htElementIDAttrDecl is null) return null; else return GetIDInfoByElement_(eleName); @@ -306,9 +306,9 @@ internal bool AddIdInfo(XmlName eleName, XmlName attrName) internal void AddElementWithId(string id, XmlElement elem) { - if (_htElementIdMap == null || !_htElementIdMap.Contains(id)) + if (_htElementIdMap is null || !_htElementIdMap.Contains(id)) { - if (_htElementIdMap == null) + if (_htElementIdMap is null) _htElementIdMap = new Hashtable(); ArrayList elementList = new ArrayList(); elementList.Add(new WeakReference(elem)); @@ -318,18 +318,18 @@ internal void AddElementWithId(string id, XmlElement elem) { // there are other element(s) that has the same id ArrayList elementList = (ArrayList)(_htElementIdMap[id]!); - if (GetElement(elementList, elem) == null) + if (GetElement(elementList, elem) is null) elementList.Add(new WeakReference(elem)); } } internal void RemoveElementWithId(string id, XmlElement elem) { - if (_htElementIdMap != null && _htElementIdMap.Contains(id)) + if (_htElementIdMap is not null && _htElementIdMap.Contains(id)) { ArrayList elementList = (ArrayList)(_htElementIdMap[id]!); WeakReference? elemRef = GetElement(elementList, elem); - if (elemRef != null) + if (elemRef is not null) { elementList.Remove(elemRef); if (elementList.Count == 0) @@ -425,7 +425,7 @@ public XmlSchemaSet Schemas { get { - if (_schemas == null) + if (_schemas is null) { _schemas = new XmlSchemaSet(NameTable); } @@ -462,7 +462,7 @@ public virtual XmlResolver XmlResolver bSetResolver = true; XmlDocumentType? dtd = this.DocumentType; - if (dtd != null) + if (dtd is not null) { dtd.DtdSchemaInfo = null; } @@ -479,17 +479,17 @@ internal override bool IsValidChildType(XmlNodeType type) return true; case XmlNodeType.DocumentType: - if (DocumentType != null) + if (DocumentType is not null) throw new InvalidOperationException(SR.Xdom_DualDocumentTypeNode); return true; case XmlNodeType.Element: - if (DocumentElement != null) + if (DocumentElement is not null) throw new InvalidOperationException(SR.Xdom_DualDocumentElementNode); return true; case XmlNodeType.XmlDeclaration: - if (Declaration != null) + if (Declaration is not null) throw new InvalidOperationException(SR.Xdom_DualDeclarationNode); return true; @@ -501,13 +501,13 @@ internal override bool IsValidChildType(XmlNodeType type) // if any of the nodes has type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode? refNode) { - if (refNode == null) + if (refNode is null) return false; XmlNode? node = null; - if (refNode.ParentNode != null) + if (refNode.ParentNode is not null) node = refNode.ParentNode.FirstChild; - while (node != null) + while (node is not null) { if (node.NodeType == nt) return true; @@ -523,7 +523,7 @@ private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode? refNode) private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode? refNode) { XmlNode? node = refNode; - while (node != null) + while (node is not null) { if (node.NodeType == nt) return true; @@ -534,10 +534,10 @@ private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode? refNode) internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) { - if (refChild == null) + if (refChild is null) refChild = FirstChild; - if (refChild == null) + if (refChild is null) return true; switch (newChild.NodeType) @@ -577,10 +577,10 @@ internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) { - if (refChild == null) + if (refChild is null) refChild = LastChild; - if (refChild == null) + if (refChild is null) return true; switch (newChild.NodeType) @@ -672,7 +672,7 @@ internal void AddDefaultAttributes(XmlElement elem) { SchemaInfo? schInfo = DtdSchemaInfo; SchemaElementDecl? ed = GetSchemaElementDecl(elem); - if (ed != null && ed.AttDefs != null) + if (ed is not null && ed.AttDefs is not null) { foreach (KeyValuePair attrDefs in ed.AttDefs) { @@ -703,7 +703,7 @@ internal void AddDefaultAttributes(XmlElement elem) private SchemaElementDecl? GetSchemaElementDecl(XmlElement elem) { SchemaInfo? schInfo = DtdSchemaInfo; - if (schInfo != null) + if (schInfo is not null) { //build XmlQualifiedName used to identify the element schema declaration XmlQualifiedName qname = new XmlQualifiedName(elem.LocalName, schInfo.SchemaType == SchemaType.DTD ? elem.Prefix : elem.NamespaceURI); @@ -726,7 +726,7 @@ private XmlAttribute PrepareDefaultAttribute(SchemaAttDef attdef, string attrPre defattr.InnerXml = attdef.DefaultValueRaw; //during the expansion of the tree, the flag could be set to true, we need to set it back. XmlUnspecifiedAttribute? unspAttr = defattr as XmlUnspecifiedAttribute; - if (unspAttr != null) + if (unspAttr is not null) { unspAttr.SetSpecified(false); } @@ -787,7 +787,7 @@ public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string? text case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: parent = node.ParentNode; - if (parent != null) + if (parent is not null) { do { @@ -805,13 +805,13 @@ public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string? text break; } } - while (parent != null); + while (parent is not null); } node = NormalizeText(node)!; break; case XmlNodeType.Whitespace: parent = node.ParentNode; - if (parent != null) + if (parent is not null) { do { @@ -830,7 +830,7 @@ public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string? text break; } } - while (parent != null); + while (parent is not null); } node = NormalizeText(node)!; break; @@ -864,14 +864,14 @@ internal static bool IsTextNode(XmlNodeType nt) retnode = n; n = n.PreviousSibling; - if (n == null) + if (n is null) { XmlNode intnode = retnode; while (true) { - if (intnode.ParentNode != null && intnode.ParentNode.NodeType == XmlNodeType.EntityReference) + if (intnode.ParentNode is not null && intnode.ParentNode.NodeType == XmlNodeType.EntityReference) { - if (intnode.ParentNode.PreviousSibling != null) + if (intnode.ParentNode.PreviousSibling is not null) { n = intnode.ParentNode.PreviousSibling; break; @@ -879,7 +879,7 @@ internal static bool IsTextNode(XmlNodeType nt) else { intnode = intnode.ParentNode; - if (intnode == null) + if (intnode is null) break; } } @@ -888,7 +888,7 @@ internal static bool IsTextNode(XmlNodeType nt) } } - if (n == null) + if (n is null) break; while (n.NodeType == XmlNodeType.EntityReference) @@ -946,15 +946,15 @@ public virtual XmlNodeList GetElementsByTagName(string localName, string namespa // Returns the XmlElement with the specified ID. public virtual XmlElement? GetElementById(string elementId) { - if (_htElementIdMap != null) + if (_htElementIdMap is not null) { ArrayList? elementList = (ArrayList?)(_htElementIdMap[elementId]); - if (elementList != null) + if (elementList is not null) { foreach (WeakReference elemRef in elementList) { XmlElement? elem = (XmlElement?)elemRef.Target; - if (elem != null + if (elem is not null && elem.IsConnected()) return elem; } @@ -971,7 +971,7 @@ public virtual XmlNode ImportNode(XmlNode node, bool deep) private XmlNode ImportNodeInternal(XmlNode node, bool deep) { - if (node == null) + if (node is null) { throw new InvalidOperationException(SR.Xdom_Import_NullNode); } @@ -1055,7 +1055,7 @@ private void ImportAttributes(XmlNode fromElem, XmlNode toElem) private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep) { Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference); - for (XmlNode? n = fromNode.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = fromNode.FirstChild; n is not null; n = n.NextSibling) { toNode.AppendChild(ImportNodeInternal(n, deep)); } @@ -1107,7 +1107,7 @@ internal XmlNamedNodeMap Entities { get { - if (_entities == null) + if (_entities is null) _entities = new XmlNamedNodeMap(this); return _entities; } @@ -1133,13 +1133,13 @@ public virtual XmlNode CreateNode(XmlNodeType type, string? prefix, string name, switch (type) { case XmlNodeType.Element: - if (prefix != null) + if (prefix is not null) return CreateElement(prefix, name, namespaceURI); else return CreateElement(name, namespaceURI); case XmlNodeType.Attribute: - if (prefix != null) + if (prefix is not null) return CreateAttribute(prefix, name, namespaceURI); else return CreateAttribute(name, namespaceURI); @@ -1371,7 +1371,7 @@ internal Encoding? TextEncoding { get { - if (Declaration != null) + if (Declaration is not null) { string value = Declaration.Encoding; if (value.Length > 0) @@ -1408,7 +1408,7 @@ public override string InnerXml //Saves out the to the file with exact content in the XmlDocument. public virtual void Save(string filename) { - if (DocumentElement == null) + if (DocumentElement is null) throw new XmlException(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle); XmlDOMTextWriter xw = new XmlDOMTextWriter(filename, TextEncoding); try @@ -1453,7 +1453,7 @@ public virtual void Save(TextWriter writer) public virtual void Save(XmlWriter w) { XmlNode? n = this.FirstChild; - if (n == null) + if (n is null) return; if (w.WriteState == WriteState.Start) { @@ -1472,7 +1472,7 @@ public virtual void Save(XmlWriter w) w.WriteStartDocument(); } } - while (n != null) + while (n is not null) { n.WriteTo(w); n = n.NextSibling; @@ -1506,7 +1506,7 @@ public void Validate(ValidationEventHandler? validationEventHandler) public void Validate(ValidationEventHandler? validationEventHandler, XmlNode nodeToValidate) { - if (_schemas == null || _schemas.Count == 0) + if (_schemas is null || _schemas.Count == 0) { //Should we error throw new InvalidOperationException(SR.XmlDocument_NoSchemaInfo); } @@ -1606,19 +1606,19 @@ public event XmlNodeChangedEventHandler NodeChanged switch (action) { case XmlNodeChangedAction.Insert: - if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) + if (_onNodeInsertingDelegate is null && _onNodeInsertedDelegate is null) { return null; } break; case XmlNodeChangedAction.Remove: - if (_onNodeRemovingDelegate == null && _onNodeRemovedDelegate == null) + if (_onNodeRemovingDelegate is null && _onNodeRemovedDelegate is null) { return null; } break; case XmlNodeChangedAction.Change: - if (_onNodeChangingDelegate == null && _onNodeChangedDelegate == null) + if (_onNodeChangingDelegate is null && _onNodeChangedDelegate is null) { return null; } @@ -1629,7 +1629,7 @@ public event XmlNodeChangedEventHandler NodeChanged internal XmlNodeChangedEventArgs? GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent) { - if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) + if (_onNodeInsertingDelegate is null && _onNodeInsertedDelegate is null) { return null; } @@ -1639,22 +1639,22 @@ public event XmlNodeChangedEventHandler NodeChanged internal override void BeforeEvent(XmlNodeChangedEventArgs args) { - if (args != null) + if (args is not null) { switch (args.Action) { case XmlNodeChangedAction.Insert: - if (_onNodeInsertingDelegate != null) + if (_onNodeInsertingDelegate is not null) _onNodeInsertingDelegate(this, args); break; case XmlNodeChangedAction.Remove: - if (_onNodeRemovingDelegate != null) + if (_onNodeRemovingDelegate is not null) _onNodeRemovingDelegate(this, args); break; case XmlNodeChangedAction.Change: - if (_onNodeChangingDelegate != null) + if (_onNodeChangingDelegate is not null) _onNodeChangingDelegate(this, args); break; } @@ -1663,22 +1663,22 @@ internal override void BeforeEvent(XmlNodeChangedEventArgs args) internal override void AfterEvent(XmlNodeChangedEventArgs args) { - if (args != null) + if (args is not null) { switch (args.Action) { case XmlNodeChangedAction.Insert: - if (_onNodeInsertedDelegate != null) + if (_onNodeInsertedDelegate is not null) _onNodeInsertedDelegate(this, args); break; case XmlNodeChangedAction.Remove: - if (_onNodeRemovedDelegate != null) + if (_onNodeRemovedDelegate is not null) _onNodeRemovedDelegate(this, args); break; case XmlNodeChangedAction.Change: - if (_onNodeChangedDelegate != null) + if (_onNodeChangedDelegate is not null) _onNodeChangedDelegate(this, args); break; } @@ -1693,7 +1693,7 @@ internal override void AfterEvent(XmlNodeChangedEventArgs args) { SchemaInfo? schInfo = DtdSchemaInfo; SchemaElementDecl? ed = GetSchemaElementDecl(elem); - if (ed != null && ed.AttDefs != null) + if (ed is not null && ed.AttDefs is not null) { foreach (KeyValuePair attrDefs in ed.AttDefs) { @@ -1722,7 +1722,7 @@ internal string? Version get { XmlDeclaration? decl = Declaration; - if (decl != null) + if (decl is not null) return decl.Version; return null; } @@ -1733,7 +1733,7 @@ internal string? Encoding get { XmlDeclaration? decl = Declaration; - if (decl != null) + if (decl is not null) return decl.Encoding; return null; } @@ -1744,7 +1744,7 @@ internal string? Standalone get { XmlDeclaration? decl = Declaration; - if (decl != null) + if (decl is not null) return decl.Standalone; return null; } @@ -1752,10 +1752,10 @@ internal string? Standalone internal XmlEntity? GetEntityNode(string name) { - if (DocumentType != null) + if (DocumentType is not null) { XmlNamedNodeMap entites = DocumentType.Entities; - if (entites != null) + if (entites is not null) return (XmlEntity?)(entites.GetNamedItem(name)); } return null; @@ -1768,7 +1768,7 @@ public override IXmlSchemaInfo SchemaInfo if (_reportValidity) { XmlElement? documentElement = DocumentElement; - if (documentElement != null) + if (documentElement is not null) { switch (documentElement.SchemaInfo.Validity) { @@ -1805,12 +1805,12 @@ internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) XmlNodeChangedEventArgs? args = GetInsertEventArgsForLoad(newChild, this); - if (args != null) + if (args is not null) BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; - if (_lastChild == null) + if (_lastChild is null) { newNode.next = newNode; } @@ -1823,7 +1823,7 @@ internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) _lastChild = newNode; newNode.SetParentForLoad(this); - if (args != null) + if (args is not null) AfterEvent(args); return newNode; @@ -1843,7 +1843,7 @@ internal XmlAttribute NamespaceXml { get { - if (_namespaceXml == null) + if (_namespaceXml is null) { _namespaceXml = new XmlAttribute(AddAttrXmlName(strXmlns, strXml, strReservedXmlns, null), this); _namespaceXml.Value = strReservedXml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs index e0a26aa7d1418a..ecd3bb9193e6a7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs @@ -47,7 +47,7 @@ public class XmlDocumentFragment : XmlNode protected internal XmlDocumentFragment(XmlDocument ownerDocument) : base() { - if (ownerDocument == null) + if (ownerDocument is null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); parentNode = ownerDocument; @@ -106,7 +106,7 @@ public override string InnerXml // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); XmlDocument doc = OwnerDocument; XmlDocumentFragment clone = doc.CreateDocumentFragment(); if (deep) @@ -142,7 +142,7 @@ internal override bool IsValidChildType(XmlNodeType type) case XmlNodeType.XmlDeclaration: //if there is an XmlDeclaration node, it has to be the first node; XmlNode? firstNode = FirstChild; - if (firstNode == null || firstNode.NodeType != XmlNodeType.XmlDeclaration) + if (firstNode is null || firstNode.NodeType != XmlNodeType.XmlDeclaration) return true; else return false; //not allowed to insert a second XmlDeclaration node @@ -152,13 +152,13 @@ internal override bool IsValidChildType(XmlNodeType type) } internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) { - Debug.Assert(newChild != null); //should be checked that newChild is not null before this function call + Debug.Assert(newChild is not null); //should be checked that newChild is not null before this function call if (newChild.NodeType == XmlNodeType.XmlDeclaration) { - if (refChild == null) + if (refChild is null) { //append at the end - return (LastNode == null); + return (LastNode is null); } else return false; @@ -168,10 +168,10 @@ internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) { - Debug.Assert(newChild != null); //should be checked that newChild is not null before this function call + Debug.Assert(newChild is not null); //should be checked that newChild is not null before this function call if (newChild.NodeType == XmlNodeType.XmlDeclaration) { - return (refChild == null || refChild == FirstChild); + return (refChild is null || refChild == FirstChild); } return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs index 4d468eb53ba0fd..e227dc5507bfef 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs @@ -27,7 +27,7 @@ protected internal XmlDocumentType(string name, string? publicId, string? system _systemId = systemId; _namespaces = true; _internalSubset = internalSubset; - Debug.Assert(doc != null); + Debug.Assert(doc is not null); if (!doc.IsLoading) { doc.IsLoading = true; @@ -58,7 +58,7 @@ public override XmlNodeType NodeType // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateDocumentType(_name, _publicId, _systemId, _internalSubset); } @@ -80,7 +80,7 @@ public XmlNamedNodeMap Entities { get { - if (_entities == null) + if (_entities is null) _entities = new XmlNamedNodeMap(this); return _entities; @@ -92,7 +92,7 @@ public XmlNamedNodeMap Notations { get { - if (_notations == null) + if (_notations is null) _notations = new XmlNamedNodeMap(this); return _notations; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs index 15193b42b73c91..dd4bbee5a5b1ad 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs @@ -20,7 +20,7 @@ public class XmlElement : XmlLinkedNode internal XmlElement(XmlName name, bool empty, XmlDocument doc) : base(doc) { - Debug.Assert(name != null); + Debug.Assert(name is not null); this.parentNode = null; if (!doc.IsLoading) { @@ -51,7 +51,7 @@ internal XmlName XmlName // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); XmlDocument doc = OwnerDocument; bool OrigLoadingStatus = doc.IsLoading; doc.IsLoading = true; @@ -66,7 +66,7 @@ public override XmlNode CloneNode(bool deep) { XmlAttribute newAttr = (XmlAttribute)(attr.CloneNode(true)); XmlUnspecifiedAttribute? unspecAttr = newAttr as XmlUnspecifiedAttribute; - if (unspecAttr != null && attr.Specified == false) + if (unspecAttr is not null && attr.Specified == false) { unspecAttr.SetSpecified(false); } @@ -138,14 +138,14 @@ internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); - if (args != null) + if (args is not null) doc.BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; - if (_lastChild == null + if (_lastChild is null || _lastChild == this) - { // if LastNode == null + { // if LastNode is null newNode.next = newNode; _lastChild = newNode; // LastNode = newNode; newNode.SetParentForLoad(this); @@ -167,7 +167,7 @@ internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) } } - if (args != null) + if (args is not null) doc.AfterEvent(args); return newNode; @@ -238,11 +238,11 @@ public override XmlAttributeCollection Attributes { get { - if (_attributes == null) + if (_attributes is null) { lock (OwnerDocument.objLock) { - if (_attributes == null) + if (_attributes is null) { _attributes = new XmlAttributeCollection(this); } @@ -259,7 +259,7 @@ public virtual bool HasAttributes { get { - if (_attributes == null) + if (_attributes is null) return false; else return _attributes.Count > 0; @@ -270,7 +270,7 @@ public virtual bool HasAttributes public virtual string GetAttribute(string name) { XmlAttribute? attr = GetAttributeNode(name); - if (attr != null) + if (attr is not null) return attr.Value; return string.Empty; @@ -281,7 +281,7 @@ public virtual string GetAttribute(string name) public virtual void SetAttribute(string name, string? value) { XmlAttribute? attr = GetAttributeNode(name); - if (attr == null) + if (attr is null) { attr = OwnerDocument.CreateAttribute(name); attr.Value = value; @@ -311,7 +311,7 @@ public virtual void RemoveAttribute(string name) // Adds the specified XmlAttribute. public virtual XmlAttribute? SetAttributeNode(XmlAttribute newAttr) { - if (newAttr.OwnerElement != null) + if (newAttr.OwnerElement is not null) throw new InvalidOperationException(SR.Xdom_Attr_InUse); return (XmlAttribute)Attributes.SetNamedItem(newAttr); @@ -340,7 +340,7 @@ public virtual XmlNodeList GetElementsByTagName(string name) public virtual string GetAttribute(string localName, string? namespaceURI) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); - if (attr != null) + if (attr is not null) return attr.Value; return string.Empty; @@ -352,7 +352,7 @@ public virtual string GetAttribute(string localName, string? namespaceURI) public virtual string? SetAttribute(string localName, string? namespaceURI, string? value) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); - if (attr == null) + if (attr is null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); attr.Value = value; @@ -384,7 +384,7 @@ public virtual void RemoveAttribute(string localName, string? namespaceURI) public virtual XmlAttribute SetAttributeNode(string localName, string? namespaceURI) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); - if (attr == null) + if (attr is null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); Attributes.InternalAppendAttribute(attr); @@ -416,14 +416,14 @@ public virtual XmlNodeList GetElementsByTagName(string localName, string namespa // Determines whether the current node has the specified attribute. public virtual bool HasAttribute(string name) { - return GetAttributeNode(name) != null; + return GetAttributeNode(name) is not null; } // Determines whether the current node has the specified // attribute from the specified namespace. public virtual bool HasAttribute(string localName, string? namespaceURI) { - return GetAttributeNode(localName, namespaceURI) != null; + return GetAttributeNode(localName, namespaceURI) is not null; } // Saves the current node to the specified XmlWriter. @@ -461,7 +461,7 @@ private static void WriteElementTo(XmlWriter writer, XmlElement el) { e = n as XmlElement; // Only use the inlined write logic for XmlElement, not for derived classes - if (e != null && e.GetType() == typeof(XmlElement)) + if (e is not null && e.GetType() == typeof(XmlElement)) { // Write the element e.WriteStartElement(writer); @@ -471,7 +471,7 @@ private static void WriteElementTo(XmlWriter writer, XmlElement el) // No content; use a short end element writer.WriteEndElement(); } - else if (e._lastChild == null) + else if (e._lastChild is null) { // No actual content; use a full end element writer.WriteFullEndElement(); @@ -480,7 +480,7 @@ private static void WriteElementTo(XmlWriter writer, XmlElement el) { // There are child node(s); move to first child n = e.FirstChild; - Debug.Assert(n != null); + Debug.Assert(n is not null); continue; } } @@ -494,7 +494,7 @@ private static void WriteElementTo(XmlWriter writer, XmlElement el) while (n != root && n == n.ParentNode!.LastChild) { n = n.ParentNode; - Debug.Assert(n != null); + Debug.Assert(n is not null); writer.WriteFullEndElement(); } @@ -502,7 +502,7 @@ private static void WriteElementTo(XmlWriter writer, XmlElement el) break; n = n.NextSibling; - Debug.Assert(n != null); + Debug.Assert(n is not null); } } @@ -525,7 +525,7 @@ private void WriteStartElement(XmlWriter w) // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { - for (XmlNode? node = FirstChild; node != null; node = node.NextSibling) + for (XmlNode? node = FirstChild; node is not null; node = node.NextSibling) { node.WriteTo(w); } @@ -599,7 +599,7 @@ public override string InnerText set { XmlLinkedNode? linkedNode = LastNode; - if (linkedNode != null && //there is one child + if (linkedNode is not null && //there is one child linkedNode.NodeType == XmlNodeType.Text && //which is text node linkedNode.next == linkedNode) // and it is the only child { @@ -618,7 +618,7 @@ public override XmlNode? NextSibling { get { - if (this.parentNode != null + if (this.parentNode is not null && this.parentNode.LastNode != this) return next; @@ -641,7 +641,7 @@ internal override string GetXPAttribute(string localName, string ns) return string.Empty; XmlAttribute? attr = GetAttributeNode(localName, ns); - if (attr != null) + if (attr is not null) return attr.Value; return string.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs index 6401227842be55..fcfc83f4384ad8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs @@ -26,10 +26,10 @@ internal class XmlElementList : XmlNodeList private XmlElementList(XmlNode parent) { - Debug.Assert(parent != null); + Debug.Assert(parent is not null); Debug.Assert(parent.NodeType == XmlNodeType.Element || parent.NodeType == XmlNodeType.Document); _rootNode = parent; - Debug.Assert(parent.Document != null); + Debug.Assert(parent.Document is not null); _curInd = -1; _curElem = _rootNode; _changeCount = 0; @@ -69,9 +69,9 @@ internal void ConcurrencyCheck(XmlNodeChangedEventArgs args) internal XmlElementList(XmlNode parent, string name) : this(parent) { - Debug.Assert(parent.Document != null); + Debug.Assert(parent.Document is not null); XmlNameTable nt = parent.Document.NameTable; - Debug.Assert(nt != null); + Debug.Assert(nt is not null); _asterisk = nt.Add("*"); _name = nt.Add(name); _localName = null; @@ -80,13 +80,13 @@ internal XmlElementList(XmlNode parent, string name) : this(parent) internal XmlElementList(XmlNode parent, string localName, string namespaceURI) : this(parent) { - Debug.Assert(parent.Document != null); + Debug.Assert(parent.Document is not null); XmlNameTable nt = parent.Document.NameTable; - Debug.Assert(nt != null); + Debug.Assert(nt is not null); _asterisk = nt.Add("*"); _localName = nt.Get(localName); _namespaceURI = nt.Get(namespaceURI); - if ((_localName == null) || (_namespaceURI == null)) + if ((_localName is null) || (_namespaceURI is null)) { _empty = true; _atomized = false; @@ -105,22 +105,22 @@ internal int ChangeCount // return the next element node that is in PreOrder private XmlNode? NextElemInPreOrder(XmlNode curNode) { - Debug.Assert(curNode != null); + Debug.Assert(curNode is not null); //For preorder walking, first try its child XmlNode? retNode = curNode.FirstChild; - if (retNode == null) + if (retNode is null) { //if no child, the next node forward will the be the NextSibling of the first ancestor which has NextSibling //so, first while-loop find out such an ancestor (until no more ancestor or the ancestor is the rootNode retNode = curNode; - while (retNode != null + while (retNode is not null && retNode != _rootNode - && retNode.NextSibling == null) + && retNode.NextSibling is null) { retNode = retNode.ParentNode; } //then if such ancestor exists, set the retNode to its NextSibling - if (retNode != null && retNode != _rootNode) + if (retNode is not null && retNode != _rootNode) retNode = retNode.NextSibling; } if (retNode == _rootNode) @@ -132,18 +132,18 @@ internal int ChangeCount // return the previous element node that is in PreOrder private XmlNode? PrevElemInPreOrder(XmlNode curNode) { - Debug.Assert(curNode != null); + Debug.Assert(curNode is not null); //For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode XmlNode? retNode = curNode.PreviousSibling; // so if the PreviousSibling is not null, going through the tree down to find the right-most node - while (retNode != null) + while (retNode is not null) { - if (retNode.LastChild == null) + if (retNode.LastChild is null) break; retNode = retNode.LastChild; } // if no PreviousSibling, the previous node will be the curNode's parentNode - if (retNode == null) + if (retNode is null) retNode = curNode.ParentNode; // if the final retNode is rootNode, consider having walked through the tree and no more previous node if (retNode == _rootNode) @@ -156,7 +156,7 @@ private bool IsMatch(XmlNode curNode) { if (curNode.NodeType == XmlNodeType.Element) { - if (_name != null) + if (_name is not null) { if (Ref.Equal(_name, _asterisk) || Ref.Equal(curNode.Name, _name)) return true; @@ -177,7 +177,7 @@ private bool IsMatch(XmlNode curNode) private XmlNode? GetMatchingNode(XmlNode n, bool bNext) { - Debug.Assert(n != null); + Debug.Assert(n is not null); XmlNode? node = n; do { @@ -185,18 +185,18 @@ private bool IsMatch(XmlNode curNode) node = NextElemInPreOrder(node); else node = PrevElemInPreOrder(node); - } while (node != null && !IsMatch(node)); + } while (node is not null && !IsMatch(node)); return node; } private XmlNode? GetNthMatchingNode(XmlNode n, bool bNext, int nCount) { - Debug.Assert(n != null); + Debug.Assert(n is not null); XmlNode? node = n; for (int ind = 0; ind < nCount; ind++) { node = GetMatchingNode(node, bNext); - if (node == null) + if (node is null) return null; } @@ -208,13 +208,13 @@ private bool IsMatch(XmlNode curNode) { if (_empty == true) return null; - XmlNode node = (n == null) ? _rootNode : n; + XmlNode node = (n is null) ? _rootNode : n; return GetMatchingNode(node, true); } public override XmlNode? Item(int index) { - if (_rootNode == null || index < 0) + if (_rootNode is null || index < 0) return null; if (_empty == true) @@ -227,7 +227,7 @@ private bool IsMatch(XmlNode curNode) nDiff = -nDiff; XmlNode? node; - if ((node = GetNthMatchingNode(_curElem, bForward, nDiff)) != null) + if ((node = GetNthMatchingNode(_curElem, bForward, nDiff)) is not null) { _curInd = index; _curElem = node; @@ -282,10 +282,10 @@ protected override void PrivateDisposeNodeList() protected virtual void Dispose(bool disposing) { - if (_listener != null) + if (_listener is not null) { XmlElementListListener? listener = (XmlElementListListener?)_listener.Target; - if (listener != null) + if (listener is not null) { listener.Unregister(); } @@ -319,7 +319,7 @@ public bool MoveNext() { _curElem = _list.GetNextNode(_curElem); } - return _curElem != null; + return _curElem is not null; } public void Reset() @@ -375,10 +375,10 @@ private void OnListChanged(object sender, XmlNodeChangedEventArgs args) { lock (this) { - if (_elemList != null) + if (_elemList is not null) { XmlElementList? el = (XmlElementList?)_elemList.Target; - if (null != el) + if (el is not null) { el.ConcurrencyCheck(args); } @@ -397,7 +397,7 @@ internal void Unregister() { lock (this) { - if (_elemList != null) + if (_elemList is not null) { _doc.NodeInserted -= _nodeChangeHandler; _doc.NodeRemoved -= _nodeChangeHandler; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs index 88a405193b0226..bc896ce7181066 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs @@ -75,7 +75,7 @@ internal override XmlLinkedNode? LastNode { get { - if (_lastChild == null && !_childrenFoliating) + if (_lastChild is null && !_childrenFoliating) { //expand the unparsedreplacementstring _childrenFoliating = true; //wrap the replacement string with an element diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs index 150e85f165903f..327034ed84cf34 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs @@ -81,7 +81,7 @@ public override XmlNodeType NodeType // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); XmlEntityReference eref = OwnerDocument.CreateEntityReference(_name); return eref; } @@ -107,7 +107,7 @@ internal override bool IsContainer internal override void SetParent(XmlNode? node) { base.SetParent(node); - if (LastNode == null && node != null && node != OwnerDocument) + if (LastNode is null && node is not null && node != OwnerDocument) { //first time insert the entity reference into the tree, we should expand its children now XmlLoader loader = new XmlLoader(); @@ -181,7 +181,7 @@ public override string BaseURI private string ConstructBaseURI(string baseURI, string systemId) { - if (baseURI == null) + if (baseURI is null) return systemId; int nCount = baseURI.LastIndexOf('/') + 1; string buf = baseURI; @@ -199,7 +199,7 @@ internal string ChildBaseURI { //get the associate entity and return its baseUri XmlEntity? ent = OwnerDocument!.GetEntityNode(_name); - if (ent != null) + if (ent is not null) { if (!string.IsNullOrEmpty(ent.SystemId)) return ConstructBaseURI(ent.BaseURI, ent.SystemId); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs index 395c4ef29bb879..003350a18522a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs @@ -24,7 +24,7 @@ public bool HasFeature(string strFeature, string strVersion) { if (string.Equals("XML", strFeature, StringComparison.OrdinalIgnoreCase)) { - if (strVersion == null || strVersion == "1.0" || strVersion == "2.0") + if (strVersion is null || strVersion == "1.0" || strVersion == "2.0") return true; } return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs index 41a7e41401a544..94493a8597d05b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs @@ -19,10 +19,10 @@ public override XmlNode? PreviousSibling get { XmlNode? parent = ParentNode; - if (parent != null) + if (parent is not null) { XmlNode? node = parent.FirstChild; - while (node != null) + while (node is not null) { XmlNode? nextSibling = node.NextSibling; if (nextSibling == this) @@ -46,7 +46,7 @@ public override XmlNode? NextSibling get { XmlNode? parent = ParentNode; - if (parent != null) + if (parent is not null) { if (next != parent.FirstChild) return next; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs index 75145a14e671d8..988241673d48c3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs @@ -33,12 +33,12 @@ internal void Load(XmlDocument doc, XmlReader reader, bool preserveWhitespace) _reader = reader; } _preserveWhitespace = preserveWhitespace; - if (doc == null) + if (doc is null) throw new ArgumentException(SR.Xdom_Load_NoDocument); - if (reader == null) + if (reader is null) throw new ArgumentException(SR.Xdom_Load_NoReader); doc.SetBaseURI(reader.BaseURI!); - if (reader.Settings != null + if (reader.Settings is not null && reader.Settings.ValidationType == ValidationType.Schema) { doc.Schemas = reader.Settings.Schemas; @@ -54,10 +54,10 @@ internal void Load(XmlDocument doc, XmlReader reader, bool preserveWhitespace) //The function will start loading the document from where current XmlReader is pointing at. private void LoadDocSequence(XmlDocument parentDoc) { - Debug.Assert(_reader != null); - Debug.Assert(parentDoc != null); + Debug.Assert(_reader is not null); + Debug.Assert(parentDoc is not null); XmlNode? node = null; - while ((node = LoadNode(true)) != null) + while ((node = LoadNode(true)) is not null) { parentDoc.AppendChildForLoad(node, parentDoc); if (!_reader.Read()) @@ -71,9 +71,9 @@ private void LoadDocSequence(XmlDocument parentDoc) _reader = reader; // WS are optional only for loading (see XmlDocument.PreserveWhitespace) _preserveWhitespace = true; - if (doc == null) + if (doc is null) throw new ArgumentException(SR.Xdom_Load_NoDocument); - if (reader == null) + if (reader is null) throw new ArgumentException(SR.Xdom_Load_NoReader); if (reader.ReadState == ReadState.Initial) @@ -125,7 +125,7 @@ private void LoadDocSequence(XmlDocument parentDoc) // recursively load all children. if (!fEmptyElement) { - if (parent != null) + if (parent is not null) { parent.AppendChildForLoad(element, _doc); } @@ -135,7 +135,7 @@ private void LoadDocSequence(XmlDocument parentDoc) else { schemaInfo = r.SchemaInfo; - if (schemaInfo != null) + if (schemaInfo is not null) { element.XmlName = _doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); } @@ -144,21 +144,21 @@ private void LoadDocSequence(XmlDocument parentDoc) } case XmlNodeType.EndElement: - if (parent == null) + if (parent is null) { return null; } Debug.Assert(parent.NodeType == XmlNodeType.Element); schemaInfo = r.SchemaInfo; - if (schemaInfo != null) + if (schemaInfo is not null) { element = parent as XmlElement; - if (element != null) + if (element is not null) { element.XmlName = _doc!.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); } } - if (parent.ParentNode == null) + if (parent.ParentNode is null) { return parent; } @@ -170,7 +170,7 @@ private void LoadDocSequence(XmlDocument parentDoc) break; case XmlNodeType.EndEntity: - Debug.Assert(parent == null); + Debug.Assert(parent is null); return null; case XmlNodeType.Attribute: @@ -191,7 +191,7 @@ private void LoadDocSequence(XmlDocument parentDoc) node = _doc!.CreateWhitespace(r.Value); break; } - else if (parent == null && !skipOverWhitespace) + else if (parent is null && !skipOverWhitespace) { // if called from LoadEntityReferenceNode, just return null return null; @@ -225,8 +225,8 @@ private void LoadDocSequence(XmlDocument parentDoc) throw UnexpectedNodeType(r.NodeType); } - Debug.Assert(node != null); - if (parent != null) + Debug.Assert(node is not null); + if (parent is not null) { parent.AppendChildForLoad(node, _doc!); } @@ -238,9 +238,9 @@ private void LoadDocSequence(XmlDocument parentDoc) while (r.Read()); // when the reader ended before full subtree is read, return whatever we have created so far - if (parent != null) + if (parent is not null) { - while (parent.ParentNode != null) + while (parent.ParentNode is not null) { parent = parent.ParentNode; } @@ -261,7 +261,7 @@ private XmlAttribute LoadAttributeNode() XmlAttribute attr = _doc!.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); IXmlSchemaInfo? schemaInfo = r.SchemaInfo; - if (schemaInfo != null) + if (schemaInfo is not null) { attr.XmlName = _doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo); } @@ -282,7 +282,7 @@ private XmlAttribute LoadAttributeNode() LoadAttributeValue(node, false); // Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true, // if the reader does not present any children for the ent-ref - if (node.FirstChild == null) + if (node.FirstChild is null) { node.AppendChildForLoad(_doc.CreateTextNode(string.Empty), _doc); } @@ -292,7 +292,7 @@ private XmlAttribute LoadAttributeNode() throw UnexpectedNodeType(r.NodeType); } - Debug.Assert(node != null); + Debug.Assert(node is not null); attr.AppendChildForLoad(node, _doc); } @@ -306,7 +306,7 @@ private XmlAttribute LoadDefaultAttribute() XmlReader r = _reader; XmlAttribute attr = _doc!.CreateDefaultAttribute(r.Prefix, r.LocalName, r.NamespaceURI); IXmlSchemaInfo? schemaInfo = r.SchemaInfo; - if (schemaInfo != null) + if (schemaInfo is not null) { attr.XmlName = _doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo); } @@ -315,7 +315,7 @@ private XmlAttribute LoadDefaultAttribute() XmlUnspecifiedAttribute? defAttr = attr as XmlUnspecifiedAttribute; // If user overrides CreateDefaultAttribute, then attr will NOT be a XmlUnspecifiedAttribute instance. - if (defAttr != null) + if (defAttr is not null) defAttr.SetSpecified(false); return attr; @@ -342,7 +342,7 @@ private void LoadAttributeValue(XmlNode parent, bool direct) LoadAttributeValue(node, direct); // Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true, // if the reader does not present any children for the ent-ref - if (node.FirstChild == null) + if (node.FirstChild is null) { node.AppendChildForLoad(direct ? new XmlText(string.Empty) : _doc!.CreateTextNode(string.Empty), _doc!); } @@ -351,7 +351,7 @@ private void LoadAttributeValue(XmlNode parent, bool direct) default: throw UnexpectedNodeType(r.NodeType); } - Debug.Assert(node != null); + Debug.Assert(node is not null); parent.AppendChildForLoad(node, _doc!); } return; @@ -367,14 +367,14 @@ private XmlEntityReference LoadEntityReferenceNode(bool direct) while (_reader.Read() && _reader.NodeType != XmlNodeType.EndEntity) { XmlNode? node = direct ? LoadNodeDirect() : LoadNode(false); - if (node != null) + if (node is not null) { eref.AppendChildForLoad(node, _doc!); } } // Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true, // if the reader does not present any children for the ent-ref - if (eref.LastChild == null) + if (eref.LastChild is null) eref.AppendChildForLoad(_doc!.CreateTextNode(string.Empty), _doc); } return eref; @@ -412,7 +412,7 @@ private XmlDeclaration LoadDeclarationNode() // For readers that do not break xml decl into attributes, we must parse the xml decl ourselves. We use version attr, b/c xml decl MUST contain // at least version attr, so if the reader implements them as attr, then version must be present - if (version == null) + if (version is null) ParseXmlDeclarationValue(_reader.Value, out version, out encoding, out standalone); return _doc!.CreateXmlDeclaration(version!, encoding, standalone); @@ -442,7 +442,7 @@ private XmlDocumentType LoadDocumentTypeNode() XmlDocumentType dtNode = _doc!.CreateDocumentType(localName, publicId, systemId, internalSubset); IDtdInfo? dtdInfo = _reader.DtdInfo; - if (dtdInfo != null) + if (dtdInfo is not null) LoadDocumentType(dtdInfo, dtNode); else { @@ -496,7 +496,7 @@ private XmlDocumentType LoadDocumentTypeNode() case XmlNodeType.EndElement: Debug.Assert(parent!.NodeType == XmlNodeType.Element); - if (parent.ParentNode == null) + if (parent.ParentNode is null) { return parent; } @@ -550,8 +550,8 @@ private XmlDocumentType LoadDocumentTypeNode() throw UnexpectedNodeType(_reader!.NodeType); } - Debug.Assert(node != null); - if (parent != null) + Debug.Assert(node is not null); + if (parent is not null) { parent.AppendChildForLoad(node, _doc!); } @@ -615,19 +615,19 @@ private void ParseDocumentType(XmlDocumentType dtNode, bool bUseResolver, XmlRes private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) { SchemaInfo? schInfo = dtdInfo as SchemaInfo; - if (schInfo == null) + if (schInfo is null) { throw new XmlException(SR.Xml_InternalError, string.Empty); } dtNode.DtdSchemaInfo = schInfo; - if (schInfo != null) + if (schInfo is not null) { //set the schema information into the document _doc!.DtdSchemaInfo = schInfo; // Notation hashtable - if (schInfo.Notations != null) + if (schInfo.Notations is not null) { foreach (SchemaNotation scNot in schInfo.Notations.Values) { @@ -636,7 +636,7 @@ private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) } // Entity hashtables - if (schInfo.GeneralEntities != null) + if (schInfo.GeneralEntities is not null) { foreach (SchemaEntity scEnt in schInfo.GeneralEntities.Values) { @@ -646,7 +646,7 @@ private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) } } - if (schInfo.ParameterEntities != null) + if (schInfo.ParameterEntities is not null) { foreach (SchemaEntity scEnt in schInfo.ParameterEntities.Values) { @@ -661,7 +661,7 @@ private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) foreach (KeyValuePair elementDecls in schInfo.ElementDecls) { SchemaElementDecl elementDecl = elementDecls.Value; - if (elementDecl.AttDefs != null) + if (elementDecl.AttDefs is not null) { foreach (KeyValuePair attDefs in elementDecl.AttDefs) { @@ -694,10 +694,10 @@ private XmlParserContext GetContext(XmlNode? node) bool bHasDefXmlnsAttr = false; // Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes - while (node != null && node != _doc) + while (node is not null && node != _doc) { XmlElement? element = node as XmlElement; - if (element != null && element.HasAttributes) + if (element is not null && element.HasAttributes) { mgr.PushScope(); foreach (XmlAttribute attr in element.Attributes) @@ -722,7 +722,7 @@ private XmlParserContext GetContext(XmlNode? node) else if (attr.Value == "preserve") spaceMode = XmlSpace.Preserve; } - else if (lang == null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang) + else if (lang is null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang) { // Save xml:lag context lang = attr.Value; @@ -735,10 +735,10 @@ private XmlParserContext GetContext(XmlNode? node) return new XmlParserContext( nt, mgr, - (docType == null) ? null : docType.Name, - (docType == null) ? null : docType.PublicId, - (docType == null) ? null : docType.SystemId, - (docType == null) ? null : docType.InternalSubset, + (docType is null) ? null : docType.Name, + (docType is null) ? null : docType.PublicId, + (docType is null) ? null : docType.SystemId, + (docType is null) ? null : docType.InternalSubset, baseURI, lang, spaceMode @@ -752,7 +752,7 @@ internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string inne //the function shouldn't be used to set innerxml for XmlDocument node Debug.Assert(parentNode.NodeType != XmlNodeType.Document); _doc = parentNode.OwnerDocument; - Debug.Assert(_doc != null); + Debug.Assert(_doc is not null); XmlParserContext pc = GetContext(parentNode); _reader = CreateInnerXmlReader(innerxmltext, nt, pc, _doc); try @@ -764,7 +764,7 @@ internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string inne if (nt == XmlNodeType.Entity) { XmlNode? node = null; - while (_reader.Read() && (node = LoadNodeDirect()) != null) + while (_reader.Read() && (node = LoadNodeDirect()) is not null) { parentNode.AppendChildForLoad(node, _doc); } @@ -772,7 +772,7 @@ internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string inne else { XmlNode? node = null; - while (_reader.Read() && (node = LoadNode(true)) != null) + while (_reader.Read() && (node = LoadNode(true)) is not null) { parentNode.AppendChildForLoad(node, _doc); } @@ -817,7 +817,7 @@ private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, if (attr.Prefix == _doc!.strXmlns) { string? nsUri = mgr.LookupNamespace(attr.LocalName); - if (nsUri != null) + if (nsUri is not null) { if (attr.Value == nsUri) elem.Attributes.RemoveNodeAt(i); @@ -834,7 +834,7 @@ private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, else if (attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns) { string nsUri = mgr.DefaultNamespace; - if (nsUri != null) + if (nsUri is not null) { if (attr.Value == nsUri) elem.Attributes.RemoveNodeAt(i); @@ -852,10 +852,10 @@ private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, } //now recursively remove the duplicate attributes on the children XmlNode? child = elem.FirstChild; - while (child != null) + while (child is not null) { XmlElement? childElem = child as XmlElement; - if (childElem != null) + if (childElem is not null) RemoveDuplicateNamespace(childElem, mgr, true); child = child.NextSibling; } @@ -948,10 +948,10 @@ private XmlReader CreateInnerXmlReader(string xmlFragment, XmlNodeType nt, XmlPa Debug.Assert(tr.EntityHandling == EntityHandling.ExpandCharEntities); XmlDocumentType? dtdNode = doc.DocumentType; - if (dtdNode != null) + if (dtdNode is not null) { tr.Namespaces = dtdNode.ParseWithNamespaces; - if (dtdNode.DtdSchemaInfo != null) + if (dtdNode.DtdSchemaInfo is not null) { tr.SetDtdInfo(dtdNode.DtdSchemaInfo); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs index 0cd270a420d8d2..f4e4339b255825 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs @@ -19,7 +19,7 @@ internal class XmlName : IXmlSchemaInfo public static XmlName Create(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo? schemaInfo) { - if (schemaInfo == null) + if (schemaInfo is null) { return new XmlName(prefix, localName, ns, hashCode, ownerDoc, next); } @@ -84,9 +84,9 @@ public string Name { get { - if (_name == null) + if (_name is null) { - Debug.Assert(_prefix != null); + Debug.Assert(_prefix is not null); if (_prefix.Length > 0) { if (_localName.Length > 0) @@ -94,7 +94,7 @@ public string Name string n = string.Concat(_prefix, ":", _localName); lock (ownerDoc.NameTable) { - if (_name == null) + if (_name is null) { _name = ownerDoc.NameTable.Add(n); } @@ -173,13 +173,13 @@ public virtual XmlSchemaAttribute? SchemaAttribute public virtual bool Equals(IXmlSchemaInfo? schemaInfo) { - return schemaInfo == null; + return schemaInfo is null; } public static int GetHashCode(string name) { int hashCode = 0; - if (name != null) + if (name is not null) { return string.GetHashCode(name.AsSpan(name.LastIndexOf(':') + 1)); } @@ -209,7 +209,7 @@ internal XmlNameEx(string prefix, string localName, string ns, int hashCode, Xml SetIsNil(schemaInfo.IsNil); _memberType = schemaInfo.MemberType; _schemaType = schemaInfo.SchemaType; - _decl = schemaInfo.SchemaElement != null + _decl = schemaInfo.SchemaElement is not null ? (object)schemaInfo.SchemaElement : (object?)schemaInfo.SchemaAttribute; } @@ -289,7 +289,7 @@ public void SetIsNil(bool value) public override bool Equals(IXmlSchemaInfo? schemaInfo) { - if (schemaInfo != null + if (schemaInfo is not null && schemaInfo.Validity == (XmlSchemaValidity)(_flags & ValidityMask) && schemaInfo.IsDefault == ((_flags & IsDefaultBit) != 0) && schemaInfo.IsNil == ((_flags & IsNilBit) != 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs index cb217eb5b6c22b..3b3b27d2657fb5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs @@ -23,11 +23,11 @@ public int Count { get { - if (_field == null) + if (_field is null) return 0; List? list = _field as List; - if (list != null) + if (list is not null) return list.Count; return 1; @@ -38,11 +38,11 @@ public object this[int index] { get { - if (_field == null) + if (_field is null) throw new ArgumentOutOfRangeException(nameof(index)); List? list = _field as List; - if (list != null) + if (list is not null) return list[index]; if (index != 0) @@ -54,9 +54,9 @@ public object this[int index] public void Add(object value) { - if (_field == null) + if (_field is null) { - if (value == null) + if (value is null) { Debug.Fail("Null was added to the collection which didn't expect it"); // If a single null value needs to be stored, then @@ -72,7 +72,7 @@ public void Add(object value) } List? list = _field as List; - if (list != null) + if (list is not null) { list.Add(value); } @@ -87,11 +87,11 @@ public void Add(object value) public void RemoveAt(int index) { - if (_field == null) + if (_field is null) throw new ArgumentOutOfRangeException(nameof(index)); List? list = _field as List; - if (list != null) + if (list is not null) { list.RemoveAt(index); return; @@ -105,7 +105,7 @@ public void RemoveAt(int index) public void Insert(int index, object value) { - if (_field == null) + if (_field is null) { if (index != 0) throw new ArgumentOutOfRangeException(nameof(index)); @@ -114,7 +114,7 @@ public void Insert(int index, object value) } List? list = _field as List; - if (list != null) + if (list is not null) { list.Insert(index, value); return; @@ -183,13 +183,13 @@ public void Reset() public IEnumerator GetEnumerator() { - if (_field == null) + if (_field is null) { return XmlDocument.EmptyEnumerator; } List? list = _field as List; - if (list != null) + if (list is not null) { return list.GetEnumerator(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs index bfaf118ea670b4..7ba16853a2c9fc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs @@ -29,7 +29,7 @@ internal XmlNamedNodeMap(XmlNode parent) // Adds a XmlNode using its Name property public virtual XmlNode? SetNamedItem(XmlNode? node) { - if (node == null) + if (node is null) return null; int offset = FindNodeOffset(node.LocalName, node.NamespaceURI); @@ -150,13 +150,13 @@ internal virtual XmlNode AddNode(XmlNode node) string? nodeValue = node.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); - if (args != null) + if (args is not null) parent.BeforeEvent(args); nodes.Add(node); node.SetParent(parent); - if (args != null) + if (args is not null) parent.AfterEvent(args); return node; @@ -165,14 +165,14 @@ internal virtual XmlNode AddNode(XmlNode node) internal virtual XmlNode AddNodeForLoad(XmlNode node, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(node, parent); - if (args != null) + if (args is not null) { doc.BeforeEvent(args); } nodes.Add(node); node.SetParent(parent); - if (args != null) + if (args is not null) { doc.AfterEvent(args); } @@ -187,13 +187,13 @@ internal virtual XmlNode RemoveNodeAt(int i) string? oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(oldNode, parent, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); - if (args != null) + if (args is not null) parent.BeforeEvent(args); nodes.RemoveAt(i); oldNode.SetParent(null); - if (args != null) + if (args is not null) parent.AfterEvent(args); return oldNode; @@ -217,13 +217,13 @@ internal virtual XmlNode InsertNodeAt(int i, XmlNode node) string? nodeValue = node.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); - if (args != null) + if (args is not null) parent.BeforeEvent(args); nodes.Insert(i, node); node.SetParent(parent); - if (args != null) + if (args is not null) parent.AfterEvent(args); return node; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index f1ccbfc0273228..8c0be12a1b6129 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -26,7 +26,7 @@ internal XmlNode() internal XmlNode(XmlDocument doc) { - if (doc == null) + if (doc is null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); this.parentNode = doc; @@ -35,13 +35,13 @@ internal XmlNode(XmlDocument doc) public virtual XPathNavigator? CreateNavigator() { XmlDocument? thisAsDoc = this as XmlDocument; - if (thisAsDoc != null) + if (thisAsDoc is not null) { return thisAsDoc.CreateNavigator(this); } XmlDocument? doc = OwnerDocument; - Debug.Assert(doc != null); + Debug.Assert(doc is not null); return doc.CreateNavigator(this); } @@ -50,7 +50,7 @@ internal XmlNode(XmlDocument doc) { XmlNodeList? list = SelectNodes(xpath); // SelectNodes returns null for certain node types - return list != null ? list[0] : null; + return list is not null ? list[0] : null; } // Selects the first node that matches the xpath expression and given namespace context. @@ -59,7 +59,7 @@ internal XmlNode(XmlDocument doc) XPathNavigator? xn = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. - if (xn == null) + if (xn is null) return null; XPathExpression exp = xn.Compile(xpath); @@ -73,7 +73,7 @@ internal XmlNode(XmlDocument doc) XPathNavigator? n = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. - if (n == null) + if (n is null) return null; return new XPathNodeList(n.Select(xpath)); @@ -85,7 +85,7 @@ internal XmlNode(XmlDocument doc) XPathNavigator? xn = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. - if (xn == null) + if (xn is null) return null; XPathExpression exp = xn.Compile(xpath); @@ -117,7 +117,7 @@ public virtual XmlNode? ParentNode { get { - Debug.Assert(parentNode != null); + Debug.Assert(parentNode is not null); if (parentNode.NodeType != XmlNodeType.Document) { @@ -126,7 +126,7 @@ public virtual XmlNode? ParentNode // Linear lookup through the children of the document XmlLinkedNode? firstChild = parentNode.FirstChild as XmlLinkedNode; - if (firstChild != null) + if (firstChild is not null) { XmlLinkedNode? node = firstChild; do @@ -138,7 +138,7 @@ public virtual XmlNode? ParentNode node = node.next; } - while (node != null + while (node is not null && node != firstChild); } @@ -176,7 +176,7 @@ public virtual XmlDocument? OwnerDocument { get { - Debug.Assert(parentNode != null); + Debug.Assert(parentNode is not null); if (parentNode.NodeType == XmlNodeType.Document) return (XmlDocument)parentNode; return parentNode.OwnerDocument; @@ -189,7 +189,7 @@ public virtual XmlNode? FirstChild get { XmlLinkedNode? linkedNode = LastNode; - if (linkedNode != null) + if (linkedNode is not null) return linkedNode.next; return null; @@ -217,7 +217,7 @@ internal bool AncestorNode(XmlNode node) { XmlNode? n = this.ParentNode; - while (n != null && n != this) + while (n is not null && n != this) { if (n == node) return true; @@ -231,9 +231,9 @@ internal bool AncestorNode(XmlNode node) internal bool IsConnected() { XmlNode? parent = ParentNode; - while (parent != null && !(parent.NodeType == XmlNodeType.Document)) + while (parent is not null && !(parent.NodeType == XmlNodeType.Document)) parent = parent.ParentNode; - return parent != null; + return parent is not null; } // Inserts the specified node immediately before the specified reference node. @@ -242,7 +242,7 @@ internal bool IsConnected() if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); - if (refChild == null) + if (refChild is null) return AppendChild(newChild); if (!IsContainer) @@ -256,13 +256,13 @@ internal bool IsConnected() XmlDocument? childDoc = newChild.OwnerDocument; XmlDocument? thisDoc = OwnerDocument; - if (childDoc != null && childDoc != thisDoc && childDoc != this) + if (childDoc is not null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertBefore(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); - if (newChild.ParentNode != null) + if (newChild.ParentNode is not null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. @@ -270,7 +270,7 @@ internal bool IsConnected() { XmlNode? first = newChild.FirstChild; XmlNode? node = first; - if (node != null) + if (node is not null) { newChild.RemoveChild(node); InsertBefore(node, refChild); @@ -290,7 +290,7 @@ internal bool IsConnected() string? newChildValue = newChild.Value; XmlNodeChangedEventArgs? args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); - if (args != null) + if (args is not null) BeforeEvent(args); if (refNode == FirstChild) @@ -345,7 +345,7 @@ internal bool IsConnected() } } - if (args != null) + if (args is not null) AfterEvent(args); return newNode; @@ -357,7 +357,7 @@ internal bool IsConnected() if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); - if (refChild == null) + if (refChild is null) return PrependChild(newChild); if (!IsContainer) @@ -371,13 +371,13 @@ internal bool IsConnected() XmlDocument? childDoc = newChild.OwnerDocument; XmlDocument? thisDoc = OwnerDocument; - if (childDoc != null && childDoc != thisDoc && childDoc != this) + if (childDoc is not null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertAfter(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); - if (newChild.ParentNode != null) + if (newChild.ParentNode is not null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. @@ -386,7 +386,7 @@ internal bool IsConnected() XmlNode last = refChild; XmlNode? first = newChild.FirstChild; XmlNode? node = first; - while (node != null) + while (node is not null) { XmlNode? next = node.NextSibling; newChild.RemoveChild(node); @@ -406,7 +406,7 @@ internal bool IsConnected() string? newChildValue = newChild.Value; XmlNodeChangedEventArgs? args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); - if (args != null) + if (args is not null) BeforeEvent(args); if (refNode == LastNode) @@ -463,7 +463,7 @@ internal bool IsConnected() } - if (args != null) + if (args is not null) AfterEvent(args); return newNode; @@ -492,7 +492,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) string? oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs? args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); - if (args != null) + if (args is not null) BeforeEvent(args); XmlLinkedNode? lastNode = LastNode; @@ -558,7 +558,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) } } - if (args != null) + if (args is not null) AfterEvent(args); return oldChild; @@ -574,7 +574,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) public virtual XmlNode? AppendChild(XmlNode newChild) { XmlDocument? thisDoc = OwnerDocument; - if (thisDoc == null) + if (thisDoc is null) { thisDoc = this as XmlDocument; } @@ -584,11 +584,11 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); - if (newChild.ParentNode != null) + if (newChild.ParentNode is not null) newChild.ParentNode.RemoveChild(newChild); XmlDocument? childDoc = newChild.OwnerDocument; - if (childDoc != null && childDoc != thisDoc && childDoc != this) + if (childDoc is not null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); // special case for doc-fragment. @@ -596,7 +596,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) { XmlNode? first = newChild.FirstChild; XmlNode? node = first; - while (node != null) + while (node is not null) { XmlNode? next = node.NextSibling; newChild.RemoveChild(node); @@ -617,13 +617,13 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) string? newChildValue = newChild.Value; XmlNodeChangedEventArgs? args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); - if (args != null) + if (args is not null) BeforeEvent(args); XmlLinkedNode? refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; - if (refNode == null) + if (refNode is null) { newNode.next = newNode; LastNode = newNode; @@ -645,7 +645,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) } } - if (args != null) + if (args is not null) AfterEvent(args); return newNode; @@ -656,13 +656,13 @@ internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); - if (args != null) + if (args is not null) doc.BeforeEvent(args); XmlLinkedNode? refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; - if (refNode == null) + if (refNode is null) { newNode.next = newNode; LastNode = newNode; @@ -684,7 +684,7 @@ internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) } } - if (args != null) + if (args is not null) doc.AfterEvent(args); return newNode; @@ -708,7 +708,7 @@ internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) // Gets a value indicating whether this node has any child nodes. public virtual bool HasChildNodes { - get { return LastNode != null; } + get { return LastNode is not null; } } // Creates a duplicate of this node. @@ -716,7 +716,7 @@ public virtual bool HasChildNodes internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep) { - for (XmlNode? child = container.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = container.FirstChild; child is not null; child = child.NextSibling) { AppendChildForLoad(child.CloneNode(deep), doc); } @@ -733,7 +733,7 @@ public virtual void Normalize() { XmlNode? firstChildTextLikeNode = null; StringBuilder sb = StringBuilderCache.Acquire(); - for (XmlNode? crtChild = this.FirstChild; crtChild != null;) + for (XmlNode? crtChild = this.FirstChild; crtChild is not null;) { XmlNode? nextChild = crtChild.NextSibling; switch (crtChild.NodeType) @@ -750,7 +750,7 @@ public virtual void Normalize() } else { - if (firstChildTextLikeNode != null) + if (firstChildTextLikeNode is not null) this.RemoveChild(firstChildTextLikeNode); firstChildTextLikeNode = crtChild; } @@ -764,7 +764,7 @@ public virtual void Normalize() } default: { - if (firstChildTextLikeNode != null) + if (firstChildTextLikeNode is not null) { firstChildTextLikeNode.Value = sb.ToString(); firstChildTextLikeNode = null; @@ -776,7 +776,7 @@ public virtual void Normalize() } crtChild = nextChild; } - if (firstChildTextLikeNode != null && sb.Length > 0) + if (firstChildTextLikeNode is not null && sb.Length > 0) firstChildTextLikeNode.Value = sb.ToString(); StringBuilderCache.Release(sb); @@ -785,7 +785,7 @@ public virtual void Normalize() private XmlNode? NormalizeWinner(XmlNode? firstNode, XmlNode secondNode) { //first node has the priority - if (firstNode == null) + if (firstNode is null) return secondNode; Debug.Assert(firstNode.NodeType == XmlNodeType.Text || firstNode.NodeType == XmlNodeType.SignificantWhitespace @@ -814,7 +814,7 @@ public virtual bool Supports(string feature, string version) { if (string.Equals("XML", feature, StringComparison.OrdinalIgnoreCase)) { - if (version == null || version == "1.0" || version == "2.0") + if (version is null || version == "1.0" || version == "2.0") return true; } return false; @@ -852,7 +852,7 @@ public virtual bool IsReadOnly internal static bool HasReadOnlyParent(XmlNode? n) { - while (n != null) + while (n is not null) { switch (n.NodeType) { @@ -897,9 +897,9 @@ public IEnumerator GetEnumerator() private void AppendChildText(StringBuilder builder) { - for (XmlNode? child = FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = FirstChild; child is not null; child = child.NextSibling) { - if (child.FirstChild == null) + if (child.FirstChild is null) { if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA || child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace) @@ -919,11 +919,11 @@ public virtual string InnerText get { XmlNode? fc = FirstChild; - if (fc == null) + if (fc is null) { return string.Empty; } - if (fc.NextSibling == null) + if (fc.NextSibling is null) { XmlNodeType nodeType = fc.NodeType; switch (nodeType) @@ -944,8 +944,8 @@ public virtual string InnerText set { XmlNode? firstChild = FirstChild; - if (firstChild != null //there is one child - && firstChild.NextSibling == null // and exactly one + if (firstChild is not null //there is one child + && firstChild.NextSibling is null // and exactly one && firstChild.NodeType == XmlNodeType.Text)//which is a text node { //this branch is for perf reason and event fired when TextNode.Value is changed @@ -1015,7 +1015,7 @@ public virtual string BaseURI get { XmlNode? curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref - while (curNode != null) + while (curNode is not null) { XmlNodeType nt = curNode.NodeType; //EntityReference's children come from the dtd where they are defined. @@ -1045,7 +1045,7 @@ public virtual void RemoveAll() XmlNode? child = FirstChild; XmlNode? sibling = null; - while (child != null) + while (child is not null) { sibling = child.NextSibling; RemoveChild(child); @@ -1077,14 +1077,14 @@ public virtual string GetNamespaceOfPrefix(string prefix) XmlDocument doc = Document; string? pref = prefix; - if (doc != null) + if (doc is not null) { pref = doc.NameTable.Get(pref); - if (pref == null) + if (pref is null) return null; XmlNode? node = this; - while (node != null) + while (node is not null) { if (node.NodeType == XmlNodeType.Element) { @@ -1159,18 +1159,18 @@ public virtual string GetNamespaceOfPrefix(string prefix) public virtual string GetPrefixOfNamespace(string namespaceURI) { string? prefix = GetPrefixOfNamespaceStrict(namespaceURI); - return prefix != null ? prefix : string.Empty; + return prefix is not null ? prefix : string.Empty; } internal string? GetPrefixOfNamespaceStrict(string namespaceURI) { XmlDocument doc = Document; - if (doc != null) + if (doc is not null) { namespaceURI = doc.NameTable.Add(namespaceURI); XmlNode? node = this; - while (node != null) + while (node is not null) { if (node.NodeType == XmlNodeType.Element) { @@ -1238,7 +1238,7 @@ public virtual XmlElement? this[string name] { get { - for (XmlNode? n = FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = FirstChild; n is not null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.Name == name) return (XmlElement)n; @@ -1254,7 +1254,7 @@ public virtual XmlElement? this[string name] { get { - for (XmlNode? n = FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = FirstChild; n is not null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns) return (XmlElement)n; @@ -1266,7 +1266,7 @@ public virtual XmlElement? this[string name] internal virtual void SetParent(XmlNode? node) { - if (node == null) + if (node is null) { this.parentNode = OwnerDocument; } @@ -1298,7 +1298,7 @@ internal static void SplitName(string name, out string prefix, out string localN internal virtual XmlNode? FindChild(XmlNodeType type) { - for (XmlNode? child = FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = FirstChild; child is not null; child = child.NextSibling) { if (child.NodeType == type) { @@ -1312,11 +1312,11 @@ internal static void SplitName(string name, out string prefix, out string localN internal virtual XmlNodeChangedEventArgs? GetEventArgs(XmlNode node, XmlNode? oldParent, XmlNode? newParent, string? oldValue, string? newValue, XmlNodeChangedAction action) { XmlDocument? doc = OwnerDocument; - if (doc != null) + if (doc is not null) { if (!doc.IsLoading) { - if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly))) + if (((newParent is not null && newParent.IsReadOnly) || (oldParent is not null && oldParent.IsReadOnly))) throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly); } @@ -1328,13 +1328,13 @@ internal static void SplitName(string name, out string prefix, out string localN internal virtual void BeforeEvent(XmlNodeChangedEventArgs args) { - if (args != null) + if (args is not null) OwnerDocument!.BeforeEvent(args); } internal virtual void AfterEvent(XmlNodeChangedEventArgs args) { - if (args != null) + if (args is not null) OwnerDocument!.AfterEvent(args); } @@ -1347,7 +1347,7 @@ internal virtual XmlSpace XmlSpace do { elem = node as XmlElement; - if (elem != null && elem.HasAttribute("xml:space")) + if (elem is not null && elem.HasAttribute("xml:space")) { switch (XmlConvert.TrimString(elem.GetAttribute("xml:space"))) { @@ -1362,7 +1362,7 @@ internal virtual XmlSpace XmlSpace } node = node.ParentNode; - } while (node != null); + } while (node is not null); return XmlSpace.None; } @@ -1377,14 +1377,14 @@ internal virtual string XmlLang do { elem = node as XmlElement; - if (elem != null) + if (elem is not null) { if (elem.HasAttribute("xml:lang")) return elem.GetAttribute("xml:lang"); } node = node.ParentNode; - } while (node != null); + } while (node is not null); return string.Empty; } 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 705ad125aafb22..bcc8199bf84fc6 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 @@ -215,7 +215,7 @@ public bool HasValue Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount); return true; } - if (_curNode.Value != null || _curNode.NodeType == XmlNodeType.DocumentType) + if (_curNode.Value is not null || _curNode.NodeType == XmlNodeType.DocumentType) return true; return false; } @@ -255,7 +255,7 @@ public string Value } else retValue = _curNode.Value; - return (retValue == null) ? string.Empty : retValue; + return (retValue is null) ? string.Empty : retValue; } } @@ -354,21 +354,21 @@ private void InitDecAttr() { int i = 0; string? strTemp = _doc.Version; - if (strTemp != null && strTemp.Length != 0) + if (strTemp is not null && strTemp.Length != 0) { decNodeAttributes[i].name = strVersion; decNodeAttributes[i].value = strTemp; i++; } strTemp = _doc.Encoding; - if (strTemp != null && strTemp.Length != 0) + if (strTemp is not null && strTemp.Length != 0) { decNodeAttributes[i].name = strEncoding; decNodeAttributes[i].value = strTemp; i++; } strTemp = _doc.Standalone; - if (strTemp != null && strTemp.Length != 0) + if (strTemp is not null && strTemp.Length != 0) { decNodeAttributes[i].name = strStandalone; decNodeAttributes[i].value = strTemp; @@ -412,14 +412,14 @@ private void InitDocTypeAttr() { int i = 0; XmlDocumentType? docType = _doc.DocumentType; - if (docType == null) + if (docType is null) { _nDocTypeAttrCount = 0; return; } string? strTemp = docType.PublicId; - if (strTemp != null) + if (strTemp is not null) { docTypeNodeAttributes[i].name = strPublicID; docTypeNodeAttributes[i].value = strTemp; @@ -427,7 +427,7 @@ private void InitDocTypeAttr() } strTemp = docType.SystemId; - if (strTemp != null) + if (strTemp is not null) { docTypeNodeAttributes[i].name = strSystemID; docTypeNodeAttributes[i].value = strTemp; @@ -469,7 +469,7 @@ public int GetDocTypeAttrInd(string name) private string? GetAttributeFromElement(XmlElement elem, string name) { XmlAttribute? attr = elem.GetAttributeNode(name); - if (attr != null) + if (attr is not null) return attr.Value; return null; } @@ -492,7 +492,7 @@ public int GetDocTypeAttrInd(string name) private string? GetAttributeFromElement(XmlElement elem, string name, string? ns) { XmlAttribute? attr = elem.GetAttributeNode(name, ns); - if (attr != null) + if (attr is not null) return attr.Value; return null; } @@ -631,7 +631,7 @@ private bool MoveToAttributeFromElement(XmlElement elem, string name, string ns) attr = elem.GetAttributeNode(name); else attr = elem.GetAttributeNode(name, ns); - if (attr != null) + if (attr is not null) { _bOnAttrVal = false; _elemNode = elem; @@ -683,7 +683,7 @@ public void MoveToAttribute(int attributeIndex) case XmlNodeType.Element: CheckIndexCondition(attributeIndex); attr = ((XmlElement)_curNode).Attributes[attributeIndex]; - if (attr != null) + if (attr is not null) { _elemNode = _curNode; _curNode = (XmlNode)attr; @@ -693,7 +693,7 @@ public void MoveToAttribute(int attributeIndex) case XmlNodeType.Attribute: CheckIndexCondition(attributeIndex); attr = ((XmlElement)_elemNode!).Attributes[attributeIndex]; - if (attr != null) + if (attr is not null) { _curNode = (XmlNode)attr; _attrIndex = attributeIndex; @@ -765,7 +765,7 @@ public bool MoveToNextAttribute(ref int level) public bool MoveToParent() { XmlNode? parent = _curNode.ParentNode; - if (parent != null) + if (parent is not null) { _curNode = parent; if (!_bOnAttrVal) @@ -778,7 +778,7 @@ public bool MoveToParent() public bool MoveToFirstChild() { XmlNode? firstChild = _curNode.FirstChild; - if (firstChild != null) + if (firstChild is not null) { _curNode = firstChild; if (!_bOnAttrVal) @@ -792,7 +792,7 @@ public bool MoveToFirstChild() private bool MoveToNextSibling(XmlNode node) { XmlNode? nextSibling = node.NextSibling; - if (nextSibling != null) + if (nextSibling is not null) { _curNode = nextSibling; if (!_bOnAttrVal) @@ -818,7 +818,7 @@ public bool MoveToElement() switch (_curNode.NodeType) { case XmlNodeType.Attribute: - if (_elemNode != null) + if (_elemNode is not null) { _curNode = _elemNode; _attrIndex = -1; @@ -854,7 +854,7 @@ public bool MoveToElement() // construct the name of the xmlns attribute string attrName; - if (prefix == null) + if (prefix is null) prefix = string.Empty; if (prefix.Length == 0) attrName = "xmlns"; @@ -863,7 +863,7 @@ public bool MoveToElement() // walk up the XmlNode parent chain, looking for the xmlns attribute XmlNode? node = _curNode; - while (node != null) + while (node is not null) { if (node.NodeType == XmlNodeType.Element) { @@ -871,7 +871,7 @@ public bool MoveToElement() if (elem.HasAttributes) { XmlAttribute? attr = elem.GetAttributeNode(attrName); - if (attr != null) + if (attr is not null) { return attr.Value; } @@ -913,7 +913,7 @@ public bool MoveToElement() internal string? LookupPrefix(string namespaceName) { - if (_bCreatedOnAttribute || namespaceName == null) + if (_bCreatedOnAttribute || namespaceName is null) { return null; } @@ -931,7 +931,7 @@ public bool MoveToElement() } // walk up the XmlNode parent chain, looking for the xmlns attribute with namespaceName value XmlNode? node = _curNode; - while (node != null) + while (node is not null) { if (node.NodeType == XmlNodeType.Element) { @@ -983,7 +983,7 @@ internal IDictionary GetNamespacesInScope(XmlNamespaceScope scop // walk up the XmlNode parent chain and add all namespace declarations to the dictionary XmlNode? node = _curNode; - while (node != null) + while (node is not null) { if (node.NodeType == XmlNodeType.Element) { @@ -1056,7 +1056,7 @@ public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNo if (_curNode.NodeType == XmlNodeType.Attribute) { XmlNode? firstChild = _curNode.FirstChild; - if (firstChild != null) + if (firstChild is not null) { _curNode = firstChild; nt = _curNode.NodeType; @@ -1072,7 +1072,7 @@ public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNo { //going down to ent ref node _curNode = _curNode.FirstChild!; - Debug.Assert(_curNode != null); + Debug.Assert(_curNode is not null); nt = _curNode.NodeType; level++; bResolveEntity = false; @@ -1080,11 +1080,11 @@ public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNo } else nextSibling = _curNode.NextSibling; - if (nextSibling == null) + if (nextSibling is null) { XmlNode? parentNode = _curNode.ParentNode; //Check if its parent is entity ref node is sufficient, because in this senario, ent ref node can't have more than 1 level of children that are not other ent ref nodes - if (parentNode != null && parentNode.NodeType == XmlNodeType.EntityReference) + if (parentNode is not null && parentNode.NodeType == XmlNodeType.EntityReference) { //come back from ent ref node _curNode = parentNode; @@ -1093,7 +1093,7 @@ public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNo return true; } } - if (nextSibling != null) + if (nextSibling is not null) { _curNode = nextSibling; nt = _curNode.NodeType; @@ -1135,7 +1135,7 @@ public class XmlNodeReader : XmlReader, IXmlNamespaceResolver // Creates an instance of the XmlNodeReader class using the specified XmlNode. public XmlNodeReader(XmlNode node) { - if (node == null) + if (node is null) { throw new ArgumentNullException(nameof(node)); } @@ -1343,7 +1343,7 @@ public override int AttributeCount //if not on Attribute, only element node could have attributes if (!IsInReadingStates()) return null; - string ns = (namespaceURI == null) ? string.Empty : namespaceURI; + string ns = (namespaceURI is null) ? string.Empty : namespaceURI; return _readerNav.GetAttribute(name, ns); } @@ -1383,7 +1383,7 @@ public override bool MoveToAttribute(string name, string? namespaceURI) if (!IsInReadingStates()) return false; _readerNav.ResetMove(ref _curDepth, ref _nodeType); - string ns = (namespaceURI == null) ? string.Empty : namespaceURI; + string ns = (namespaceURI is null) ? string.Empty : namespaceURI; if (_readerNav.MoveToAttribute(name, ns)) { //, ref curDepth ) ) { _curDepth++; @@ -1759,7 +1759,7 @@ public override XmlNameTable NameTable if (!IsInReadingStates()) return null; string? ns = _readerNav.LookupNamespace(prefix); - if (ns != null && ns.Length == 0) + if (ns is not null && ns.Length == 0) { return null; } @@ -1920,7 +1920,7 @@ IDictionary IXmlNamespaceResolver.GetNamespacesInScope(XmlNamesp } string? ns = _readerNav.LookupNamespace(prefix); - if (ns != null) + if (ns is not null) { ns = _readerNav.NameTable.Add(ns); } 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 193454132445a7..47e562a808a1d0 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 @@ -25,7 +25,7 @@ public override string Name { get { - if (_target != null) + if (_target is not null) return _target; return string.Empty; } @@ -60,10 +60,10 @@ public string Data { XmlNode? parent = ParentNode; XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); - if (args != null) + if (args is not null) BeforeEvent(args); _data = value; - if (args != null) + if (args is not null) AfterEvent(args); } } @@ -85,7 +85,7 @@ public override XmlNodeType NodeType // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateProcessingInstruction(_target, _data); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs index fb58b8f0537617..3878518ccea1ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs @@ -69,7 +69,7 @@ public override XmlNode? ParentNode // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateSignificantWhitespace(Data); } @@ -123,7 +123,7 @@ public override XmlNode? PreviousText { get { - if (parentNode != null && parentNode.IsText) + if (parentNode is not null && parentNode.IsText) { return parentNode; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs index 788c2e2e1ea147..337a765b9b759b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs @@ -73,7 +73,7 @@ public override XmlNode? ParentNode // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateTextNode(Data); } @@ -88,10 +88,10 @@ public override string? Value { Data = value; XmlNode? parent = parentNode; - if (parent != null && parent.NodeType == XmlNodeType.Attribute) + if (parent is not null && parent.NodeType == XmlNodeType.Attribute) { XmlUnspecifiedAttribute? attr = parent as XmlUnspecifiedAttribute; - if (attr != null && !attr.Specified) + if (attr is not null && !attr.Specified) { attr.SetSpecified(true); } @@ -108,7 +108,7 @@ public virtual XmlText SplitText(int offset) if (offset > length) throw new ArgumentOutOfRangeException(nameof(offset)); //if the text node is out of the living tree, throw exception. - if (parentNode == null) + if (parentNode is null) throw new InvalidOperationException(SR.Xdom_TextNode_SplitText); int count = length - offset; @@ -151,7 +151,7 @@ public override XmlNode? PreviousText { get { - if (parentNode != null && parentNode.IsText) + if (parentNode is not null && parentNode.IsText) { return parentNode; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs index 5113a488563f82..bf4fa69b0a93a2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs @@ -85,7 +85,7 @@ public override string? Value // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { - Debug.Assert(OwnerDocument != null); + Debug.Assert(OwnerDocument is not null); return OwnerDocument.CreateWhitespace(Data); } @@ -123,7 +123,7 @@ public override XmlNode? PreviousText { get { - if (parentNode != null && parentNode.IsText) + if (parentNode is not null && parentNode.IsText) { return parentNode; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs index 87246bb3258e6e..d3b486395f49c6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs @@ -19,7 +19,7 @@ internal class PositionInfo : IXmlLineInfo public static PositionInfo GetPositionInfo(object o) { IXmlLineInfo? li = o as IXmlLineInfo; - if (li != null) + if (li is not null) { return new ReaderPositionInfo(li); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs index 14575914d1f20f..edb99d3d53af1f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -55,7 +55,7 @@ public NameTable() /// public override string Add(string key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -68,7 +68,7 @@ public override string Add(string key) int hashCode = ComputeHash32(key); - for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) + for (Entry e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.hashCode == hashCode && e.str.Equals(key)) { @@ -106,7 +106,7 @@ public override string Add(char[] key, int start, int len) int hashCode = ComputeHash32(key, start, len); - for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) + for (Entry e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.hashCode == hashCode && TextEquals(e.str, key, start, len)) { @@ -122,7 +122,7 @@ public override string Add(char[] key, int start, int len) /// public override string? Get(string value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -134,7 +134,7 @@ public override string Add(char[] key, int start, int len) int hashCode = ComputeHash32(value); - for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) + for (Entry e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.hashCode == hashCode && e.str.Equals(value)) { @@ -169,7 +169,7 @@ public override string Add(char[] key, int start, int len) int hashCode = ComputeHash32(key, start, len); - for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) + for (Entry e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.hashCode == hashCode && TextEquals(e.str, key, start, len)) { @@ -182,7 +182,7 @@ public override string Add(char[] key, int start, int len) internal string GetOrAddEntry(string str, int hashCode) { - for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) + for (Entry e = _entries[hashCode & _mask]; e is not null; e = e.next) { if (e.hashCode == hashCode && e.str.Equals(str)) { @@ -227,7 +227,7 @@ private void Grow() for (int i = 0; i < oldEntries.Length; i++) { Entry e = oldEntries[i]; - while (e != null) + while (e is not null) { int newIndex = e.hashCode & newMask; Entry tmp = e.next; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs index 277e7045124ad4..95c223d32f856b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs @@ -61,7 +61,7 @@ internal void MoveToParent(int depth, ForwardAxis parent) this.rootDepth = this.curDepth = -1; return; } - else if (this.curNode.Input != null) + else if (this.curNode.Input is not null) { // else cur-depth --, cur-node change this.curNode = (DoubleLinkAxis)(this.curNode.Input); this.curDepth--; @@ -187,9 +187,9 @@ internal void Pop() internal static bool Equal(string thisname, string? thisURN, string name, string? URN) { // which means "b" in xpath, no namespace should be specified - if (thisURN == null) + if (thisURN is null) { - if (!((URN == null) || (URN.Length == 0))) + if (!((URN is null) || (URN.Length == 0))) { return false; } @@ -265,7 +265,7 @@ internal bool MoveToAttribute(string name, string? URN, int depth) bool result = false; // no stack element for single attribute, so dealing with it separately - if (_subtree.TopNode.Input == null) + if (_subtree.TopNode.Input is null) { return (_subtree.IsDss || (depth == 1)); } @@ -421,7 +421,7 @@ internal DoubleLinkAxis(Axis axis, DoubleLinkAxis? inputaxis) this.next = null; this.Urn = axis.Urn; this.abbrAxis = axis.AbbrAxis; - if (inputaxis != null) + if (inputaxis is not null) { inputaxis.Next = this; } @@ -431,7 +431,7 @@ internal DoubleLinkAxis(Axis axis, DoubleLinkAxis? inputaxis) [return: NotNullIfNotNull("axis")] internal static DoubleLinkAxis? ConvertTree(Axis? axis) { - if (axis == null) + if (axis is null) { return null; } @@ -487,7 +487,7 @@ public ForwardAxis(DoubleLinkAxis axis, bool isdesorself) _isAttribute = Asttree.IsAttribute(axis); _topNode = axis; _rootNode = axis; - while (_rootNode.Input != null) + while (_rootNode.Input is not null) { _rootNode = (DoubleLinkAxis)(_rootNode.Input); } @@ -547,7 +547,7 @@ internal static bool IsSelf(Axis ast) // for whitespace thing, i will directly trim the tree built here... public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) { - if ((xPath == null) || (xPath.Length == 0)) + if ((xPath is null) || (xPath.Length == 0)) { throw new XmlSchemaException(SR.Sch_EmptyXPath, string.Empty); } @@ -582,7 +582,7 @@ public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) // field can have an attribute: // throw exceptions during casting - if ((stepAst = ast) == null) + if ((stepAst = ast) is null) { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } @@ -612,7 +612,7 @@ public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) } // field or selector - while ((stepAst != null) && (IsNameTest(stepAst) || IsSelf(stepAst))) + while ((stepAst is not null) && (IsNameTest(stepAst) || IsSelf(stepAst))) { // trim tree "." node, if it's not the top one if (IsSelf(stepAst) && (ast != stepAst)) @@ -641,9 +641,9 @@ public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) // the rest part can only be .// or null // trim the rest part, but need compile the rest part first top.Input = null; - if (stepAst == null) + if (stepAst is null) { // top "." and has other element beneath, trim this "." node too - if (IsSelf(ast) && (ast.Input != null)) + if (IsSelf(ast) && (ast.Input is not null)) { _fAxisArray.Add(new ForwardAxis(DoubleLinkAxis.ConvertTree((Axis)(ast.Input)), false)); } @@ -665,13 +665,13 @@ public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } - if ((stepAst == null) || (!IsSelf(stepAst)) || (stepAst.Input != null)) + if ((stepAst is null) || (!IsSelf(stepAst)) || (stepAst.Input is not null)) { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } // trim top "." if it's not the only node - if (IsSelf(ast) && (ast.Input != null)) + if (IsSelf(ast) && (ast.Input is not null)) { _fAxisArray.Add(new ForwardAxis(DoubleLinkAxis.ConvertTree((Axis)(ast.Input)), true)); } @@ -696,7 +696,7 @@ private void SetURN(Axis axis, XmlNamespaceManager nsmgr) { // (1) (4) axis.Urn = nsmgr.LookupNamespace(axis.Prefix); - if (axis.Urn == null) + if (axis.Urn is null) { throw new XmlSchemaException(SR.Sch_UnresolvedPrefix, axis.Prefix); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs index eb87b34495f882..14e7c1ebad9f53 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs @@ -50,7 +50,7 @@ public override void CompleteValidation() { } private ValidationType DetectValidationType() { //Type not yet detected : Check in Schema Collection - if (reader.Schemas != null && reader.Schemas.Count > 0) + if (reader.Schemas is not null && reader.Schemas.Count > 0) { XmlSchemaCollectionEnumerator enumerator = reader.Schemas.GetEnumerator(); while (enumerator.MoveNext()) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs index d389ff72a5bc58..932b6207ed174f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs @@ -151,7 +151,7 @@ public override int GetHashCode() public override bool Equals(object? obj) { // assume the same type - if (obj != null) + if (obj is not null) { if (this == obj) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs index 0ddc7dba2bfba8..2f1414e43632e0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs @@ -207,7 +207,7 @@ public bool IsDecimal { get { - Debug.Assert(_dstruct != null); + Debug.Assert(_dstruct is not null); return _dstruct.IsDecimal; } } @@ -215,7 +215,7 @@ public decimal[] Dvalue { get { - Debug.Assert(_dstruct != null); + Debug.Assert(_dstruct is not null); return _dstruct.Dvalue; } } @@ -254,7 +254,7 @@ public override string ToString() public void SetDecimal() { - if (_dstruct != null) + if (_dstruct is not null) { return; } @@ -353,13 +353,13 @@ public bool Equals(TypedObject other) { //this is a list and other is a single value Array? arr1 = this.Value as System.Array; XmlAtomicValue[]? atomicValues1 = arr1 as XmlAtomicValue[]; - if (atomicValues1 != null) + if (atomicValues1 is not null) { // this is a list of union return atomicValues1.Length == 1 && atomicValues1.GetValue(0)!.Equals(other.Value); } else { - Debug.Assert(arr1 != null); + Debug.Assert(arr1 is not null); return arr1.Length == 1 && arr1.GetValue(0)!.Equals(other.Value); } } @@ -368,13 +368,13 @@ public bool Equals(TypedObject other) { Array? arr2 = other.Value as System.Array; XmlAtomicValue[]? atomicValues2 = arr2 as XmlAtomicValue[]; - if (atomicValues2 != null) + if (atomicValues2 is not null) { // other is a list of union return atomicValues2.Length == 1 && atomicValues2.GetValue(0)!.Equals(this.Value); } else { - Debug.Assert(arr2 != null); + Debug.Assert(arr2 is not null); return arr2.Length == 1 && arr2.GetValue(0)!.Equals(this.Value); } } @@ -429,7 +429,7 @@ internal bool IsQualified() { for (int i = 0; i < _ks.Length; ++i) { - if ((_ks[i] == null) || (_ks[i].Value == null)) return false; + if ((_ks[i] is null) || (_ks[i].Value is null)) return false; } return true; } @@ -460,7 +460,7 @@ public override int GetHashCode() if (_ks[i].Value is Array arr) { XmlAtomicValue[]? atomicValues = arr as XmlAtomicValue[]; - if (atomicValues != null) + if (atomicValues is not null) { for (int j = 0; j < atomicValues.Length; j++) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index 5b3f63a96ee90a..ccea96b45d72c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -72,7 +72,7 @@ public bool IsUpaEnforced public int AddName(XmlQualifiedName name, object? particle) { object? lookup = _names[name]; - if (lookup != null) + if (lookup is not null) { int symbol = (int)lookup; if (_particles[symbol] != particle) @@ -116,20 +116,20 @@ public void AddNamespaceList(NamespaceList list, object particle, bool allowLoca private void AddWildcard(string wildcard, object? particle) { - if (_wildcards == null) + if (_wildcards is null) { _wildcards = new Hashtable(); } object? lookup = _wildcards[wildcard]; - if (lookup == null) + if (lookup is null) { _wildcards.Add(wildcard, _last); _particles.Add(particle); Debug.Assert(_particles.Count == _last + 1); _last++; } - else if (particle != null) + else if (particle is not null) { _particles[(int)lookup] = particle; } @@ -140,14 +140,14 @@ public ICollection GetNamespaceListSymbols(NamespaceList list) ArrayList match = new ArrayList(); foreach (XmlQualifiedName? name in _names.Keys) { - Debug.Assert(name != null); + Debug.Assert(name is not null); if (name != XmlQualifiedName.Empty && list.Allows(name)) { match.Add(_names[name]); } } - if (_wildcards != null) + if (_wildcards is not null) { foreach (string wildcard in _wildcards.Keys) { @@ -174,15 +174,15 @@ public int this[XmlQualifiedName name] get { object? lookup = _names[name]; - if (lookup != null) + if (lookup is not null) { return (int)lookup; } - if (_wildcards != null) + if (_wildcards is not null) { lookup = _wildcards[name.Namespace]; - if (lookup != null) + if (lookup is not null) { return (int)lookup; } @@ -198,7 +198,7 @@ public int this[XmlQualifiedName name] public bool Exists(XmlQualifiedName name) { object? lookup = _names[name]; - if (lookup != null) + if (lookup is not null) { return true; } @@ -227,7 +227,7 @@ public string NameOf(int symbol) } } - if (_wildcards != null) + if (_wildcards is not null) { foreach (DictionaryEntry de in _wildcards) { @@ -389,7 +389,7 @@ public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, } LeafNode node = new LeafNode(positions.Add(symbol, particle)); - if (replacementNode == null) + if (replacementNode is null) { replacementNode = node; } @@ -469,7 +469,7 @@ protected void ExpandTreeNoRecursive(InteriorNode parent, SymbolsDictionary symb this_._leftChild!.ExpandTree(this_, symbols, positions); ProcessRight: - if (this_._rightChild != null) + if (this_._rightChild is not null) { this_._rightChild.ExpandTree(this_, symbols, positions); } @@ -485,7 +485,7 @@ protected void ExpandTreeNoRecursive(InteriorNode parent, SymbolsDictionary symb public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, Positions positions) { _leftChild!.ExpandTree(this, symbols, positions); - if (_rightChild != null) + if (_rightChild is not null) { _rightChild.ExpandTree(this, symbols, positions); } @@ -577,7 +577,7 @@ public override bool IsNullable n = this_.LeftChild; this_ = n as SequenceNode; } - while (this_ != null); + while (this_ is not null); return n!.IsNullable; } @@ -641,7 +641,7 @@ public override void ConstructPos(BitSet firstpos, BitSet lastpos, BitSet[] foll ConstructChildPos(this_.RightChild!, firstPosTemp, lastPosTemp, followpos); n = this_.LeftChild!; this_ = n as ChoiceNode; - } while (this_ != null); + } while (this_ is not null); n!.ConstructPos(firstpos, lastpos, followpos); firstpos.Or(firstPosTemp); @@ -661,7 +661,7 @@ public override bool IsNullable n = this_.LeftChild!; this_ = n as ChoiceNode; } - while (this_ != null); + while (this_ is not null); return n.IsNullable; } } @@ -1042,11 +1042,11 @@ public static void AddParticleToExpected(XmlSchemaParticle p, XmlSchemaSet schem } //Only then it can be head of substitutionGrp, if it is, add its members XmlSchemaElement? elem = p as XmlSchemaElement; - if (elem != null && (global || !elem.RefName.IsEmpty)) + if (elem is not null && (global || !elem.RefName.IsEmpty)) { XmlSchemaObjectTable substitutionGroups = schemaSet.SubstitutionGroups; XmlSchemaSubstitutionGroup? grp = (XmlSchemaSubstitutionGroup?)substitutionGroups[elem.QualifiedName]; - if (grp != null) + if (grp is not null) { //Grp members wil contain the head as well, so filter head as we added it already for (int i = 0; i < grp.Members.Count; ++i) @@ -1114,7 +1114,7 @@ public void OpenGroup() public void CloseGroup() { SyntaxTreeNode? node = _stack!.Pop(); - if (node == null) + if (node is null) { return; } @@ -1128,7 +1128,7 @@ public void CloseGroup() { // some collapsing to do... InteriorNode? inNode = (InteriorNode?)_stack.Pop(); - if (inNode != null) + if (inNode is not null) { inNode.RightChild = node; node = inNode; @@ -1167,7 +1167,7 @@ private void AddLeafNode(SyntaxTreeNode node) if (_stack!.Count > 0) { InteriorNode? inNode = (InteriorNode?)_stack.Pop(); - if (inNode != null) + if (inNode is not null) { inNode.RightChild = node; node = inNode; @@ -1231,7 +1231,7 @@ private void Closure(InteriorNode node) { SyntaxTreeNode? topNode = _stack!.Pop(); InteriorNode? inNode = topNode as InteriorNode; - if (_isPartial && inNode != null) + if (_isPartial && inNode is not null) { // need to reach in and wrap right hand side of element. // and n remains the same. @@ -1246,7 +1246,7 @@ private void Closure(InteriorNode node) } _stack.Push(topNode); } - else if (_contentNode != null) + else if (_contentNode is not null) { //If there is content to wrap // wrap whole content node.LeftChild = _contentNode; @@ -1257,7 +1257,7 @@ private void Closure(InteriorNode node) public ContentValidator Finish(bool useDFA) { Debug.Assert(ContentType == XmlSchemaContentType.ElementOnly || ContentType == XmlSchemaContentType.Mixed); - if (_contentNode == null) + if (_contentNode is null) { if (ContentType == XmlSchemaContentType.Mixed) { @@ -1323,7 +1323,7 @@ public ContentValidator Finish(bool useDFA) transitionTable = BuildTransitionTable(firstpos, followpos, endMarker.Pos); } - if (transitionTable != null) + if (transitionTable is not null) { return new DfaContentValidator(transitionTable, _symbols, this.ContentType, this.IsOpen, contentRoot.LeftChild.IsNullable); } @@ -1350,7 +1350,7 @@ private BitSet[] CalculateTotalFollowposForRangeNodes(BitSet firstpos, BitSet[] if (p.symbol == -2) { //P is a LeafRangeNode LeafRangeNode? lrNode = p.particle as LeafRangeNode; - Debug.Assert(lrNode != null); + Debug.Assert(lrNode is not null); BitSet tempFollowPos = new BitSet(positionsCount); tempFollowPos.Clear(); tempFollowPos.Or(followpos[i]); //Add the followpos of the range node @@ -1368,7 +1368,7 @@ private BitSet[] CalculateTotalFollowposForRangeNodes(BitSet firstpos, BitSet[] if (p1.symbol == -2) { LeafRangeNode? lrNode1 = p1.particle as LeafRangeNode; - Debug.Assert(lrNode1 != null); + Debug.Assert(lrNode1 is not null); tempFollowPos.Or(minmaxFollowPos[lrNode1.Pos]); } } @@ -1391,7 +1391,7 @@ private void CheckCMUPAWithLeafRangeNodes(BitSet curpos) int symbol = currentPosition.symbol; if (symbol >= 0) { //its not a range position - if (symbolMatches[symbol] != null) + if (symbolMatches[symbol] is not null) { throw new UpaException(symbolMatches[symbol], currentPosition.particle); } @@ -1416,7 +1416,7 @@ private BitSet GetApplicableMinMaxFollowPos(BitSet curpos, BitSet posWithRangeTe for (int pos = newSet.NextSet(-1); pos != -1; pos = newSet.NextSet(pos)) { LeafRangeNode? lrNode = _positions[pos].particle as LeafRangeNode; - Debug.Assert(lrNode != null); + Debug.Assert(lrNode is not null); curpos.Or(minmaxFollowPos[lrNode.Pos]); } } @@ -1440,7 +1440,7 @@ private void CheckUniqueParticleAttribution(BitSet curpos) { // if position can follow int symbol = _positions![pos].symbol; - if (particles[symbol] == null) + if (particles[symbol] is null) { // set particle for the symbol particles[symbol] = _positions[pos].particle; @@ -1510,7 +1510,7 @@ private void CheckUniqueParticleAttribution(BitSet curpos) // if U is not empty and is not in Dstates then // add U as an unmarked state to Dstates object? lookup = stateTable[newset]; - if (lookup != null) + if (lookup is not null) { transition[symbol] = (int)lookup; } @@ -1555,7 +1555,7 @@ private void Dump(StringBuilder bb, BitSet[] followpos, int[][] transitionTable) bb.AppendLine(); } - if (transitionTable != null) + if (transitionTable is not null) { // Temporary printout bb.AppendLine("Transitions"); @@ -1644,19 +1644,19 @@ public override bool CompleteValidation(ValidationState context) { ArrayList? names = null; int[] transition = _transitionTable[context.CurrentState.State]; - if (transition != null) + if (transition is not null) { for (int i = 0; i < transition.Length - 1; i++) { if (transition[i] != -1) { - if (names == null) + if (names is null) { names = new ArrayList(); } XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i); - if (p == null) + if (p is null) { string s = _symbols.NameOf(i); if (s.Length != 0) @@ -1683,14 +1683,14 @@ public override ArrayList ExpectedParticles(ValidationState context, bool isRequ { ArrayList particles = new ArrayList(); int[] transition = _transitionTable[context.CurrentState.State]; - if (transition != null) + if (transition is not null) { for (int i = 0; i < transition.Length - 1; i++) { if (transition[i] != -1) { XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i); - if (p == null) + if (p is null) { continue; } @@ -1772,7 +1772,7 @@ public override void InitValidation(ValidationState context) #if FINDUPA_PARTICLE private bool FindUPAParticle(ref object originalParticle, object newParticle) { - if (originalParticle == null) { + if (originalParticle is null) { originalParticle = newParticle; if (originalParticle is XmlSchemaElement) { //if the first particle is element, then break, otherwise try to find an element return true; @@ -1803,12 +1803,12 @@ public override bool CompleteValidation(ValidationState context) BitSet curpos = context.CurPos[context.CurrentState.CurPosIndex]; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { - if (names == null) + if (names is null) { names = new ArrayList(); } XmlSchemaParticle? p = (XmlSchemaParticle?)_positions[pos].particle; - if (p == null) + if (p is null) { string s = _symbols.NameOf(_positions[pos].symbol); if (s.Length != 0) @@ -1835,7 +1835,7 @@ public override ArrayList ExpectedParticles(ValidationState context, bool isRequ for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { XmlSchemaParticle? p = (XmlSchemaParticle?)_positions[pos].particle; - if (p == null) + if (p is null) { continue; } @@ -1879,7 +1879,7 @@ internal RangeContentValidator( public override void InitValidation(ValidationState context) { List? runningPositions = context.RunningPositions; - if (runningPositions != null) + if (runningPositions is not null) { Debug.Assert(_minMaxNodesCount != 0); runningPositions.Clear(); @@ -2002,7 +2002,7 @@ public override void InitValidation(ValidationState context) countingPosition.And(_positionsWithRangeTerminals); int cPos = countingPosition.NextSet(-1); //Get the first position where leaf range node appears LeafRangeNode? lrNode = _positions[cPos].particle as LeafRangeNode; //For a position with leaf range node, the particle is the node itself - Debug.Assert(lrNode != null); + Debug.Assert(lrNode is not null); rposInfo = runningPositions[j]; if (matchCount + 2 >= runningPositions.Count) @@ -2012,7 +2012,7 @@ public override void InitValidation(ValidationState context) } RangePositionInfo newRPosInfo = runningPositions[matchCount]; - if (newRPosInfo.rangeCounters == null) + if (newRPosInfo.rangeCounters is null) { newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount]; } @@ -2040,7 +2040,7 @@ public override void InitValidation(ValidationState context) runningPositions[matchCount] = newRPosInfo; j = matchCount + 1; newRPosInfo = runningPositions[j]; - if (newRPosInfo.rangeCounters == null) + if (newRPosInfo.rangeCounters is null) { newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount]; } @@ -2075,18 +2075,18 @@ public override bool CompleteValidation(ValidationState context) { ArrayList? names = null; BitSet expectedPos; - if (context.RunningPositions != null) + if (context.RunningPositions is not null) { List runningPositions = context.RunningPositions; expectedPos = new BitSet(_positions.Count); for (int i = context.CurrentState.NumberOfRunningPos - 1; i >= 0; i--) { - Debug.Assert(runningPositions[i].curpos != null); + Debug.Assert(runningPositions[i].curpos is not null); expectedPos.Or(runningPositions[i].curpos); } for (int pos = expectedPos.NextSet(-1); pos != -1; pos = expectedPos.NextSet(pos)) { - if (names == null) + if (names is null) { names = new ArrayList(); } @@ -2094,7 +2094,7 @@ public override bool CompleteValidation(ValidationState context) if (symbol >= 0) { //non range nodes XmlSchemaParticle? p = _positions[pos].particle as XmlSchemaParticle; - if (p == null) + if (p is null) { string s = _symbols.NameOf(_positions[pos].symbol); if (s.Length != 0) @@ -2121,13 +2121,13 @@ public override ArrayList ExpectedParticles(ValidationState context, bool isRequ { ArrayList particles = new ArrayList(); BitSet expectedPos; - if (context.RunningPositions != null) + if (context.RunningPositions is not null) { List runningPositions = context.RunningPositions; expectedPos = new BitSet(_positions.Count); for (int i = context.CurrentState.NumberOfRunningPos - 1; i >= 0; i--) { - Debug.Assert(runningPositions[i].curpos != null); + Debug.Assert(runningPositions[i].curpos is not null); expectedPos.Or(runningPositions[i].curpos); } for (int pos = expectedPos.NextSet(-1); pos != -1; pos = expectedPos.NextSet(pos)) @@ -2136,7 +2136,7 @@ public override ArrayList ExpectedParticles(ValidationState context, bool isRequ if (symbol >= 0) { //non range nodes XmlSchemaParticle? p = _positions[pos].particle as XmlSchemaParticle; - if (p == null) + if (p is null) { continue; } @@ -2165,7 +2165,7 @@ public AllElementsContentValidator(XmlSchemaContentType contentType, int size, b public bool AddElement(XmlQualifiedName name, object particle, bool isEmptiable) { - if (_elements[name] != null) + if (_elements[name] is not null) { return false; } @@ -2196,7 +2196,7 @@ public override void InitValidation(ValidationState context) { object? lookup = _elements[name]; errorCode = 0; - if (lookup == null) + if (lookup is null) { context.NeedValidateChildren = false; return null; @@ -2240,7 +2240,7 @@ public override bool CompleteValidation(ValidationState context) { if (!context.AllElementsSet![(int)entry.Value!] && (!isRequiredOnly || _isRequired[(int)entry.Value])) { - if (names == null) + if (names is null) { names = new ArrayList(); } 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 29310bc5b62821..bf24158e2e3a3b 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 @@ -168,7 +168,7 @@ static DatatypeImplementation() internal static XmlSchemaSimpleType StartBuiltinType(XmlQualifiedName qname, XmlSchemaDatatype dataType) { XmlSchemaSimpleType simpleType; - Debug.Assert(qname != null && dataType != null); + Debug.Assert(qname is not null && dataType is not null); simpleType = new XmlSchemaSimpleType(); simpleType.SetQualifiedName(qname); @@ -184,7 +184,7 @@ internal static XmlSchemaSimpleType StartBuiltinType(XmlQualifiedName qname, Xml /// internal static void FinishBuiltinType(XmlSchemaSimpleType derivedType, XmlSchemaSimpleType baseType) { - Debug.Assert(derivedType != null && baseType != null); + Debug.Assert(derivedType is not null && baseType is not null); // Create link from the derived type to the base type derivedType.SetBaseSchemaType(baseType); @@ -321,7 +321,7 @@ internal static XmlSchemaSimpleType GetSimpleTypeFromTypeCode(XmlTypeCode typeCo internal static XmlSchemaSimpleType GetNormalizedStringTypeV1Compat() { - if (s_normalizedStringTypeV1Compat == null) + if (s_normalizedStringTypeV1Compat is null) { XmlSchemaSimpleType correctType = GetSimpleTypeFromTypeCode(XmlTypeCode.NormalizedString); XmlSchemaSimpleType tempNormalizedStringTypeV1Compat = (correctType.Clone() as XmlSchemaSimpleType)!; @@ -336,7 +336,7 @@ internal static XmlSchemaSimpleType GetNormalizedStringTypeV1Compat() internal static XmlSchemaSimpleType GetTokenTypeV1Compat() { - if (s_tokenTypeV1Compat == null) + if (s_tokenTypeV1Compat is null) { XmlSchemaSimpleType correctType = GetSimpleTypeFromTypeCode(XmlTypeCode.Token); XmlSchemaSimpleType tempTokenTypeV1Compat = (correctType.Clone() as XmlSchemaSimpleType)!; @@ -359,7 +359,7 @@ internal static XmlTypeCode GetPrimitiveTypeCode(XmlTypeCode typeCode) while (currentType.BaseXmlSchemaType != DatatypeImplementation.AnySimpleType) { currentType = (currentType.BaseXmlSchemaType as XmlSchemaSimpleType)!; - Debug.Assert(currentType != null); + Debug.Assert(currentType is not null); } return currentType.TypeCode; } @@ -411,13 +411,13 @@ internal override void VerifySchemaValid(XmlSchemaObjectTable notations, XmlSche public override bool IsDerivedFrom(XmlSchemaDatatype datatype) { - if (datatype == null) + if (datatype is null) { return false; } //Common case - Derived by restriction - for (DatatypeImplementation? dt = this; dt != null; dt = dt._baseType) + for (DatatypeImplementation? dt = this; dt is not null; dt = dt._baseType) { if (dt == datatype) { @@ -425,7 +425,7 @@ public override bool IsDerivedFrom(XmlSchemaDatatype datatype) } } - if (((DatatypeImplementation)datatype)._baseType == null) + if (((DatatypeImplementation)datatype)._baseType is null) { //Both are built-in types Type derivedType = this.GetType(); Type baseType = datatype.GetType(); @@ -435,7 +435,7 @@ public override bool IsDerivedFrom(XmlSchemaDatatype datatype) { //base type is union (not a restriction of union) and derived type is not union return ((Datatype_union)datatype).IsUnionBaseOf(this); } - else if ((_variety == XmlSchemaDatatypeVariety.Union || _variety == XmlSchemaDatatypeVariety.List) && _restriction == null) + else if ((_variety == XmlSchemaDatatypeVariety.Union || _variety == XmlSchemaDatatypeVariety.List) && _restriction is null) { //derived type is union (not a restriction) return (datatype == s__anySimpleType.Datatype); } @@ -475,7 +475,7 @@ internal override XmlValueConverter ValueConverter { get { - if (_valueConverter == null) + if (_valueConverter is null) { _valueConverter = CreateValueConverter(_parentSchemaType!); } @@ -507,7 +507,7 @@ internal override bool HasLexicalFacets { get { - RestrictionFlags flags = _restriction != null ? _restriction.Flags : 0; + RestrictionFlags flags = _restriction is not null ? _restriction.Flags : 0; if (flags != 0 && (flags & (RestrictionFlags.Pattern | RestrictionFlags.WhiteSpace | RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) != 0) { return true; @@ -519,7 +519,7 @@ internal override bool HasValueFacets { get { - RestrictionFlags flags = _restriction != null ? _restriction.Flags : 0; + RestrictionFlags flags = _restriction is not null ? _restriction.Flags : 0; if (flags != 0 && (flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength | RestrictionFlags.MaxExclusive | RestrictionFlags.MaxInclusive | RestrictionFlags.MinExclusive | RestrictionFlags.MinInclusive | RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits | RestrictionFlags.Enumeration)) != 0) { return true; @@ -540,12 +540,12 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa { object? typedValue; Exception? exception = TryParseValue(s, nameTable, nsmgr, out typedValue); - if (exception != null) + if (exception is not null) { throw new XmlSchemaException(SR.Sch_InvalidValueDetailed, new string[] { s, GetTypeName(), exception.Message }, exception, null, 0, 0, null); } - Debug.Assert(typedValue != null); + Debug.Assert(typedValue is not null); if (this.Variety == XmlSchemaDatatypeVariety.Union) { @@ -561,12 +561,12 @@ internal override object ParseValue(string s, XmlNameTable? nameTable, IXmlNames { object? typedValue; Exception? exception = TryParseValue(s, nameTable, nsmgr, out typedValue); - if (exception != null) + if (exception is not null) { throw new XmlSchemaException(SR.Sch_InvalidValueDetailed, new string[] { s, GetTypeName(), exception.Message }, exception, null, 0, 0, null); } - Debug.Assert(typedValue != null); + Debug.Assert(typedValue is not null); return typedValue; } else @@ -580,13 +580,13 @@ internal override object ParseValue(string s, XmlNameTable? nameTable, IXmlNames Exception? exception = null; typedValue = null; - if (value == null) + if (value is null) { return new ArgumentNullException(nameof(value)); } string? s = value as string; - if (s != null) + if (s is not null) { return TryParseValue(s, nameTable, namespaceResolver, out typedValue); } @@ -601,12 +601,12 @@ internal override object ParseValue(string s, XmlNameTable? nameTable, IXmlNames { string s1 = (string)this.ValueConverter.ChangeType(value, typeof(string), namespaceResolver); //Using value here to avoid info loss exception = this.FacetsChecker.CheckLexicalFacets(ref s1, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; } if (this.HasValueFacets) { exception = this.FacetsChecker.CheckValueFacets(valueToCheck, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; } typedValue = valueToCheck; return null; @@ -636,7 +636,7 @@ internal string GetTypeName() { XmlSchemaType? simpleType = _parentSchemaType; string typeName; - if (simpleType == null || simpleType.QualifiedName.IsEmpty) + if (simpleType is null || simpleType.QualifiedName.IsEmpty) { //If no QName, get typecode, no line info since it is not pertinent without file name typeName = TypeCodeString; } @@ -931,37 +931,37 @@ internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaTyp XmlSchemaComplexType? complexType; complexType = schemaType as XmlSchemaComplexType; - if (complexType != null) + if (complexType is not null) { do { simpleType = complexType.BaseXmlSchemaType as XmlSchemaSimpleType; - if (simpleType != null) + if (simpleType is not null) { break; } complexType = complexType.BaseXmlSchemaType as XmlSchemaComplexType; - } while (complexType != null && complexType != XmlSchemaComplexType.AnyType); + } while (complexType is not null && complexType != XmlSchemaComplexType.AnyType); } else { simpleType = schemaType as XmlSchemaSimpleType; } - if (simpleType != null) + if (simpleType is not null) { do { XmlSchemaSimpleTypeList? listType = simpleType.Content as XmlSchemaSimpleTypeList; - if (listType != null) + if (listType is not null) { listItemType = listType.BaseItemType; break; } simpleType = simpleType.BaseXmlSchemaType as XmlSchemaSimpleType; - } while (simpleType != null && simpleType != DatatypeImplementation.AnySimpleType); + } while (simpleType is not null && simpleType != DatatypeImplementation.AnySimpleType); } - if (listItemType == null) + if (listItemType is null) { //Get built-in simple type for the typecode listItemType = DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType!.Datatype!.TypeCode); } @@ -979,7 +979,7 @@ internal override int Compare(object value1, object value2) System.Array arr1 = (System.Array)value1; System.Array arr2 = (System.Array)value2; - Debug.Assert(arr1 != null && arr2 != null); + Debug.Assert(arr1 is not null && arr2 is not null); int length = arr1.Length; if (length != arr2.Length) { @@ -987,10 +987,10 @@ internal override int Compare(object value1, object value2) } XmlAtomicValue[]? atomicValues1 = arr1 as XmlAtomicValue[]; - if (atomicValues1 != null) + if (atomicValues1 is not null) { XmlAtomicValue[]? atomicValues2 = arr2 as XmlAtomicValue[]; - Debug.Assert(atomicValues2 != null); + Debug.Assert(atomicValues2 is not null); XmlSchemaType xmlType1; for (int i = 0; i < atomicValues1.Length; i++) { @@ -1043,14 +1043,14 @@ internal override RestrictionFlags ValidRestrictionFlags internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) { Exception? exception; - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } string? s = value as string; typedValue = null; - if (s != null) + if (s is not null) { return TryParseValue(s, nameTable, namespaceResolver, out typedValue); } @@ -1059,7 +1059,7 @@ internal override RestrictionFlags ValidRestrictionFlags { object valueToCheck = this.ValueConverter.ChangeType(value, this.ValueType, namespaceResolver); Array valuesToCheck = (valueToCheck as Array)!; - Debug.Assert(valuesToCheck != null); + Debug.Assert(valuesToCheck is not null); bool checkItemLexical = _itemType.HasLexicalFacets; bool checkItemValue = _itemType.HasValueFacets; @@ -1074,12 +1074,12 @@ internal override RestrictionFlags ValidRestrictionFlags { string s1 = (string)itemValueConverter.ChangeType(item, typeof(string), namespaceResolver); exception = itemFacetsChecker.CheckLexicalFacets(ref s1, _itemType); - if (exception != null) goto Error; + if (exception is not null) goto Error; } if (checkItemValue) { exception = itemFacetsChecker.CheckValueFacets(item, _itemType); - if (exception != null) goto Error; + if (exception is not null) goto Error; } } @@ -1088,12 +1088,12 @@ internal override RestrictionFlags ValidRestrictionFlags { string s1 = (string)this.ValueConverter.ChangeType(valueToCheck, typeof(string), namespaceResolver); exception = listFacetsChecker.CheckLexicalFacets(ref s1, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; } if (this.HasValueFacets) { exception = listFacetsChecker.CheckValueFacets(valueToCheck, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; } typedValue = valueToCheck; return null; @@ -1126,7 +1126,7 @@ internal override RestrictionFlags ValidRestrictionFlags typedValue = null; exception = listFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; ArrayList values = new ArrayList(); object array; @@ -1138,9 +1138,9 @@ internal override RestrictionFlags ValidRestrictionFlags { //Parse items in list according to the itemType exception = _itemType.TryParseValue(splitString[i], nameTable, nsmgr, out unionTypedValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; - Debug.Assert(unionTypedValue != null); + Debug.Assert(unionTypedValue is not null); XsdSimpleValue simpleValue = (XsdSimpleValue)unionTypedValue; values.Add(new XmlAtomicValue(simpleValue.XmlType, simpleValue.TypedValue, nsmgr)); @@ -1153,7 +1153,7 @@ internal override RestrictionFlags ValidRestrictionFlags for (int i = 0; i < splitString.Length; ++i) { exception = _itemType.TryParseValue(splitString[i], nameTable, nsmgr, out typedValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; values.Add(typedValue); } @@ -1166,7 +1166,7 @@ internal override RestrictionFlags ValidRestrictionFlags } exception = listFacetsChecker.CheckValueFacets(array, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = array; @@ -1199,7 +1199,7 @@ internal override int Compare(object value1, object value2) XsdSimpleValue? simpleValue1 = value1 as XsdSimpleValue; XsdSimpleValue? simpleValue2 = value2 as XsdSimpleValue; - if (simpleValue1 == null || simpleValue2 == null) + if (simpleValue1 is null || simpleValue2 is null) { return -1; } @@ -1273,22 +1273,22 @@ internal bool IsUnionBaseOf(DatatypeImplementation derivedType) typedValue = null; exception = unionFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; //Parse string to CLR value for (int i = 0; i < _types.Length; ++i) { exception = _types[i].Datatype!.TryParseValue(s, nameTable, nsmgr, out typedValue); - if (exception == null) + if (exception is null) { memberType = _types[i]; break; } } - Debug.Assert(typedValue != null); + Debug.Assert(typedValue is not null); - if (memberType == null) + if (memberType is null) { exception = new XmlSchemaException(SR.Sch_UnionFailedEx, s); goto Error; @@ -1296,7 +1296,7 @@ internal bool IsUnionBaseOf(DatatypeImplementation derivedType) typedValue = new XsdSimpleValue(memberType, typedValue); exception = unionFacetsChecker.CheckValueFacets(typedValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; return null; @@ -1307,13 +1307,13 @@ internal bool IsUnionBaseOf(DatatypeImplementation derivedType) internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { Exception? exception; - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } typedValue = null; string? s = value as string; - if (s != null) + if (s is not null) { return TryParseValue(s, nameTable, nsmgr, out typedValue); } @@ -1322,14 +1322,14 @@ internal bool IsUnionBaseOf(DatatypeImplementation derivedType) XmlSchemaSimpleType? memberType = null; for (int i = 0; i < _types.Length; ++i) { - if (_types[i].Datatype!.TryParseValue(value, nameTable, nsmgr, out valueToCheck) == null) + if (_types[i].Datatype!.TryParseValue(value, nameTable, nsmgr, out valueToCheck) is null) { //no error memberType = _types[i]; break; } } - if (valueToCheck == null) + if (valueToCheck is null) { exception = new XmlSchemaException(SR.Sch_UnionFailedEx, value.ToString()); goto Error; @@ -1341,15 +1341,15 @@ internal bool IsUnionBaseOf(DatatypeImplementation derivedType) { string s1 = (string)this.ValueConverter.ChangeType(valueToCheck, typeof(string), nsmgr); //Using value here to avoid info loss exception = unionFacetsChecker.CheckLexicalFacets(ref s1, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; } - Debug.Assert(memberType != null); + Debug.Assert(memberType is not null); typedValue = new XsdSimpleValue(memberType, valueToCheck); if (this.HasValueFacets) { exception = unionFacetsChecker.CheckValueFacets(typedValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; } return null; } @@ -1495,10 +1495,10 @@ internal override RestrictionFlags ValidRestrictionFlags typedValue = null; exception = stringFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = stringFacetsChecker.CheckValueFacets(s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = s; return null; @@ -1568,11 +1568,11 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = miscFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; bool boolValue; exception = XmlConvert.TryToBoolean(s, out boolValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = boolValue; @@ -1654,14 +1654,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = numeric2FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; float singleValue; exception = XmlConvert.TryToSingle(s, out singleValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = numeric2FacetsChecker.CheckValueFacets(singleValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = singleValue; @@ -1742,14 +1742,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = numeric2FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; double doubleValue; exception = XmlConvert.TryToDouble(s, out doubleValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = numeric2FacetsChecker.CheckValueFacets(doubleValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = doubleValue; @@ -1837,14 +1837,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; decimal decimalValue; exception = XmlConvert.TryToDecimal(s, out decimalValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets(decimalValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = decimalValue; @@ -1926,20 +1926,20 @@ internal override int Compare(object value1, object value2) Exception? exception; typedValue = null; - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } exception = durationFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; TimeSpan timeSpanValue; exception = XmlConvert.TryToTimeSpan(s, out timeSpanValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = durationFacetsChecker.CheckValueFacets(timeSpanValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = timeSpanValue; @@ -1957,25 +1957,25 @@ internal class Datatype_yearMonthDuration : Datatype_duration Exception? exception; typedValue = null; - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } exception = durationFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; XsdDuration duration; exception = XsdDuration.TryParse(s, XsdDuration.DurationType.YearMonthDuration, out duration); - if (exception != null) goto Error; + if (exception is not null) goto Error; TimeSpan timeSpanValue; exception = duration.TryToTimeSpan(XsdDuration.DurationType.YearMonthDuration, out timeSpanValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = durationFacetsChecker.CheckValueFacets(timeSpanValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = timeSpanValue; @@ -1996,24 +1996,24 @@ internal class Datatype_dayTimeDuration : Datatype_duration typedValue = null; - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } exception = durationFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; XsdDuration duration; exception = XsdDuration.TryParse(s, XsdDuration.DurationType.DayTimeDuration, out duration); - if (exception != null) goto Error; + if (exception is not null) goto Error; TimeSpan timeSpanValue; exception = duration.TryToTimeSpan(XsdDuration.DurationType.DayTimeDuration, out timeSpanValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = durationFacetsChecker.CheckValueFacets(timeSpanValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = timeSpanValue; @@ -2084,7 +2084,7 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = dateTimeFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; XsdDateTime dateTime; if (!XsdDateTime.TryParse(s, _dateTimeFlags, out dateTime)) @@ -2105,7 +2105,7 @@ internal override int Compare(object value1, object value2) } exception = dateTimeFacetsChecker.CheckValueFacets(dateTimeValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = dateTimeValue; @@ -2470,7 +2470,7 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = binaryFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; byte[]? byteArrayValue = null; try @@ -2489,7 +2489,7 @@ internal override int Compare(object value1, object value2) } exception = binaryFacetsChecker.CheckValueFacets(byteArrayValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = byteArrayValue; @@ -2571,7 +2571,7 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = binaryFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; byte[]? byteArrayValue = null; try @@ -2590,7 +2590,7 @@ internal override int Compare(object value1, object value2) } exception = binaryFacetsChecker.CheckValueFacets(byteArrayValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = byteArrayValue; @@ -2678,17 +2678,17 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = stringFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; Uri? uri; exception = XmlConvert.TryToUri(s, out uri); - if (exception != null) goto Error; + if (exception is not null) goto Error; - Debug.Assert(uri != null); + Debug.Assert(uri is not null); string stringValue = uri.OriginalString; exception = ((StringFacetsChecker)stringFacetsChecker).CheckValueFacets(stringValue, this, false); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = uri; @@ -2765,13 +2765,13 @@ internal override RestrictionFlags ValidRestrictionFlags typedValue = null; - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } exception = qnameFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; XmlQualifiedName? qname = null; try @@ -2791,7 +2791,7 @@ internal override RestrictionFlags ValidRestrictionFlags } exception = qnameFacetsChecker.CheckValueFacets(qname, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = qname; @@ -2966,10 +2966,10 @@ internal class Datatype_NCName : Datatype_Name typedValue = null; exception = stringFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = stringFacetsChecker.CheckValueFacets(s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; nameTable!.Add(s); @@ -3101,13 +3101,13 @@ internal override RestrictionFlags ValidRestrictionFlags typedValue = null; - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } exception = qnameFacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; XmlQualifiedName? qname = null; try @@ -3127,7 +3127,7 @@ internal override RestrictionFlags ValidRestrictionFlags } exception = qnameFacetsChecker.CheckValueFacets(qname, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = qname; @@ -3141,9 +3141,9 @@ internal override void VerifySchemaValid(XmlSchemaObjectTable notations, XmlSche { // Only datatypes that are derived from NOTATION by specifying a value for enumeration can be used in a schema. // Furthermore, the value of all enumeration facets must match the name of a notation declared in the current schema. // - for (Datatype_NOTATION? dt = this; dt != null; dt = (Datatype_NOTATION?)dt.Base) + for (Datatype_NOTATION? dt = this; dt is not null; dt = (Datatype_NOTATION?)dt.Base) { - if (dt.Restriction != null && (dt.Restriction.Flags & RestrictionFlags.Enumeration) != 0) + if (dt.Restriction is not null && (dt.Restriction.Flags & RestrictionFlags.Enumeration) != 0) { for (int i = 0; i < dt.Restriction.Enumeration!.Count; ++i) { @@ -3182,14 +3182,14 @@ internal class Datatype_integer : Datatype_decimal typedValue = null; exception = FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; decimal decimalValue; exception = XmlConvert.TryToInteger(s, out decimalValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = FacetsChecker.CheckValueFacets(decimalValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = decimalValue; @@ -3300,14 +3300,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; long int64Value; exception = XmlConvert.TryToInt64(s, out int64Value); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets(int64Value, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = int64Value; @@ -3356,14 +3356,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; int int32Value; exception = XmlConvert.TryToInt32(s, out int32Value); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets(int32Value, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = int32Value; @@ -3413,14 +3413,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; short int16Value; exception = XmlConvert.TryToInt16(s, out int16Value); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets(int16Value, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = int16Value; @@ -3469,14 +3469,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; sbyte sbyteValue; exception = XmlConvert.TryToSByte(s, out sbyteValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets((short)sbyteValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = sbyteValue; @@ -3557,14 +3557,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; ulong uint64Value; exception = XmlConvert.TryToUInt64(s, out uint64Value); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets((decimal)uint64Value, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = uint64Value; @@ -3613,14 +3613,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; uint uint32Value; exception = XmlConvert.TryToUInt32(s, out uint32Value); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets((long)uint32Value, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = uint32Value; @@ -3669,14 +3669,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; ushort uint16Value; exception = XmlConvert.TryToUInt16(s, out uint16Value); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets((int)uint16Value, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = uint16Value; @@ -3724,14 +3724,14 @@ internal override int Compare(object value1, object value2) typedValue = null; exception = s_numeric10FacetsChecker.CheckLexicalFacets(ref s, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; byte byteValue; exception = XmlConvert.TryToByte(s, out byteValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; exception = s_numeric10FacetsChecker.CheckValueFacets((short)byteValue, this); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = byteValue; @@ -3818,11 +3818,11 @@ internal class Datatype_QNameXdr : Datatype_anySimpleType public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { throw new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } - if (nsmgr == null) + if (nsmgr is null) { throw new ArgumentNullException(nameof(nsmgr)); } @@ -3892,7 +3892,7 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa char charValue; exception = XmlConvert.TryToChar(s, out charValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = charValue; @@ -3914,7 +3914,7 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa Numeric10FacetsChecker facetsChecker = (this.FacetsChecker as Numeric10FacetsChecker)!; decimal value = XmlConvert.ToDecimal(s); exception = facetsChecker.CheckTotalAndFractionDigits(value, 14 + 4, 4, true, true); - if (exception != null) goto Error; + if (exception is not null) goto Error; return value; } @@ -3938,11 +3938,11 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa decimal decimalValue; exception = XmlConvert.TryToDecimal(s, out decimalValue); - if (exception != null) goto Error; + if (exception is not null) goto Error; Numeric10FacetsChecker facetsChecker = (this.FacetsChecker as Numeric10FacetsChecker)!; exception = facetsChecker.CheckTotalAndFractionDigits(decimalValue, 14 + 4, 4, true, true); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = decimalValue; @@ -3993,7 +3993,7 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa Guid guid; exception = XmlConvert.TryToGuid(s, out guid); - if (exception != null) goto Error; + if (exception is not null) goto Error; typedValue = guid; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs index 56ef6f58a50b55..f93728f140fce9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs @@ -54,12 +54,12 @@ private async Task ParseAsync(bool saveInternalSubset) _schemaInfo.Finish(); // check undeclared forward references - if (_validate && _undeclaredNotations != null) + if (_validate && _undeclaredNotations is not null) { foreach (UndeclaredNotation un in _undeclaredNotations.Values) { UndeclaredNotation? tmpUn = un; - while (tmpUn != null) + while (tmpUn is not null) { SendValidationEvent(XmlSeverityType.Error, new XmlSchemaException(SR.Sch_UndeclaredNotation, un.name, BaseUriStr, (int)un.lineNo, (int)un.linePos)); tmpUn = tmpUn.next; @@ -111,7 +111,7 @@ private async Task ParseInDocumentDtdAsync(bool saveInternalSubset) } SaveParsingBuffer(); - if (_systemId != null && _systemId.Length > 0) + if (_systemId is not null && _systemId.Length > 0) { await ParseExternalSubsetAsync().ConfigureAwait(false); } @@ -126,7 +126,7 @@ private async Task ParseFreeFloatingDtdAsync() SaveParsingBuffer(); } - if (_systemId != null && _systemId.Length > 0) + if (_systemId is not null && _systemId.Length > 0) { await ParseExternalSubsetAsync().ConfigureAwait(false); } @@ -149,7 +149,7 @@ private async Task ParseExternalSubsetAsync() } Uri? baseUri = _readerAdapter.BaseUri; - if (baseUri != null) + if (baseUri is not null) { _externalDtdBaseUri = baseUri.ToString(); } @@ -229,7 +229,7 @@ private async Task ParseSubsetAsync() Throw(_curPos, SR.Xml_UnclosedConditionalSection); } // append the rest to internal subset value but not the closing ']' - if (_internalSubsetValueSb != null) + if (_internalSubsetValueSb is not null) { Debug.Assert(_curPos > 0 && _chars[_curPos - 1] == ']'); SaveParsingBuffer(_curPos - 1); @@ -324,7 +324,7 @@ private async Task ParseAttlistDeclAsync() // BUG BUG: For backward compatibility, we check the correct type and values of the // xml:space attribute only on the last attribute in the list. // See Webdata bugs #97457 and #93935. - if (attrDef != null && attrDef.Prefix.Length > 0 && attrDef.Prefix.Equals("xml") && attrDef.Name.Name == "space") + if (attrDef is not null && attrDef.Prefix.Length > 0 && attrDef.Prefix.Equals("xml") && attrDef.Name.Name == "space") { attrDef.Reserved = SchemaAttDef.Reserve.XmlSpace; if (attrDef.Datatype.TokenizedType != XmlTokenizedType.ENUMERATION) @@ -342,7 +342,7 @@ private async Task ParseAttlistDeclAsync() goto UnexpectedError; } - bool attrDefAlreadyExists = (elementDecl.GetAttDef(attrDef.Name) != null); + bool attrDefAlreadyExists = (elementDecl.GetAttDef(attrDef.Name) is not null); await ParseAttlistTypeAsync(attrDef, elementDecl, attrDefAlreadyExists).ConfigureAwait(false); await ParseAttlistDefaultAsync(attrDef, attrDefAlreadyExists).ConfigureAwait(false); @@ -416,7 +416,7 @@ private async Task ParseAttlistTypeAsync(SchemaAttDef attrDef, SchemaElementDecl if (_validate && elementDecl.IsIdDeclared) { SchemaAttDef? idAttrDef = elementDecl.GetAttDef(attrDef.Name); - if ((idAttrDef == null || idAttrDef.Datatype.TokenizedType != XmlTokenizedType.ID) && !ignoreErrors) + if ((idAttrDef is null || idAttrDef.Datatype.TokenizedType != XmlTokenizedType.ID) && !ignoreErrors) { SendValidationEvent(XmlSeverityType.Error, SR.Sch_IdAttrDeclared, elementDecl.Name.ToString()); } @@ -435,7 +435,7 @@ private async Task ParseAttlistTypeAsync(SchemaAttDef attrDef, SchemaElementDecl } else { - if (elementDecl.ContentValidator != null && + if (elementDecl.ContentValidator is not null && elementDecl.ContentValidator.ContentType == XmlSchemaContentType.Empty && !ignoreErrors) { @@ -462,7 +462,7 @@ private async Task ParseAttlistTypeAsync(SchemaAttDef attrDef, SchemaElementDecl { AddUndeclaredNotation(notationName); } - if (_validate && !_v1Compat && attrDef.Values != null && attrDef.Values.Contains(notationName) && !ignoreErrors) + if (_validate && !_v1Compat && attrDef.Values is not null && attrDef.Values.Contains(notationName) && !ignoreErrors) { SendValidationEvent(XmlSeverityType.Error, new XmlSchemaException(SR.Xml_AttlistDuplNotationValue, notationName, BaseUriStr, (int)LineNo, (int)LinePos)); } @@ -501,7 +501,7 @@ private async Task ParseAttlistTypeAsync(SchemaAttDef attrDef, SchemaElementDecl if (await GetTokenAsync(false).ConfigureAwait(false) != Token.Nmtoken) goto UnexpectedError; string nmtoken = GetNmtokenString(); - if (_validate && !_v1Compat && attrDef.Values != null && attrDef.Values.Contains(nmtoken) && !ignoreErrors) + if (_validate && !_v1Compat && attrDef.Values is not null && attrDef.Values.Contains(nmtoken) && !ignoreErrors) { SendValidationEvent(XmlSeverityType.Error, new XmlSchemaException(SR.Xml_AttlistDuplEnumValue, nmtoken, BaseUriStr, (int)LineNo, (int)LinePos)); } @@ -951,7 +951,7 @@ private async Task ParseNotationDeclAsync() SchemaNotation? notation = null; if (!_schemaInfo.Notations.ContainsKey(notationName.Name)) { - if (_undeclaredNotations != null) + if (_undeclaredNotations is not null) { _undeclaredNotations.Remove(notationName.Name); } @@ -978,7 +978,7 @@ private async Task ParseNotationDeclAsync() notationPublicId = tuple_2.Item1; notationSystemId = tuple_2.Item2; - if (notation != null) + if (notation is not null) { notation.SystemLiteral = notationSystemId; notation.Pubid = notationPublicId; @@ -1000,7 +1000,7 @@ private async Task ParseCommentAsync() { if (SaveInternalSubsetValue) { - Debug.Assert(_internalSubsetValueSb != null); + Debug.Assert(_internalSubsetValueSb is not null); await _readerAdapter.ParseCommentAsync(_internalSubsetValueSb).ConfigureAwait(false); _internalSubsetValueSb.Append("-->"); } @@ -1028,7 +1028,7 @@ private async Task ParsePIAsync() SaveParsingBuffer(); if (SaveInternalSubsetValue) { - Debug.Assert(_internalSubsetValueSb != null); + Debug.Assert(_internalSubsetValueSb is not null); await _readerAdapter.ParsePIAsync(_internalSubsetValueSb).ConfigureAwait(false); _internalSubsetValueSb.Append("?>"); } @@ -1056,7 +1056,7 @@ private async Task ParseCondSectionAsync() } if (_validate) { - if (_condSectionEntityIds == null) + if (_condSectionEntityIds is null) { _condSectionEntityIds = new int[CondSectionEntityIdsInitialSize]; } @@ -2603,7 +2603,7 @@ private async Task HandleEntityReferenceAsync(XmlQualifiedName entityName, } SchemaEntity? entity = VerifyEntityReference(entityName, paramEntity, true, inAttribute); - if (entity == null) + if (entity is null) { return false; } 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 49a8beb01819a9..dc98cb1ac782c5 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 @@ -42,8 +42,8 @@ public FacetsCompiler(DatatypeImplementation baseDatatype, RestrictionFacets res _pattern_facet = null; _datatype = baseDatatype; _derivedRestriction = restriction; - _baseFlags = _datatype.Restriction != null ? _datatype.Restriction.Flags : 0; - _baseFixedFlags = _datatype.Restriction != null ? _datatype.Restriction.FixedFlags : 0; + _baseFlags = _datatype.Restriction is not null ? _datatype.Restriction.Flags : 0; + _baseFixedFlags = _datatype.Restriction is not null ? _datatype.Restriction.FixedFlags : 0; _validRestrictionFlags = _datatype.ValidRestrictionFlags; _nonNegativeInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.NonNegativeInteger).Datatype!; _builtInEnum = !(_datatype is Datatype_union || _datatype is Datatype_List) ? _datatype.TypeCode : 0; @@ -171,7 +171,7 @@ internal void CompilePatternFacet(XmlSchemaPatternFacet facet) internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited); - if (_derivedRestriction.Enumeration == null) + if (_derivedRestriction.Enumeration is null) { _derivedRestriction.Enumeration = new ArrayList(); } @@ -357,7 +357,7 @@ internal void FinishFacetCompile() //needs to be converted to a RegEx if (_firstPattern == false) { - if (_derivedRestriction.Patterns == null) + if (_derivedRestriction.Patterns is null) { _derivedRestriction.Patterns = new ArrayList(); } @@ -590,7 +590,7 @@ private void CopyFacetsFromBaseType() } if ((_baseFlags & RestrictionFlags.Pattern) != 0) { - if (_derivedRestriction.Patterns == null) + if (_derivedRestriction.Patterns is null) { _derivedRestriction.Patterns = baseRestriction.Patterns; } @@ -604,7 +604,7 @@ private void CopyFacetsFromBaseType() if ((_baseFlags & RestrictionFlags.Enumeration) != 0) { - if (_derivedRestriction.Enumeration == null) + if (_derivedRestriction.Enumeration is null) { _derivedRestriction.Enumeration = baseRestriction.Enumeration; } @@ -673,7 +673,7 @@ private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, { object? typedValue; Exception? ex = datatype.TryParseValue(facet.Value!, nameTable, nsmgr, out typedValue); - if (ex == null) + if (ex is null) { return typedValue!; } @@ -858,7 +858,7 @@ internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) { s = XmlComplianceUtil.CDataNormalize(s); } - else if (restriction != null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0) + else if (restriction is not null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0) { //Restriction has whitespace facet specified if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Replace) { @@ -877,7 +877,7 @@ internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) } internal Exception? CheckPatternFacets(RestrictionFacets? restriction, string value) { - if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0) + if (restriction is not null && (restriction.Flags & RestrictionFlags.Pattern) != 0) { for (int i = 0; i < restriction.Patterns!.Count; ++i) { @@ -907,7 +907,7 @@ internal virtual RestrictionFacets ConstructRestriction(DatatypeImplementation d for (int i = 0; i < facets.Count; ++i) { XmlSchemaFacet facet = (XmlSchemaFacet)facets[i]; - if (facet.Value == null) + if (facet.Value is null) { throw new XmlSchemaException(SR.Sch_InvalidFacet, facet); } @@ -1013,7 +1013,7 @@ internal Numeric10FacetsChecker(decimal minVal, decimal maxVal) internal override Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; //Check built-in facets @@ -1024,7 +1024,7 @@ internal Numeric10FacetsChecker(decimal minVal, decimal maxVal) //Check user-defined facets if (flags != 0) { - Debug.Assert(restriction != null); + Debug.Assert(restriction is not null); if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDecimal(restriction.MaxInclusive!)) @@ -1138,7 +1138,7 @@ internal class Numeric2FacetsChecker : FacetsChecker internal override Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; if ((flags & RestrictionFlags.MaxInclusive) != 0) @@ -1214,7 +1214,7 @@ internal class DurationFacetsChecker : FacetsChecker internal override Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { @@ -1285,7 +1285,7 @@ internal class DateTimeFacetsChecker : FacetsChecker internal override Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { @@ -1356,7 +1356,7 @@ private static Regex LanguagePattern { get { - if (s_languagePattern == null) + if (s_languagePattern is null) { Regex langRegex = new Regex("^([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*$"); Interlocked.CompareExchange(ref s_languagePattern, langRegex, null); @@ -1381,11 +1381,11 @@ private static Regex LanguagePattern //Length, MinLength, MaxLength int length = value.Length; RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; Exception? exception; exception = CheckBuiltInFacets(value, datatype.TypeCode, verifyUri); - if (exception != null) return exception; + if (exception is not null) return exception; if (flags != 0) { @@ -1474,7 +1474,7 @@ private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaData break; case XmlTypeCode.Language: - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } @@ -1516,10 +1516,10 @@ internal class QNameFacetsChecker : FacetsChecker internal override Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; if (flags != 0) { - Debug.Assert(restriction != null); + Debug.Assert(restriction is not null); // If there are facets defined string strValue = value.ToString(); @@ -1590,7 +1590,7 @@ internal class BinaryFacetsChecker : FacetsChecker //Length, MinLength, MaxLength RestrictionFacets? restriction = datatype.Restriction; int length = value.Length; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; if (flags != 0) { //if it has facets defined if ((flags & RestrictionFlags.Length) != 0) @@ -1648,10 +1648,10 @@ internal class ListFacetsChecker : FacetsChecker { // Check for facets allowed on lists - Length, MinLength, MaxLength Array values = (value as Array)!; - Debug.Assert(values != null); + Debug.Assert(values is not null); RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; if ((flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0) { @@ -1708,7 +1708,7 @@ internal class UnionFacetsChecker : FacetsChecker internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; - RestrictionFlags flags = restriction != null ? restriction.Flags : 0; + RestrictionFlags flags = restriction is not null ? restriction.Flags : 0; if ((flags & RestrictionFlags.Enumeration) != 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index 58e9c0ddf9354d..341d020cdb3887 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -170,7 +170,7 @@ public XmlSchemaSet InferSchema(XmlReader instanceDocument) public XmlSchemaSet InferSchema(XmlReader instanceDocument, XmlSchemaSet schemas) { - if (schemas == null) + if (schemas is null) { schemas = new XmlSchemaSet(_nametable); } @@ -179,7 +179,7 @@ public XmlSchemaSet InferSchema(XmlReader instanceDocument, XmlSchemaSet schemas internal XmlSchemaSet InferSchema1(XmlReader instanceDocument, XmlSchemaSet schemas) { - if (instanceDocument == null) + if (instanceDocument is null) { throw new ArgumentNullException(nameof(instanceDocument)); } @@ -212,7 +212,7 @@ internal XmlSchemaSet InferSchema1(XmlReader instanceDocument, XmlSchemaSet sche } } - if (_rootSchema == null) + if (_rootSchema is null) { //rootSchema = CreateXmlSchema(xtr.NamespaceURI); xse = AddElement(_xtr.LocalName, _xtr.Prefix, _xtr.NamespaceURI, null, null, -1); @@ -228,7 +228,7 @@ internal XmlSchemaSet InferSchema1(XmlReader instanceDocument, XmlSchemaSet sche if (listItem.position < listItem.col.Count) { XmlSchemaElement particle = listItem.col[listItem.position] as XmlSchemaElement; - if (particle != null && (particle.RefName.Namespace == XmlSchema.Namespace)) + if (particle is not null && (particle.RefName.Namespace == XmlSchema.Namespace)) { XmlSchemaAny any = new XmlSchemaAny(); if (particle.MaxOccurs != 1) @@ -257,7 +257,7 @@ internal XmlSchemaSet InferSchema1(XmlReader instanceDocument, XmlSchemaSet sche } } } - Debug.Assert(_rootSchema != null, "rootSchema is null"); + Debug.Assert(_rootSchema is not null, "rootSchema is null"); schemas.Reprocess(_rootSchema); schemas.Compile(); //break; @@ -282,7 +282,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string XmlSchema? xs = null; bool add = true; - Debug.Assert(compiledAttributes != null); //AttributeUses is never null + Debug.Assert(compiledAttributes is not null); //AttributeUses is never null // First we need to look into the already compiled attributes // (they come from the schemaset which we got on input) // If there are none or we don't find it there, then we must search the list of attributes @@ -305,11 +305,11 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string XmlSchemaAttribute? attributeReference = null; //see if the reference exists attributeReference = FindAttributeRef(searchCollectionPrimary, localName, childURI); - if (attributeReference == null && searchCollectionSecondary != null) + if (attributeReference is null && searchCollectionSecondary is not null) { attributeReference = FindAttributeRef(searchCollectionSecondary, localName, childURI); } - if (attributeReference == null) + if (attributeReference is null) { attributeReference = new XmlSchemaAttribute(); attributeReference.RefName = new XmlQualifiedName(localName, childURI); @@ -333,7 +333,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string xs = parentSchema; add = false; } - else if (childURI != null && !_schemaSet!.Contains(childURI)) + else if (childURI is not null && !_schemaSet!.Contains(childURI)) { /*if (parentSchema.AttributeFormDefault = XmlSchemaForm.Unqualified && childURI.Length == 0) { @@ -354,7 +354,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string else { ArrayList? col = _schemaSet!.Schemas(childURI) as ArrayList; - if (col != null && col.Count > 0) + if (col is not null && col.Count > 0) { xs = col[0] as XmlSchema; } @@ -365,11 +365,11 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string XmlSchemaAttribute? attributeReference = null; //see if the reference exists attributeReference = FindAttributeRef(searchCollectionPrimary, localName, childURI); - if (attributeReference == null & searchCollectionSecondary != null) + if (attributeReference is null & searchCollectionSecondary is not null) { attributeReference = FindAttributeRef(searchCollectionSecondary!, localName, childURI); } - if (attributeReference == null) + if (attributeReference is null) { attributeReference = new XmlSchemaAttribute(); attributeReference.RefName = new XmlQualifiedName(localName, childURI); @@ -388,7 +388,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string //see if the attribute exists on the global level xsa = FindAttribute(xs!.Items, localName); - if (xsa == null) + if (xsa is null) { xsa = new XmlSchemaAttribute(); xsa.Name = localName; @@ -398,7 +398,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string } else { - if (xsa.Parent == null) + if (xsa.Parent is null) { AttributeType = xsa.LineNumber; // we use LineNumber to store flags of valid types } @@ -414,11 +414,11 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string else { xsa = FindAttribute(searchCollectionPrimary, localName); - if (xsa == null && searchCollectionSecondary != null) + if (xsa is null && searchCollectionSecondary is not null) { xsa = FindAttribute(searchCollectionSecondary, localName); } - if (xsa == null) + if (xsa is null) { xsa = new XmlSchemaAttribute(); xsa.Name = localName; @@ -436,7 +436,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string } else { - if (xsa.Parent == null) + if (xsa.Parent is null) { AttributeType = xsa.LineNumber; // we use LineNumber to store flags of valid types } @@ -457,7 +457,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string for (int i = 0; i < parentSchema.Includes.Count; ++i) { XmlSchemaImport? import = parentSchema.Includes[i] as XmlSchemaImport; - if (import == null) + if (import is null) { continue; } @@ -487,7 +487,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string private XmlSchema CreateXmlSchema(string targetNS) { - Debug.Assert(targetNS == null || targetNS.Length > 0, "targetns for schema is empty"); + Debug.Assert(targetNS is null || targetNS.Length > 0, "targetns for schema is empty"); XmlSchema xs = new XmlSchema(); xs.AttributeFormDefault = XmlSchemaForm.Unqualified; xs.ElementFormDefault = XmlSchemaForm.Qualified; @@ -513,12 +513,12 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi } // The new element belongs to the same ns as parent and addlocation is not null - if (parentSchema != null && childURI == parentSchema.TargetNamespace) + if (parentSchema is not null && childURI == parentSchema.TargetNamespace) { xse = new XmlSchemaElement(); xse.Name = localName; xs = parentSchema; - if (xs.ElementFormDefault != XmlSchemaForm.Qualified && addLocation != null) + if (xs.ElementFormDefault != XmlSchemaForm.Qualified && addLocation is not null) { xse.Form = XmlSchemaForm.Qualified; } @@ -526,10 +526,10 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi else if (_schemaSet!.Contains(childURI)) { xse = this.FindGlobalElement(childURI, localName, out xs); - if (xse == null) + if (xse is null) { ArrayList? col = _schemaSet.Schemas(childURI) as ArrayList; - if (col != null && col.Count > 0) + if (col is not null && col.Count > 0) { xs = col[0] as XmlSchema; } @@ -549,7 +549,7 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi xse.Name = localName; xs.Items.Add(xse); //add global element declaration only when creating new schema } - if (parentSchema == null) + if (parentSchema is null) { parentSchema = xs; _rootSchema = parentSchema; @@ -562,7 +562,7 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi for (int i = 0; i < parentSchema.Includes.Count; ++i) { XmlSchemaImport? import = parentSchema.Includes[i] as XmlSchemaImport; - if (import == null) + if (import is null) { continue; } @@ -582,7 +582,7 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi } } returnedElement = xse; - if (addLocation != null) + if (addLocation is not null) { if (childURI == parentSchema.TargetNamespace) { @@ -652,12 +652,12 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else { - if (!bCreatingNewType && ct != null) + if (!bCreatingNewType && ct is not null) { //if type already exists and can potentially have attributes MakeExistingAttributesOptional(ct, null); } } - if (ct == null || ct == XmlSchemaComplexType.AnyType) + if (ct is null || ct == XmlSchemaComplexType.AnyType) { //It was null or simple type, after processing attributes, this might have been set ct = xse.SchemaType as XmlSchemaComplexType; } @@ -666,14 +666,14 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem { if (!bCreatingNewType) { - if (null != ct) + if (ct is not null) { - if (null != ct.Particle) + if (ct.Particle is not null) { ct.Particle.MinOccurs = 0; } - else if (null != ct.ContentModel) + else if (ct.ContentModel is not null) { XmlSchemaSimpleContentExtension sce = CheckSimpleContentExtension(ct); sce.BaseTypeName = ST_string; @@ -711,9 +711,9 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem { if (bWhiteSpace) { - if (ct != null) + if (ct is not null) { - if (null != ct.ContentModel) + if (ct.ContentModel is not null) { XmlSchemaSimpleContentExtension sce = CheckSimpleContentExtension(ct); sce.BaseTypeName = ST_string; @@ -721,7 +721,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else if (bCreatingNewType) { - //attributes exist, but both Particle and ContentModel == null - this must be complex type with simpleContent extension + //attributes exist, but both Particle and ContentModel is null - this must be complex type with simpleContent extension XmlSchemaSimpleContent sc = new XmlSchemaSimpleContent(); ct.ContentModel = sc; XmlSchemaSimpleContentExtension sce = new XmlSchemaSimpleContentExtension(); @@ -748,13 +748,13 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else { - if (null != ct) + if (ct is not null) { - if (null != ct.Particle) + if (ct.Particle is not null) { ct.Particle.MinOccurs = 0; } - else if (null != ct.ContentModel) + else if (ct.ContentModel is not null) { XmlSchemaSimpleContentExtension sce = CheckSimpleContentExtension(ct); sce.BaseTypeName = ST_string; @@ -778,9 +778,9 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem iChildNumber++; if ((_xtr.NodeType == XmlNodeType.Text) || (_xtr.NodeType == XmlNodeType.CDATA)) //node can be simple type, complex with simple content or complex with mixed content { - if (null != ct) + if (ct is not null) { - if (null != ct.Particle) + if (ct.Particle is not null) { ct.IsMixed = true; if (iChildNumber == 1) @@ -792,13 +792,13 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem ct.Particle.MinOccurs = decimal.Zero; } } - else if (null != ct.ContentModel) + else if (ct.ContentModel is not null) { //complexType with simpleContent XmlSchemaSimpleContentExtension sce = CheckSimpleContentExtension(ct); if ((_xtr.NodeType == XmlNodeType.Text) && (iChildNumber == 1)) { int SimpleType = -1; - if (xse.Parent == null) + if (xse.Parent is null) { SimpleType = sce.LineNumber; // we use LineNumber to represent valid type flags } @@ -818,7 +818,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else { - //attributes exist, but both Particle and ContentModel == null - this must be complex type with simpleContent extension + //attributes exist, but both Particle and ContentModel is null - this must be complex type with simpleContent extension XmlSchemaSimpleContent sc = new XmlSchemaSimpleContent(); ct.ContentModel = sc; XmlSchemaSimpleContentExtension sce = new XmlSchemaSimpleContentExtension(); @@ -869,7 +869,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else if (_xtr.NodeType == XmlNodeType.Text) { - if (xse.Parent == null) + if (xse.Parent is null) { TypeFlags = xse.LineNumber; } @@ -905,7 +905,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem { table.Add(qname, null); } - if (ct == null) + if (ct is null) { //untill now the element was empty or SimpleType - it now becomes complex type ct = new XmlSchemaComplexType(); xse.SchemaType = ct; @@ -915,13 +915,13 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem xse.SchemaTypeName = XmlQualifiedName.Empty; } } - if (ct.ContentModel != null) + if (ct.ContentModel is not null) { //type was previously identified as simple content extension - we need to convert it to sequence XmlSchemaSimpleContentExtension sce = CheckSimpleContentExtension(ct); MoveAttributes(sce, ct); ct.ContentModel = null; ct.IsMixed = true; - if (ct.Particle != null) + if (ct.Particle is not null) throw new XmlSchemaInferenceException(SR.SchInf_particle, 0, 0); ct.Particle = new XmlSchemaSequence(); bCreatingNewSequence = true; @@ -930,7 +930,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem if (!bCreatingNewType) ct.Particle.MinOccurs = 0; //previously this was simple type so subelements did not exist } - else if (ct.Particle == null) + else if (ct.Particle is null) { ct.Particle = new XmlSchemaSequence(); bCreatingNewSequence = true; @@ -951,7 +951,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else if (_xtr.NodeType == XmlNodeType.Text) { - if (ct == null) + if (ct is null) throw new XmlSchemaInferenceException(SR.SchInf_ct, 0, 0); ct.IsMixed = true; } @@ -987,12 +987,12 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem private XmlSchemaSimpleContentExtension CheckSimpleContentExtension(XmlSchemaComplexType ct) { XmlSchemaSimpleContent? sc = ct.ContentModel as XmlSchemaSimpleContent; - if (sc == null) + if (sc is null) { throw new XmlSchemaInferenceException(SR.SchInf_simplecontent, 0, 0); } XmlSchemaSimpleContentExtension? sce = sc.Content as XmlSchemaSimpleContentExtension; - if (sce == null) + if (sce is null) { throw new XmlSchemaInferenceException(SR.SchInf_extension, 0, 0); } @@ -1002,25 +1002,25 @@ private XmlSchemaSimpleContentExtension CheckSimpleContentExtension(XmlSchemaCom private XmlSchemaType? GetEffectiveSchemaType(XmlSchemaElement elem, bool bCreatingNewType) { XmlSchemaType? effectiveSchemaType = null; - if (!bCreatingNewType && elem.ElementSchemaType != null) + if (!bCreatingNewType && elem.ElementSchemaType is not null) { effectiveSchemaType = elem.ElementSchemaType; } else { //creating new type, hence look up pre-compiled info - Debug.Assert(elem.ElementDecl == null); - if (elem.SchemaType != null) + Debug.Assert(elem.ElementDecl is null); + if (elem.SchemaType is not null) { effectiveSchemaType = elem.SchemaType; } else if (elem.SchemaTypeName != XmlQualifiedName.Empty) { effectiveSchemaType = _schemaSet!.GlobalTypes[elem.SchemaTypeName] as XmlSchemaType; - if (effectiveSchemaType == null) + if (effectiveSchemaType is null) { effectiveSchemaType = XmlSchemaType.GetBuiltInSimpleType(elem.SchemaTypeName); } - if (effectiveSchemaType == null) + if (effectiveSchemaType is null) { effectiveSchemaType = XmlSchemaType.GetBuiltInComplexType(elem.SchemaTypeName); } @@ -1071,7 +1071,7 @@ internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader x for (int i = 0; i < xsch.Items.Count; ++i) { XmlSchemaElement? el = xsch.Items[i] as XmlSchemaElement; - if (el == null) + if (el is null) { throw new XmlSchemaInferenceException(SR.SchInf_UnknownParticle, 0, 0); } @@ -1099,7 +1099,7 @@ internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader x iSeqItem = lastUsedSeqItem; XmlSchemaParticle? particle = xss.Items[iSeqItem] as XmlSchemaParticle; XmlSchemaElement? el = particle as XmlSchemaElement; - if (el == null) + if (el is null) { throw new XmlSchemaInferenceException(SR.SchInf_UnknownParticle, 0, 0); } @@ -1129,7 +1129,7 @@ internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader x { particle = xss.Items[iSeqItem] as XmlSchemaParticle; el = particle as XmlSchemaElement; - if (el == null) + if (el is null) { throw new XmlSchemaInferenceException(SR.SchInf_UnknownParticle, 0, 0); } @@ -1175,12 +1175,12 @@ internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader x else { subElement = FindElementRef(xss.Items, xtr.LocalName, xtr.NamespaceURI); - if (subElement != null) + if (subElement is not null) { actualElement = FindGlobalElement(childURI, xtr.LocalName, out parentSchema); } } - if (null != subElement) + if (subElement is not null) { XmlSchemaChoice xsc = new XmlSchemaChoice(); xsc.MaxOccurs = decimal.MaxValue; @@ -1240,7 +1240,7 @@ internal void ProcessAttributes(ref XmlSchemaElement xse, XmlSchemaType? effecti } else { - if (ct == null || ct == XmlSchemaComplexType.AnyType) + if (ct is null || ct == XmlSchemaComplexType.AnyType) { ct = new XmlSchemaComplexType(); xse.SchemaType = ct; @@ -1250,10 +1250,10 @@ internal void ProcessAttributes(ref XmlSchemaElement xse, XmlSchemaType? effecti //The earlier assumption of checking just schemaTypeName !Empty is not correct for schemas that are not generated by us, schemaTypeName can point to any complex type as well //Check that it is a simple type by checking typeCode //Switch to complex type simple content extension - if (effectiveSchemaType != null && effectiveSchemaType.Datatype != null && !xse.SchemaTypeName.IsEmpty) + if (effectiveSchemaType is not null && effectiveSchemaType.Datatype is not null && !xse.SchemaTypeName.IsEmpty) { //type was previously simple type, now it will become complex with simple type extension - Debug.Assert(ct != null); + Debug.Assert(ct is not null); XmlSchemaSimpleContent sc = new XmlSchemaSimpleContent(); ct.ContentModel = sc; XmlSchemaSimpleContentExtension sce = new XmlSchemaSimpleContentExtension(); @@ -1264,18 +1264,18 @@ internal void ProcessAttributes(ref XmlSchemaElement xse, XmlSchemaType? effecti xse.SchemaTypeName = XmlQualifiedName.Empty; //re-set the name } - Debug.Assert(ct != null); //either the user-defined type itself is a complex type or we switched from a simple type to a complex type - if (ct.ContentModel != null) + Debug.Assert(ct is not null); //either the user-defined type itself is a complex type or we switched from a simple type to a complex type + if (ct.ContentModel is not null) { XmlSchemaSimpleContentExtension sce = CheckSimpleContentExtension(ct); - Debug.Assert(sce != null); + Debug.Assert(sce is not null); xsa = AddAttribute(_xtr.LocalName, _xtr.Prefix, _xtr.NamespaceURI, _xtr.Value, bCreatingNewType, parentSchema, sce.Attributes, ct.AttributeUses); } else //add attributes directly to complex type { xsa = AddAttribute(_xtr.LocalName, _xtr.Prefix, _xtr.NamespaceURI, _xtr.Value, bCreatingNewType, parentSchema, ct.Attributes, ct.AttributeUses); } - if (xsa != null) + if (xsa is not null) { attributesSeen.Add(xsa); } @@ -1284,7 +1284,7 @@ internal void ProcessAttributes(ref XmlSchemaElement xse, XmlSchemaType? effecti if (!bCreatingNewType) { //make attributes that did not appear this time optional - if (ct != null) + if (ct is not null) { MakeExistingAttributesOptional(ct, attributesSeen); } @@ -1328,7 +1328,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten foreach (XmlSchemaObject? xsa in attributes) { XmlSchemaAttribute? schemaAttribute = xsa as XmlSchemaAttribute; - if (schemaAttribute != null) + if (schemaAttribute is not null) { if (schemaAttribute.Name == attrName) { @@ -1347,7 +1347,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten foreach (XmlSchema? schema in col) { xse = FindElement(schema!.Items, localName); - if (xse != null) + if (xse is not null) { parentSchema = schema; return xse; @@ -1362,7 +1362,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten for (int i = 0; i < elements.Count; ++i) { XmlSchemaElement? xse = elements[i] as XmlSchemaElement; - if (xse != null && xse.RefName != null) + if (xse is not null && xse.RefName is not null) { if (xse.Name == elementName) { @@ -1379,7 +1379,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten foreach (XmlSchemaObject? xsa in attributes) { XmlSchemaAttribute? schemaAttribute = xsa as XmlSchemaAttribute; - if (schemaAttribute != null) + if (schemaAttribute is not null) { if (schemaAttribute.RefName.Name == attributeName && schemaAttribute.RefName.Namespace == nsURI) { @@ -1396,7 +1396,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten for (int i = 0; i < elements.Count; ++i) { XmlSchemaElement? xse = elements[i] as XmlSchemaElement; - if (xse != null && xse.RefName != null) + if (xse is not null && xse.RefName is not null) { if (xse.RefName.Name == elementName && xse.RefName.Namespace == nsURI) { @@ -1410,11 +1410,11 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten internal void MakeExistingAttributesOptional(XmlSchemaComplexType ct, XmlSchemaObjectCollection? attributesInInstance) { - if (ct == null) + if (ct is null) { throw new XmlSchemaInferenceException(SR.SchInf_noct, 0, 0); } - if (ct.ContentModel != null) + if (ct.ContentModel is not null) { XmlSchemaSimpleContentExtension xssce = CheckSimpleContentExtension(ct); SwitchUseToOptional(xssce.Attributes, attributesInInstance); @@ -1430,20 +1430,20 @@ private void SwitchUseToOptional(XmlSchemaObjectCollection attributes, XmlSchema for (int i = 0; i < attributes.Count; ++i) { XmlSchemaAttribute? attr = attributes[i] as XmlSchemaAttribute; - if (attr != null) + if (attr is not null) { - if (attributesInInstance != null) + if (attributesInInstance is not null) { if (attr.RefName.Name.Length == 0) { //If the attribute is not present in this instance, make it optional - if (null == FindAttribute(attributesInInstance, attr.Name!)) + if (FindAttribute(attributesInInstance, attr.Name!) is null) { attr.Use = XmlSchemaUse.Optional; } } else { - if (null == FindAttributeRef(attributesInInstance, attr.RefName.Name, attr.RefName.Namespace)) + if (FindAttributeRef(attributesInInstance, attr.RefName.Name, attr.RefName.Namespace) is null) { attr.Use = XmlSchemaUse.Optional; } @@ -1748,7 +1748,7 @@ internal XmlQualifiedName RefineSimpleType(string s, ref int iTypeFlags) Debug.Fail("Expected type not matched"); return ST_string; } - /* if (currentType == null) + /* if (currentType is null) return SimpleTypes[newType]; else return SimpleTypes[ST_Map[newType,(short) ST_Codes[currentType]]]; @@ -2513,7 +2513,7 @@ private static int GetSchemaType(XmlQualifiedName qname) { return TF_string; } - if (qname == null || qname.IsEmpty) + if (qname is null || qname.IsEmpty) { return -1; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs index 6a83819b7fb400..7477a6dedad8bb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs @@ -58,7 +58,7 @@ public void StartParsing(XmlReader reader, string? targetNamespace) _reader = reader; _positionInfo = PositionInfo.GetPositionInfo(reader); _namespaceManager = reader.NamespaceManager; - if (_namespaceManager == null) + if (_namespaceManager is null) { _namespaceManager = new XmlNamespaceManager(_nameTable); _isProcessNamespaces = true; @@ -205,7 +205,7 @@ public bool ParseReaderNode() { //AppInfo and Documentation _markupDepth = _reader.Depth; _processMarkup = true; - if (_annotationNSManager == null) + if (_annotationNSManager is null) { _annotationNSManager = new XmlNamespaceManager(_nameTable); _xmlns = _nameTable.Add("xmlns"); @@ -238,7 +238,7 @@ public bool ParseReaderNode() { if (_processMarkup) { - Debug.Assert(_parentNode != null); + Debug.Assert(_parentNode is not null); XmlNodeList list = _parentNode.ChildNodes; XmlNode?[] markup = new XmlNode[list.Count]; for (int i = 0; i < list.Count; i++) @@ -321,8 +321,8 @@ private void ProcessAppInfoDocMarkup(bool root) break; default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc - Debug.Assert(currentNode != null); - Debug.Assert(_parentNode != null); + Debug.Assert(currentNode is not null); + Debug.Assert(_parentNode is not null); _parentNode.AppendChild(currentNode); break; } @@ -359,7 +359,7 @@ private XmlElement LoadElementNode(bool root) } r.MoveToElement(); string? ns = _annotationNSManager!.LookupNamespace(r.Prefix); - if (ns == null) + if (ns is null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager!.LookupNamespace(r.Prefix)!); attributes.Append(attr); @@ -379,7 +379,7 @@ private XmlElement LoadElementNode(bool root) if (r.Prefix.Length != 0) { string? attNS = _annotationNSManager.LookupNamespace(r.Prefix); - if (attNS == null) + if (attNS is null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager!.LookupNamespace(r.Prefix)!); attributes.Append(attr); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs index be4c75527c211b..2dd350bdd479ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs @@ -19,7 +19,7 @@ public async Task StartParsingAsync(XmlReader reader, string? targetNamespace) _reader = reader; _positionInfo = PositionInfo.GetPositionInfo(reader); _namespaceManager = reader.NamespaceManager; - if (_namespaceManager == null) + if (_namespaceManager is null) { _namespaceManager = new XmlNamespaceManager(_nameTable); _isProcessNamespaces = true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index 26f8fcb7688464..496be3affb1ae2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -43,7 +43,7 @@ private void Prepare() if (!element!.SubstitutionGroup.IsEmpty) { XmlSchemaSubstitutionGroup? substitutionGroup = (XmlSchemaSubstitutionGroup?)_examplars[element.SubstitutionGroup]; - if (substitutionGroup == null) + if (substitutionGroup is null) { substitutionGroup = new XmlSchemaSubstitutionGroupV1Compat(); substitutionGroup.Examplar = element.SubstitutionGroup; @@ -97,12 +97,12 @@ internal static void Cleanup(XmlSchema schema) for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; - if (include.Schema != null) + if (include.Schema is not null) { Cleanup(include.Schema); } XmlSchemaRedefine? rdef = include as XmlSchemaRedefine; - if (rdef != null) + if (rdef is not null) { rdef.AttributeGroups.Clear(); rdef.Groups.Clear(); @@ -118,27 +118,27 @@ internal static void Cleanup(XmlSchema schema) XmlSchemaElement? element; XmlSchemaGroup? group; - if ((attr = item as XmlSchemaAttribute) != null) + if ((attr = item as XmlSchemaAttribute) is not null) { CleanupAttribute(attr); } - else if ((attrgroup = item as XmlSchemaAttributeGroup) != null) + else if ((attrgroup = item as XmlSchemaAttributeGroup) is not null) { CleanupAttributeGroup(attrgroup); } - else if ((complextype = item as XmlSchemaComplexType) != null) + else if ((complextype = item as XmlSchemaComplexType) is not null) { CleanupComplexType(complextype); } - else if ((simpletype = item as XmlSchemaSimpleType) != null) + else if ((simpletype = item as XmlSchemaSimpleType) is not null) { CleanupSimpleType(simpletype); } - else if ((element = item as XmlSchemaElement) != null) + else if ((element = item as XmlSchemaElement) is not null) { CleanupElement(element); } - else if ((group = item as XmlSchemaGroup) != null) + else if ((group = item as XmlSchemaGroup) is not null) { CleanupGroup(group); } @@ -156,27 +156,27 @@ internal static void Cleanup(XmlSchema schema) XmlSchemaElement? element; XmlSchemaGroup? group; - if ((attr = item as XmlSchemaAttribute) != null) + if ((attr = item as XmlSchemaAttribute) is not null) { CleanupAttribute(attr); } - else if ((attrgroup = schema.Items[i] as XmlSchemaAttributeGroup) != null) + else if ((attrgroup = schema.Items[i] as XmlSchemaAttributeGroup) is not null) { CleanupAttributeGroup(attrgroup); } - else if ((complextype = schema.Items[i] as XmlSchemaComplexType) != null) + else if ((complextype = schema.Items[i] as XmlSchemaComplexType) is not null) { CleanupComplexType(complextype); } - else if ((simpletype = schema.Items[i] as XmlSchemaSimpleType) != null) + else if ((simpletype = schema.Items[i] as XmlSchemaSimpleType) is not null) { CleanupSimpleType(simpletype); } - else if ((element = schema.Items[i] as XmlSchemaElement) != null) + else if ((element = schema.Items[i] as XmlSchemaElement) is not null) { CleanupElement(element); } - else if ((group = schema.Items[i] as XmlSchemaGroup) != null) + else if ((group = schema.Items[i] as XmlSchemaGroup) is not null) { CleanupGroup(group); } @@ -224,7 +224,7 @@ private void Compile() } foreach (XmlSchemaElement? element in _schema.Elements.Values) { - if (element!.ElementDecl == null) + if (element!.ElementDecl is null) { CompileElement(element); } @@ -232,7 +232,7 @@ private void Compile() foreach (XmlSchemaAttribute? attribute in _schema.Attributes.Values) { - if (attribute!.AttDef == null) + if (attribute!.AttDef is null) { CompileAttribute(attribute); } @@ -240,7 +240,7 @@ private void Compile() foreach (XmlSchemaIdentityConstraint? identityConstraint in _schema.IdentityConstraints.Values) { - if (identityConstraint!.CompiledConstraint == null) + if (identityConstraint!.CompiledConstraint is null) { CompileIdentityConstraint(identityConstraint); } @@ -294,7 +294,7 @@ private void Output(SchemaInfo schemaInfo) { schemaInfo.TargetNamespaces[type!.QualifiedName.Namespace] = true; XmlSchemaComplexType? complexType = type as XmlSchemaComplexType; - if (complexType == null || (!complexType.IsAbstract && type != XmlSchemaComplexType.AnyType)) + if (complexType is null || (!complexType.IsAbstract && type != XmlSchemaComplexType.AnyType)) { schemaInfo.ElementDeclsByType.Add(type.QualifiedName, type.ElementDecl!); } @@ -314,7 +314,7 @@ private void Output(SchemaInfo schemaInfo) private static void CleanupAttribute(XmlSchemaAttribute attribute) { - if (attribute.SchemaType != null) + if (attribute.SchemaType is not null) { CleanupSimpleType((XmlSchemaSimpleType)attribute.SchemaType); } @@ -330,7 +330,7 @@ private static void CleanupAttributeGroup(XmlSchemaAttributeGroup attributeGroup private static void CleanupComplexType(XmlSchemaComplexType complexType) { - if (complexType.ContentModel != null) + if (complexType.ContentModel is not null) { //simpleContent or complexContent if (complexType.ContentModel is XmlSchemaSimpleContent) { @@ -382,10 +382,10 @@ private static void CleanupSimpleType(XmlSchemaSimpleType simpleType) private static void CleanupElement(XmlSchemaElement element) { - if (element.SchemaType != null) + if (element.SchemaType is not null) { XmlSchemaComplexType? complexType = element.SchemaType as XmlSchemaComplexType; - if (complexType != null) + if (complexType is not null) { CleanupComplexType(complexType); } @@ -406,7 +406,7 @@ private static void CleanupAttributes(XmlSchemaObjectCollection attributes) for (int i = 0; i < attributes.Count; ++i) { XmlSchemaAttribute? attribute = attributes[i] as XmlSchemaAttribute; - if (attribute != null) + if (attribute is not null) { CleanupAttribute(attribute); } @@ -450,7 +450,7 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroupV1Compat substit } substitutionGroup.IsProcessing = true; - if (examplar != null) + if (examplar is not null) { if (examplar.FinalResolved == XmlSchemaDerivationMethod.All) { @@ -462,7 +462,7 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroupV1Compat substit XmlSchemaElement element = (XmlSchemaElement)substitutionGroup.Members[i]!; //Chain to other head's that are members of this head's substGroup XmlSchemaSubstitutionGroupV1Compat? g = (XmlSchemaSubstitutionGroupV1Compat?)_examplars[element!.QualifiedName]; - if (g != null) + if (g is not null) { CompileSubstitutionGroup(g); for (int j = 0; j < g.Choice.Items.Count; ++j) @@ -488,7 +488,7 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroupV1Compat substit private void CheckSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGroup) { XmlSchemaElement? examplar = (XmlSchemaElement?)_schema!.Elements[substitutionGroup.Examplar]; - if (examplar != null) + if (examplar is not null) { for (int i = 0; i < substitutionGroup.Members.Count; ++i) { @@ -515,11 +515,11 @@ private void CompileGroup(XmlSchemaGroup group) else { group.IsProcessing = true; - if (group.CanonicalParticle == null) + if (group.CanonicalParticle is null) { group.CanonicalParticle = CannonicalizeParticle(group.Particle, true, true); } - Debug.Assert(group.CanonicalParticle != null); + Debug.Assert(group.CanonicalParticle is not null); group.IsProcessing = false; } } @@ -530,7 +530,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) { throw new XmlSchemaException(SR.Sch_TypeCircularRef, simpleType); } - if (simpleType.ElementDecl != null) + if (simpleType.ElementDecl is not null) { // already compiled return; } @@ -551,7 +551,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) else { XmlSchemaSimpleType? type = GetSimpleType(list.ItemTypeName); - if (type != null) + if (type is not null) { if ((type.FinalResolved & XmlSchemaDerivationMethod.List) != 0) { @@ -578,7 +578,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) simpleType.SetBaseSchemaType(restriction.BaseType); datatype = restriction.BaseType!.Datatype!; } - else if (simpleType.Redefined != null && restriction.BaseTypeName == simpleType.Redefined.QualifiedName) + else if (simpleType.Redefined is not null && restriction.BaseTypeName == simpleType.Redefined.QualifiedName) { CompileSimpleType((XmlSchemaSimpleType)simpleType.Redefined); simpleType.SetBaseSchemaType(simpleType.Redefined.BaseXmlSchemaType); @@ -591,7 +591,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) throw new XmlSchemaException(SR.Sch_InvalidSimpleTypeRestriction, restriction.BaseTypeName.ToString(), simpleType); } XmlSchemaSimpleType? type = GetSimpleType(restriction.BaseTypeName); - if (type != null) + if (type is not null) { if ((type.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) { @@ -619,7 +619,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(simpleType); } @@ -645,12 +645,12 @@ private XmlSchemaSimpleType[] CompileBaseMemberTypes(XmlSchemaSimpleType simpleT XmlSchemaSimpleTypeUnion mainUnion = (XmlSchemaSimpleTypeUnion)simpleType.Content!; XmlQualifiedName[]? mainMemberTypes = mainUnion.MemberTypes; - if (mainMemberTypes != null) + if (mainMemberTypes is not null) { for (int i = 0; i < mainMemberTypes.Length; ++i) { unionMember = GetSimpleType(mainMemberTypes[i]); - if (unionMember != null) + if (unionMember is not null) { if (unionMember.Datatype!.Variety == XmlSchemaDatatypeVariety.Union) { //union of union @@ -675,7 +675,7 @@ private XmlSchemaSimpleType[] CompileBaseMemberTypes(XmlSchemaSimpleType simpleT //Now add the baseTypes that are defined inside the union itself XmlSchemaObjectCollection mainBaseTypes = mainUnion.BaseTypes; - if (mainBaseTypes != null) + if (mainBaseTypes is not null) { for (int i = 0; i < mainBaseTypes.Count; ++i) { @@ -713,7 +713,7 @@ private void CheckUnionType(XmlSchemaSimpleType unionMember, ArrayList memberTyp private void CompileComplexType(XmlSchemaComplexType complexType) { - if (complexType.ElementDecl != null) + if (complexType.ElementDecl is not null) { //already compiled return; } @@ -723,7 +723,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) return; } complexType.IsProcessing = true; - if (complexType.ContentModel != null) + if (complexType.ContentModel is not null) { //simpleContent or complexContent if (complexType.ContentModel is XmlSchemaSimpleContent) { @@ -765,7 +765,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) if (attribute!.Use != XmlSchemaUse.Prohibited) { XmlSchemaDatatype? datatype = attribute.Datatype; - if (datatype != null && datatype.TokenizedType == XmlTokenizedType.ID) + if (datatype is not null && datatype.TokenizedType == XmlTokenizedType.ID) { if (hasID) { @@ -796,7 +796,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) } else { - if (!decl.AttDefs.ContainsKey(attribute.QualifiedName) && attribute.AttDef != null && attribute.AttDef.Name != XmlQualifiedName.Empty && attribute.AttDef != SchemaAttDef.Empty) + if (!decl.AttDefs.ContainsKey(attribute.QualifiedName) && attribute.AttDef is not null && attribute.AttDef.Name != XmlQualifiedName.Empty && attribute.AttDef != SchemaAttDef.Empty) { decl.AddAttDef(attribute.AttDef); } @@ -812,7 +812,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, XmlSchemaSimpleContentExtension simpleExtension) { XmlSchemaComplexType? baseType = null; - if (complexType.Redefined != null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -822,7 +822,7 @@ private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, Xml else { XmlSchemaType? bto = GetAnySchemaType(simpleExtension.BaseTypeName); - if (bto == null) + if (bto is null) { SendValidationEvent(SR.Sch_UndeclaredType, simpleExtension.BaseTypeName.ToString(), complexType); } @@ -833,7 +833,7 @@ private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, Xml } baseType = bto as XmlSchemaComplexType; } - if (baseType != null) + if (baseType is not null) { if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Extension) != 0) { @@ -852,7 +852,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X { XmlSchemaComplexType? baseType = null; XmlSchemaDatatype? datatype = null; - if (complexType.Redefined != null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -861,14 +861,14 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X else { baseType = GetComplexType(simpleRestriction.BaseTypeName); - if (baseType == null) + if (baseType is null) { SendValidationEvent(SR.Sch_UndefBaseRestriction, simpleRestriction.BaseTypeName.ToString(), simpleRestriction); return; } if (baseType.ContentType == XmlSchemaContentType.TextOnly) { - if (simpleRestriction.BaseType == null) + if (simpleRestriction.BaseType is null) { datatype = baseType.Datatype; //There is a bug here. Need to check if simpleRestriction has facets. @@ -886,7 +886,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X } else if (baseType.ContentType == XmlSchemaContentType.Mixed && baseType.ElementDecl!.ContentValidator!.IsEmptiable) { - if (simpleRestriction.BaseType != null) + if (simpleRestriction.BaseType is not null) { CompileSimpleType(simpleRestriction.BaseType); complexType.SetBaseSchemaType(simpleRestriction.BaseType); @@ -902,18 +902,18 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X SendValidationEvent(SR.Sch_NotSimpleContent, complexType); } } - if (baseType != null && baseType.ElementDecl != null) + if (baseType is not null && baseType.ElementDecl is not null) { if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) { SendValidationEvent(SR.Sch_BaseFinalRestriction, complexType); } } - if (baseType != null) + if (baseType is not null) { complexType.SetBaseSchemaType(baseType); } - if (datatype != null) + if (datatype is not null) { try { @@ -921,7 +921,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(complexType); } @@ -936,7 +936,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X private void CompileComplexContentExtension(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentExtension complexExtension) { XmlSchemaComplexType? baseType = null; - if (complexType.Redefined != null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -944,13 +944,13 @@ private void CompileComplexContentExtension(XmlSchemaComplexType complexType, Xm else { baseType = GetComplexType(complexExtension.BaseTypeName); - if (baseType == null) + if (baseType is null) { SendValidationEvent(SR.Sch_UndefBaseExtension, complexExtension.BaseTypeName.ToString(), complexExtension); return; } } - if (baseType != null && baseType.ElementDecl != null) + if (baseType is not null && baseType.ElementDecl is not null) { if (baseType.ContentType == XmlSchemaContentType.TextOnly) { @@ -1002,7 +1002,7 @@ private void CompileComplexContentExtension(XmlSchemaComplexType complexType, Xm private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentRestriction complexRestriction) { XmlSchemaComplexType? baseType = null; - if (complexType.Redefined != null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -1010,13 +1010,13 @@ private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, else { baseType = GetComplexType(complexRestriction.BaseTypeName); - if (baseType == null) + if (baseType is null) { SendValidationEvent(SR.Sch_UndefBaseRestriction, complexRestriction.BaseTypeName.ToString(), complexRestriction); return; } } - if (baseType != null && baseType.ElementDecl != null) + if (baseType is not null && baseType.ElementDecl is not null) { if (baseType.ContentType == XmlSchemaContentType.TextOnly) { @@ -1036,11 +1036,11 @@ private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, complexType.SetContentType(GetSchemaContentType(complexType, complexContent, complexType.ContentTypeParticle)); if (complexType.ContentType == XmlSchemaContentType.Empty) { - if (baseType.ElementDecl != null) + if (baseType.ElementDecl is not null) { - Debug.Assert(baseType.ElementDecl.ContentValidator != null); + Debug.Assert(baseType.ElementDecl.ContentValidator is not null); } - if (baseType.ElementDecl != null && !baseType.ElementDecl.ContentValidator!.IsEmptiable) + if (baseType.ElementDecl is not null && !baseType.ElementDecl.ContentValidator!.IsEmptiable) { SendValidationEvent(SR.Sch_InvalidContentRestriction, complexType); } @@ -1052,7 +1052,7 @@ private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, private void CheckParticleDerivation(XmlSchemaComplexType complexType) { XmlSchemaComplexType? baseType = complexType.BaseXmlSchemaType as XmlSchemaComplexType; - if (baseType != null && baseType != XmlSchemaComplexType.AnyType && complexType.DerivedBy == XmlSchemaDerivationMethod.Restriction) + if (baseType is not null && baseType != XmlSchemaComplexType.AnyType && complexType.DerivedBy == XmlSchemaDerivationMethod.Restriction) { if (!IsValidRestriction(complexType.ContentTypeParticle, baseType.ContentTypeParticle)) { @@ -1065,7 +1065,7 @@ private XmlSchemaParticle CompileContentTypeParticle(XmlSchemaParticle? particle { XmlSchemaParticle ctp = CannonicalizeParticle(particle, true, substitution); XmlSchemaChoice? choice = ctp as XmlSchemaChoice; - if (choice != null && choice.Items.Count == 0) + if (choice is not null && choice.Items.Count == 0) { if (choice.MinOccurs != decimal.Zero) { @@ -1078,7 +1078,7 @@ private XmlSchemaParticle CompileContentTypeParticle(XmlSchemaParticle? particle private XmlSchemaParticle CannonicalizeParticle(XmlSchemaParticle? particle, bool root, bool substitution) { - if (particle == null || particle.IsEmpty) + if (particle is null || particle.IsEmpty) { return XmlSchemaParticle.Empty; } @@ -1113,7 +1113,7 @@ private XmlSchemaParticle CannonicalizeElement(XmlSchemaElement element, bool su if (!element.RefName.IsEmpty && substitution && (element.BlockResolved & XmlSchemaDerivationMethod.Substitution) == 0) { XmlSchemaSubstitutionGroupV1Compat? substitutionGroup = (XmlSchemaSubstitutionGroupV1Compat?)_examplars[element.QualifiedName]; - if (substitutionGroup == null) + if (substitutionGroup is null) { return element; } @@ -1134,7 +1134,7 @@ private XmlSchemaParticle CannonicalizeElement(XmlSchemaElement element, bool su private XmlSchemaParticle CannonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool root, bool substitution) { XmlSchemaGroup? group; - if (groupRef.Redefined != null) + if (groupRef.Redefined is not null) { group = groupRef.Redefined; } @@ -1142,12 +1142,12 @@ private XmlSchemaParticle CannonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool { group = (XmlSchemaGroup?)_schema!.Groups[groupRef.RefName]; } - if (group == null) + if (group is null) { SendValidationEvent(SR.Sch_UndefGroupRef, groupRef.RefName.ToString(), groupRef); return XmlSchemaParticle.Empty; } - if (group.CanonicalParticle == null) + if (group.CanonicalParticle is null) { CompileGroup(group); } @@ -1334,11 +1334,11 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart { return true; } - else if (derivedParticle == null || derivedParticle == XmlSchemaParticle.Empty) + else if (derivedParticle is null || derivedParticle == XmlSchemaParticle.Empty) { return IsParticleEmptiable(baseParticle); } - else if (baseParticle == null || baseParticle == XmlSchemaParticle.Empty) + else if (baseParticle is null || baseParticle == XmlSchemaParticle.Empty) { return false; } @@ -1422,9 +1422,9 @@ private bool IsElementFromElement(XmlSchemaElement derivedElement, XmlSchemaElem return (derivedElement.QualifiedName == baseElement.QualifiedName) && (derivedElement.IsNillable == baseElement.IsNillable) && IsValidOccurrenceRangeRestriction(derivedElement, baseElement) && - (baseElement.FixedValue == null || baseElement.FixedValue == derivedElement.FixedValue) && + (baseElement.FixedValue is null || baseElement.FixedValue == derivedElement.FixedValue) && ((derivedElement.BlockResolved | baseElement.BlockResolved) == derivedElement.BlockResolved) && - (derivedElement.ElementSchemaType != null) && (baseElement.ElementSchemaType != null) && + (derivedElement.ElementSchemaType is not null) && (baseElement.ElementSchemaType is not null) && XmlSchemaType.IsDerivedFrom(derivedElement.ElementSchemaType, baseElement.ElementSchemaType, ~XmlSchemaDerivationMethod.Restriction); } @@ -1707,12 +1707,12 @@ private void PushComplexType(XmlSchemaComplexType complexType) private XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent? complexContent, XmlSchemaParticle particle) { - if ((complexContent != null && complexContent.IsMixed) || - (complexContent == null && complexType.IsMixed)) + if ((complexContent is not null && complexContent.IsMixed) || + (complexContent is null && complexType.IsMixed)) { return XmlSchemaContentType.Mixed; } - else if (particle != null && !particle.IsEmpty) + else if (particle is not null && !particle.IsEmpty) { return XmlSchemaContentType.ElementOnly; } @@ -1738,13 +1738,13 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) for (int i = 0; i < attributeGroup.Attributes.Count; ++i) { XmlSchemaAttribute? attribute = attributeGroup.Attributes[i] as XmlSchemaAttribute; - if (attribute != null) + if (attribute is not null) { if (attribute.Use != XmlSchemaUse.Prohibited) { CompileAttribute(attribute); } - if (attributeGroup.AttributeUses[attribute.QualifiedName] == null) + if (attributeGroup.AttributeUses[attribute.QualifiedName] is null) { attributeGroup.AttributeUses.Add(attribute.QualifiedName, attribute); } @@ -1757,7 +1757,7 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) { // XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributeGroup.Attributes[i]; XmlSchemaAttributeGroup? attributeGroupResolved; - if (attributeGroup.Redefined != null && attributeGroupRef.RefName == attributeGroup.Redefined.QualifiedName) + if (attributeGroup.Redefined is not null && attributeGroupRef.RefName == attributeGroup.Redefined.QualifiedName) { attributeGroupResolved = (XmlSchemaAttributeGroup)attributeGroup.Redefined; } @@ -1765,12 +1765,12 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) { attributeGroupResolved = (XmlSchemaAttributeGroup?)_schema!.AttributeGroups[attributeGroupRef.RefName]; } - if (attributeGroupResolved != null) + if (attributeGroupResolved is not null) { CompileAttributeGroup(attributeGroupResolved); foreach (XmlSchemaAttribute? attributeValue in attributeGroupResolved.AttributeUses.Values) { - if (attributeGroup.AttributeUses[attributeValue!.QualifiedName] == null) + if (attributeGroup.AttributeUses[attributeValue!.QualifiedName] is null) { attributeGroup.AttributeUses.Add(attributeValue.QualifiedName, attributeValue); } @@ -1794,11 +1794,11 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaComplexType derivedType, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute? anyAttribute, XmlSchemaDerivationMethod derivedBy) { - XmlSchemaAnyAttribute? baseAttributeWildcard = baseType != null ? baseType.AttributeWildcard : null; + XmlSchemaAnyAttribute? baseAttributeWildcard = baseType is not null ? baseType.AttributeWildcard : null; for (int i = 0; i < attributes.Count; ++i) { XmlSchemaAttribute? attribute = attributes[i] as XmlSchemaAttribute; - if (attribute != null) + if (attribute is not null) { if (attribute.Use != XmlSchemaUse.Prohibited) { @@ -1807,7 +1807,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom if (attribute.Use != XmlSchemaUse.Prohibited || (attribute.Use == XmlSchemaUse.Prohibited && derivedBy == XmlSchemaDerivationMethod.Restriction && baseType != XmlSchemaComplexType.AnyType)) { - if (derivedType.AttributeUses[attribute.QualifiedName] == null) + if (derivedType.AttributeUses[attribute.QualifiedName] is null) { derivedType.AttributeUses.Add(attribute.QualifiedName, attribute); } @@ -1825,7 +1825,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom { // is XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributes[i]; XmlSchemaAttributeGroup? attributeGroup = (XmlSchemaAttributeGroup?)_schema!.AttributeGroups[attributeGroupRef.RefName]; - if (attributeGroup != null) + if (attributeGroup is not null) { CompileAttributeGroup(attributeGroup); foreach (XmlSchemaAttribute? attributeValue in attributeGroup.AttributeUses.Values) @@ -1833,7 +1833,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom if (attributeValue!.Use != XmlSchemaUse.Prohibited || (attributeValue.Use == XmlSchemaUse.Prohibited && derivedBy == XmlSchemaDerivationMethod.Restriction && baseType != XmlSchemaComplexType.AnyType)) { - if (derivedType.AttributeUses[attributeValue.QualifiedName] == null) + if (derivedType.AttributeUses[attributeValue.QualifiedName] is null) { derivedType.AttributeUses.Add(attributeValue.QualifiedName, attributeValue); } @@ -1857,7 +1857,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom } // check derivation rules - if (baseType != null) + if (baseType is not null) { if (derivedBy == XmlSchemaDerivationMethod.Extension) { @@ -1865,7 +1865,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom foreach (XmlSchemaAttribute? attributeBase in baseType.AttributeUses.Values) { XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)derivedType.AttributeUses[attributeBase!.QualifiedName]; - if (attribute != null) + if (attribute is not null) { Debug.Assert(attribute.Use != XmlSchemaUse.Prohibited); if (attribute.AttributeSchemaType != attributeBase.AttributeSchemaType || attributeBase.Use == XmlSchemaUse.Prohibited) @@ -1882,7 +1882,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom else { // derivedBy == XmlSchemaDerivationMethod.Restriction // Schema Component Constraint: Derivation Valid (Restriction, Complex) - if ((anyAttribute != null) && (baseAttributeWildcard == null || !XmlSchemaAnyAttribute.IsSubset(anyAttribute, baseAttributeWildcard))) + if ((anyAttribute is not null) && (baseAttributeWildcard is null || !XmlSchemaAnyAttribute.IsSubset(anyAttribute, baseAttributeWildcard))) { SendValidationEvent(SR.Sch_InvalidAnyAttributeRestriction, derivedType); } @@ -1895,7 +1895,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom foreach (XmlSchemaAttribute? attributeBase in baseType.AttributeUses.Values) { XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)derivedType.AttributeUses[attributeBase!.QualifiedName]; - if (attribute == null) + if (attribute is null) { derivedType.AttributeUses.Add(attributeBase.QualifiedName, attributeBase); } @@ -1909,7 +1909,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom { continue; } - else if (attributeBase.AttributeSchemaType == null || attribute.AttributeSchemaType == null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) + else if (attributeBase.AttributeSchemaType is null || attribute.AttributeSchemaType is null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) { SendValidationEvent(SR.Sch_AttributeRestrictionInvalid, attribute); } @@ -1920,12 +1920,12 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom foreach (XmlSchemaAttribute? attribute in derivedType.AttributeUses.Values) { XmlSchemaAttribute? attributeBase = (XmlSchemaAttribute?)baseType.AttributeUses[attribute!.QualifiedName]; - if (attributeBase != null) + if (attributeBase is not null) { continue; } - if (baseAttributeWildcard == null || !baseAttributeWildcard.Allows(attribute.QualifiedName)) + if (baseAttributeWildcard is null || !baseAttributeWildcard.Allows(attribute.QualifiedName)) { SendValidationEvent(SR.Sch_AttributeRestrictionInvalidFromWildcard, attribute); } @@ -1940,18 +1940,18 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom private XmlSchemaAnyAttribute? CompileAnyAttributeUnion(XmlSchemaAnyAttribute? a, XmlSchemaAnyAttribute? b) { - if (a == null) + if (a is null) { return b; } - else if (b == null) + else if (b is null) { return a; } else { XmlSchemaAnyAttribute? attribute = XmlSchemaAnyAttribute.Union(a, b, true); //true for v1Compat - if (attribute == null) + if (attribute is null) { SendValidationEvent(SR.Sch_UnexpressibleAnyAttribute, a); } @@ -1961,18 +1961,18 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom private XmlSchemaAnyAttribute? CompileAnyAttributeIntersection(XmlSchemaAnyAttribute? a, XmlSchemaAnyAttribute? b) { - if (a == null) + if (a is null) { return b; } - else if (b == null) + else if (b is null) { return a; } else { XmlSchemaAnyAttribute? attribute = XmlSchemaAnyAttribute.Intersection(a, b, true); //true for v1Compat - if (attribute == null) + if (attribute is null) { SendValidationEvent(SR.Sch_UnexpressibleAnyAttribute, a); } @@ -1987,7 +1987,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) SendValidationEvent(SR.Sch_AttributeCircularRef, xa); return; } - if (xa.AttDef != null) + if (xa.AttDef is not null) { //already compiled? return; } @@ -1998,25 +1998,25 @@ private void CompileAttribute(XmlSchemaAttribute xa) if (!xa.RefName.IsEmpty) { XmlSchemaAttribute? a = (XmlSchemaAttribute?)_schema!.Attributes[xa.RefName]; - if (a == null) + if (a is null) { throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, xa.RefName.ToString(), xa); } CompileAttribute(a); - if (a.AttDef == null) + if (a.AttDef is null) { throw new XmlSchemaException(SR.Sch_RefInvalidAttribute, xa.RefName.ToString(), xa); } decl = a.AttDef.Clone(); - if (decl.Datatype != null) + if (decl.Datatype is not null) { - if (a.FixedValue != null) + if (a.FixedValue is not null) { - if (xa.DefaultValue != null) + if (xa.DefaultValue is not null) { throw new XmlSchemaException(SR.Sch_FixedDefaultInRef, xa.RefName.ToString(), xa); } - else if (xa.FixedValue != null) + else if (xa.FixedValue is not null) { if (xa.FixedValue != a.FixedValue) { @@ -2030,9 +2030,9 @@ private void CompileAttribute(XmlSchemaAttribute xa) decl.DefaultValueTyped = decl.Datatype.ParseValue(decl.DefaultValueRaw, NameTable, new SchemaNamespaceManager(xa), true); } } - else if (a.DefaultValue != null) + else if (a.DefaultValue is not null) { - if (xa.DefaultValue == null && xa.FixedValue == null) + if (xa.DefaultValue is null && xa.FixedValue is null) { decl.Presence = SchemaDeclBase.Use.Default; decl.DefaultValueRaw = decl.DefaultValueExpanded = a.DefaultValue; @@ -2045,7 +2045,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) else { decl = new SchemaAttDef(xa.QualifiedName); - if (xa.SchemaType != null) + if (xa.SchemaType is not null) { CompileSimpleType(xa.SchemaType); xa.SetAttributeType(xa.SchemaType); @@ -2055,7 +2055,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) else if (!xa.SchemaTypeName.IsEmpty) { XmlSchemaSimpleType? simpleType = GetSimpleType(xa.SchemaTypeName); - if (simpleType != null) + if (simpleType is not null) { xa.SetAttributeType(simpleType); decl.Datatype = simpleType.Datatype!; @@ -2073,13 +2073,13 @@ private void CompileAttribute(XmlSchemaAttribute xa) xa.SetAttributeType(DatatypeImplementation.AnySimpleType); } } - if (decl.Datatype != null) + if (decl.Datatype is not null) { decl.Datatype.VerifySchemaValid(_schema!.Notations, xa); } - if (xa.DefaultValue != null || xa.FixedValue != null) + if (xa.DefaultValue is not null || xa.FixedValue is not null) { - if (xa.DefaultValue != null) + if (xa.DefaultValue is not null) { decl.Presence = SchemaDeclBase.Use.Default; decl.DefaultValueRaw = decl.DefaultValueExpanded = xa.DefaultValue; @@ -2089,7 +2089,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) decl.Presence = SchemaDeclBase.Use.Fixed; decl.DefaultValueRaw = decl.DefaultValueExpanded = xa.FixedValue; } - if (decl.Datatype != null) + if (decl.Datatype is not null) { decl.DefaultValueTyped = decl.Datatype.ParseValue(decl.DefaultValueRaw, NameTable, new SchemaNamespaceManager(xa), true); } @@ -2114,7 +2114,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(xa); } @@ -2136,7 +2136,7 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) return; } - if (xi.CompiledConstraint != null) + if (xi.CompiledConstraint is not null) { return; } @@ -2150,12 +2150,12 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) if (xi is XmlSchemaKeyref) { XmlSchemaIdentityConstraint? ic = (XmlSchemaIdentityConstraint?)_schema!.IdentityConstraints[((XmlSchemaKeyref)xi).Refer]; - if (ic == null) + if (ic is null) { throw new XmlSchemaException(SR.Sch_UndeclaredIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); } CompileIdentityConstraint(ic); - if (ic.CompiledConstraint == null) + if (ic.CompiledConstraint is null) { throw new XmlSchemaException(SR.Sch_RefInvalidIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); } @@ -2174,7 +2174,7 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(xi); } @@ -2195,7 +2195,7 @@ private void CompileElement(XmlSchemaElement xe) SendValidationEvent(SR.Sch_ElementCircularRef, xe); return; } - if (xe.ElementDecl != null) + if (xe.ElementDecl is not null) { return; } @@ -2206,12 +2206,12 @@ private void CompileElement(XmlSchemaElement xe) if (!xe.RefName.IsEmpty) { XmlSchemaElement? e = (XmlSchemaElement?)_schema!.Elements[xe.RefName]; - if (e == null) + if (e is null) { throw new XmlSchemaException(SR.Sch_UndeclaredElement, xe.RefName.ToString(), xe); } CompileElement(e); - if (e.ElementDecl == null) + if (e.ElementDecl is null) { throw new XmlSchemaException(SR.Sch_RefInvalidElement, xe.RefName.ToString(), xe); } @@ -2220,14 +2220,14 @@ private void CompileElement(XmlSchemaElement xe) } else { - if (xe.SchemaType != null) + if (xe.SchemaType is not null) { xe.SetElementType(xe.SchemaType); } else if (!xe.SchemaTypeName.IsEmpty) { xe.SetElementType(GetAnySchemaType(xe.SchemaTypeName)); - if (xe.ElementSchemaType == null) + if (xe.ElementSchemaType is null) { throw new XmlSchemaException(SR.Sch_UndeclaredType, xe.SchemaTypeName.ToString(), xe); } @@ -2235,7 +2235,7 @@ private void CompileElement(XmlSchemaElement xe) else if (!xe.SubstitutionGroup.IsEmpty) { XmlSchemaElement? examplar = (XmlSchemaElement?)_schema!.Elements[xe.SubstitutionGroup]; - if (examplar == null) + if (examplar is null) { throw new XmlSchemaException(SR.Sch_UndeclaredEquivClass, xe.SubstitutionGroup.Name, xe); } @@ -2244,7 +2244,7 @@ private void CompileElement(XmlSchemaElement xe) return; } CompileElement(examplar); - if (examplar.ElementDecl == null) + if (examplar.ElementDecl is null) { //If head is invalid, fall back to AnyType xe.SetElementType(XmlSchemaComplexType.AnyType); decl = XmlSchemaComplexType.AnyType.ElementDecl!.Clone(); @@ -2261,14 +2261,14 @@ private void CompileElement(XmlSchemaElement xe) decl = XmlSchemaComplexType.AnyType.ElementDecl!.Clone(); } - if (decl == null) + if (decl is null) { - Debug.Assert(xe.ElementSchemaType != null); + Debug.Assert(xe.ElementSchemaType is not null); if (xe.ElementSchemaType is XmlSchemaComplexType) { XmlSchemaComplexType complexType = (XmlSchemaComplexType)xe.ElementSchemaType; CompileComplexType(complexType); - if (complexType.ElementDecl != null) + if (complexType.ElementDecl is not null) { decl = complexType.ElementDecl.Clone(); // decl.LocalElements = complexType.LocalElementDecls; @@ -2278,7 +2278,7 @@ private void CompileElement(XmlSchemaElement xe) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)xe.ElementSchemaType; CompileSimpleType(simpleType); - if (simpleType.ElementDecl != null) + if (simpleType.ElementDecl is not null) { decl = simpleType.ElementDecl.Clone(); } @@ -2288,25 +2288,25 @@ private void CompileElement(XmlSchemaElement xe) decl!.Name = xe.QualifiedName; decl.IsAbstract = xe.IsAbstract; XmlSchemaComplexType? ct = xe.ElementSchemaType as XmlSchemaComplexType; - if (ct != null) + if (ct is not null) { decl.IsAbstract |= ct.IsAbstract; } decl.IsNillable = xe.IsNillable; decl.Block |= xe.BlockResolved; } - if (decl.Datatype != null) + if (decl.Datatype is not null) { decl.Datatype.VerifySchemaValid(_schema!.Notations, xe); } - if (xe.DefaultValue != null || xe.FixedValue != null) + if (xe.DefaultValue is not null || xe.FixedValue is not null) { - if (decl.ContentValidator != null) + if (decl.ContentValidator is not null) { if (decl.ContentValidator.ContentType == XmlSchemaContentType.TextOnly) { - if (xe.DefaultValue != null) + if (xe.DefaultValue is not null) { decl.Presence = SchemaDeclBase.Use.Default; decl.DefaultValueRaw = xe.DefaultValue; @@ -2316,7 +2316,7 @@ private void CompileElement(XmlSchemaElement xe) decl.Presence = SchemaDeclBase.Use.Fixed; decl.DefaultValueRaw = xe.FixedValue!; } - if (decl.Datatype != null) + if (decl.Datatype is not null) { decl.DefaultValueTyped = decl.Datatype.ParseValue(decl.DefaultValueRaw, NameTable, new SchemaNamespaceManager(xe), true); } @@ -2346,7 +2346,7 @@ private void CompileElement(XmlSchemaElement xe) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(xe); } @@ -2370,7 +2370,7 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) return ContentValidator.TextOnly; } XmlSchemaParticle particle = complexType.ContentTypeParticle; - if (particle == null || particle == XmlSchemaParticle.Empty) + if (particle is null || particle == XmlSchemaParticle.Empty) { if (complexType.ContentType == XmlSchemaContentType.ElementOnly) { @@ -2601,7 +2601,7 @@ private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchema { XmlSchemaElement localElement = (XmlSchemaElement)particle; CompileElement(localElement); - if (complexType.LocalElements[localElement.QualifiedName] == null) + if (complexType.LocalElements[localElement.QualifiedName] is null) { complexType.LocalElements.Add(localElement.QualifiedName, localElement); } @@ -2644,7 +2644,7 @@ private void CompileCompexTypeElements(XmlSchemaComplexType complexType) private XmlSchemaSimpleType? GetSimpleType(XmlQualifiedName name) { XmlSchemaSimpleType? type = _schema!.SchemaTypes[name] as XmlSchemaSimpleType; - if (type != null) + if (type is not null) { CompileSimpleType(type); } @@ -2652,7 +2652,7 @@ private void CompileCompexTypeElements(XmlSchemaComplexType complexType) { type = DatatypeImplementation.GetSimpleTypeFromXsdType(name); //Re-assign datatype impl for V1Compat - if (type != null) + if (type is not null) { if (type.TypeCode == XmlTypeCode.NormalizedString) { @@ -2671,7 +2671,7 @@ private void CompileCompexTypeElements(XmlSchemaComplexType complexType) private XmlSchemaComplexType? GetComplexType(XmlQualifiedName name) { XmlSchemaComplexType? type = _schema!.SchemaTypes[name] as XmlSchemaComplexType; - if (type != null) + if (type is not null) { CompileComplexType(type); } @@ -2681,7 +2681,7 @@ private void CompileCompexTypeElements(XmlSchemaComplexType complexType) private XmlSchemaType? GetAnySchemaType(XmlQualifiedName name) { XmlSchemaType? type = (XmlSchemaType?)_schema!.SchemaTypes[name]; - if (type != null) + if (type is not null) { if (type is XmlSchemaComplexType) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs index afd5c7840d4eda..ed21e6081728cd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs @@ -74,7 +74,7 @@ internal Dictionary GeneralEntities { get { - if (_generalEntities == null) + if (_generalEntities is null) { _generalEntities = new Dictionary(); } @@ -86,7 +86,7 @@ internal Dictionary ParameterEntities { get { - if (_parameterEntities == null) + if (_parameterEntities is null) { _parameterEntities = new Dictionary(); } @@ -119,7 +119,7 @@ internal Dictionary Notations { get { - if (_notations == null) + if (_notations is null) { _notations = new Dictionary(); } @@ -159,7 +159,7 @@ internal int ErrorCount internal XmlSchemaElement? GetElement(XmlQualifiedName qname) { SchemaElementDecl? ed = GetElementDecl(qname); - if (ed != null) + if (ed is not null) { return ed.SchemaElement; } @@ -180,10 +180,10 @@ internal bool Contains(string ns) internal SchemaAttDef? GetAttributeXdr(SchemaElementDecl? ed, XmlQualifiedName qname) { SchemaAttDef? attdef = null; - if (ed != null) + if (ed is not null) { attdef = ed.GetAttDef(qname); ; - if (attdef == null) + if (attdef is null) { if (!ed.ContentValidator!.IsOpen || qname.Namespace.Length == 0) { @@ -204,16 +204,16 @@ internal bool Contains(string ns) { SchemaAttDef? attdef = null; attributeMatchState = AttributeMatchState.UndeclaredAttribute; - if (ed != null) + if (ed is not null) { attdef = ed.GetAttDef(qname); - if (attdef != null) + if (attdef is not null) { attributeMatchState = AttributeMatchState.AttributeFound; return attdef; } XmlSchemaAnyAttribute? any = ed.AnyAttribute; - if (any != null) + if (any is not null) { if (!any.NamespaceList!.Allows(qname)) { @@ -247,10 +247,10 @@ internal bool Contains(string ns) attributeMatchState = AttributeMatchState.ProhibitedAttribute; } } - else if (partialValidationType != null) + else if (partialValidationType is not null) { XmlSchemaAttribute? attr = partialValidationType as XmlSchemaAttribute; - if (attr != null) + if (attr is not null) { if (qname.Equals(attr.QualifiedName)) { @@ -320,7 +320,7 @@ internal void Add(SchemaInfo sinfo, ValidationEventHandler? eventhandler) } else if (_schemaType != sinfo.SchemaType) { - if (eventhandler != null) + if (eventhandler is not null) { eventhandler(this, new ValidationEventArgs(new XmlSchemaException(SR.Sch_MixSchemaTypes, string.Empty))); } @@ -376,7 +376,7 @@ internal void Finish() { _hasNonCDataAttributes = true; } - if (e.DefaultAttDefs != null) + if (e.DefaultAttDefs is not null) { _hasDefaultAttributes = true; } @@ -426,7 +426,7 @@ IEnumerable IDtdInfo.GetAttributeLists() IDtdEntityInfo? IDtdInfo.LookupEntity(string name) { - if (_generalEntities == null) + if (_generalEntities is null) { return null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs index 9c3b9055f30270..ee7a039064c565 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs @@ -24,10 +24,10 @@ public SchemaNamespaceManager(XmlSchemaObject node) return XmlReservedNs.NsXml; } Dictionary namespaces; - for (XmlSchemaObject? current = _node; current != null; current = current.Parent) + for (XmlSchemaObject? current = _node; current is not null; current = current.Parent) { namespaces = current.Namespaces.Namespaces; - if (namespaces != null && namespaces.Count > 0) + if (namespaces is not null && namespaces.Count > 0) { string? uri; if (namespaces.TryGetValue(prefix, out uri)) @@ -44,10 +44,10 @@ public SchemaNamespaceManager(XmlSchemaObject node) return "xml"; } Dictionary namespaces; - for (XmlSchemaObject? current = _node; current != null; current = current.Parent) + for (XmlSchemaObject? current = _node; current is not null; current = current.Parent) { namespaces = current.Namespaces.Namespaces; - if (namespaces != null && namespaces.Count > 0) + if (namespaces is not null && namespaces.Count > 0) { foreach (KeyValuePair entry in namespaces) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index 98b63e36e8748e..e0efe2f34226b5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -48,7 +48,7 @@ public bool Execute(XmlSchemaSet schemaSet, SchemaInfo schemaCompiledInfo) internal void Prepare(XmlSchema schema, bool cleanup) { - if (_schemasToCompile[schema] != null) + if (_schemasToCompile[schema] is not null) { return; } @@ -99,7 +99,7 @@ internal void Prepare(XmlSchema schema, bool cleanup) if (cleanup) { XmlSchemaComplexType? ct = type as XmlSchemaComplexType; - if (ct != null) + if (ct is not null) { CleanupComplexType(ct); } @@ -125,7 +125,7 @@ internal void Prepare(XmlSchema schema, bool cleanup) private void UpdateSForSSimpleTypes() { - Debug.Assert(_schemaForSchema != null); + Debug.Assert(_schemaForSchema is not null); XmlSchemaSimpleType[] schemaSimpleTypes = DatatypeImplementation.GetBuiltInTypes(); XmlSchemaSimpleType builtInType; //Using enumToTypeCode array; indexed by XmlTypeCode; Start indexing from 12 since schema types start there and iterate till Length - 2 as the last 2 are xquery types @@ -144,7 +144,7 @@ private void Output(SchemaInfo schemaInfo) foreach (XmlSchema? schema in _schemasToCompile.Values) { tns = schema!.TargetNamespace; - if (tns == null) + if (tns is null) { tns = string.Empty; } @@ -197,7 +197,7 @@ internal void ImportAllCompiledSchemas(XmlSchemaSet schemaSet) internal bool Compile() { _schemaTypes.Insert(DatatypeImplementation.QnAnyType, XmlSchemaComplexType.AnyType); - if (_schemaForSchema != null) + if (_schemaForSchema is not null) { //Get our built-in types _schemaForSchema.SchemaTypes.Replace(DatatypeImplementation.QnAnyType, XmlSchemaComplexType.AnyType); UpdateSForSSimpleTypes(); @@ -216,7 +216,7 @@ internal bool Compile() foreach (XmlSchemaType? type in _schemaTypes.Values) { XmlSchemaComplexType? ct = type as XmlSchemaComplexType; - if (ct != null) + if (ct is not null) { CompileComplexType(ct); } @@ -228,7 +228,7 @@ internal bool Compile() foreach (XmlSchemaElement? element in _elements.Values) { - if (element!.ElementDecl == null) + if (element!.ElementDecl is null) { CompileElement(element); } @@ -236,7 +236,7 @@ internal bool Compile() foreach (XmlSchemaAttribute? attribute in _attributes.Values) { - if (attribute!.AttDef == null) + if (attribute!.AttDef is null) { CompileAttribute(attribute); } @@ -244,7 +244,7 @@ internal bool Compile() foreach (XmlSchemaIdentityConstraint? identityConstraint in _identityConstraints.Values) { - if (identityConstraint!.CompiledConstraint == null) + if (identityConstraint!.CompiledConstraint is null) { CompileIdentityConstraint(identityConstraint); } @@ -261,7 +261,7 @@ internal bool Compile() foreach (XmlSchemaType? type in _schemaTypes.Values) { XmlSchemaComplexType? localType = type as XmlSchemaComplexType; - if (localType != null) + if (localType is not null) { CheckParticleDerivation(localType); } @@ -270,7 +270,7 @@ internal bool Compile() foreach (XmlSchemaElement? element in _elements.Values) { XmlSchemaComplexType? localComplexType = element!.ElementSchemaType as XmlSchemaComplexType; - if (localComplexType != null && element.SchemaTypeName == XmlQualifiedName.Empty) + if (localComplexType is not null && element.SchemaTypeName == XmlQualifiedName.Empty) { // only local schemaTypes CheckParticleDerivation(localComplexType); } @@ -279,7 +279,7 @@ internal bool Compile() foreach (XmlSchemaGroup? group in _groups.Values) { //Check particle derivation for redefined groups XmlSchemaGroup? baseGroup = group!.Redefined; - if (baseGroup != null) + if (baseGroup is not null) { RecursivelyCheckRedefinedGroups(group, baseGroup); } @@ -288,7 +288,7 @@ internal bool Compile() foreach (XmlSchemaAttributeGroup? attributeGroup in _attributeGroups.Values) { XmlSchemaAttributeGroup? baseAttributeGroup = attributeGroup!.Redefined; - if (baseAttributeGroup != null) + if (baseAttributeGroup is not null) { RecursivelyCheckRedefinedAttributeGroups(attributeGroup, baseAttributeGroup); } @@ -299,7 +299,7 @@ internal bool Compile() private void CleanupAttribute(XmlSchemaAttribute attribute) { - if (attribute.SchemaType != null) + if (attribute.SchemaType is not null) { CleanupSimpleType((XmlSchemaSimpleType)attribute.SchemaType); } @@ -311,7 +311,7 @@ private void CleanupAttributeGroup(XmlSchemaAttributeGroup attributeGroup) CleanupAttributes(attributeGroup.Attributes); attributeGroup.AttributeUses.Clear(); attributeGroup.AttributeWildcard = null; - if (attributeGroup.Redefined != null) + if (attributeGroup.Redefined is not null) { CleanupAttributeGroup(attributeGroup.Redefined); } @@ -324,7 +324,7 @@ private void CleanupComplexType(XmlSchemaComplexType complexType) return; } - if (complexType.ContentModel != null) + if (complexType.ContentModel is not null) { //simpleContent or complexContent if (complexType.ContentModel is XmlSchemaSimpleContent) { @@ -371,7 +371,7 @@ private void CleanupComplexType(XmlSchemaComplexType complexType) complexType.HasWildCard = false; //Clean up the original type if this is a redefined type - if (complexType.Redefined != null) + if (complexType.Redefined is not null) { CleanupComplexType((complexType.Redefined as XmlSchemaComplexType)!); } @@ -385,7 +385,7 @@ private void CleanupSimpleType(XmlSchemaSimpleType simpleType) } simpleType.ElementDecl = null; //Clean up the original group if this is a redefined group - if (simpleType.Redefined != null) + if (simpleType.Redefined is not null) { CleanupSimpleType((simpleType.Redefined as XmlSchemaSimpleType)!); } @@ -393,10 +393,10 @@ private void CleanupSimpleType(XmlSchemaSimpleType simpleType) private void CleanupElement(XmlSchemaElement element) { - if (element.SchemaType != null) + if (element.SchemaType is not null) { XmlSchemaComplexType? complexType = element.SchemaType as XmlSchemaComplexType; - if (complexType != null) + if (complexType is not null) { CleanupComplexType(complexType); } @@ -418,7 +418,7 @@ private void CleanupAttributes(XmlSchemaObjectCollection attributes) for (int i = 0; i < attributes.Count; ++i) { XmlSchemaAttribute? attribute = attributes[i] as XmlSchemaAttribute; - if (attribute != null) + if (attribute is not null) { CleanupAttribute(attribute); } @@ -430,7 +430,7 @@ private void CleanupGroup(XmlSchemaGroup group) CleanupParticle(group.Particle); group.CanonicalParticle = null; //Clean up the original group if this is a redefined group - if (group.Redefined != null) + if (group.Redefined is not null) { CleanupGroup(group.Redefined); } @@ -439,14 +439,14 @@ private void CleanupGroup(XmlSchemaGroup group) private void CleanupParticle(XmlSchemaParticle? particle) { XmlSchemaElement? element = particle as XmlSchemaElement; - if (element != null) + if (element is not null) { CleanupElement(element); return; } XmlSchemaGroupBase? groupBase = particle as XmlSchemaGroupBase; - if (groupBase != null) + if (groupBase is not null) { for (int i = 0; i < groupBase.Items.Count; ++i) { @@ -462,7 +462,7 @@ private void ProcessSubstitutionGroups() if (!element!.SubstitutionGroup.IsEmpty) { XmlSchemaElement? headElement = _elements[element.SubstitutionGroup!] as XmlSchemaElement; - if (headElement == null) + if (headElement is null) { SendValidationEvent(SR.Sch_NoExamplar, element); continue; @@ -476,7 +476,7 @@ private void ProcessSubstitutionGroups() //Create substitutionGroup XmlSchemaSubstitutionGroup? substitutionGroup = (XmlSchemaSubstitutionGroup?)_examplars[element.SubstitutionGroup]; - if (substitutionGroup == null) + if (substitutionGroup is null) { substitutionGroup = new XmlSchemaSubstitutionGroup(); substitutionGroup.Examplar = element.SubstitutionGroup; @@ -507,7 +507,7 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro } XmlSchemaElement examplar = (XmlSchemaElement)_elements[substitutionGroup.Examplar]!; - Debug.Assert(examplar != null); //Headelement presence is checked while building subst groups + Debug.Assert(examplar is not null); //Headelement presence is checked while building subst groups if (substitutionGroup.Members.Contains(examplar)) {// already checked return; @@ -530,14 +530,14 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro if ((element.ElementDecl!.Block & XmlSchemaDerivationMethod.Substitution) == 0) { //Chain only if substitution is not blocked XmlSchemaSubstitutionGroup? g = (XmlSchemaSubstitutionGroup?)_examplars[element.QualifiedName]; - if (g != null) + if (g is not null) { CompileSubstitutionGroup(g); for (int j = 0; j < g.Members.Count; ++j) { if (g.Members[j] != element) { //Exclude the head - if (newMembers == null) + if (newMembers is null) { newMembers = new ArrayList(); } @@ -548,7 +548,7 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro } } - if (newMembers != null) + if (newMembers is not null) { for (int i = 0; i < newMembers.Count; ++i) { @@ -566,19 +566,19 @@ private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro private void RecursivelyCheckRedefinedGroups(XmlSchemaGroup redefinedGroup, XmlSchemaGroup baseGroup) { - if (baseGroup.Redefined != null) + if (baseGroup.Redefined is not null) { RecursivelyCheckRedefinedGroups(baseGroup, baseGroup.Redefined); } if (redefinedGroup.SelfReferenceCount == 0) { - if (baseGroup.CanonicalParticle == null) + if (baseGroup.CanonicalParticle is null) { baseGroup.CanonicalParticle = CannonicalizeParticle(baseGroup.Particle, true); } - if (redefinedGroup.CanonicalParticle == null) + if (redefinedGroup.CanonicalParticle is null) { redefinedGroup.CanonicalParticle = CannonicalizeParticle(redefinedGroup.Particle, true); } @@ -591,7 +591,7 @@ private void RecursivelyCheckRedefinedGroups(XmlSchemaGroup redefinedGroup, XmlS private void RecursivelyCheckRedefinedAttributeGroups(XmlSchemaAttributeGroup attributeGroup, XmlSchemaAttributeGroup baseAttributeGroup) { - if (baseAttributeGroup.Redefined != null) + if (baseAttributeGroup.Redefined is not null) { RecursivelyCheckRedefinedAttributeGroups(baseAttributeGroup, baseAttributeGroup.Redefined); } @@ -613,11 +613,11 @@ private void CompileGroup(XmlSchemaGroup group) else { group.IsProcessing = true; - if (group.CanonicalParticle == null) + if (group.CanonicalParticle is null) { group.CanonicalParticle = CannonicalizeParticle(group.Particle, true); } - Debug.Assert(group.CanonicalParticle != null); + Debug.Assert(group.CanonicalParticle is not null); group.IsProcessing = false; //Not enclosung in try -finally as cannonicalizeParticle will not throw exception } } @@ -629,7 +629,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) throw new XmlSchemaException(SR.Sch_TypeCircularRef, simpleType); } - if (simpleType.ElementDecl != null) + if (simpleType.ElementDecl is not null) { // already compiled return; } @@ -651,7 +651,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) else { XmlSchemaSimpleType? type = GetSimpleType(list.ItemTypeName); - if (type != null) + if (type is not null) { if ((type.FinalResolved & XmlSchemaDerivationMethod.List) != 0) { @@ -680,7 +680,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) simpleType.SetBaseSchemaType(restriction.BaseType); datatype = restriction.BaseType!.Datatype!; } - else if (simpleType.Redefined != null && restriction.BaseTypeName == simpleType.Redefined.QualifiedName) + else if (simpleType.Redefined is not null && restriction.BaseTypeName == simpleType.Redefined.QualifiedName) { CompileSimpleType((XmlSchemaSimpleType)simpleType.Redefined); simpleType.SetBaseSchemaType(simpleType.Redefined.BaseXmlSchemaType); @@ -697,7 +697,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) } } XmlSchemaSimpleType? type = GetSimpleType(restriction.BaseTypeName); - if (type != null) + if (type is not null) { if ((type.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) { @@ -724,7 +724,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(simpleType); } @@ -751,12 +751,12 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) XmlSchemaSimpleTypeUnion mainUnion = (XmlSchemaSimpleTypeUnion)simpleType.Content!; XmlQualifiedName[]? mainMemberTypes = mainUnion.MemberTypes; - if (mainMemberTypes != null) + if (mainMemberTypes is not null) { for (int i = 0; i < mainMemberTypes.Length; ++i) { unionMember = GetSimpleType(mainMemberTypes[i]); - if (unionMember != null) + if (unionMember is not null) { if (unionMember.Datatype!.Variety == XmlSchemaDatatypeVariety.Union) { //union of union @@ -781,7 +781,7 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) //Now add the baseTypes that are defined inside the union itself XmlSchemaObjectCollection mainBaseTypes = mainUnion.BaseTypes; - if (mainBaseTypes != null) + if (mainBaseTypes is not null) { for (int i = 0; i < mainBaseTypes.Count; ++i) { @@ -818,7 +818,7 @@ private void CheckUnionType(XmlSchemaSimpleType unionMember, ArrayList memberTyp private void CompileComplexType(XmlSchemaComplexType complexType) { - if (complexType.ElementDecl != null) + if (complexType.ElementDecl is not null) { //already compiled return; } @@ -830,7 +830,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) complexType.IsProcessing = true; try { - if (complexType.ContentModel != null) + if (complexType.ContentModel is not null) { //simpleContent or complexContent if (complexType.ContentModel is XmlSchemaSimpleContent) { @@ -888,7 +888,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) } else { - if (!decl.AttDefs.ContainsKey(attribute.QualifiedName) && attribute.AttDef != null && attribute.AttDef.Name != XmlQualifiedName.Empty && attribute.AttDef != SchemaAttDef.Empty) + if (!decl.AttDefs.ContainsKey(attribute.QualifiedName) && attribute.AttDef is not null && attribute.AttDef.Name != XmlQualifiedName.Empty && attribute.AttDef != SchemaAttDef.Empty) { decl.AddAttDef(attribute.AttDef); } @@ -906,7 +906,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, XmlSchemaSimpleContentExtension simpleExtension) { XmlSchemaComplexType? baseType = null; - if (complexType.Redefined != null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -916,7 +916,7 @@ private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, Xml else { XmlSchemaType? bto = GetAnySchemaType(simpleExtension.BaseTypeName); - if (bto == null) + if (bto is null) { SendValidationEvent(SR.Sch_UndeclaredType, simpleExtension.BaseTypeName.ToString(), simpleExtension); } @@ -928,7 +928,7 @@ private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, Xml baseType = bto as XmlSchemaComplexType; } - if (baseType != null) + if (baseType is not null) { if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Extension) != 0) { @@ -948,7 +948,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X { XmlSchemaComplexType? baseType = null; XmlSchemaDatatype? datatype = null; - if (complexType.Redefined != null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -957,14 +957,14 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X else { baseType = GetComplexType(simpleRestriction.BaseTypeName); - if (baseType == null) + if (baseType is null) { SendValidationEvent(SR.Sch_UndefBaseRestriction, simpleRestriction.BaseTypeName.ToString(), simpleRestriction); return; } if (baseType.ContentType == XmlSchemaContentType.TextOnly) { - if (simpleRestriction.BaseType == null) + if (simpleRestriction.BaseType is null) { datatype = baseType.Datatype; //There is a bug here. Need to check if simpleRestriction has facets. @@ -982,7 +982,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X } else if (baseType.ContentType == XmlSchemaContentType.Mixed && baseType.ElementDecl!.ContentValidator!.IsEmptiable) { - if (simpleRestriction.BaseType != null) + if (simpleRestriction.BaseType is not null) { CompileSimpleType(simpleRestriction.BaseType); complexType.SetBaseSchemaType(simpleRestriction.BaseType); @@ -999,7 +999,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X } } - if (baseType != null && baseType.ElementDecl != null) + if (baseType is not null && baseType.ElementDecl is not null) { if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) { @@ -1007,12 +1007,12 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X } } - if (baseType != null) + if (baseType is not null) { complexType.SetBaseSchemaType(baseType); } - if (datatype != null) + if (datatype is not null) { try { @@ -1020,7 +1020,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(complexType); } @@ -1035,7 +1035,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X private void CompileComplexContentExtension(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentExtension complexExtension) { XmlSchemaComplexType? baseType = null; - if (complexType.Redefined != null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -1043,7 +1043,7 @@ private void CompileComplexContentExtension(XmlSchemaComplexType complexType, Xm else { baseType = GetComplexType(complexExtension.BaseTypeName); - if (baseType == null) + if (baseType is null) { SendValidationEvent(SR.Sch_UndefBaseExtension, complexExtension.BaseTypeName.ToString(), complexExtension); return; @@ -1106,7 +1106,7 @@ private void CompileComplexContentExtension(XmlSchemaComplexType complexType, Xm private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentRestriction complexRestriction) { XmlSchemaComplexType? baseType = null; - if (complexType.Redefined != null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) + if (complexType.Redefined is not null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; CompileComplexType(baseType); @@ -1114,7 +1114,7 @@ private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, else { baseType = GetComplexType(complexRestriction.BaseTypeName!); - if (baseType == null) + if (baseType is null) { SendValidationEvent(SR.Sch_UndefBaseRestriction, complexRestriction.BaseTypeName.ToString(), complexRestriction); return; @@ -1133,7 +1133,7 @@ private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, switch (derivedContentType) { case XmlSchemaContentType.Empty: - if (baseType.ElementDecl != null && !baseType.ElementDecl.ContentValidator!.IsEmptiable) + if (baseType.ElementDecl is not null && !baseType.ElementDecl.ContentValidator!.IsEmptiable) { //base is either TextOnly or its ElementOnly/Mixed and not emptiable SendValidationEvent(SR.Sch_InvalidContentRestrictionDetailed, SR.Sch_InvalidBaseToEmpty, complexType); } @@ -1153,13 +1153,13 @@ private void CheckParticleDerivation(XmlSchemaComplexType complexType) { XmlSchemaComplexType? baseType = complexType.BaseXmlSchemaType as XmlSchemaComplexType; _restrictionErrorMsg = null; - if (baseType != null && baseType != XmlSchemaComplexType.AnyType && complexType.DerivedBy == XmlSchemaDerivationMethod.Restriction) + if (baseType is not null && baseType != XmlSchemaComplexType.AnyType && complexType.DerivedBy == XmlSchemaDerivationMethod.Restriction) { XmlSchemaParticle derivedParticle = CannonicalizePointlessRoot(complexType.ContentTypeParticle); XmlSchemaParticle baseParticle = CannonicalizePointlessRoot(baseType.ContentTypeParticle); if (!IsValidRestriction(derivedParticle, baseParticle)) { - if (_restrictionErrorMsg != null) + if (_restrictionErrorMsg is not null) { SendValidationEvent(SR.Sch_InvalidParticleRestrictionDetailed, _restrictionErrorMsg, complexType); } @@ -1179,7 +1179,7 @@ private void CheckParticleDerivation(XmlSchemaComplexType complexType) } XmlSchemaComplexType? localComplexType = localElement.ElementSchemaType as XmlSchemaComplexType; - if (localComplexType != null && localElement.SchemaTypeName == XmlQualifiedName.Empty && localElement.RefName == XmlQualifiedName.Empty) + if (localComplexType is not null && localElement.SchemaTypeName == XmlQualifiedName.Empty && localElement.RefName == XmlQualifiedName.Empty) { //Only local elements localElement.IsLocalTypeDerivationChecked = true; //Not clearing this flag after recursion to make sure this check is not repeated for multiple references of the same local element (through group refs) CheckParticleDerivation(localComplexType); @@ -1195,7 +1195,7 @@ private void CheckParticleDerivation(XmlSchemaParticle derivedParticle, XmlSchem baseParticle = CannonicalizePointlessRoot(baseParticle); if (!IsValidRestriction(derivedParticle, baseParticle)) { - if (_restrictionErrorMsg != null) + if (_restrictionErrorMsg is not null) { SendValidationEvent(SR.Sch_InvalidParticleRestrictionDetailed, _restrictionErrorMsg, derivedParticle); } @@ -1210,7 +1210,7 @@ private XmlSchemaParticle CompileContentTypeParticle(XmlSchemaParticle? particle { XmlSchemaParticle ctp = CannonicalizeParticle(particle, true); XmlSchemaChoice? choice = ctp as XmlSchemaChoice; - if (choice != null && choice.Items.Count == 0) + if (choice is not null && choice.Items.Count == 0) { if (choice.MinOccurs != decimal.Zero) { @@ -1224,7 +1224,7 @@ private XmlSchemaParticle CompileContentTypeParticle(XmlSchemaParticle? particle private XmlSchemaParticle CannonicalizeParticle(XmlSchemaParticle? particle, bool root) { - if (particle == null || particle.IsEmpty) + if (particle is null || particle.IsEmpty) { return XmlSchemaParticle.Empty; } @@ -1260,7 +1260,7 @@ private XmlSchemaParticle CannonicalizeElement(XmlSchemaElement element) if (!element.RefName.IsEmpty && (element.ElementDecl!.Block & XmlSchemaDerivationMethod.Substitution) == 0) { XmlSchemaSubstitutionGroup? substitutionGroup = (XmlSchemaSubstitutionGroup?)_examplars[element.QualifiedName]; - if (substitutionGroup == null) + if (substitutionGroup is null) { return element; } @@ -1286,7 +1286,7 @@ private XmlSchemaParticle CannonicalizeElement(XmlSchemaElement element) private XmlSchemaParticle CannonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool root) { XmlSchemaGroup? group; - if (groupRef.Redefined != null) + if (groupRef.Redefined is not null) { group = groupRef.Redefined; } @@ -1295,13 +1295,13 @@ private XmlSchemaParticle CannonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool group = (XmlSchemaGroup?)_groups[groupRef.RefName]; } - if (group == null) + if (group is null) { SendValidationEvent(SR.Sch_UndefGroupRef, groupRef.RefName.ToString(), groupRef); return XmlSchemaParticle.Empty; } - if (group.CanonicalParticle == null) + if (group.CanonicalParticle is null) { CompileGroup(group); } @@ -1449,7 +1449,7 @@ private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool if (p1 != XmlSchemaParticle.Empty) { XmlSchemaSequence p1Sequence = (p1 as XmlSchemaSequence)!; - if (p1.MinOccurs == decimal.One && p1.MaxOccurs == decimal.One && p1Sequence != null) + if (p1.MinOccurs == decimal.One && p1.MaxOccurs == decimal.One && p1Sequence is not null) { for (int j = 0; j < p1Sequence.Items.Count; ++j) { @@ -1481,7 +1481,7 @@ private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool [return: NotNullIfNotNull("particle")] private XmlSchemaParticle? CannonicalizePointlessRoot(XmlSchemaParticle particle) { - if (particle == null) + if (particle is null) { return null; } @@ -1491,7 +1491,7 @@ private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool XmlSchemaAll? xsa; decimal one = decimal.One; - if ((xss = (particle as XmlSchemaSequence)) != null) + if ((xss = (particle as XmlSchemaSequence)) is not null) { XmlSchemaObjectCollection items = xss.Items; int count = items.Count; @@ -1503,7 +1503,7 @@ private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool } } } - else if ((xsc = (particle as XmlSchemaChoice)) != null) + else if ((xsc = (particle as XmlSchemaChoice)) is not null) { XmlSchemaObjectCollection items = xsc.Items; int count = items.Count; @@ -1520,7 +1520,7 @@ private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool return XmlSchemaParticle.Empty; } } - else if ((xsa = (particle as XmlSchemaAll)) != null) + else if ((xsa = (particle as XmlSchemaAll)) is not null) { XmlSchemaObjectCollection items = xsa.Items; int count = items.Count; @@ -1543,11 +1543,11 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart { return true; } - else if (derivedParticle == null || derivedParticle == XmlSchemaParticle.Empty) + else if (derivedParticle is null || derivedParticle == XmlSchemaParticle.Empty) { return IsParticleEmptiable(baseParticle); } - else if (baseParticle == null || baseParticle == XmlSchemaParticle.Empty) + else if (baseParticle is null || baseParticle == XmlSchemaParticle.Empty) { return false; } @@ -1628,7 +1628,7 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart XmlSchemaChoice baseChoice = (baseParticle as XmlSchemaChoice)!; XmlSchemaChoice derivedChoice = (derivedParticle as XmlSchemaChoice)!; - if (baseChoice.Parent == null || derivedChoice.Parent == null) + if (baseChoice.Parent is null || derivedChoice.Parent is null) { //using parent property to indicate this choice was created on the fly for substitutionGroup return IsChoiceFromChoiceSubstGroup(derivedChoice!, baseChoice); } @@ -1696,9 +1696,9 @@ private bool IsElementFromElement(XmlSchemaElement derivedElement, XmlSchemaElem if (!((derivedElement.QualifiedName == baseElement.QualifiedName) && (baseElement.IsNillable || !derivedElement.IsNillable) && IsValidOccurrenceRangeRestriction(derivedElement, baseElement) && - (baseElement.FixedValue == null || IsFixedEqual(baseElement.ElementDecl, derivedElement.ElementDecl)) && + (baseElement.FixedValue is null || IsFixedEqual(baseElement.ElementDecl, derivedElement.ElementDecl)) && ((derivedEffectiveBlock | baseEffectiveBlock) == derivedEffectiveBlock) && - (derivedElement.ElementSchemaType != null) && (baseElement.ElementSchemaType != null) && + (derivedElement.ElementSchemaType is not null) && (baseElement.ElementSchemaType is not null) && XmlSchemaType.IsDerivedFrom(derivedElement.ElementSchemaType, baseElement.ElementSchemaType, ~(XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union)))) { _restrictionErrorMsg = SR.Format(SR.Sch_ElementFromElement, derivedElement.QualifiedName, baseElement.QualifiedName); @@ -1892,7 +1892,7 @@ private bool IsGroupBaseFromGroupBase(XmlSchemaGroupBase derivedGroupBase, XmlSc } else if (skipEmptableOnly && !IsParticleEmptiable(baseParticle)) { - if (_restrictionErrorMsg == null) + if (_restrictionErrorMsg is null) { //If restriction failed on previous check, do not overwrite error _restrictionErrorMsg = SR.Sch_GroupBaseRestNotEmptiable; } @@ -2002,7 +2002,7 @@ private void CalculateEffectiveTotalRange(XmlSchemaParticle particle, out decima minOccurs = particle.MinOccurs; maxOccurs = particle.MaxOccurs; } - else if (choice != null) + else if (choice is not null) { if (choice.Items.Count == 0) { @@ -2078,12 +2078,12 @@ private void PushComplexType(XmlSchemaComplexType complexType) private XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent? complexContent, XmlSchemaParticle particle) { - if ((complexContent != null && complexContent.IsMixed) || - (complexContent == null && complexType.IsMixed)) + if ((complexContent is not null && complexContent.IsMixed) || + (complexContent is null && complexType.IsMixed)) { return XmlSchemaContentType.Mixed; } - else if (particle != null && !particle.IsEmpty) + else if (particle is not null && !particle.IsEmpty) { return XmlSchemaContentType.ElementOnly; } @@ -2112,14 +2112,14 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) for (int i = 0; i < attributeGroup.Attributes.Count; ++i) { XmlSchemaAttribute? attr = attributeGroup.Attributes[i] as XmlSchemaAttribute; - if (attr != null) + if (attr is not null) { if (attr.Use == XmlSchemaUse.Prohibited) { continue; } CompileAttribute(attr); - if (attributeGroup.AttributeUses[attr.QualifiedName] == null) + if (attributeGroup.AttributeUses[attr.QualifiedName] is null) { attributeGroup.AttributeUses.Add(attr.QualifiedName, attr); } @@ -2132,7 +2132,7 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) { // XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributeGroup.Attributes[i]; XmlSchemaAttributeGroup? attributeGroupResolved; - if (attributeGroup.Redefined != null && attributeGroupRef.RefName == attributeGroup.Redefined.QualifiedName) + if (attributeGroup.Redefined is not null && attributeGroupRef.RefName == attributeGroup.Redefined.QualifiedName) { attributeGroupResolved = (XmlSchemaAttributeGroup)attributeGroup.Redefined; } @@ -2141,12 +2141,12 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) attributeGroupResolved = (XmlSchemaAttributeGroup?)_attributeGroups[attributeGroupRef.RefName]; } - if (attributeGroupResolved != null) + if (attributeGroupResolved is not null) { CompileAttributeGroup(attributeGroupResolved); foreach (XmlSchemaAttribute? attribute in attributeGroupResolved.AttributeUses.Values) { - if (attributeGroup.AttributeUses[attribute!.QualifiedName] == null) + if (attributeGroup.AttributeUses[attribute!.QualifiedName] is null) { attributeGroup.AttributeUses.Add(attribute.QualifiedName, attribute); } @@ -2174,11 +2174,11 @@ private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaComplexType derivedType, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute? anyAttribute, XmlSchemaDerivationMethod derivedBy) { - XmlSchemaAnyAttribute? baseAttributeWildcard = baseType != null ? baseType.AttributeWildcard : null; + XmlSchemaAnyAttribute? baseAttributeWildcard = baseType is not null ? baseType.AttributeWildcard : null; for (int i = 0; i < attributes.Count; ++i) { XmlSchemaAttribute? attr = attributes[i] as XmlSchemaAttribute; - if (attr != null) + if (attr is not null) { if (attr.Use != XmlSchemaUse.Prohibited) { @@ -2187,7 +2187,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom if (attr.Use != XmlSchemaUse.Prohibited || (attr.Use == XmlSchemaUse.Prohibited && derivedBy == XmlSchemaDerivationMethod.Restriction && baseType != XmlSchemaComplexType.AnyType)) { - if (derivedType.AttributeUses[attr.QualifiedName] == null) + if (derivedType.AttributeUses[attr.QualifiedName] is null) { derivedType.AttributeUses.Add(attr.QualifiedName, attr); } @@ -2205,7 +2205,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom { // is XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributes[i]; XmlSchemaAttributeGroup? attributeGroup = (XmlSchemaAttributeGroup?)_attributeGroups[attributeGroupRef.RefName]; - if (attributeGroup != null) + if (attributeGroup is not null) { CompileAttributeGroup(attributeGroup); foreach (XmlSchemaAttribute? attribute in attributeGroup.AttributeUses.Values) @@ -2213,7 +2213,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom if (attribute!.Use != XmlSchemaUse.Prohibited || (attribute.Use == XmlSchemaUse.Prohibited && derivedBy == XmlSchemaDerivationMethod.Restriction && baseType != XmlSchemaComplexType.AnyType)) { - if (derivedType.AttributeUses[attribute.QualifiedName] == null) + if (derivedType.AttributeUses[attribute.QualifiedName] is null) { derivedType.AttributeUses.Add(attribute.QualifiedName, attribute); } @@ -2238,7 +2238,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom } // check derivation rules - if (baseType != null) + if (baseType is not null) { if (derivedBy == XmlSchemaDerivationMethod.Extension) { @@ -2246,7 +2246,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom foreach (XmlSchemaAttribute? attributeBase in baseType.AttributeUses.Values) { XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)derivedType.AttributeUses[attributeBase!.QualifiedName]; - if (attribute == null) + if (attribute is null) { derivedType.AttributeUses.Add(attributeBase.QualifiedName, attributeBase); } @@ -2263,7 +2263,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom else { // derivedBy == XmlSchemaDerivationMethod.Restriction // Schema Component Constraint: Derivation Valid (Restriction, Complex) - if ((anyAttribute != null) && (baseAttributeWildcard == null || !XmlSchemaAnyAttribute.IsSubset(anyAttribute, baseAttributeWildcard) || !IsProcessContentsRestricted(baseType, anyAttribute, baseAttributeWildcard))) + if ((anyAttribute is not null) && (baseAttributeWildcard is null || !XmlSchemaAnyAttribute.IsSubset(anyAttribute, baseAttributeWildcard) || !IsProcessContentsRestricted(baseType, anyAttribute, baseAttributeWildcard))) { SendValidationEvent(SR.Sch_InvalidAnyAttributeRestriction, derivedType); } @@ -2276,7 +2276,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom foreach (XmlSchemaAttribute? attributeBase in baseType.AttributeUses.Values) { XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)derivedType.AttributeUses[attributeBase!.QualifiedName]; - if (attribute == null) + if (attribute is null) { derivedType.AttributeUses.Add(attributeBase.QualifiedName, attributeBase); } @@ -2294,7 +2294,7 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom { continue; } - else if (attributeBase.AttributeSchemaType == null || attribute.AttributeSchemaType == null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) + else if (attributeBase.AttributeSchemaType is null || attribute.AttributeSchemaType is null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) { SendValidationEvent(SR.Sch_AttributeRestrictionInvalid, attribute); } @@ -2309,12 +2309,12 @@ private void CompileLocalAttributes(XmlSchemaComplexType? baseType, XmlSchemaCom foreach (XmlSchemaAttribute? attribute in derivedType.AttributeUses.Values) { XmlSchemaAttribute? attributeBase = (XmlSchemaAttribute?)baseType.AttributeUses[attribute!.QualifiedName]; - if (attributeBase != null) + if (attributeBase is not null) { continue; } - if (baseAttributeWildcard == null || !baseAttributeWildcard.Allows(attribute.QualifiedName)) + if (baseAttributeWildcard is null || !baseAttributeWildcard.Allows(attribute.QualifiedName)) { SendValidationEvent(SR.Sch_AttributeRestrictionInvalidFromWildcard, attribute); } @@ -2332,7 +2332,7 @@ private void CheckAtrributeGroupRestriction(XmlSchemaAttributeGroup baseAttribut XmlSchemaAnyAttribute? baseAnyAtt = baseAttributeGroup.AttributeWildcard; XmlSchemaAnyAttribute? derivedAnyAtt = derivedAttributeGroup.AttributeWildcard; - if ((derivedAnyAtt != null) && (baseAnyAtt == null || !XmlSchemaAnyAttribute.IsSubset(derivedAnyAtt, baseAnyAtt) || !IsProcessContentsRestricted(null, derivedAnyAtt, baseAnyAtt))) + if ((derivedAnyAtt is not null) && (baseAnyAtt is null || !XmlSchemaAnyAttribute.IsSubset(derivedAnyAtt, baseAnyAtt) || !IsProcessContentsRestricted(null, derivedAnyAtt, baseAnyAtt))) { SendValidationEvent(SR.Sch_InvalidAnyAttributeRestriction, derivedAttributeGroup); } @@ -2340,7 +2340,7 @@ private void CheckAtrributeGroupRestriction(XmlSchemaAttributeGroup baseAttribut foreach (XmlSchemaAttribute? attributeBase in baseAttributeGroup.AttributeUses.Values) { XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)derivedAttributeGroup.AttributeUses[attributeBase!.QualifiedName]; - if (attribute != null) + if (attribute is not null) { if (attributeBase.Use == XmlSchemaUse.Prohibited && attribute.Use != XmlSchemaUse.Prohibited) { @@ -2354,7 +2354,7 @@ private void CheckAtrributeGroupRestriction(XmlSchemaAttributeGroup baseAttribut { //If derived att is prohibited, continue continue; } - else if (attributeBase.AttributeSchemaType == null || attribute.AttributeSchemaType == null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) + else if (attributeBase.AttributeSchemaType is null || attribute.AttributeSchemaType is null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) { SendValidationEvent(SR.Sch_AttributeRestrictionInvalid, attribute); } @@ -2372,12 +2372,12 @@ private void CheckAtrributeGroupRestriction(XmlSchemaAttributeGroup baseAttribut foreach (XmlSchemaAttribute? attribute in derivedAttributeGroup.AttributeUses.Values) { XmlSchemaAttribute? attributeBase = (XmlSchemaAttribute?)baseAttributeGroup.AttributeUses[attribute!.QualifiedName]; - if (attributeBase != null) + if (attributeBase is not null) { continue; } - if (baseAnyAtt == null || !baseAnyAtt.Allows(attribute.QualifiedName)) + if (baseAnyAtt is null || !baseAnyAtt.Allows(attribute.QualifiedName)) { SendValidationEvent(SR.Sch_AttributeRestrictionInvalidFromWildcard, attribute); } @@ -2399,18 +2399,18 @@ private bool IsProcessContentsRestricted(XmlSchemaComplexType? baseType, XmlSche private XmlSchemaAnyAttribute? CompileAnyAttributeUnion(XmlSchemaAnyAttribute? a, XmlSchemaAnyAttribute? b) { - if (a == null) + if (a is null) { return b; } - else if (b == null) + else if (b is null) { return a; } else { XmlSchemaAnyAttribute? attribute = XmlSchemaAnyAttribute.Union(a, b, false); //false is for v1Compatd - if (attribute == null) + if (attribute is null) { SendValidationEvent(SR.Sch_UnexpressibleAnyAttribute, a); } @@ -2421,18 +2421,18 @@ private bool IsProcessContentsRestricted(XmlSchemaComplexType? baseType, XmlSche private XmlSchemaAnyAttribute? CompileAnyAttributeIntersection(XmlSchemaAnyAttribute? a, XmlSchemaAnyAttribute? b) { - if (a == null) + if (a is null) { return b; } - else if (b == null) + else if (b is null) { return a; } else { XmlSchemaAnyAttribute? attribute = XmlSchemaAnyAttribute.Intersection(a, b, false); //false is for v1Compat - if (attribute == null) + if (attribute is null) { SendValidationEvent(SR.Sch_UnexpressibleAnyAttribute, a); } @@ -2448,7 +2448,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) SendValidationEvent(SR.Sch_AttributeCircularRef, xa); return; } - if (xa.AttDef != null) + if (xa.AttDef is not null) { //already compiled? return; } @@ -2459,31 +2459,31 @@ private void CompileAttribute(XmlSchemaAttribute xa) if (!xa.RefName.IsEmpty) { XmlSchemaAttribute? a = (XmlSchemaAttribute?)_attributes[xa.RefName]; - if (a == null) + if (a is null) { throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, xa.RefName.ToString(), xa); } CompileAttribute(a); - if (a.AttDef == null) + if (a.AttDef is null) { throw new XmlSchemaException(SR.Sch_RefInvalidAttribute, xa.RefName.ToString(), xa); } decl = a.AttDef.Clone(); XmlSchemaDatatype datatype = decl.Datatype; - if (datatype != null) + if (datatype is not null) { - if (a.FixedValue == null && a.DefaultValue == null) + if (a.FixedValue is null && a.DefaultValue is null) { SetDefaultFixed(xa, decl); } - else if (a.FixedValue != null) + else if (a.FixedValue is not null) { - if (xa.DefaultValue != null) + if (xa.DefaultValue is not null) { throw new XmlSchemaException(SR.Sch_FixedDefaultInRef, xa.RefName.ToString(), xa); } - else if (xa.FixedValue != null) + else if (xa.FixedValue is not null) { object refFixedValue = datatype.ParseValue(xa.FixedValue, NameTable, new SchemaNamespaceManager(xa), true); if (!datatype.IsEqual(decl.DefaultValueTyped!, refFixedValue)) @@ -2498,7 +2498,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) else { decl = new SchemaAttDef(xa.QualifiedName); - if (xa.SchemaType != null) + if (xa.SchemaType is not null) { CompileSimpleType(xa.SchemaType); xa.SetAttributeType(xa.SchemaType); @@ -2508,7 +2508,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) else if (!xa.SchemaTypeName.IsEmpty) { XmlSchemaSimpleType? simpleType = GetSimpleType(xa.SchemaTypeName); - if (simpleType != null) + if (simpleType is not null) { xa.SetAttributeType(simpleType); decl.Datatype = simpleType.Datatype!; @@ -2526,7 +2526,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) xa.SetAttributeType(DatatypeImplementation.AnySimpleType); } //} //Removed this here since the following should be done only if RefName is Empty - if (decl.Datatype != null) + if (decl.Datatype is not null) { decl.Datatype.VerifySchemaValid(_notations, xa); } @@ -2538,7 +2538,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(xa); } @@ -2553,9 +2553,9 @@ private void CompileAttribute(XmlSchemaAttribute xa) private void SetDefaultFixed(XmlSchemaAttribute xa, SchemaAttDef decl) { - if (xa.DefaultValue != null || xa.FixedValue != null) + if (xa.DefaultValue is not null || xa.FixedValue is not null) { - if (xa.DefaultValue != null) + if (xa.DefaultValue is not null) { decl.Presence = SchemaDeclBase.Use.Default; decl.DefaultValueRaw = decl.DefaultValueExpanded = xa.DefaultValue; @@ -2574,7 +2574,7 @@ private void SetDefaultFixed(XmlSchemaAttribute xa, SchemaAttDef decl) decl.DefaultValueRaw = decl.DefaultValueExpanded = xa.FixedValue; } - if (decl.Datatype != null) + if (decl.Datatype is not null) { if (decl.Datatype.TypeCode == XmlTypeCode.Id) { @@ -2612,7 +2612,7 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) return; } - if (xi.CompiledConstraint != null) + if (xi.CompiledConstraint is not null) { return; } @@ -2626,13 +2626,13 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) if (xi is XmlSchemaKeyref) { XmlSchemaIdentityConstraint? ic = (XmlSchemaIdentityConstraint?)_identityConstraints[((XmlSchemaKeyref)xi).Refer]; - if (ic == null) + if (ic is null) { throw new XmlSchemaException(SR.Sch_UndeclaredIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); } CompileIdentityConstraint(ic); - if (ic.CompiledConstraint == null) + if (ic.CompiledConstraint is null) { throw new XmlSchemaException(SR.Sch_RefInvalidIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); } @@ -2653,7 +2653,7 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(xi); } @@ -2674,7 +2674,7 @@ private void CompileElement(XmlSchemaElement xe) SendValidationEvent(SR.Sch_ElementCircularRef, xe); return; } - if (xe.ElementDecl != null) + if (xe.ElementDecl is not null) { return; } @@ -2685,12 +2685,12 @@ private void CompileElement(XmlSchemaElement xe) if (!xe.RefName.IsEmpty) { XmlSchemaElement? e = (XmlSchemaElement?)_elements[xe.RefName]; - if (e == null) + if (e is null) { throw new XmlSchemaException(SR.Sch_UndeclaredElement, xe.RefName.ToString(), xe); } CompileElement(e); - if (e.ElementDecl == null) + if (e.ElementDecl is null) { throw new XmlSchemaException(SR.Sch_RefInvalidElement, xe.RefName.ToString(), xe); } @@ -2699,14 +2699,14 @@ private void CompileElement(XmlSchemaElement xe) } else { - if (xe.SchemaType != null) + if (xe.SchemaType is not null) { xe.SetElementType(xe.SchemaType); } else if (!xe.SchemaTypeName.IsEmpty) { xe.SetElementType(GetAnySchemaType(xe.SchemaTypeName)); - if (xe.ElementSchemaType == null) + if (xe.ElementSchemaType is null) { throw new XmlSchemaException(SR.Sch_UndeclaredType, xe.SchemaTypeName.ToString(), xe); } @@ -2714,7 +2714,7 @@ private void CompileElement(XmlSchemaElement xe) else if (!xe.SubstitutionGroup.IsEmpty) { XmlSchemaElement? examplar = (XmlSchemaElement?)_elements[xe.SubstitutionGroup]; - if (examplar == null) + if (examplar is null) { throw new XmlSchemaException(SR.Sch_UndeclaredEquivClass, xe.SubstitutionGroup.Name, xe); } @@ -2723,7 +2723,7 @@ private void CompileElement(XmlSchemaElement xe) return; } CompileElement(examplar); - if (examplar.ElementDecl == null) + if (examplar.ElementDecl is null) { //If head is invalid, fall back to AnyType xe.SetElementType(XmlSchemaComplexType.AnyType); decl = XmlSchemaComplexType.AnyType.ElementDecl!.Clone(); @@ -2740,14 +2740,14 @@ private void CompileElement(XmlSchemaElement xe) decl = XmlSchemaComplexType.AnyType.ElementDecl!.Clone(); } - if (decl == null) + if (decl is null) { - Debug.Assert(xe.ElementSchemaType != null); + Debug.Assert(xe.ElementSchemaType is not null); if (xe.ElementSchemaType is XmlSchemaComplexType) { XmlSchemaComplexType complexType = (XmlSchemaComplexType)xe.ElementSchemaType; CompileComplexType(complexType); - if (complexType.ElementDecl != null) + if (complexType.ElementDecl is not null) { decl = complexType.ElementDecl.Clone(); // decl.LocalElements = complexType.LocalElementDecls; @@ -2757,35 +2757,35 @@ private void CompileElement(XmlSchemaElement xe) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)xe.ElementSchemaType; CompileSimpleType(simpleType); - if (simpleType.ElementDecl != null) + if (simpleType.ElementDecl is not null) { decl = simpleType.ElementDecl.Clone(); } } } - Debug.Assert(decl != null); + Debug.Assert(decl is not null); decl.Name = xe.QualifiedName; decl.IsAbstract = xe.IsAbstract; XmlSchemaComplexType? ct = xe.ElementSchemaType as XmlSchemaComplexType; - if (ct != null) + if (ct is not null) { decl.IsAbstract |= ct.IsAbstract; } decl.IsNillable = xe.IsNillable; decl.Block |= xe.BlockResolved; } - if (decl.Datatype != null) + if (decl.Datatype is not null) { decl.Datatype.VerifySchemaValid(_notations, xe); } - if (xe.DefaultValue != null || xe.FixedValue != null) + if (xe.DefaultValue is not null || xe.FixedValue is not null) { - if (decl.ContentValidator != null) + if (decl.ContentValidator is not null) { if (decl.ContentValidator.ContentType == XmlSchemaContentType.TextOnly || (decl.ContentValidator.ContentType == XmlSchemaContentType.Mixed && decl.ContentValidator.IsEmptiable)) { - if (xe.DefaultValue != null) + if (xe.DefaultValue is not null) { decl.Presence = SchemaDeclBase.Use.Default; decl.DefaultValueRaw = xe.DefaultValue; @@ -2795,7 +2795,7 @@ private void CompileElement(XmlSchemaElement xe) decl.Presence = SchemaDeclBase.Use.Fixed; decl.DefaultValueRaw = xe.FixedValue!; } - if (decl.Datatype != null) + if (decl.Datatype is not null) { if (decl.Datatype.TypeCode == XmlTypeCode.Id) { @@ -2835,7 +2835,7 @@ private void CompileElement(XmlSchemaElement xe) } catch (XmlSchemaException e) { - if (e.SourceSchemaObject == null) + if (e.SourceSchemaObject is null) { e.SetSource(xe); } @@ -2859,7 +2859,7 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) return ContentValidator.TextOnly; } XmlSchemaParticle particle = complexType.ContentTypeParticle; - if (particle == null || particle == XmlSchemaParticle.Empty) + if (particle is null || particle == XmlSchemaParticle.Empty) { if (complexType.ContentType == XmlSchemaContentType.ElementOnly) { @@ -3000,7 +3000,7 @@ private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchema { XmlSchemaElement localElement = (XmlSchemaElement)particle; CompileElement(localElement); - if (complexType.LocalElements[localElement.QualifiedName] == null) + if (complexType.LocalElements[localElement.QualifiedName] is null) { complexType.LocalElements.Add(localElement.QualifiedName, localElement); } @@ -3064,7 +3064,7 @@ private void CompileComplexTypeElements(XmlSchemaComplexType complexType) private XmlSchemaSimpleType? GetSimpleType(XmlQualifiedName name) { XmlSchemaSimpleType? type = _schemaTypes[name] as XmlSchemaSimpleType; - if (type != null) + if (type is not null) { CompileSimpleType(type); } @@ -3078,7 +3078,7 @@ private void CompileComplexTypeElements(XmlSchemaComplexType complexType) private XmlSchemaComplexType? GetComplexType(XmlQualifiedName name) { XmlSchemaComplexType? type = _schemaTypes[name] as XmlSchemaComplexType; - if (type != null) + if (type is not null) { CompileComplexType(type); } @@ -3089,7 +3089,7 @@ private void CompileComplexTypeElements(XmlSchemaComplexType complexType) private XmlSchemaType? GetAnySchemaType(XmlQualifiedName name) { XmlSchemaType? type = (XmlSchemaType?)_schemaTypes[name]; - if (type != null) + if (type is not null) { if (type is XmlSchemaComplexType) { @@ -3126,14 +3126,14 @@ private bool IsFixedEqual(SchemaDeclBase baseDecl, SchemaDeclBase derivedDecl) { object baseFixedValue = baseDecl.DefaultValueTyped!; - Debug.Assert(baseFixedValue != null); + Debug.Assert(baseFixedValue is not null); if (derivedDecl.Presence != SchemaDeclBase.Use.Fixed && derivedDecl.Presence != SchemaDeclBase.Use.RequiredFixed) { return false; } object derivedFixedValue = derivedDecl.DefaultValueTyped!; - Debug.Assert(derivedFixedValue != null); + Debug.Assert(derivedFixedValue is not null); XmlSchemaDatatype baseDatatype = baseDecl.Datatype; XmlSchemaDatatype derivedDatatype = derivedDecl.Datatype; @@ -3149,7 +3149,7 @@ private bool IsFixedEqual(SchemaDeclBase baseDecl, SchemaDeclBase derivedDecl) else { //Base is union and derived is member of union XsdSimpleValue simpleFixedValue = (baseDecl.DefaultValueTyped as XsdSimpleValue)!; - Debug.Assert(simpleFixedValue != null); + Debug.Assert(simpleFixedValue is not null); XmlSchemaDatatype memberType = simpleFixedValue.XmlType.Datatype!; if (!memberType.IsComparable(derivedDatatype) || !derivedDatatype.IsEqual(simpleFixedValue.TypedValue, derivedFixedValue)) { //base type {Union of long & string}, derived type {int} diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs index bbbffb483e92cd..cba71685b1fa97 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs @@ -42,7 +42,7 @@ internal XdrValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schema private void Init() { _nsManager = reader.NamespaceManager!; - if (_nsManager == null) + if (_nsManager is null) { _nsManager = new XmlNamespaceManager(NameTable); _isProcessContents = true; @@ -119,7 +119,7 @@ private void ValidateChildElement() private bool IsInlineSchemaStarted { - get { return _inlineSchemaParser != null; } + get { return _inlineSchemaParser is not null; } } private void ProcessInlineSchema() @@ -128,7 +128,7 @@ private void ProcessInlineSchema() { // Done _inlineSchemaParser.FinishParsing(); SchemaInfo? xdrSchema = _inlineSchemaParser.XdrSchema; - if (xdrSchema != null && xdrSchema.ErrorCount == 0) + if (xdrSchema is not null && xdrSchema.ErrorCount == 0) { foreach (string inlineNS in xdrSchema.TargetNamespaces.Keys) { @@ -153,7 +153,7 @@ private void ProcessElement() } context!.ElementDecl = ThoroughGetElementDecl(); - if (context.ElementDecl != null) + if (context.ElementDecl is not null) { ValidateStartElement(); ValidateEndStartElement(); @@ -169,7 +169,7 @@ private void ValidateEndElement() _nsManager.PopScope(); } - if (context!.ElementDecl != null) + if (context!.ElementDecl is not null) { if (context.NeedValidateChildren) { @@ -225,7 +225,7 @@ private void ValidateEndElement() } SchemaElementDecl? elementDecl = schemaInfo!.GetElementDecl(elementName); - if (elementDecl == null) + if (elementDecl is null) { if (schemaInfo.TargetNamespaces.ContainsKey(context!.Namespace!)) { @@ -237,9 +237,9 @@ private void ValidateEndElement() private void ValidateStartElement() { - if (context!.ElementDecl != null) + if (context!.ElementDecl is not null) { - if (context.ElementDecl.SchemaType != null) + if (context.ElementDecl.SchemaType is not null) { reader.SchemaTypeObject = context.ElementDecl.SchemaType; } @@ -247,7 +247,7 @@ private void ValidateStartElement() { reader.SchemaTypeObject = context.ElementDecl.Datatype; } - if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped != null) + if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped is not null) { reader.TypedValueObject = context.ElementDecl.DefaultValueTyped; context.IsNill = true; // reusing IsNill @@ -271,14 +271,14 @@ private void ValidateStartElement() { reader.SchemaTypeObject = null; SchemaAttDef? attnDef = schemaInfo!.GetAttributeXdr(context.ElementDecl, QualifiedName(reader.LocalName, reader.NamespaceURI)); - if (attnDef != null) + if (attnDef is not null) { - if (context.ElementDecl != null && context.ElementDecl.HasRequiredAttribute) + if (context.ElementDecl is not null && context.ElementDecl.HasRequiredAttribute) { _attPresence.Add(attnDef.Name, attnDef); } - reader.SchemaTypeObject = (attnDef.SchemaType != null) ? (object)attnDef.SchemaType : (object)attnDef.Datatype; - if (attnDef.Datatype != null) + reader.SchemaTypeObject = (attnDef.SchemaType is not null) ? (object)attnDef.SchemaType : (object)attnDef.Datatype; + if (attnDef.Datatype is not null) { string attributeValue = reader.Value; // need to check the contents of this attribute to make sure @@ -320,7 +320,7 @@ private void ValidateEndStartElement() } } - if (context.ElementDecl.Datatype != null) + if (context.ElementDecl.Datatype is not null) { checkDatatype = true; hasSibling = false; @@ -361,12 +361,12 @@ private void LoadSchemaFromLocation(string uri) } finally { - if (reader != null) + if (reader is not null) { reader.Close(); } } - if (xdrSchema != null && xdrSchema.ErrorCount == 0) + if (xdrSchema is not null && xdrSchema.ErrorCount == 0) { schemaInfo!.Add(xdrSchema, EventHandler); SchemaCollection!.Add(uri, xdrSchema, null, false); @@ -379,16 +379,16 @@ private void LoadSchema(string uri) { return; } - if (this.XmlResolver == null) + if (this.XmlResolver is null) { return; } SchemaInfo? schemaInfo = null; - if (SchemaCollection != null) + if (SchemaCollection is not null) schemaInfo = SchemaCollection.GetSchemaInfo(uri); - if (schemaInfo != null) + if (schemaInfo is not null) { if (schemaInfo.SchemaType != SchemaType.XDR) { @@ -406,7 +406,7 @@ private void LoadSchema(string uri) public override bool PreserveWhitespace { - get { return context!.ElementDecl != null ? context.ElementDecl.ContentValidator!.PreserveWhitespace : false; } + get { return context!.ElementDecl is not null ? context.ElementDecl.ContentValidator!.PreserveWhitespace : false; } } private void ProcessTokenizedType( @@ -417,7 +417,7 @@ string name switch (ttype) { case XmlTokenizedType.ID: - if (FindId(name) != null) + if (FindId(name) is not null) { SendValidationEvent(SR.Sch_DupId, name); } @@ -428,7 +428,7 @@ string name break; case XmlTokenizedType.IDREF: object? p = FindId(name); - if (p == null) + if (p is null) { // add it to linked list to check it later _idRefListHead = new IdRefNode(_idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition); } @@ -463,10 +463,10 @@ private void CheckValue( try { reader.TypedValueObject = null; - bool isAttn = attdef != null; + bool isAttn = attdef is not null; XmlSchemaDatatype? dtype = isAttn ? attdef!.Datatype : context!.ElementDecl!.Datatype; - if (dtype == null) + if (dtype is null) { return; // no reason to check } @@ -517,7 +517,7 @@ private void CheckValue( SendValidationEvent(SR.Sch_MinLengthConstraintFailed, value); } } - if (decl.Values != null && !decl.CheckEnumeration(typedValue)) + if (decl.Values is not null && !decl.CheckEnumeration(typedValue)) { if (dtype.TokenizedType == XmlTokenizedType.NOTATION) { @@ -542,7 +542,7 @@ private void CheckValue( } catch (XmlSchemaException) { - if (attdef != null) + if (attdef is not null) { SendValidationEvent(SR.Sch_AttributeValueDataType, attdef.Name.ToString()); } @@ -569,7 +569,7 @@ int linePos try { XmlSchemaDatatype dtype = attdef.Datatype; - if (dtype == null) + if (dtype is null) { return; // no reason to check } @@ -606,7 +606,7 @@ int linePos if (!attdef.CheckEnumeration(typedValue)) { XmlSchemaException e = new XmlSchemaException(SR.Sch_EnumerationValue, typedValue.ToString(), baseUri, lineNo, linePos); - if (eventhandler != null) + if (eventhandler is not null) { eventhandler(sender, new ValidationEventArgs(e)); } @@ -625,7 +625,7 @@ int linePos #endif { XmlSchemaException e = new XmlSchemaException(SR.Sch_AttributeDefaultDataType, attdef.Name.ToString(), baseUri, lineNo, linePos); - if (eventhandler != null) + if (eventhandler is not null) { eventhandler(sender, new ValidationEventArgs(e)); } @@ -641,7 +641,7 @@ internal void AddID(string name, object? node) // Note: It used to be true that we only called this if _fValidate was true, // but due to the fact that you can now dynamically type somethign as an ID // that is no longer true. - if (_IDs == null) + if (_IDs is null) { _IDs = new Hashtable(); } @@ -651,13 +651,13 @@ internal void AddID(string name, object? node) public override object? FindId(string name) { - return _IDs == null ? null : _IDs[name]; + return _IDs is null ? null : _IDs[name]; } private void Push(XmlQualifiedName elementName) { context = (ValidationState)_validationStack.Push(); - if (context == null) + if (context is null) { context = new ValidationState(); _validationStack.AddToTop(context); @@ -682,9 +682,9 @@ private void Pop() private void CheckForwardRefs() { IdRefNode? next = _idRefListHead; - while (next != null) + while (next is not null) { - if (FindId(next.Id) == null) + if (FindId(next.Id) is null) { SendValidationEvent(new XmlSchemaException(SR.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs index 0ba7f5af19a217..ac10ee551d317e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs @@ -80,7 +80,7 @@ public IDictionary GetNamespacesInScope(XmlNamespaceScope scope) internal XmlAtomicValue(XmlSchemaType xmlType, bool value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Boolean; _unionVal.boolVal = value; @@ -88,7 +88,7 @@ internal XmlAtomicValue(XmlSchemaType xmlType, bool value) internal XmlAtomicValue(XmlSchemaType xmlType, DateTime value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.DateTime; _unionVal.dtVal = value; @@ -96,7 +96,7 @@ internal XmlAtomicValue(XmlSchemaType xmlType, DateTime value) internal XmlAtomicValue(XmlSchemaType xmlType, double value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Double; _unionVal.dblVal = value; @@ -104,7 +104,7 @@ internal XmlAtomicValue(XmlSchemaType xmlType, double value) internal XmlAtomicValue(XmlSchemaType xmlType, int value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Int32; _unionVal.i32Val = value; @@ -112,7 +112,7 @@ internal XmlAtomicValue(XmlSchemaType xmlType, int value) internal XmlAtomicValue(XmlSchemaType xmlType, long value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Int64; _unionVal.i64Val = value; @@ -120,19 +120,19 @@ internal XmlAtomicValue(XmlSchemaType xmlType, long value) internal XmlAtomicValue(XmlSchemaType xmlType, string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; } internal XmlAtomicValue(XmlSchemaType xmlType, string value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; - if (nsResolver != null && (_xmlType.TypeCode == XmlTypeCode.QName || _xmlType.TypeCode == XmlTypeCode.Notation)) + if (nsResolver is not null && (_xmlType.TypeCode == XmlTypeCode.QName || _xmlType.TypeCode == XmlTypeCode.Notation)) { string prefix = GetPrefixFromQName(value)!; _nsPrefix = new NamespacePrefixForQName(prefix, nsResolver.LookupNamespace(prefix)!); @@ -141,23 +141,23 @@ internal XmlAtomicValue(XmlSchemaType xmlType, string value, IXmlNamespaceResolv internal XmlAtomicValue(XmlSchemaType xmlType, object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; } internal XmlAtomicValue(XmlSchemaType xmlType, object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (xmlType is null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; - if (nsResolver != null && (_xmlType.TypeCode == XmlTypeCode.QName || _xmlType.TypeCode == XmlTypeCode.Notation)) + if (nsResolver is not null && (_xmlType.TypeCode == XmlTypeCode.QName || _xmlType.TypeCode == XmlTypeCode.Notation)) { //Its a qualifiedName XmlQualifiedName qname = (_objVal as XmlQualifiedName)!; - Debug.Assert(qname != null); //string representation is handled in a different overload + Debug.Assert(qname is not null); //string representation is handled in a different overload string ns = qname.Namespace; _nsPrefix = new NamespacePrefixForQName(nsResolver.LookupPrefix(ns)!, ns); } @@ -210,7 +210,7 @@ public override object TypedValue { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -232,7 +232,7 @@ public override bool ValueAsBoolean { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -255,7 +255,7 @@ public override DateTime ValueAsDateTime { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -279,7 +279,7 @@ public override double ValueAsDouble { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -302,7 +302,7 @@ public override int ValueAsInt { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -325,7 +325,7 @@ public override long ValueAsLong { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -349,7 +349,7 @@ public override object ValueAs(Type type, IXmlNamespaceResolver? nsResolver) if (type == typeof(XPathItem) || type == typeof(XmlAtomicValue)) return this; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { @@ -371,7 +371,7 @@ public override string Value { XmlValueConverter valueConverter = _xmlType.ValueConverter; - if (_objVal == null) + if (_objVal is null) { switch (_clrType) { 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 309fb8ffa402ef..787d433a8e5bcb 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 @@ -75,7 +75,7 @@ public XmlSchema() { } } catch (XmlSchemaException e) { - if (validationEventHandler != null) + if (validationEventHandler is not null) { validationEventHandler(null, new ValidationEventArgs(e)); } @@ -122,16 +122,16 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema)); XmlSerializerNamespaces ns; - if (namespaceManager != null) + if (namespaceManager is not null) { ns = new XmlSerializerNamespaces(); bool ignoreXS = false; - if (this.Namespaces != null) + if (this.Namespaces is not null) { //User may have set both nsManager and Namespaces property on the XmlSchema object ignoreXS = this.Namespaces.Namespaces.ContainsKey("xs") || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs); } - if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && - namespaceManager.LookupNamespace("xs") == null) + if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) is null && + namespaceManager.LookupNamespace("xs") is null) { ns.Add("xs", XmlReservedNs.NsXs); } @@ -143,7 +143,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) } } } - else if (this.Namespaces != null && this.Namespaces.Count > 0) + else if (this.Namespaces is not null && this.Namespaces.Count > 0) { Dictionary serializerNS = this.Namespaces.Namespaces; if (!serializerNS.ContainsKey("xs") && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) @@ -156,7 +156,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) { ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); - if (_targetNs != null && _targetNs.Length != 0) + if (_targetNs is not null && _targetNs.Length != 0) { ns.Add("tns", _targetNs); } @@ -310,7 +310,7 @@ public XmlSchemaObjectTable Attributes { get { - if (_attributes == null) + if (_attributes is null) { _attributes = new XmlSchemaObjectTable(); } @@ -323,7 +323,7 @@ public XmlSchemaObjectTable AttributeGroups { get { - if (_attributeGroups == null) + if (_attributeGroups is null) { _attributeGroups = new XmlSchemaObjectTable(); } @@ -336,7 +336,7 @@ public XmlSchemaObjectTable SchemaTypes { get { - if (_types == null) + if (_types is null) { _types = new XmlSchemaObjectTable(); } @@ -349,7 +349,7 @@ public XmlSchemaObjectTable Elements { get { - if (_elements == null) + if (_elements is null) { _elements = new XmlSchemaObjectTable(); } @@ -434,7 +434,7 @@ internal Hashtable Ids [XmlIgnore] internal XmlDocument Document { - get { if (_document == null) _document = new XmlDocument(); return _document; } + get { if (_document is null) _document = new XmlDocument(); return _document; } } [XmlIgnore] @@ -484,15 +484,15 @@ internal XmlSchema DeepClone() XmlSchemaElement? element; XmlSchemaGroup? group; - if ((complexType = _items[i] as XmlSchemaComplexType) != null) + if ((complexType = _items[i] as XmlSchemaComplexType) is not null) { newItem = complexType.Clone(this); } - else if ((element = _items[i] as XmlSchemaElement) != null) + else if ((element = _items[i] as XmlSchemaElement) is not null) { newItem = element.Clone(this); } - else if ((group = _items[i] as XmlSchemaGroup) != null) + else if ((group = _items[i] as XmlSchemaGroup) is not null) { newItem = group.Clone(this); } @@ -539,14 +539,14 @@ internal override void AddAnnotation(XmlSchemaAnnotation annotation) internal XmlNameTable NameTable { - get { if (_nameTable == null) _nameTable = new System.Xml.NameTable(); return _nameTable; } + get { if (_nameTable is null) _nameTable = new System.Xml.NameTable(); return _nameTable; } } internal ArrayList ImportedSchemas { get { - if (_importedSchemas == null) + if (_importedSchemas is null) { _importedSchemas = new ArrayList(); } @@ -558,7 +558,7 @@ internal ArrayList ImportedNamespaces { get { - if (_importedNamespaces == null) + if (_importedNamespaces is null) { _importedNamespaces = new ArrayList(); } @@ -568,7 +568,7 @@ internal ArrayList ImportedNamespaces internal void GetExternalSchemasList(IList extList, XmlSchema schema) { - Debug.Assert(extList != null && schema != null); + Debug.Assert(extList is not null && schema is not null); if (extList.Contains(schema)) { return; @@ -577,7 +577,7 @@ internal void GetExternalSchemasList(IList extList, XmlSchema schema) for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i]; - if (ext.Schema != null) + if (ext.Schema is not null) { GetExternalSchemasList(extList, ext.Schema); } @@ -590,14 +590,14 @@ internal void AddCompiledInfo(SchemaInfo schemaInfo) { foreach (XmlSchemaElement element in elements.Values) { itemName = element.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; - if (schemaInfo.ElementDecls[itemName] == null) { + if (schemaInfo.ElementDecls[itemName] is null) { schemaInfo.ElementDecls.Add(itemName, element.ElementDecl); } } foreach (XmlSchemaAttribute attribute in attributes.Values) { itemName = attribute.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; - if (schemaInfo.ElementDecls[itemName] == null) { + if (schemaInfo.ElementDecls[itemName] is null) { schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef); } } @@ -605,7 +605,7 @@ internal void AddCompiledInfo(SchemaInfo schemaInfo) { itemName = type.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; XmlSchemaComplexType complexType = type as XmlSchemaComplexType; - if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) { + if ((complexType is null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] is null) { schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl); } } @@ -615,7 +615,7 @@ internal void AddCompiledInfo(SchemaInfo schemaInfo) { SchemaNotation no = new SchemaNotation(itemName); no.SystemLiteral = notation.System; no.Pubid = notation.Public; - if (schemaInfo.Notations[itemName.Name] == null) { + if (schemaInfo.Notations[itemName.Name] is null) { schemaInfo.Notations.Add(itemName.Name, no); } } 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 dee86d0ee407e5..8ec33dfa843c61 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 (_ns is null || _ns.Length == 0) { return "##any"; } @@ -86,7 +86,7 @@ internal override string NameString internal void BuildNamespaceList(string? targetNamespace) { - if (_ns != null) + if (_ns is not null) { //If namespace="" default to namespace="##any" _namespaceList = new NamespaceList(_ns, targetNamespace!); } @@ -98,7 +98,7 @@ internal void BuildNamespaceList(string? targetNamespace) internal void BuildNamespaceListV1Compat(string targetNamespace) { - if (_ns != null) + if (_ns is not null) { _namespaceList = new NamespaceListV1Compat(_ns, targetNamespace); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs index 48775d8ca67521..1db4efa871939c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs @@ -42,7 +42,7 @@ internal XmlSchemaContentProcessing ProcessContentsCorrect internal void BuildNamespaceList(string? targetNamespace) { - if (_ns != null) + if (_ns is not null) { _namespaceList = new NamespaceList(_ns, targetNamespace!); } @@ -54,7 +54,7 @@ internal void BuildNamespaceList(string? targetNamespace) internal void BuildNamespaceListV1Compat(string targetNamespace) { - if (_ns != null) + if (_ns is not null) { _namespaceList = new NamespaceListV1Compat(_ns, targetNamespace); } @@ -77,7 +77,7 @@ internal static bool IsSubset(XmlSchemaAnyAttribute sub, XmlSchemaAnyAttribute s internal static XmlSchemaAnyAttribute? Intersection(XmlSchemaAnyAttribute o1, XmlSchemaAnyAttribute o2, bool v1Compat) { NamespaceList? nsl = NamespaceList.Intersection(o1.NamespaceList!, o2.NamespaceList!, v1Compat); - if (nsl != null) + if (nsl is not null) { XmlSchemaAnyAttribute anyAttribute = new XmlSchemaAnyAttribute(); anyAttribute._namespaceList = nsl; @@ -95,7 +95,7 @@ internal static bool IsSubset(XmlSchemaAnyAttribute sub, XmlSchemaAnyAttribute s internal static XmlSchemaAnyAttribute? Union(XmlSchemaAnyAttribute o1, XmlSchemaAnyAttribute o2, bool v1Compat) { NamespaceList? nsl = NamespaceList.Union(o1.NamespaceList!, o2.NamespaceList!, v1Compat); - if (nsl != null) + if (nsl is not null) { XmlSchemaAnyAttribute anyAttribute = new XmlSchemaAnyAttribute(); anyAttribute._namespaceList = nsl; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs index d1cc422f95b8fc..e813c311b5dbd4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs @@ -60,14 +60,14 @@ public string? Name public XmlQualifiedName RefName { get { return _refName; } - set { _refName = (value == null ? XmlQualifiedName.Empty : value); } + set { _refName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlAttribute("type")] public XmlQualifiedName SchemaTypeName { get { return _typeName; } - set { _typeName = (value == null ? XmlQualifiedName.Empty : value); } + set { _typeName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlElement("simpleType")] @@ -96,7 +96,7 @@ public object? AttributeType { get { - if (_attributeType == null) + if (_attributeType is null) return null; if (_attributeType.QualifiedName.Namespace == XmlReservedNs.NsXs) @@ -116,7 +116,7 @@ public XmlSchemaSimpleType? AttributeSchemaType [return: NotNullIfNotNull("schemaSet")] internal XmlReader? Validate(XmlReader reader, XmlResolver? resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { - if (schemaSet != null) + if (schemaSet is not null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; @@ -132,7 +132,7 @@ internal XmlSchemaDatatype? Datatype { get { - if (_attributeType != null) + if (_attributeType is not null) { return _attributeType.Datatype; } @@ -158,7 +158,7 @@ internal SchemaAttDef? AttDef internal bool HasDefault { - get { return _defaultValue != null; } + get { return _defaultValue is not null; } } [XmlIgnore] diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs index 36c56f39f488a9..60ab7ab6eb2a87 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs @@ -49,7 +49,7 @@ internal XmlSchemaObjectTable AttributeUses { get { - if (_attributeUses == null) + if (_attributeUses is null) { _attributeUses = new XmlSchemaObjectTable(); } 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 fd646d96c64ace..de2f85f82f3d15 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 @@ -44,7 +44,7 @@ public XmlSchemaCollection() : this(new NameTable()) /// public XmlSchemaCollection(XmlNameTable nametable) { - if (nametable == null) + if (nametable is null) { throw new ArgumentNullException(nameof(nametable)); } @@ -98,7 +98,7 @@ internal XmlResolver? XmlResolver /// public XmlSchema? Add(string? ns, string uri) { - if (uri == null || uri.Length == 0) + if (uri is null || uri.Length == 0) throw new ArgumentNullException(nameof(uri)); XmlTextReader reader = new XmlTextReader(uri, _nameTable); reader.XmlResolver = _xmlResolver; @@ -128,7 +128,7 @@ internal XmlResolver? XmlResolver /// public XmlSchema? Add(string? ns, XmlReader reader, XmlResolver? resolver) { - if (reader == null) + if (reader is null) throw new ArgumentNullException(nameof(reader)); XmlNameTable readerNameTable = reader.NameTable; SchemaInfo schemaInfo = new SchemaInfo(); @@ -164,7 +164,7 @@ internal XmlResolver? XmlResolver public XmlSchema? Add(XmlSchema schema, XmlResolver? resolver) { - if (schema == null) + if (schema is null) throw new ArgumentNullException(nameof(schema)); SchemaInfo schemaInfo = new SchemaInfo(); @@ -178,7 +178,7 @@ internal XmlResolver? XmlResolver /// public void Add(XmlSchemaCollection schema) { - if (schema == null) + if (schema is null) throw new ArgumentNullException(nameof(schema)); if (this == schema) return; @@ -198,24 +198,24 @@ public XmlSchema? this[string? ns] { get { - XmlSchemaCollectionNode? node = (XmlSchemaCollectionNode?)_collection[(ns != null) ? ns : string.Empty]; - return (node != null) ? node.Schema : null; + XmlSchemaCollectionNode? node = (XmlSchemaCollectionNode?)_collection[(ns is not null) ? ns : string.Empty]; + return (node is not null) ? node.Schema : null; } } public bool Contains(XmlSchema schema) { - if (schema == null) + if (schema is null) { throw new ArgumentNullException(nameof(schema)); } - return this[schema.TargetNamespace] != null; + return this[schema.TargetNamespace] is not null; } public bool Contains(string? ns) { - return _collection[(ns != null) ? ns : string.Empty] != null; + return _collection[(ns is not null) ? ns : string.Empty] is not null; } /// @@ -233,7 +233,7 @@ public XmlSchemaCollectionEnumerator GetEnumerator() void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); @@ -249,14 +249,14 @@ void ICollection.CopyTo(Array array, int index) public void CopyTo(XmlSchema[] array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) { XmlSchema? schema = e.Current; - if (schema != null) + if (schema is not null) { if (index == array.Length) { @@ -285,8 +285,8 @@ int ICollection.Count internal SchemaInfo? GetSchemaInfo(string? ns) { - XmlSchemaCollectionNode? node = (XmlSchemaCollectionNode?)_collection[(ns != null) ? ns : string.Empty]; - return (node != null) ? node.SchemaInfo : null; + XmlSchemaCollectionNode? node = (XmlSchemaCollectionNode?)_collection[(ns is not null) ? ns : string.Empty]; + return (node is not null) ? node.SchemaInfo : null; } internal SchemaNames GetSchemaNames(XmlNameTable nt) @@ -297,7 +297,7 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) } else { - if (_schemaNames == null) + if (_schemaNames is null) { _schemaNames = new SchemaNames(_nameTable); } @@ -313,7 +313,7 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) private XmlSchema? Add(string? ns, SchemaInfo schemaInfo, XmlSchema? schema, bool compile, XmlResolver? resolver) { int errorCount = 0; - if (schema != null) + if (schema is not null) { if (schema.ErrorCount == 0 && compile) { @@ -322,15 +322,15 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) errorCount = 1; } - ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; + ns = schema.TargetNamespace is null ? string.Empty : schema.TargetNamespace; } errorCount += schema.ErrorCount; } else { errorCount += schemaInfo.ErrorCount; - //ns = ns == null? string.Empty : NameTable.Add(ns); - ns = NameTable.Add(ns!); //Added without checking for ns == null, since XDR cannot have null namespace + //ns = ns is null? string.Empty : NameTable.Add(ns); + ns = NameTable.Add(ns!); //Added without checking for ns is null, since XDR cannot have null namespace } if (errorCount == 0) { @@ -347,7 +347,7 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) private void AddNonThreadSafe(string ns, XmlSchemaCollectionNode? node) { - if (_collection[ns] != null) + if (_collection[ns] is not null) _collection.Remove(ns); _collection.Add(ns, node); } @@ -369,7 +369,7 @@ private void Add(string ns, XmlSchemaCollectionNode? node) private void SendValidationEvent(XmlSchemaException e) { - if (_validationEventHandler != null) + if (_validationEventHandler is not null) { _validationEventHandler(this, new ValidationEventArgs(e)); } @@ -451,7 +451,7 @@ public XmlSchema? Current get { XmlSchemaCollectionNode? n = (XmlSchemaCollectionNode?)_enumerator.Value; - if (n != null) + if (n is not null) return n.Schema; else return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs index 0b382791dcf65b..0cbfde35c1eeb5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs @@ -17,7 +17,7 @@ public class XmlSchemaComplexContentRestriction : XmlSchemaContent public XmlQualifiedName BaseTypeName { get { return _baseTypeName; } - set { _baseTypeName = (value == null ? XmlQualifiedName.Empty : value); } + set { _baseTypeName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlElement("group", typeof(XmlSchemaGroupRef)), diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs index 0b82c430a82b32..1ef45fda3b5c12 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs @@ -192,7 +192,7 @@ public XmlSchemaObjectCollection Attributes { get { - if (_attributes == null) + if (_attributes is null) { _attributes = new XmlSchemaObjectCollection(); } @@ -231,7 +231,7 @@ public XmlSchemaObjectTable AttributeUses { get { - if (_attributeUses == null) + if (_attributeUses is null) { _attributeUses = new XmlSchemaObjectTable(); } @@ -250,7 +250,7 @@ internal XmlSchemaObjectTable LocalElements { get { - if (_localElements == null) + if (_localElements is null) { _localElements = new XmlSchemaObjectTable(); } @@ -296,7 +296,7 @@ internal override XmlQualifiedName DerivedFrom { get { - if (_contentModel == null) + if (_contentModel is null) { // type derived from anyType return XmlQualifiedName.Empty; @@ -327,7 +327,7 @@ internal bool ContainsIdAttribute(bool findAll) if (attribute!.Use != XmlSchemaUse.Prohibited) { XmlSchemaDatatype? datatype = attribute.Datatype; - if (datatype != null && datatype.TypeCode == XmlTypeCode.Id) + if (datatype is not null && datatype.TypeCode == XmlTypeCode.Id) { idCount++; if (idCount > 1) @@ -351,15 +351,15 @@ internal XmlSchemaObject Clone(XmlSchema? parentSchema) XmlSchemaComplexType complexType = (XmlSchemaComplexType)MemberwiseClone(); //Deep clone the QNames as these will be updated on chameleon includes - if (complexType.ContentModel != null) + if (complexType.ContentModel is not null) { //simpleContent or complexContent XmlSchemaSimpleContent? simpleContent = complexType.ContentModel as XmlSchemaSimpleContent; - if (simpleContent != null) + if (simpleContent is not null) { XmlSchemaSimpleContent newSimpleContent = (XmlSchemaSimpleContent)simpleContent.Clone(); XmlSchemaSimpleContentExtension? simpleExt = simpleContent.Content as XmlSchemaSimpleContentExtension; - if (simpleExt != null) + if (simpleExt is not null) { XmlSchemaSimpleContentExtension newSimpleExt = (XmlSchemaSimpleContentExtension)simpleExt.Clone(); newSimpleExt.BaseTypeName = simpleExt.BaseTypeName.Clone(); @@ -383,7 +383,7 @@ internal XmlSchemaObject Clone(XmlSchema? parentSchema) XmlSchemaComplexContent newComplexContent = (XmlSchemaComplexContent)complexContent.Clone(); XmlSchemaComplexContentExtension? complexExt = complexContent.Content as XmlSchemaComplexContentExtension; - if (complexExt != null) + if (complexExt is not null) { XmlSchemaComplexContentExtension newComplexExt = (XmlSchemaComplexContentExtension)complexExt.Clone(); newComplexExt.BaseTypeName = complexExt.BaseTypeName.Clone(); @@ -447,7 +447,7 @@ internal static XmlSchemaObjectCollection CloneAttributes(XmlSchemaObjectCollect { xso = attributes[i]; attributeGroupRef = xso as XmlSchemaAttributeGroupRef; - if (attributeGroupRef != null) + if (attributeGroupRef is not null) { newAttGroupRef = (XmlSchemaAttributeGroupRef)attributeGroupRef.Clone(); newAttGroupRef.RefName = attributeGroupRef.RefName.Clone(); @@ -483,7 +483,7 @@ private static XmlSchemaObjectCollection CloneGroupBaseParticles(XmlSchemaObject internal static XmlSchemaParticle? CloneParticle(XmlSchemaParticle? particle, XmlSchema? parentSchema) { XmlSchemaGroupBase? groupBase = particle as XmlSchemaGroupBase; - if (groupBase != null) + if (groupBase is not null) { //Choice or sequence XmlSchemaGroupBase newGroupBase = groupBase; @@ -506,7 +506,7 @@ private static XmlSchemaObjectCollection CloneGroupBaseParticles(XmlSchemaObject // - it references its type by name // - it's form (effective) is qualified (meaning it will inherint namespace from chameleon includes if that happens) // then the element itself needs to be cloned. - if (oldElem != null && (!oldElem.RefName.IsEmpty || !oldElem.SchemaTypeName.IsEmpty || + if (oldElem is not null && (!oldElem.RefName.IsEmpty || !oldElem.SchemaTypeName.IsEmpty || GetResolvedElementForm(parentSchema, oldElem) == XmlSchemaForm.Qualified)) { XmlSchemaElement newElem = (XmlSchemaElement)oldElem.Clone(parentSchema); @@ -524,7 +524,7 @@ private static XmlSchemaObjectCollection CloneGroupBaseParticles(XmlSchemaObject // schema. private static XmlSchemaForm GetResolvedElementForm(XmlSchema? parentSchema, XmlSchemaElement element) { - if (element.Form == XmlSchemaForm.None && parentSchema != null) + if (element.Form == XmlSchemaForm.None && parentSchema is not null) { return parentSchema.ElementFormDefault; } @@ -537,7 +537,7 @@ private static XmlSchemaForm GetResolvedElementForm(XmlSchema? parentSchema, Xml internal static bool HasParticleRef(XmlSchemaParticle? particle, XmlSchema? parentSchema) { XmlSchemaGroupBase? groupBase = particle as XmlSchemaGroupBase; - if (groupBase != null) + if (groupBase is not null) { bool foundRef = false; int i = 0; @@ -555,7 +555,7 @@ internal static bool HasParticleRef(XmlSchemaParticle? particle, XmlSchema? pare // that's on purpose. This method is used to determine if we need to clone the whole particle. // If we do, then the CloneParticle is called and it will try to clone only // those elements which need cloning - and those are the ones matching this condition. - if (elem != null && (!elem.RefName.IsEmpty || !elem.SchemaTypeName.IsEmpty || + if (elem is not null && (!elem.RefName.IsEmpty || !elem.SchemaTypeName.IsEmpty || GetResolvedElementForm(parentSchema, elem) == XmlSchemaForm.Qualified)) { foundRef = true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs index 31fb39ed805e24..2e054c299c58c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs @@ -25,11 +25,11 @@ internal XmlSchemaDatatype() { } public virtual object ChangeType(object value, Type targetType) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } - if (targetType == null) + if (targetType is null) { throw new ArgumentNullException(nameof(targetType)); } @@ -38,15 +38,15 @@ public virtual object ChangeType(object value, Type targetType) public virtual object ChangeType(object value, Type targetType, IXmlNamespaceResolver namespaceResolver) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } - if (targetType == null) + if (targetType is null) { throw new ArgumentNullException(nameof(targetType)); } - if (namespaceResolver == null) + if (namespaceResolver is null) { throw new ArgumentNullException(nameof(namespaceResolver)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs index 7e88413d4050ae..3f671853a6f63f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs @@ -115,7 +115,7 @@ internal bool HasAbstractAttribute public XmlQualifiedName RefName { get { return _refName; } - set { _refName = (value == null ? XmlQualifiedName.Empty : value); } + set { _refName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlAttribute("substitutionGroup")] @@ -123,7 +123,7 @@ public XmlQualifiedName RefName public XmlQualifiedName SubstitutionGroup { get { return _substitutionGroup; } - set { _substitutionGroup = (value == null ? XmlQualifiedName.Empty : value); } + set { _substitutionGroup = (value is null ? XmlQualifiedName.Empty : value); } } [XmlAttribute("type")] @@ -131,7 +131,7 @@ public XmlQualifiedName SubstitutionGroup public XmlQualifiedName SchemaTypeName { get { return _typeName; } - set { _typeName = (value == null ? XmlQualifiedName.Empty : value); } + set { _typeName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlElement("complexType", typeof(XmlSchemaComplexType)), @@ -149,7 +149,7 @@ public XmlSchemaObjectCollection Constraints { get { - if (_constraints == null) + if (_constraints is null) { _constraints = new XmlSchemaObjectCollection(); } @@ -169,7 +169,7 @@ public object? ElementType { get { - if (_elementType == null) + if (_elementType is null) return null; if (_elementType.QualifiedName.Namespace == XmlReservedNs.NsXs) @@ -201,7 +201,7 @@ public XmlSchemaDerivationMethod FinalResolved [return: NotNullIfNotNull("schemaSet")] internal XmlReader? Validate(XmlReader reader, XmlResolver? resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { - if (schemaSet != null) + if (schemaSet is not null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; @@ -235,12 +235,12 @@ internal void SetFinalResolved(XmlSchemaDerivationMethod value) [XmlIgnore] internal bool HasDefault { - get { return _defaultValue != null && _defaultValue.Length > 0; } + get { return _defaultValue is not null && _defaultValue.Length > 0; } } internal bool HasConstraints { - get { return _constraints != null && _constraints.Count > 0; } + get { return _constraints is not null && _constraints.Count > 0; } } internal bool IsLocalTypeDerivationChecked @@ -296,7 +296,7 @@ internal XmlSchemaObject Clone(XmlSchema? parentSchema) // it needs to be cloned as well, since it may contain named elements and such. And these names // will need to be cloned since they may change their namespace on chameleon includes XmlSchemaComplexType? complexType = _type as XmlSchemaComplexType; - if (complexType != null && complexType.QualifiedName.IsEmpty) + if (complexType is not null && complexType.QualifiedName.IsEmpty) { newElem._type = (XmlSchemaType)complexType.Clone(parentSchema); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs index 9b29480ef8898f..7f0217be32f50b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs @@ -89,7 +89,7 @@ public class XmlSchemaKeyref : XmlSchemaIdentityConstraint public XmlQualifiedName Refer { get { return _refer; } - set { _refer = (value == null ? XmlQualifiedName.Empty : value); } + set { _refer = (value is null ? XmlQualifiedName.Empty : value); } } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs index 926b9ee6c92b21..8de21ac6ab3408 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs @@ -27,7 +27,7 @@ public string? MinOccursString } set { - if (value == null) + if (value is null) { _minOccurs = decimal.One; _flags &= ~Occurs.Min; @@ -53,7 +53,7 @@ public string? MaxOccursString } set { - if (value == null) + if (value is null) { _maxOccurs = decimal.One; _flags &= ~Occurs.Max; @@ -136,17 +136,17 @@ internal virtual string NameString internal XmlQualifiedName GetQualifiedName() { XmlSchemaElement? elem = this as XmlSchemaElement; - if (elem != null) + if (elem is not null) { return elem.QualifiedName; } else { XmlSchemaAny? any = this as XmlSchemaAny; - if (any != null) + if (any is not null) { string? ns = any.Namespace; - if (ns != null) + if (ns is not null) { ns = ns.Trim(); } 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 cdbe0178c0c32b..e9b90cf875e137 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 @@ -61,7 +61,7 @@ internal object InternalSyncObject { get { - if (_internalSyncObject == null) + if (_internalSyncObject is null) { object o = new object(); Interlocked.CompareExchange(ref _internalSyncObject, o, null); @@ -86,7 +86,7 @@ public XmlSchemaSet() : this(new NameTable()) /// public XmlSchemaSet(XmlNameTable nameTable) { - if (nameTable == null) + if (nameTable is null) { throw new ArgumentNullException(nameof(nameTable)); } @@ -106,7 +106,7 @@ public XmlSchemaSet(XmlNameTable nameTable) // we don't have to check XmlReaderSettings.EnableLegacyXmlSettings() here because the following // code will return same result either we are running on v4.5 or later - if (_readerSettings.GetXmlResolver() == null) + if (_readerSettings.GetXmlResolver() is null) { // The created resolver will be used in the schema validation only _readerSettings.XmlResolver = new XmlUrlResolver(); @@ -137,7 +137,7 @@ public event ValidationEventHandler ValidationEventHandler { _eventHandler -= _internalEventHandler; _eventHandler += value; - if (_eventHandler == null) + if (_eventHandler is null) { _eventHandler = _internalEventHandler; } @@ -145,7 +145,7 @@ public event ValidationEventHandler ValidationEventHandler remove { _eventHandler -= value; - if (_eventHandler == null) + if (_eventHandler is null) { _eventHandler = _internalEventHandler; } @@ -198,7 +198,7 @@ public XmlSchemaObjectTable GlobalElements { get { - if (elements == null) + if (elements is null) { elements = new XmlSchemaObjectTable(); } @@ -210,7 +210,7 @@ public XmlSchemaObjectTable GlobalAttributes { get { - if (attributes == null) + if (attributes is null) { attributes = new XmlSchemaObjectTable(); } @@ -222,7 +222,7 @@ public XmlSchemaObjectTable GlobalTypes { get { - if (schemaTypes == null) + if (schemaTypes is null) { schemaTypes = new XmlSchemaObjectTable(); } @@ -234,7 +234,7 @@ internal XmlSchemaObjectTable SubstitutionGroups { get { - if (substitutionGroups == null) + if (substitutionGroups is null) { substitutionGroups = new XmlSchemaObjectTable(); } @@ -260,7 +260,7 @@ internal XmlSchemaObjectTable TypeExtensions { get { - if (_typeExtensions == null) + if (_typeExtensions is null) { _typeExtensions = new XmlSchemaObjectTable(); } @@ -276,12 +276,12 @@ internal XmlSchemaObjectTable TypeExtensions /// public XmlSchema? Add(string? targetNamespace, string schemaUri) { - if (schemaUri == null || schemaUri.Length == 0) + if (schemaUri is null || schemaUri.Length == 0) { throw new ArgumentNullException(nameof(schemaUri)); } - if (targetNamespace != null) + if (targetNamespace is not null) { targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace); } @@ -291,7 +291,7 @@ internal XmlSchemaObjectTable TypeExtensions { //Check if schema from url has already been added XmlResolver? tempResolver = _readerSettings.GetXmlResolver(); - if (tempResolver == null) + if (tempResolver is null) { tempResolver = new XmlUrlResolver(); } @@ -326,11 +326,11 @@ internal XmlSchemaObjectTable TypeExtensions /// public XmlSchema? Add(string? targetNamespace, XmlReader schemaDocument) { - if (schemaDocument == null) + if (schemaDocument is null) { throw new ArgumentNullException(nameof(schemaDocument)); } - if (targetNamespace != null) + if (targetNamespace is not null) { targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace); } @@ -360,7 +360,7 @@ internal XmlSchemaObjectTable TypeExtensions /// public void Add(XmlSchemaSet schemas) { - if (schemas == null) + if (schemas is null) { throw new ArgumentNullException(nameof(schemas)); } @@ -405,16 +405,16 @@ public void Add(XmlSchemaSet schemas) foreach (XmlSchema? schema in schemas.SortedSchemas.Values) { tns = schema!.TargetNamespace; - if (tns == null) + if (tns is null) { tns = string.Empty; } - if (_schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) != null) + if (_schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) is not null) { //Do not already existing url continue; } currentSchema = Add(schema.TargetNamespace, schema); - if (currentSchema == null) + if (currentSchema is null) { remove = true; break; @@ -446,7 +446,7 @@ public void Add(XmlSchemaSet schemas) public XmlSchema? Add(XmlSchema schema) { - if (schema == null) + if (schema is null) { throw new ArgumentNullException(nameof(schema)); } @@ -468,7 +468,7 @@ public void Add(XmlSchemaSet schemas) public bool RemoveRecursive(XmlSchema schemaToRemove) { - if (schemaToRemove == null) + if (schemaToRemove is null) { throw new ArgumentNullException(nameof(schemaToRemove)); } @@ -488,7 +488,7 @@ public bool RemoveRecursive(XmlSchema schemaToRemove) for (int i = 0; i < schemaToRemove.ImportedNamespaces.Count; i++) { importedNS = (string)schemaToRemove.ImportedNamespaces[i]!; - if (disallowedNamespaces[importedNS] == null) + if (disallowedNamespaces[importedNS] is null) { disallowedNamespaces.Add(importedNS, importedNS); } @@ -541,17 +541,17 @@ public bool RemoveRecursive(XmlSchema schemaToRemove) public bool Contains(string? targetNamespace) { - if (targetNamespace == null) + if (targetNamespace is null) { targetNamespace = string.Empty; } - return _targetNamespaces[targetNamespace] != null; + return _targetNamespaces[targetNamespace] is not null; } public bool Contains(XmlSchema schema) { - if (schema == null) + if (schema is null) { throw new ArgumentNullException(nameof(schema)); } @@ -660,7 +660,7 @@ public XmlSchema Reprocess(XmlSchema schema) // The only difference is that we don't touch .schemas collection here to not break a code like this: // foreach (XmlSchema s in schemaset.schemas) { schemaset.Reprocess(s); } // This is by purpose. - if (schema == null) + if (schema is null) { throw new ArgumentNullException(nameof(schema)); } @@ -678,7 +678,7 @@ public XmlSchema Reprocess(XmlSchema schema) RemoveSchemaFromGlobalTables(schema); RemoveSchemaFromCaches(schema); - if (schema.BaseUri != null) + if (schema.BaseUri is not null) { _schemaLocations.Remove(schema.BaseUri); } @@ -710,11 +710,11 @@ public XmlSchema Reprocess(XmlSchema schema) #region Copied from AddSchemaToSet(XmlSchema schema) //Add to targetNamespaces table - if (_targetNamespaces[tns] == null) + if (_targetNamespaces[tns] is null) { _targetNamespaces.Add(tns, tns); } - if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) + if (_schemaForSchema is null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] is not null) { //it has xs:anyType _schemaForSchema = schema; } @@ -726,11 +726,11 @@ public XmlSchema Reprocess(XmlSchema schema) _schemas.Add(s.SchemaId, s); } tns = GetTargetNamespace(s); - if (_targetNamespaces[tns] == null) + if (_targetNamespaces[tns] is null) { _targetNamespaces.Add(tns, tns); } - if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) + if (_schemaForSchema is null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] is not null) { //it has xs:anyType _schemaForSchema = schema; } @@ -746,7 +746,7 @@ public XmlSchema Reprocess(XmlSchema schema) public void CopyTo(XmlSchema[] schemas, int index) { - if (schemas == null) + if (schemas is null) throw new ArgumentNullException(nameof(schemas)); if (index < 0 || index > schemas.Length - 1) throw new ArgumentOutOfRangeException(nameof(index)); @@ -762,7 +762,7 @@ public ICollection Schemas(string? targetNamespace) { ArrayList tnsSchemas = new ArrayList(); XmlSchema currentSchema; - if (targetNamespace == null) + if (targetNamespace is null) { targetNamespace = string.Empty; } @@ -784,7 +784,7 @@ public ICollection Schemas(string? targetNamespace) // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess // method. If you change anything here *make sure* to update Reprocess method accordingly. - if (schema == null || schema.ErrorCount != 0) + if (schema is null || schema.ErrorCount != 0) { //Schema with parsing errors cannot be loaded return null; } @@ -818,7 +818,7 @@ private void AddCompiledSchema(XmlSchema schema) { } newCompiledInfo.Add(cachedCompiledInfo, eventHandler); //Add existing compiled info cachedCompiledInfo = newCompiledInfo; - if (substitutionGroupsTable != null) { + if (substitutionGroupsTable is not null) { ProcessNewSubstitutionGroups(substitutionGroupsTable, true); } if (schemas.Count == 0) { //If its the first compiled schema being added, then set doesnt need to be compiled @@ -832,7 +832,7 @@ private void AddCompiledSchema(XmlSchema schema) { private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref XmlSchemaObjectTable substTable) { //Add schema's compiled tables to the set - if (schema.BaseUri != null && schemaLocations[schema.BaseUri] == null) { //Update schemaLocations table + if (schema.BaseUri is not null && schemaLocations[schema.BaseUri] is null) { //Update schemaLocations table schemaLocations.Add(schema.BaseUri, schema); } @@ -843,11 +843,11 @@ private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref } XmlQualifiedName head = element.SubstitutionGroup; if (!head.IsEmpty) { - if (substTable == null) { + if (substTable is null) { substTable = new XmlSchemaObjectTable(); } XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)substTable[head]; - if (substitutionGroup == null) { + if (substitutionGroup is null) { substitutionGroup = new XmlSchemaSubstitutionGroup(); substitutionGroup.Examplar = head; substTable.Add(head, substitutionGroup); @@ -879,17 +879,17 @@ private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref //For use by the validator when loading schemaLocations in the instance internal void Add(string? targetNamespace, XmlReader reader, Hashtable validatedNamespaces) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } - if (targetNamespace == null) + if (targetNamespace is null) { targetNamespace = string.Empty; } - if (validatedNamespaces[targetNamespace] != null) + if (validatedNamespaces[targetNamespace] is not null) { - if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, null) != null) + if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, null) is not null) { return; } @@ -922,11 +922,11 @@ internal void Add(string? targetNamespace, XmlReader reader, Hashtable validated { XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]!; tns = impSchema.TargetNamespace; - if (tns == null) + if (tns is null) { tns = string.Empty; } - if (validatedNamespaces[tns] != null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null)) + if (validatedNamespaces[tns] is not null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) is null)) { RemoveRecursive(schema); throw new XmlSchemaException(SR.Sch_ComponentAlreadySeenForNS, tns); @@ -938,13 +938,13 @@ internal void Add(string? targetNamespace, XmlReader reader, Hashtable validated internal XmlSchema? FindSchemaByNSAndUrl(Uri? schemaUri, string ns, DictionaryEntry[]? locationsTable) { - if (schemaUri == null || schemaUri.OriginalString.Length == 0) + if (schemaUri is null || schemaUri.OriginalString.Length == 0) { return null; } XmlSchema? schema = null; - if (locationsTable == null) + if (locationsTable is null) { schema = (XmlSchema)_schemaLocations[schemaUri]!; } @@ -960,10 +960,10 @@ internal void Add(string? targetNamespace, XmlReader reader, Hashtable validated } } - if (schema != null) + if (schema is not null) { - Debug.Assert(ns != null); - string tns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; + Debug.Assert(ns is not null); + string tns = schema.TargetNamespace is null ? string.Empty : schema.TargetNamespace; if (tns == ns) { return schema; @@ -988,14 +988,14 @@ internal void Add(string? targetNamespace, XmlReader reader, Hashtable validated private void SetDtdProcessing(XmlReader reader) { - if (reader.Settings != null) + if (reader.Settings is not null) { _readerSettings.DtdProcessing = reader.Settings.DtdProcessing; } else { XmlTextReader? v1Reader = reader as XmlTextReader; - if (v1Reader != null) + if (v1Reader is not null) { _readerSettings.DtdProcessing = v1Reader.DtdProcessing; } @@ -1016,11 +1016,11 @@ private void AddSchemaToSet(XmlSchema schema) #region This code is copied to Reprocess(XmlSchema schema) method string tns = GetTargetNamespace(schema); - if (_targetNamespaces[tns] == null) + if (_targetNamespaces[tns] is null) { _targetNamespaces.Add(tns, tns); } - if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) + if (_schemaForSchema is null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] is not null) { //it has xs:anyType _schemaForSchema = schema; } @@ -1032,11 +1032,11 @@ private void AddSchemaToSet(XmlSchema schema) _schemas.Add(s.SchemaId, s); } tns = GetTargetNamespace(s); - if (_targetNamespaces[tns] == null) + if (_targetNamespaces[tns] is null) { _targetNamespaces.Add(tns, tns); } - if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) + if (_schemaForSchema is null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] is not null) { //it has xs:anyType _schemaForSchema = schema; } @@ -1057,7 +1057,7 @@ private void ProcessNewSubstitutionGroups(XmlSchemaObjectTable substitutionGroup //Add or Merge new substitutionGroups with those that already exist in the set XmlQualifiedName head = substGroup!.Examplar; XmlSchemaSubstitutionGroup? oldSubstGroup = (XmlSchemaSubstitutionGroup?)substitutionGroups![head]; - if (oldSubstGroup != null) + if (oldSubstGroup is not null) { for (int i = 0; i < substGroup.Members.Count; ++i) { @@ -1088,7 +1088,7 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro //Chain to other head's that are members of this head's substGroup XmlSchemaSubstitutionGroup? g = (XmlSchemaSubstitutionGroup?)substTable[element.QualifiedName]; - if (g != null) + if (g is not null) { ResolveSubstitutionGroup(g, substTable); for (int j = 0; j < g.Members.Count; ++j) @@ -1096,7 +1096,7 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro XmlSchemaElement element1 = (XmlSchemaElement)g.Members[j]!; if (element1 != element) { //Exclude the head - if (newMembers == null) + if (newMembers is null) { newMembers = new List(); } @@ -1105,7 +1105,7 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro } } } - if (newMembers != null) + if (newMembers is not null) { for (int i = 0; i < newMembers.Count; ++i) { @@ -1119,7 +1119,7 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro { // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess // method. If you change anything here *make sure* to update Reprocess method accordingly. - if (schema == null) + if (schema is null) { throw new ArgumentNullException(nameof(schema)); } @@ -1139,7 +1139,7 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro RemoveSchemaFromCaches(schema); } _schemas.Remove(schema.SchemaId); - if (schema.BaseUri != null) + if (schema.BaseUri is not null) { _schemaLocations.Remove(schema.BaseUri); } @@ -1215,18 +1215,18 @@ internal void CopyFromCompiledSet(XmlSchemaSet otherSet) { currentSchema = (XmlSchema)copyFromList.GetByIndex(i)!; baseUri = currentSchema.BaseUri; - if (_schemas.ContainsKey(currentSchema.SchemaId) || (baseUri != null && baseUri.OriginalString.Length != 0 && _schemaLocations[baseUri] != null)) + if (_schemas.ContainsKey(currentSchema.SchemaId) || (baseUri is not null && baseUri.OriginalString.Length != 0 && _schemaLocations[baseUri] is not null)) { existingSchemas.Add(currentSchema); continue; } _schemas.Add(currentSchema.SchemaId, currentSchema); - if (baseUri != null && baseUri.OriginalString.Length != 0) + if (baseUri is not null && baseUri.OriginalString.Length != 0) { _schemaLocations.Add(baseUri, currentSchema); } string tns = GetTargetNamespace(currentSchema); - if (_targetNamespaces[tns] == null) + if (_targetNamespaces[tns] is null) { _targetNamespaces.Add(tns, tns); } @@ -1334,7 +1334,7 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) } else { - if (_schemaNames == null) + if (_schemaNames is null) { _schemaNames = new SchemaNames(_nameTable); } @@ -1345,7 +1345,7 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSchema? schema) { schema = null; - if (targetNamespace == null) + if (targetNamespace is null) { targetNamespace = string.Empty; } @@ -1355,10 +1355,10 @@ internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSche { //schema is present in set //Schema found } - else if (schema.TargetNamespace == null) + else if (schema.TargetNamespace is null) { //If schema not in set or namespace doesnt match, then it might be a chameleon XmlSchema? chameleonSchema = FindSchemaByNSAndUrl(schemaUri, targetNamespace, null); - if (chameleonSchema != null && _schemas.ContainsKey(chameleonSchema.SchemaId)) + if (chameleonSchema is not null && _schemas.ContainsKey(chameleonSchema.SchemaId)) { schema = chameleonSchema; } @@ -1375,7 +1375,7 @@ internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSche else { //If here, schema not present in set but in loc and might be added in loc through an earlier include - //S.TNS != null && ( tns == null or tns == s.TNS) + //S.TNS is not null && ( tns is null or tns == s.TNS) AddSchemaToSet(schema); } @@ -1388,13 +1388,13 @@ internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSche internal bool GetSchemaByUri(Uri schemaUri, [NotNullWhen(true)] out XmlSchema? schema) { schema = null; - if (schemaUri == null || schemaUri.OriginalString.Length == 0) + if (schemaUri is null || schemaUri.OriginalString.Length == 0) { return false; } schema = (XmlSchema?)_schemaLocations[schemaUri]; - if (schema != null) + if (schema is not null) { return true; } @@ -1404,7 +1404,7 @@ internal bool GetSchemaByUri(Uri schemaUri, [NotNullWhen(true)] out XmlSchema? s internal string GetTargetNamespace(XmlSchema schema) { - return schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; + return schema.TargetNamespace is null ? string.Empty : schema.TargetNamespace; } internal SortedList SortedSchemas @@ -1423,7 +1423,7 @@ private void RemoveSchemaFromCaches(XmlSchema schema) schema.GetExternalSchemasList(reprocessList, schema); for (int i = 0; i < reprocessList.Count; ++i) { //Remove schema from schemaLocations & chameleonSchemas tables - if (reprocessList[i].BaseUri != null && reprocessList[i].BaseUri!.OriginalString.Length != 0) + if (reprocessList[i].BaseUri is not null && reprocessList[i].BaseUri!.OriginalString.Length != 0) { _schemaLocations.Remove(reprocessList[i].BaseUri!); } @@ -1439,7 +1439,7 @@ private void RemoveSchemaFromCaches(XmlSchema schema) // otherwise we need to care about it as there may be more chameleon schemas without // a base URI and we want to remove only those which were created as a clone of the one // we're removing. - if (cKey.originalSchema == null || Ref.ReferenceEquals(cKey.originalSchema, reprocessList[i])) + if (cKey.originalSchema is null || Ref.ReferenceEquals(cKey.originalSchema, reprocessList[i])) { removalList.Add(cKey); } @@ -1497,7 +1497,7 @@ private bool AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlS } XmlSchemaObject? existingObject = (XmlSchemaObject?)table[qname]; - if (existingObject != null) + if (existingObject is not null) { if (existingObject == item || existingObject.SourceUri == item.SourceUri) { @@ -1549,19 +1549,19 @@ private bool AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlS private void VerifyTables() { - if (elements == null) + if (elements is null) { elements = new XmlSchemaObjectTable(); } - if (attributes == null) + if (attributes is null) { attributes = new XmlSchemaObjectTable(); } - if (schemaTypes == null) + if (schemaTypes is null) { schemaTypes = new XmlSchemaObjectTable(); } - if (substitutionGroups == null) + if (substitutionGroups is null) { substitutionGroups = new XmlSchemaObjectTable(); } @@ -1577,7 +1577,7 @@ private void InternalValidationCallback(object? sender, ValidationEventArgs e) private void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity) { - if (_eventHandler != null) + if (_eventHandler is not null) { _eventHandler(this, new ValidationEventArgs(e, severity)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs index 01fb7ade1b21b5..00778bdcb3f2db 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs @@ -15,7 +15,7 @@ public class XmlSchemaSimpleContentExtension : XmlSchemaContent public XmlQualifiedName BaseTypeName { get { return _baseTypeName; } - set { _baseTypeName = (value == null ? XmlQualifiedName.Empty : value); } + set { _baseTypeName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlElement("attribute", typeof(XmlSchemaAttribute)), diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs index f4b5ba9dcf25de..eea2c6b8ff854e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs @@ -17,7 +17,7 @@ public class XmlSchemaSimpleContentRestriction : XmlSchemaContent public XmlQualifiedName BaseTypeName { get { return _baseTypeName; } - set { _baseTypeName = (value == null ? XmlQualifiedName.Empty : value); } + set { _baseTypeName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlElement("simpleType", typeof(XmlSchemaSimpleType))] diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs index 62fe61a46dc9c6..8d48927b545172 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs @@ -28,7 +28,7 @@ internal override XmlQualifiedName DerivedFrom { get { - if (_content == null) + if (_content is null) { // type derived from anyType return XmlQualifiedName.Empty; @@ -44,7 +44,7 @@ internal override XmlQualifiedName DerivedFrom internal override XmlSchemaObject Clone() { XmlSchemaSimpleType newSimpleType = (XmlSchemaSimpleType)MemberwiseClone(); - if (_content != null) + if (_content is not null) { newSimpleType.Content = (XmlSchemaSimpleTypeContent)_content.Clone(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs index a00192dbb6d1f4..55be414d817161 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs @@ -16,7 +16,7 @@ public class XmlSchemaSimpleTypeRestriction : XmlSchemaSimpleTypeContent public XmlQualifiedName BaseTypeName { get { return _baseTypeName; } - set { _baseTypeName = (value == null ? XmlQualifiedName.Empty : value); } + set { _baseTypeName = (value is null ? XmlQualifiedName.Empty : value); } } [XmlElement("simpleType", typeof(XmlSchemaSimpleType))] diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs index 72ac95ec782e19..69cd90f75ebf74 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs @@ -38,7 +38,7 @@ internal void SetBaseMemberTypes(XmlSchemaSimpleType[] baseMemberTypes) internal override XmlSchemaObject Clone() { - if (_memberTypes != null && _memberTypes.Length > 0) + if (_memberTypes is not null && _memberTypes.Length > 0) { //Only if the union has MemberTypes defined XmlSchemaSimpleTypeUnion newUnion = (XmlSchemaSimpleTypeUnion)MemberwiseClone(); XmlQualifiedName[] newQNames = new XmlQualifiedName[_memberTypes.Length]; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs index 48a6c3129357dc..e1239d539d91d2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs @@ -31,7 +31,7 @@ public class XmlSchemaType : XmlSchemaAnnotated /// public static XmlSchemaSimpleType? GetBuiltInSimpleType(XmlQualifiedName qualifiedName) { - if (qualifiedName == null) + if (qualifiedName is null) { throw new ArgumentNullException(nameof(qualifiedName)); } @@ -65,7 +65,7 @@ public static XmlSchemaSimpleType GetBuiltInSimpleType(XmlTypeCode typeCode) /// public static XmlSchemaComplexType? GetBuiltInComplexType(XmlQualifiedName qualifiedName) { - if (qualifiedName == null) + if (qualifiedName is null) { throw new ArgumentNullException(nameof(qualifiedName)); } @@ -130,7 +130,7 @@ public object? BaseSchemaType { get { - if (_baseSchemaType == null) + if (_baseSchemaType is null) return null; if (_baseSchemaType.QualifiedName.Namespace == XmlReservedNs.NsXs) @@ -188,7 +188,7 @@ public XmlTypeCode TypeCode { return XmlTypeCode.Item; } - if (_datatype == null) + if (_datatype is null) { return XmlTypeCode.None; } @@ -201,7 +201,7 @@ internal XmlValueConverter ValueConverter { get { - if (_datatype == null) + if (_datatype is null) { //Default converter return XmlUntypedConverter.Untyped; } @@ -212,7 +212,7 @@ internal XmlValueConverter ValueConverter [return: NotNullIfNotNull("schemaSet")] internal XmlReader? Validate(XmlReader reader, XmlResolver? resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { - if (schemaSet != null) + if (schemaSet is not null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; @@ -282,7 +282,7 @@ internal void SetContentType(XmlSchemaContentType value) public static bool IsDerivedFrom(XmlSchemaType? derivedType, XmlSchemaType? baseType, XmlSchemaDerivationMethod except) { - if (derivedType == null || baseType == null) + if (derivedType is null || baseType is null) { return false; } @@ -301,7 +301,7 @@ public static bool IsDerivedFrom(XmlSchemaType? derivedType, XmlSchemaType? base { XmlSchemaSimpleType? dt = derivedType as XmlSchemaSimpleType; XmlSchemaSimpleType? bt = baseType as XmlSchemaSimpleType; - if (bt != null && dt != null) + if (bt is not null && dt is not null) { //SimpleTypes if (bt == DatatypeImplementation.AnySimpleType) { //Not checking block=restriction @@ -327,7 +327,7 @@ public static bool IsDerivedFrom(XmlSchemaType? derivedType, XmlSchemaType? base return true; } } - } while (derivedType != null); + } while (derivedType is not null); return false; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs index e8855cff7431f7..411649ce091900 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs @@ -57,8 +57,8 @@ private XmlUntypedStringConverter(bool listsAllowed) internal object FromString(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == s_objectType) destinationType = typeof(string); if (destinationType == s_booleanType) return XmlConvert.ToBoolean((string)value); @@ -170,12 +170,12 @@ private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolve } // Throw error if no namespaces are in scope - if (nsResolver == null) + if (nsResolver is null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); - if (ns == null) + if (ns is null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs index 08c6d660d189e7..c9cef82cd7917a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs @@ -230,13 +230,13 @@ protected XmlBaseConverter(XmlSchemaType schemaType) { // XmlValueConverter is defined only on types with simple content XmlSchemaDatatype? datatype = schemaType.Datatype; - Debug.Assert(schemaType != null && datatype != null, "schemaType or schemaType.Datatype may not be null"); + Debug.Assert(schemaType is not null && datatype is not null, "schemaType or schemaType.Datatype may not be null"); - while (schemaType != null && !(schemaType is XmlSchemaSimpleType)) + while (schemaType is not null && !(schemaType is XmlSchemaSimpleType)) { schemaType = schemaType.BaseXmlSchemaType!; } - if (schemaType == null) + if (schemaType is null) { //Did not find any simple type in the parent chain schemaType = XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode); } @@ -407,7 +407,7 @@ protected string XmlTypeName { XmlSchemaType? type = _schemaType; - if (type != null) + if (type is not null) { while (type!.QualifiedName.IsEmpty) { @@ -440,7 +440,7 @@ protected Type? DefaultClrType /// protected static bool IsDerivedFrom(Type? derivedType, Type baseType) { - while (derivedType != null) + while (derivedType is not null) { if (derivedType == baseType) return true; @@ -617,12 +617,12 @@ protected static XmlQualifiedName StringToQName(string value, IXmlNamespaceResol } // Throw error if no namespaces are in scope - if (nsResolver == null) + if (nsResolver is null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); - if (ns == null) + if (ns is null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName @@ -744,11 +744,11 @@ protected static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResol { string? prefix; - if (nsResolver == null) + if (nsResolver is null) return string.Concat("{", qname.Namespace, "}", qname.Name); prefix = nsResolver.LookupPrefix(qname.Namespace); - if (prefix == null) + if (prefix is null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname, qname.Namespace)); return (prefix.Length != 0) ? string.Concat(prefix, ":", qname.Name) : qname.Name; @@ -876,14 +876,14 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) #region AUTOGENERATED_XMLNUMERIC10CONVERTER public override decimal ToDecimal(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (TypeCode == XmlTypeCode.Decimal) return XmlConvert.ToDecimal((string)value); return XmlConvert.ToInteger((string)value); } public override decimal ToDecimal(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -901,14 +901,14 @@ public override int ToInt32(long value) } public override int ToInt32(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt32(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt32((string)value); } public override int ToInt32(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -926,14 +926,14 @@ public override long ToInt64(int value) } public override long ToInt64(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt64(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt64((string)value); } public override long ToInt64(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -973,7 +973,7 @@ public override string ToString(long value) } public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -993,7 +993,7 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(decimal value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)value); @@ -1008,7 +1008,7 @@ public override object ChangeType(decimal value, Type destinationType) public override object ChangeType(int value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(int)value); @@ -1023,7 +1023,7 @@ public override object ChangeType(int value, Type destinationType) public override object ChangeType(long value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(long)value); @@ -1038,8 +1038,8 @@ public override object ChangeType(long value, Type destinationType) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return this.ToDecimal((string)value); @@ -1054,8 +1054,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -1142,14 +1142,14 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) #region AUTOGENERATED_XMLNUMERIC2CONVERTER public override double ToDouble(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (TypeCode == XmlTypeCode.Float) return ((double)XmlConvert.ToSingle((string)value)); return XmlConvert.ToDouble((string)value); } public override double ToDouble(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1186,14 +1186,14 @@ public override float ToSingle(double value) } public override float ToSingle(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToSingle((string)value); return ((float)XmlConvert.ToDouble((string)value)); } public override float ToSingle(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1222,7 +1222,7 @@ public override string ToString(float value) } public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1241,7 +1241,7 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(double value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return ((double)value); @@ -1255,8 +1255,8 @@ public override object ChangeType(double value, Type destinationType) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble((string)value); @@ -1270,8 +1270,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -1319,7 +1319,7 @@ public override DateTime ToDateTime(DateTimeOffset value) public override DateTime ToDateTime(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return TypeCode switch { @@ -1335,7 +1335,7 @@ public override DateTime ToDateTime(string value) } public override DateTime ToDateTime(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1358,7 +1358,7 @@ public override DateTimeOffset ToDateTimeOffset(DateTime value) public override DateTimeOffset ToDateTimeOffset(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return TypeCode switch { @@ -1375,7 +1375,7 @@ public override DateTimeOffset ToDateTimeOffset(string value) public override DateTimeOffset ToDateTimeOffset(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1454,7 +1454,7 @@ public override string ToString(DateTimeOffset value) => public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1473,7 +1473,7 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(DateTime value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return ((DateTime)value); @@ -1487,8 +1487,8 @@ public override object ChangeType(DateTime value, Type destinationType) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime((string)value); @@ -1502,8 +1502,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -1545,13 +1545,13 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) #region AUTOGENERATED_XMLBOOLEANCONVERTER public override bool ToBoolean(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToBoolean((string)value); } public override bool ToBoolean(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1615,7 +1615,7 @@ public override string ToString(bool value) } public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1633,7 +1633,7 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(bool value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return ((bool)value); @@ -1646,8 +1646,8 @@ public override object ChangeType(bool value, Type destinationType) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); @@ -1660,8 +1660,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -1700,7 +1700,7 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) #region AUTOGENERATED_XMLMISCCONVERTER public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1742,8 +1742,8 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) @@ -1780,8 +1780,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -1929,7 +1929,7 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) #region AUTOGENERATED_XMLSTRINGCONVERTER public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -1946,8 +1946,8 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return ((string)value); @@ -1959,8 +1959,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -2007,13 +2007,13 @@ protected XmlUntypedConverter(XmlUntypedConverter atomicConverter, bool allowLis public override bool ToBoolean(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToBoolean((string)value); } public override bool ToBoolean(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2029,13 +2029,13 @@ public override bool ToBoolean(object value) public override DateTime ToDateTime(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return UntypedAtomicToDateTime((string)value); } public override DateTime ToDateTime(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2050,14 +2050,14 @@ public override DateTime ToDateTime(object value) public override DateTimeOffset ToDateTimeOffset(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return UntypedAtomicToDateTimeOffset((string)value); } public override DateTimeOffset ToDateTimeOffset(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2072,13 +2072,13 @@ public override DateTimeOffset ToDateTimeOffset(object value) public override decimal ToDecimal(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToDecimal((string)value); } public override decimal ToDecimal(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2094,13 +2094,13 @@ public override decimal ToDecimal(object value) public override double ToDouble(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToDouble((string)value); } public override double ToDouble(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2116,13 +2116,13 @@ public override double ToDouble(object value) public override int ToInt32(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToInt32((string)value); } public override int ToInt32(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2138,13 +2138,13 @@ public override int ToInt32(object value) public override long ToInt64(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToInt64((string)value); } public override long ToInt64(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2160,13 +2160,13 @@ public override long ToInt64(object value) public override float ToSingle(string value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToSingle((string)value); } public override float ToSingle(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2214,7 +2214,7 @@ public override string ToString(float value) } public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2249,7 +2249,7 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) public override object ChangeType(bool value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((bool)value); @@ -2259,7 +2259,7 @@ public override object ChangeType(bool value, Type destinationType) public override object ChangeType(DateTime value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return DateTimeToString((DateTime)value); @@ -2269,7 +2269,7 @@ public override object ChangeType(DateTime value, Type destinationType) public override object ChangeType(decimal value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((decimal)value); @@ -2279,7 +2279,7 @@ public override object ChangeType(decimal value, Type destinationType) public override object ChangeType(double value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((double)value); @@ -2289,7 +2289,7 @@ public override object ChangeType(double value, Type destinationType) public override object ChangeType(int value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((int)value); @@ -2299,7 +2299,7 @@ public override object ChangeType(int value, Type destinationType) public override object ChangeType(long value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((long)value); @@ -2309,8 +2309,8 @@ public override object ChangeType(long value, Type destinationType) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); @@ -2340,8 +2340,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -2469,7 +2469,7 @@ protected override object ChangeListType(object value, Type destinationType, IXm // 1. If there is no nested atomic converter, then do not support lists at all // 2. If list to list conversions are not allowed, only allow string => list and list => string - if ((this.atomicConverter == null) || (!_allowListToList && sourceType != StringType && destinationType != StringType)) + if ((this.atomicConverter is null) || (!_allowListToList && sourceType != StringType && destinationType != StringType)) { if (SupportsType(sourceType)) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeToString, XmlTypeName, sourceType.Name)); @@ -2525,7 +2525,7 @@ protected XmlAnyConverter(XmlTypeCode typeCode) : base(typeCode) public override bool ToBoolean(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2541,7 +2541,7 @@ public override bool ToBoolean(object value) public override DateTime ToDateTime(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2556,7 +2556,7 @@ public override DateTime ToDateTime(object value) public override DateTimeOffset ToDateTimeOffset(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2572,7 +2572,7 @@ public override DateTimeOffset ToDateTimeOffset(object value) public override decimal ToDecimal(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2588,7 +2588,7 @@ public override decimal ToDecimal(object value) public override double ToDouble(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2604,7 +2604,7 @@ public override double ToDouble(object value) public override int ToInt32(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2620,7 +2620,7 @@ public override int ToInt32(object value) public override long ToInt64(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2636,7 +2636,7 @@ public override long ToInt64(object value) public override float ToSingle(object value) { - if (value == null) throw new ArgumentNullException(nameof(value)); + if (value is null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); @@ -2659,7 +2659,7 @@ public override float ToSingle(object value) public override object ChangeType(bool value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool)value)); @@ -2669,7 +2669,7 @@ public override object ChangeType(bool value, Type destinationType) public override object ChangeType(DateTime value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime)value)); @@ -2679,7 +2679,7 @@ public override object ChangeType(DateTime value, Type destinationType) public override object ChangeType(decimal value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value)); @@ -2689,7 +2689,7 @@ public override object ChangeType(decimal value, Type destinationType) public override object ChangeType(double value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double)value)); @@ -2699,7 +2699,7 @@ public override object ChangeType(double value, Type destinationType) public override object ChangeType(int value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int)value)); @@ -2709,7 +2709,7 @@ public override object ChangeType(int value, Type destinationType) public override object ChangeType(long value, Type destinationType) { - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long)value)); @@ -2719,8 +2719,8 @@ public override object ChangeType(long value, Type destinationType) public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string)value)); @@ -2730,8 +2730,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -2855,8 +2855,8 @@ protected XmlAnyListConverter(XmlBaseConverter atomicConverter) : base(atomicCon public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); // If source value does not implement IEnumerable, or it is a string or byte[], if (!(value is IEnumerable) || value.GetType() == StringType || value.GetType() == ByteArrayType) @@ -2898,7 +2898,7 @@ public static XmlValueConverter Create(XmlValueConverter atomicConverter) if (atomicConverter == XmlAnyConverter.AnyAtomic) return XmlAnyListConverter.AnyAtomicList; - Debug.Assert(!(atomicConverter is XmlListConverter) || ((XmlListConverter)atomicConverter).atomicConverter == null, + Debug.Assert(!(atomicConverter is XmlListConverter) || ((XmlListConverter)atomicConverter).atomicConverter is null, "List converters should not be nested within one another."); return new XmlListConverter((XmlBaseConverter)atomicConverter); @@ -2911,8 +2911,8 @@ public static XmlValueConverter Create(XmlValueConverter atomicConverter) public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); return ChangeListType(value, destinationType, nsResolver); } @@ -3018,7 +3018,7 @@ private T[] ToArray(object list, IXmlNamespaceResolver? nsResolver) { // IList --> Array IList? listSrc = list as IList; - if (listSrc != null) + if (listSrc is not null) { T[] arrDst = new T[listSrc.Count]; @@ -3030,7 +3030,7 @@ private T[] ToArray(object list, IXmlNamespaceResolver? nsResolver) // IEnumerable --> Array IEnumerable enumSrc = (list as IEnumerable)!; - Debug.Assert(enumSrc != null, "Value passed to ToArray must implement IEnumerable"); + Debug.Assert(enumSrc is not null, "Value passed to ToArray must implement IEnumerable"); List listDst = new List(); foreach (object? value in enumSrc) @@ -3046,7 +3046,7 @@ private IList ToList(object list, IXmlNamespaceResolver? nsResolver) { // IList --> object[] IList? listSrc = list as IList; - if (listSrc != null) + if (listSrc is not null) { object[] arrDst = new object[listSrc.Count]; @@ -3058,7 +3058,7 @@ private IList ToList(object list, IXmlNamespaceResolver? nsResolver) // IEnumerable --> List IEnumerable enumSrc = (list as IEnumerable)!; - Debug.Assert(enumSrc != null, "Value passed to ToArray must implement IEnumerable"); + Debug.Assert(enumSrc is not null, "Value passed to ToArray must implement IEnumerable"); List listDst = new List(); foreach (object? value in enumSrc) @@ -3086,7 +3086,7 @@ private string ListAsString(IEnumerable list, IXmlNamespaceResolver? nsResolver) foreach (object? value in list) { // skip null values - if (value != null) + if (value is not null) { // Separate values by single space character if (bldr.Length != 0) @@ -3153,8 +3153,8 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + if (value is null) throw new ArgumentNullException(nameof(value)); + if (destinationType is null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs index 454d7f8eb8359b..552ae1e6f8a50c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs @@ -143,7 +143,7 @@ public XsdDuration(string s, DurationType durationType) { XsdDuration result; Exception? exception = TryParse(s, durationType, out result); - if (exception != null) + if (exception is not null) { throw exception; } @@ -244,7 +244,7 @@ public TimeSpan ToTimeSpan(DurationType durationType) { TimeSpan result; Exception? exception = TryToTimeSpan(durationType, out result); - if (exception != null) + if (exception is not null) { throw exception; } @@ -465,7 +465,7 @@ internal string ToString(DurationType durationType) if (s[pos++] != 'P') goto InvalidFormat; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; @@ -478,7 +478,7 @@ internal string ToString(DurationType durationType) if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; } @@ -492,7 +492,7 @@ internal string ToString(DurationType durationType) if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; } @@ -506,7 +506,7 @@ internal string ToString(DurationType durationType) if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; } @@ -517,7 +517,7 @@ internal string ToString(DurationType durationType) pos++; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; @@ -530,7 +530,7 @@ internal string ToString(DurationType durationType) if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; } @@ -544,7 +544,7 @@ internal string ToString(DurationType durationType) if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (pos >= length) goto InvalidFormat; } @@ -557,7 +557,7 @@ internal string ToString(DurationType durationType) result._seconds = value; errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits); - if (errorCode != null) goto Error; + if (errorCode is not null) goto Error; if (numDigits == 0) { //If there are no digits after the decimal point, assume 0 diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index ed95d6647417ab..af3d53d399cf11 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -68,7 +68,7 @@ internal XsdValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schema private void Init() { _nsManager = reader.NamespaceManager!; - if (_nsManager == null) + if (_nsManager is null) { _nsManager = new XmlNamespaceManager(NameTable); _bManageNamespaces = true; @@ -133,7 +133,7 @@ public override void CompleteValidation() private bool IsInlineSchemaStarted { - get { return _inlineSchemaParser != null; } + get { return _inlineSchemaParser is not null; } } private void ProcessInlineSchema() @@ -143,16 +143,16 @@ private void ProcessInlineSchema() _inlineSchemaParser.FinishParsing(); XmlSchema? schema = _inlineSchemaParser.XmlSchema; string? inlineNS = null; - if (schema != null && schema.ErrorCount == 0) + if (schema is not null && schema.ErrorCount == 0) { try { SchemaInfo inlineSchemaInfo = new SchemaInfo(); inlineSchemaInfo.SchemaType = SchemaType.XSD; - inlineNS = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; + inlineNS = schema.TargetNamespace is null ? string.Empty : schema.TargetNamespace; if (!SchemaInfo!.TargetNamespaces.ContainsKey(inlineNS)) { - if (SchemaCollection!.Add(inlineNS, inlineSchemaInfo, schema, true) != null) + if (SchemaCollection!.Add(inlineNS, inlineSchemaInfo, schema, true) is not null) { //If no errors on compile //Add to validator's SchemaInfo SchemaInfo.Add(inlineSchemaInfo, EventHandler); @@ -196,7 +196,7 @@ private void ValidateElement() return null; } particle = context.ElementDecl!.ContentValidator!.ValidateElement(elementName, context, out errorCode); - if (particle == null) + if (particle is null) { _processContents = context.ProcessContents = XmlSchemaContentProcessing.Skip; if (errorCode == -2) @@ -222,11 +222,11 @@ private void ProcessElement(object? particle) ProcessXsiAttributes(out xsiType, out xsiNil); if (_processContents != XmlSchemaContentProcessing.Skip) { - if (elementDecl == null || !xsiType.IsEmpty || xsiNil != null) + if (elementDecl is null || !xsiType.IsEmpty || xsiNil is not null) { elementDecl = ThoroughGetElementDecl(elementDecl, xsiType, xsiNil); } - if (elementDecl == null) + if (elementDecl is null) { if (HasSchema && _processContents == XmlSchemaContentProcessing.Strict) { @@ -242,7 +242,7 @@ private void ProcessElement(object? particle) context!.ElementDecl = elementDecl; ValidateStartElementIdentityConstraints(); ValidateStartElement(); - if (context.ElementDecl != null) + if (context.ElementDecl is not null) { ValidateEndStartElement(); context.NeedValidateChildren = _processContents != XmlSchemaContentProcessing.Skip; @@ -307,11 +307,11 @@ private void ProcessXsiAttributes(out XmlQualifiedName xsiType, out string? xsiN } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } - if (xsiNoNamespaceSchemaLocation != null) + if (xsiNoNamespaceSchemaLocation is not null) { LoadSchema(string.Empty, xsiNoNamespaceSchemaLocation); } - if (xsiSchemaLocation != null) + if (xsiSchemaLocation is not null) { for (int i = 0; i < xsiSchemaLocation.Length - 1; i += 2) { @@ -326,7 +326,7 @@ private void ValidateEndElement() { _nsManager.PopScope(); } - if (context!.ElementDecl != null) + if (context!.ElementDecl is not null) { if (!context.IsNill) { @@ -341,7 +341,7 @@ private void ValidateEndElement() if (checkDatatype && !context.IsNill) { string stringValue = !hasSibling ? textString! : textValue!.ToString(); // only for identity-constraint exception reporting - if (!(stringValue.Length == 0 && context.ElementDecl.DefaultValueTyped != null)) + if (!(stringValue.Length == 0 && context.ElementDecl.DefaultValueTyped is not null)) { CheckValue(stringValue, null); checkDatatype = false; @@ -361,10 +361,10 @@ private void ValidateEndElement() private SchemaElementDecl? FastGetElementDecl(object? particle) { SchemaElementDecl? elementDecl = null; - if (particle != null) + if (particle is not null) { XmlSchemaElement? element = particle as XmlSchemaElement; - if (element != null) + if (element is not null) { elementDecl = element.ElementDecl; } @@ -379,11 +379,11 @@ private void ValidateEndElement() private SchemaElementDecl? ThoroughGetElementDecl(SchemaElementDecl? elementDecl, XmlQualifiedName xsiType, string? xsiNil) { - if (elementDecl == null) + if (elementDecl is null) { elementDecl = schemaInfo!.GetElementDecl(elementName); } - if (elementDecl != null) + if (elementDecl is not null) { if (xsiType.IsEmpty) { @@ -393,7 +393,7 @@ private void ValidateEndElement() elementDecl = null; } } - else if (xsiNil != null && xsiNil.Equals("true")) + else if (xsiNil is not null && xsiNil.Equals("true")) { SendValidationEvent(SR.Sch_XsiNilAndType); } @@ -403,12 +403,12 @@ private void ValidateEndElement() if (!schemaInfo!.ElementDeclsByType.TryGetValue(xsiType, out elementDeclXsi) && xsiType.Namespace == _nsXs) { XmlSchemaSimpleType? simpleType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName(xsiType.Name, _nsXs)); - if (simpleType != null) + if (simpleType is not null) { elementDeclXsi = simpleType.ElementDecl; } } - if (elementDeclXsi == null) + if (elementDeclXsi is null) { SendValidationEvent(SR.Sch_XsiTypeNotFound, xsiType.ToString()); elementDecl = null; @@ -423,18 +423,18 @@ private void ValidateEndElement() elementDecl = elementDeclXsi; } } - if (elementDecl != null && elementDecl.IsNillable) + if (elementDecl is not null && elementDecl.IsNillable) { - if (xsiNil != null) + if (xsiNil is not null) { context!.IsNill = XmlConvert.ToBoolean(xsiNil); - if (context.IsNill && elementDecl.DefaultValueTyped != null) + if (context.IsNill && elementDecl.DefaultValueTyped is not null) { SendValidationEvent(SR.Sch_XsiNilAndFixed); } } } - else if (xsiNil != null) + else if (xsiNil is not null) { SendValidationEvent(SR.Sch_InvalidXsiNill); } @@ -444,7 +444,7 @@ private void ValidateEndElement() private void ValidateStartElement() { - if (context!.ElementDecl != null) + if (context!.ElementDecl is not null) { if (context.ElementDecl.IsAbstract) { @@ -453,7 +453,7 @@ private void ValidateStartElement() reader.SchemaTypeObject = context.ElementDecl.SchemaType; - if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped != null) + if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped is not null) { reader.TypedValueObject = UnWrapUnion(context.ElementDecl.DefaultValueTyped); context.IsNill = true; // reusing IsNill @@ -488,15 +488,15 @@ private void ValidateStartElement() bool skipContents = (_processContents == XmlSchemaContentProcessing.Skip); SchemaAttDef? attnDef = schemaInfo!.GetAttributeXsd(context.ElementDecl, attQName, ref skipContents); - if (attnDef != null) + if (attnDef is not null) { - if (context.ElementDecl != null && (context.ElementDecl.HasRequiredAttribute || _startIDConstraint != -1)) + if (context.ElementDecl is not null && (context.ElementDecl.HasRequiredAttribute || _startIDConstraint != -1)) { _attPresence.Add(attnDef.Name, attnDef); } - Debug.Assert(attnDef.SchemaType != null); + Debug.Assert(attnDef.SchemaType is not null); reader.SchemaTypeObject = attnDef.SchemaType; - if (attnDef.Datatype != null) + if (attnDef.Datatype is not null) { // need to check the contents of this attribute to make sure // it is valid according to the specified attribute type. @@ -509,7 +509,7 @@ private void ValidateStartElement() } else if (!skipContents) { - if (context.ElementDecl == null + if (context.ElementDecl is null && _processContents == XmlSchemaContentProcessing.Strict && attQName.Namespace.Length != 0 && schemaInfo.Contains(attQName.Namespace) @@ -561,7 +561,7 @@ private void ValidateEndStartElement() SendValidationEvent(e); } } - if (context.ElementDecl.Datatype != null) + if (context.ElementDecl.Datatype is not null) { checkDatatype = true; hasSibling = false; @@ -590,7 +590,7 @@ private void LoadSchemaFromLocation(string uri, string url) schemaInfo.SchemaType = schemaType; if (schemaType == SchemaType.XSD) { - if (SchemaCollection!.EventHandler == null) + if (SchemaCollection!.EventHandler is null) { SchemaCollection.EventHandler = this.EventHandler; } @@ -613,7 +613,7 @@ private void LoadSchemaFromLocation(string uri, string url) } finally { - if (reader != null) + if (reader is not null) { reader.Close(); } @@ -622,19 +622,19 @@ private void LoadSchemaFromLocation(string uri, string url) private void LoadSchema(string uri, string? url) { - if (this.XmlResolver == null) + if (this.XmlResolver is null) { return; } - if (SchemaInfo!.TargetNamespaces.ContainsKey(uri) && _nsManager.LookupPrefix(uri) != null) + if (SchemaInfo!.TargetNamespaces.ContainsKey(uri) && _nsManager.LookupPrefix(uri) is not null) { return; } SchemaInfo? schemaInfo = null; - if (SchemaCollection != null) + if (SchemaCollection is not null) schemaInfo = SchemaCollection.GetSchemaInfo(uri); - if (schemaInfo != null) + if (schemaInfo is not null) { if (schemaInfo.SchemaType != SchemaType.XSD) { @@ -643,7 +643,7 @@ private void LoadSchema(string uri, string? url) SchemaInfo.Add(schemaInfo, EventHandler); return; } - if (url != null) + if (url is not null) { LoadSchemaFromLocation(uri, url); } @@ -653,7 +653,7 @@ private void LoadSchema(string uri, string? url) public override bool PreserveWhitespace { - get { return context!.ElementDecl != null ? context.ElementDecl.ContentValidator!.PreserveWhitespace : false; } + get { return context!.ElementDecl is not null ? context.ElementDecl.ContentValidator!.PreserveWhitespace : false; } } @@ -665,7 +665,7 @@ string name switch (ttype) { case XmlTokenizedType.ID: - if (FindId(name) != null) + if (FindId(name) is not null) { SendValidationEvent(SR.Sch_DupId, name); } @@ -676,7 +676,7 @@ string name break; case XmlTokenizedType.IDREF: object? p = FindId(name); - if (p == null) + if (p is null) { // add it to linked list to check it later _idRefListHead = new IdRefNode(_idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition); } @@ -697,9 +697,9 @@ private void CheckValue( try { reader.TypedValueObject = null; - bool isAttn = attdef != null; + bool isAttn = attdef is not null; XmlSchemaDatatype? dtype = isAttn ? attdef!.Datatype : context!.ElementDecl!.Datatype; - if (dtype == null) + if (dtype is null) { return; // no reason to check } @@ -744,7 +744,7 @@ private void CheckValue( } catch (XmlSchemaException) { - if (attdef != null) + if (attdef is not null) { SendValidationEvent(SR.Sch_AttributeValueDataType, attdef.Name.ToString()); } @@ -762,7 +762,7 @@ internal void AddID(string name, object node) // Note: It used to be true that we only called this if _fValidate was true, // but due to the fact that you can now dynamically type somethign as an ID // that is no longer true. - if (_IDs == null) + if (_IDs is null) { _IDs = new Hashtable(); } @@ -772,7 +772,7 @@ internal void AddID(string name, object node) public override object? FindId(string name) { - return _IDs == null ? null : _IDs[name]; + return _IDs is null ? null : _IDs[name]; } public bool IsXSDRoot(string localName, string ns) @@ -783,7 +783,7 @@ public bool IsXSDRoot(string localName, string ns) private void Push(XmlQualifiedName elementName) { context = (ValidationState)_validationStack.Push(); - if (context == null) + if (context is null) { context = new ValidationState(); _validationStack.AddToTop(context); @@ -795,7 +795,7 @@ private void Push(XmlQualifiedName elementName) context.IsNill = false; context.ProcessContents = _processContents; context.NeedValidateChildren = false; - context.Constr = null; //resetting the constraints to be null incase context != null + context.Constr = null; //resetting the constraints to be null incase context is not null // when pushing onto stack; } @@ -817,9 +817,9 @@ private void Pop() private void CheckForwardRefs() { IdRefNode? next = _idRefListHead; - while (next != null) + while (next is not null) { - if (FindId(next.Id) == null) + if (FindId(next.Id) is null) { SendValidationEvent(new XmlSchemaException(SR.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos)); } @@ -835,9 +835,9 @@ private void CheckForwardRefs() private void ValidateStartElementIdentityConstraints() { // added on June 15, set the context here, so the stack can have them - if (context!.ElementDecl != null) + if (context!.ElementDecl is not null) { - if (context.ElementDecl.Constraints != null) + if (context.ElementDecl.Constraints is not null) { AddIdentityConstraints(); } @@ -874,7 +874,7 @@ private void AddIdentityConstraints() for (int level = _validationStack.Length - 1; level >= ((_startIDConstraint >= 0) ? _startIDConstraint : _validationStack.Length - 1); level--) { // no constraint for this level - if (((ValidationState)(_validationStack[level])).Constr == null) + if (((ValidationState)(_validationStack[level])).Constr is null) { continue; } @@ -885,7 +885,7 @@ private void AddIdentityConstraints() if (constraints[j].constraint.name == context.Constr[i].constraint.refer) { find = true; - if (constraints[j].keyrefTable == null) + if (constraints[j].keyrefTable is null) { constraints[j].keyrefTable = new Hashtable(); } @@ -919,7 +919,7 @@ private void ElementIdentityConstraints() for (int i = _startIDConstraint; i < _validationStack.Length; i++) { // no constraint for this level - if (((ValidationState)(_validationStack[i])).Constr == null) + if (((ValidationState)(_validationStack[i])).Constr is null) { continue; } @@ -948,9 +948,9 @@ private void ElementIdentityConstraints() { Debug.WriteLine("Element Field Match!"); // checking simpleType / simpleContent - if (context!.ElementDecl != null) + if (context!.ElementDecl is not null) { // nextElement can be null when xml/xsd are not valid - if (context.ElementDecl.Datatype == null) + if (context.ElementDecl.Datatype is null) { SendValidationEvent(SR.Sch_FieldSimpleTypeExpected, reader.LocalName); } @@ -974,7 +974,7 @@ private void AttributeIdentityConstraints(string name, string ns, object? obj, s for (int ci = _startIDConstraint; ci < _validationStack.Length; ci++) { // no constraint for this level - if (((ValidationState)(_validationStack[ci])).Constr == null) + if (((ValidationState)(_validationStack[ci])).Constr is null) { continue; } @@ -996,13 +996,13 @@ private void AttributeIdentityConstraints(string name, string ns, object? obj, s // can fill value here, yeah!! Debug.WriteLine("Attribute Field Filling Value!"); Debug.WriteLine("Name: " + name + "\t|\tURI: " + ns + "\t|\tValue: " + obj + "\n"); - if (laxis.Ks[laxis.Column] != null) + if (laxis.Ks[laxis.Column] is not null) { // should be evaluated to either an empty node-set or a node-set with exactly one member // two matches... SendValidationEvent(SR.Sch_FieldSingleValueExpected, name); } - else if ((attdef != null) && (attdef.Datatype != null)) + else if ((attdef is not null) && (attdef.Datatype is not null)) { laxis.Ks[laxis.Column] = new TypedObject(obj, sobj, attdef.Datatype); } @@ -1015,7 +1015,7 @@ private void AttributeIdentityConstraints(string name, string ns, object? obj, s private object? UnWrapUnion(object? typedValue) { XsdSimpleValue? simpleValue = typedValue as XsdSimpleValue; - if (simpleValue != null) + if (simpleValue is not null) { typedValue = simpleValue.TypedValue; } @@ -1028,7 +1028,7 @@ private void EndElementIdentityConstraints() for (int ci = _validationStack.Length - 1; ci >= _startIDConstraint; ci--) { // no constraint for this level - if (((ValidationState)(_validationStack[ci])).Constr == null) + if (((ValidationState)(_validationStack[ci])).Constr is null) { continue; } @@ -1050,7 +1050,7 @@ private void EndElementIdentityConstraints() Debug.WriteLine("Name: " + reader.LocalName + "\t|\tURI: " + reader.NamespaceURI + "\t|\tValue: " + reader.TypedValueObject + "\n"); // fill value laxis.isMatched = false; - if (laxis.Ks[laxis.Column] != null) + if (laxis.Ks[laxis.Column] is not null) { // [field...] should be evaluated to either an empty node-set or a node-set with exactly one member // two matches... already existing field value in the table. @@ -1060,7 +1060,7 @@ private void EndElementIdentityConstraints() { // for element, reader.Value = ""; string stringValue = !hasSibling ? textString! : textValue!.ToString(); // only for identity-constraint exception reporting - if (reader.TypedValueObject != null && stringValue.Length != 0) + if (reader.TypedValueObject is not null && stringValue.Length != 0) { laxis.Ks[laxis.Column] = new TypedObject(reader.TypedValueObject, stringValue, context!.ElementDecl!.Datatype); } @@ -1119,7 +1119,7 @@ private void EndElementIdentityConstraints() // is there any possibility: // 2 keyrefs: value is equal, type is not // both put in the hashtable, 1 reference, 1 not - if (constraints[i].qualifiedTable != null) + if (constraints[i].qualifiedTable is not null) { //Will be null in cases when the keyref is outside the scope of the key, that is not allowed by our impl if (!ks.IsQualified() || constraints[i].qualifiedTable!.Contains(ks)) { @@ -1135,13 +1135,13 @@ private void EndElementIdentityConstraints() // current level's constraint struct ConstraintStruct[] vcs = ((ValidationState)(_validationStack[_validationStack.Length - 1])).Constr!; - if (vcs != null) + if (vcs is not null) { // validating all referencing tables... for (int i = 0; i < vcs.Length; ++i) { if ((vcs[i].constraint.Role == CompiledIdentityConstraint.ConstraintRole.Keyref) - || (vcs[i].keyrefTable == null)) + || (vcs[i].keyrefTable is null)) { continue; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs index 447610c51f7dda..d4dff8330a9de4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs @@ -64,7 +64,7 @@ public static XPathExpression Compile(string xpath, IXmlNamespaceResolver? nsRes bool hasPrefix; Query query = new QueryBuilder().Build(xpath, out hasPrefix); CompiledXpathExpr expr = new CompiledXpathExpr(query, xpath, hasPrefix); - if (null != nsResolver) + if (nsResolver is not null) { expr.SetContext(nsResolver); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index f7c86f7f9b7232..89efc2ceeff24f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -606,7 +606,7 @@ public virtual XmlReader ReadSubtree() public virtual void WriteSubtree(XmlWriter writer) { - if (null == writer) + if (writer is null) throw new ArgumentNullException(nameof(writer)); writer.WriteNode(this, true); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs index 94c1dce35728a8..4167d3718c610b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs @@ -79,8 +79,8 @@ public static XPathNavigatorReader Create(XPathNavigator navToRead) IXmlLineInfo? xli = nav as IXmlLineInfo; IXmlSchemaInfo? xsi = nav as IXmlSchemaInfo; #if NAVREADER_SUPPORTSLINEINFO - if (null == xsi) { - if (null == xli) { + if (xsi is null) { + if (xli is null) { return new XPathNavigatorReader(nav, xli, xsi); } else { @@ -88,7 +88,7 @@ public static XPathNavigatorReader Create(XPathNavigator navToRead) } } else { - if (null == xli) { + if (xli is null) { return new XPathNavigatorReaderWithSI(nav, xli, xsi); } else { @@ -96,7 +96,7 @@ public static XPathNavigatorReader Create(XPathNavigator navToRead) } } #else - if (null == xsi) + if (xsi is null) { return new XPathNavigatorReader(nav, xli, xsi); } @@ -386,7 +386,7 @@ public override int AttributeCount // attribute count works for element, regardless of where you are in start tag XPathNavigator? tempNav = GetElemNav(); int count = 0; - if (null != tempNav) + if (tempNav is not null) { if (tempNav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { @@ -457,7 +457,7 @@ public override int AttributeCount public override string? GetAttribute(string localName, string? namespaceURI) { - if (null == localName) + if (localName is null) throw new ArgumentNullException(nameof(localName)); // reader allows calling GetAttribute, even when positioned inside attributes XPathNavigator nav = _nav; @@ -480,7 +480,7 @@ public override int AttributeCount localName = string.Empty; return nav.GetNamespace(localName); } - if (null == namespaceURI) + if (namespaceURI is null) namespaceURI = string.Empty; // We need to clone the navigator and move the clone to the attribute to see whether the attribute exists, // because XPathNavigator.GetAttribute return string.Empty for both when the attribute is not there or when @@ -523,7 +523,7 @@ public override string GetAttribute(int index) if (index < 0) goto Error; XPathNavigator? nav = GetElemNav(); - if (null == nav) + if (nav is null) goto Error; if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { @@ -532,7 +532,7 @@ public override string GetAttribute(int index) // so first count the namespaces int nsCount; string? value = GetNamespaceByIndex(nav, index, out nsCount); - if (null != value) + if (value is not null) { return value; } @@ -556,11 +556,11 @@ public override string GetAttribute(int index) public override bool MoveToAttribute(string localName, string? namespaceName) { - if (null == localName) + if (localName is null) throw new ArgumentNullException(nameof(localName)); int depth = _depth; XPathNavigator? nav = GetElemNav(out depth); - if (null != nav) + if (nav is not null) { if (namespaceName == XmlReservedNs.NsXmlNs) { @@ -577,7 +577,7 @@ public override bool MoveToAttribute(string localName, string? namespaceName) } else { - if (null == namespaceName) + if (namespaceName is null) namespaceName = string.Empty; if (nav.MoveToAttribute(localName, namespaceName)) goto FoundMatch; @@ -599,7 +599,7 @@ public override bool MoveToFirstAttribute() { int depth; XPathNavigator? nav = GetElemNav(out depth); - if (null != nav) + if (nav is not null) { if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { @@ -704,7 +704,7 @@ public override bool MoveToAttribute(string name) { int depth; XPathNavigator? nav = GetElemNav(out depth); - if (null == nav) + if (nav is null) return false; string prefix, localname; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs index 87b3da75f3b590..7c2215d14451fc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs @@ -29,11 +29,11 @@ private async Task GetNonFileStreamAsync(Uri uri, ICredentials? credenti var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { - if (credentials != null) + if (credentials is not null) { handler.Credentials = credentials; } - if (proxy != null) + if (proxy is not null) { handler.Proxy = proxy; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs index dde7f76f54a5fb..71fa95ee3e4b42 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs @@ -26,8 +26,8 @@ public class XmlException : SystemException private readonly string? _sourceUri; - // message != null for V1 exceptions deserialized in Whidbey - // message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message) + // message is not null for V1 exceptions deserialized in Whidbey + // message is null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message) private readonly string? _message; protected XmlException(SerializationInfo info, StreamingContext context) : base(info, context) @@ -53,7 +53,7 @@ protected XmlException(SerializationInfo info, StreamingContext context) : base( } } - if (version == null) + if (version is null) { // deserializing V1 exception _message = CreateMessage(_res, _args, _lineNumber, _linePosition); @@ -84,7 +84,7 @@ public XmlException() : this(null) //provided to meet the ECMA standards public XmlException(string? message) : this(message, ((Exception?)null), 0, 0) { - Debug.Assert(message == null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!"); + Debug.Assert(message is null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!"); } //provided to meet ECMA standards @@ -102,7 +102,7 @@ internal XmlException(string? message, Exception? innerException, int lineNumber base(FormatUserMessage(message, lineNumber, linePosition), innerException) { HResult = HResults.Xml; - _res = (message == null ? SR.Xml_DefaultException : SR.Xml_UserException); + _res = (message is null ? SR.Xml_DefaultException : SR.Xml_UserException); _args = new string?[] { message }; _sourceUri = sourceUri; _lineNumber = lineNumber; @@ -126,7 +126,7 @@ internal XmlException(string res, string? arg, IXmlLineInfo? lineInfo) : { } internal XmlException(string res, string? arg, Exception? innerException, IXmlLineInfo? lineInfo) : - this(res, new string?[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null) + this(res, new string?[] { arg }, innerException, (lineInfo is null ? 0 : lineInfo.LineNumber), (lineInfo is null ? 0 : lineInfo.LinePosition), null) { } internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo) : @@ -134,7 +134,7 @@ internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo) : { } internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo, string? sourceUri) : - this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri) + this(res, args, null, (lineInfo is null ? 0 : lineInfo.LineNumber), (lineInfo is null ? 0 : lineInfo.LinePosition), sourceUri) { } @@ -171,7 +171,7 @@ internal XmlException(string res, string?[]? args, Exception? innerException, in private static string FormatUserMessage(string? message, int lineNumber, int linePosition) { - if (message == null) + if (message is null) { return CreateMessage(SR.Xml_DefaultException, null, lineNumber, linePosition); } @@ -194,7 +194,7 @@ private static string CreateMessage(string res, string?[]? args, int lineNumber, { try { - string message = (args == null) ? res : string.Format(res, args); + string message = (args is null) ? res : string.Format(res, args); // Line information is available -> we need to append it to the error message if (lineNumber != 0) @@ -273,7 +273,7 @@ public override string Message { get { - return (_message == null) ? base.Message : _message; + return (_message is null) ? base.Message : _message; } } @@ -287,7 +287,7 @@ internal string ResString internal static bool IsCatchableException(Exception e) { - Debug.Assert(e != null, "Unexpected null exception"); + Debug.Assert(e is not null, "Unexpected null exception"); return !( e is OutOfMemoryException || e is NullReferenceException diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs index 62125f9d8042b0..a2fdf32e5e4f4b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs @@ -11,7 +11,7 @@ public partial class XmlUrlResolver : XmlResolver // Maps a URI to an Object containing the actual resource. public override async Task GetEntityAsync(Uri absoluteUri, string? role, Type? ofObjectToReturn) { - if (ofObjectToReturn == null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object)) + if (ofObjectToReturn is null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object)) { return await DownloadManager.GetStreamAsync(absoluteUri, _credentials, _proxy).ConfigureAwait(false); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs index 8130d26d8f2a2b..22680abe979481 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs @@ -65,7 +65,7 @@ public XmlILStorageMethods(Type storageType) { string aggTypeName = "System.Xml.Xsl.Runtime." + storageType.Name + "Aggregator"; Type? aggType = Type.GetType(aggTypeName); - Debug.Assert(aggType != null, $"Could not find type `{aggTypeName}`"); + Debug.Assert(aggType is not null, $"Could not find type `{aggTypeName}`"); AggAvg = XmlILMethods.GetMethod(aggType, "Average"); AggAvgResult = XmlILMethods.GetMethod(aggType, "get_AverageResult"); AggCreate = XmlILMethods.GetMethod(aggType, "Create"); @@ -96,7 +96,7 @@ public XmlILStorageMethods(Type storageType) } FieldInfo? seqEmpty = SeqType.GetField("Empty"); - Debug.Assert(seqEmpty != null, "Field `Empty` could not be found"); + Debug.Assert(seqEmpty is not null, "Field `Empty` could not be found"); SeqEmpty = seqEmpty; SeqReuse = XmlILMethods.GetMethod(SeqType, "CreateOrReuse", SeqType); SeqReuseSgl = XmlILMethods.GetMethod(SeqType, "CreateOrReuse", SeqType, storageType); @@ -146,14 +146,14 @@ internal static class XmlILConstructors private static ConstructorInfo GetConstructor(Type className) { ConstructorInfo constrInfo = className.GetConstructor(Array.Empty())!; - Debug.Assert(constrInfo != null, "Constructor " + className + " cannot be null."); + Debug.Assert(constrInfo is not null, "Constructor " + className + " cannot be null."); return constrInfo; } private static ConstructorInfo GetConstructor(Type className, params Type[] args) { ConstructorInfo constrInfo = className.GetConstructor(args)!; - Debug.Assert(constrInfo != null, "Constructor " + className + " cannot be null."); + Debug.Assert(constrInfo is not null, "Constructor " + className + " cannot be null."); return constrInfo; } } @@ -421,14 +421,14 @@ internal static class XmlILMethods public static MethodInfo GetMethod(Type className, string methName) { MethodInfo? methInfo = className.GetMethod(methName); - Debug.Assert(methInfo != null, "Method " + className.Name + "." + methName + " cannot be null."); + Debug.Assert(methInfo is not null, "Method " + className.Name + "." + methName + " cannot be null."); return methInfo; } public static MethodInfo GetMethod(Type className, string methName, params Type[] args) { MethodInfo? methInfo = className.GetMethod(methName, args); - Debug.Assert(methInfo != null, "Method " + methName + " cannot be null."); + Debug.Assert(methInfo is not null, "Method " + methName + " cannot be null."); return methInfo; } } @@ -520,7 +520,7 @@ public void MethodBegin(MethodBase methInfo, ISourceLineInfo? sourceInfo, bool i DebugStartScope(); // DebugInfo: Sequence point just before generating code for this function - if (sourceInfo != null) + if (sourceInfo is not null) { // Don't call DebugSequencePoint, as it puts Nop *before* the sequence point. That is // wrong in this case, because we need source line information to be emitted before any @@ -535,7 +535,7 @@ public void MethodBegin(MethodBase methInfo, ISourceLineInfo? sourceInfo, bool i else if (_module.EmitSymbols) { // For a retail build, put source information on methods only - if (sourceInfo != null) + if (sourceInfo is not null) { MarkSequencePoint(sourceInfo); // Set this.lastSourceInfo back to null to prevent generating additional sequence points @@ -585,7 +585,7 @@ public void MethodEnd() public void CallSyncToNavigator() { // Get helper method from module - if (_methSyncToNav == null) + if (_methSyncToNav is null) _methSyncToNav = _module.FindMethod("SyncToNavigator"); Call(_methSyncToNav!); @@ -818,7 +818,7 @@ public void Call(MethodInfo meth) TraceCall(opcode, meth); _ilgen!.Emit(opcode, meth); - if (_lastSourceInfo != null) + if (_lastSourceInfo is not null) { // Emit a "no source" sequence point, otherwise the debugger would return to the wrong line // once the call has finished. We are guaranteed not to emit adjacent sequence points because @@ -1107,7 +1107,7 @@ private void EnsureWriter() _initWriters = true; } - Debug.Assert(_locXOut != null); + Debug.Assert(_locXOut is not null); } @@ -1352,7 +1352,7 @@ public void CallValueAs(Type clrType) MethodInfo? meth; meth = XmlILMethods.StorageMethods[clrType].ValueAs; - if (meth == null) + if (meth is null) { // Call (Type) item.ValueAs(Type, null) LoadType(clrType); @@ -1378,7 +1378,7 @@ public void AddSortKey(XmlQueryType? keyType) { MethodInfo? meth = null; - if (keyType == null) + if (keyType is null) { meth = XmlILMethods.SortKeyEmpty; } @@ -1441,8 +1441,8 @@ public void DebugEndScope() /// public void DebugSequencePoint(ISourceLineInfo sourceInfo) { - Debug.Assert(_isDebug && _lastSourceInfo != null); - Debug.Assert(sourceInfo != null); + Debug.Assert(_isDebug && _lastSourceInfo is not null); + Debug.Assert(sourceInfo is not null); // When emitting sequence points, be careful to always follow two rules: // 1. Never emit adjacent sequence points, as this messes up the debugger. We guarantee this by @@ -1477,7 +1477,7 @@ private void MarkSequencePoint(ISourceLineInfo sourceInfo) Debug.Assert(_module.EmitSymbols); // Do not emit adjacent 0xfeefee sequence points, as that slows down stepping in the debugger - if (sourceInfo.IsNoSource && _lastSourceInfo != null && _lastSourceInfo.IsNoSource) + if (sourceInfo.IsNoSource && _lastSourceInfo is not null && _lastSourceInfo.IsNoSource) { return; } @@ -1524,7 +1524,7 @@ public Label DefineLabel() public void MarkLabel(Label lbl) { - if (_lastSourceInfo != null && !_lastSourceInfo.IsNoSource) + if (_lastSourceInfo is not null && !_lastSourceInfo.IsNoSource) { // Emit a "no source" sequence point, otherwise the debugger would show // a wrong line if we jumped to this label from another place @@ -1718,7 +1718,7 @@ public void EmitUnconditionalBranch(OpCode opcode, Label lblTarget) #endif _ilgen!.Emit(opcode, lblTarget); - if (_lastSourceInfo != null && (opcode.Equals(OpCodes.Br) || opcode.Equals(OpCodes.Br_S))) + if (_lastSourceInfo is not null && (opcode.Equals(OpCodes.Br) || opcode.Equals(OpCodes.Br_S))) { // Emit a "no source" sequence point, otherwise the following label will be preceded // with a dead Nop operation, which may lead to unverifiable code (SQLBUDT 423393). diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs index 4c3965fac095f9..d45e5001bea3d1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs @@ -70,14 +70,14 @@ internal class OptimizerPatterns : IQilAnnotation public static OptimizerPatterns Read(QilNode nd) { XmlILAnnotation? ann = nd.Annotation as XmlILAnnotation; - OptimizerPatterns? optPatt = (ann != null) ? ann.Patterns : null; + OptimizerPatterns? optPatt = (ann is not null) ? ann.Patterns : null; - if (optPatt == null) + if (optPatt is null) { if (!nd.XmlType!.MaybeMany) { // Expressions with ZeroOrOne cardinality should always report IsDocOrderDistinct and NoContainedNodes - if (s_zeroOrOneDefault == null) + if (s_zeroOrOneDefault is null) { optPatt = new OptimizerPatterns(); optPatt.AddPattern(OptimizerPatternName.IsDocOrderDistinct); @@ -93,7 +93,7 @@ public static OptimizerPatterns Read(QilNode nd) } else if (nd.XmlType.IsDod) { - if (s_dodDefault == null) + if (s_dodDefault is null) { optPatt = new OptimizerPatterns(); optPatt.AddPattern(OptimizerPatternName.IsDocOrderDistinct); @@ -108,7 +108,7 @@ public static OptimizerPatterns Read(QilNode nd) } else { - if (s_maybeManyDefault == null) + if (s_maybeManyDefault is null) { optPatt = new OptimizerPatterns(); optPatt._isReadOnly = true; @@ -133,7 +133,7 @@ public static OptimizerPatterns Write(QilNode nd) XmlILAnnotation ann = XmlILAnnotation.Write(nd); OptimizerPatterns? optPatt = ann.Patterns; - if (optPatt == null || optPatt._isReadOnly) + if (optPatt is null || optPatt._isReadOnly) { optPatt = new OptimizerPatterns(); ann.Patterns = optPatt; @@ -233,7 +233,7 @@ public object GetArgument(OptimizerPatternArgument argNum) case 2: arg = _arg2; break; } - Debug.Assert(arg != null, "There is no '" + argNum + "' argument."); + Debug.Assert(arg is not null, "There is no '" + argNum + "' argument."); return arg; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs index c9e25cdad922bd..37fcfa356798da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs @@ -74,7 +74,7 @@ internal class StaticDataManager /// public int DeclareName(string name) { - if (_uniqueNames == null) + if (_uniqueNames is null) _uniqueNames = new UniqueList(); return _uniqueNames.Add(name); @@ -85,7 +85,7 @@ public int DeclareName(string name) /// public string[]? Names { - get { return (_uniqueNames != null) ? _uniqueNames.ToArray() : null; } + get { return (_uniqueNames is not null) ? _uniqueNames.ToArray() : null; } } /// @@ -94,7 +94,7 @@ public string[]? Names /// public int DeclareNameFilter(string locName, string nsUri) { - if (_uniqueFilters == null) + if (_uniqueFilters is null) _uniqueFilters = new UniqueList(); return _uniqueFilters.Add(new Int32Pair(DeclareName(locName), DeclareName(nsUri))); @@ -106,7 +106,7 @@ public int DeclareNameFilter(string locName, string nsUri) /// public Int32Pair[]? NameFilters { - get { return (_uniqueFilters != null) ? _uniqueFilters.ToArray() : null; } + get { return (_uniqueFilters is not null) ? _uniqueFilters.ToArray() : null; } } /// @@ -123,14 +123,14 @@ public int DeclarePrefixMappings(IList list) { // Each entry in mappings array must be a constant NamespaceDeclaration QilBinary ndNmspDecl = (QilBinary)list[i]; - Debug.Assert(ndNmspDecl != null); + Debug.Assert(ndNmspDecl is not null); Debug.Assert(ndNmspDecl.Left is QilLiteral && ndNmspDecl.Right is QilLiteral); prefixMappings[i] = new StringPair((string)(QilLiteral)ndNmspDecl.Left, (string)(QilLiteral)ndNmspDecl.Right); } // Add mappings to list and return index - if (_prefixMappingsList == null) + if (_prefixMappingsList is null) _prefixMappingsList = new List(); _prefixMappingsList.Add(prefixMappings); @@ -142,7 +142,7 @@ public int DeclarePrefixMappings(IList list) /// public StringPair[][]? PrefixMappingsList { - get { return (_prefixMappingsList != null) ? _prefixMappingsList.ToArray() : null; } + get { return (_prefixMappingsList is not null) ? _prefixMappingsList.ToArray() : null; } } /// @@ -152,7 +152,7 @@ public int DeclareGlobalValue(string name) { int idx; - if (_globalNames == null) + if (_globalNames is null) _globalNames = new List(); idx = _globalNames.Count; @@ -165,7 +165,7 @@ public int DeclareGlobalValue(string name) /// public string[]? GlobalNames { - get { return (_globalNames != null) ? _globalNames.ToArray() : null; } + get { return (_globalNames is not null) ? _globalNames.ToArray() : null; } } /// @@ -174,7 +174,7 @@ public string[]? GlobalNames /// public int DeclareEarlyBound(string namespaceUri, Type ebType) { - if (_earlyInfo == null) + if (_earlyInfo is null) _earlyInfo = new UniqueList(); return _earlyInfo.Add(new EarlyBoundInfo(namespaceUri, ebType)); @@ -187,7 +187,7 @@ public EarlyBoundInfo[]? EarlyBound { get { - if (_earlyInfo != null) + if (_earlyInfo is not null) return _earlyInfo.ToArray(); return null; @@ -200,7 +200,7 @@ public EarlyBoundInfo[]? EarlyBound /// public int DeclareXmlType(XmlQueryType type) { - if (_uniqueXmlTypes == null) + if (_uniqueXmlTypes is null) _uniqueXmlTypes = new UniqueList(); XmlQueryTypeFactory.CheckSerializability(type); @@ -212,7 +212,7 @@ public int DeclareXmlType(XmlQueryType type) /// public XmlQueryType[]? XmlTypes { - get { return (_uniqueXmlTypes != null) ? _uniqueXmlTypes.ToArray() : null; } + get { return (_uniqueXmlTypes is not null) ? _uniqueXmlTypes.ToArray() : null; } } /// @@ -221,7 +221,7 @@ public XmlQueryType[]? XmlTypes /// public int DeclareCollation(string collation) { - if (_uniqueCollations == null) + if (_uniqueCollations is null) _uniqueCollations = new UniqueList(); return _uniqueCollations.Add(XmlCollation.Create(collation)); @@ -232,7 +232,7 @@ public int DeclareCollation(string collation) /// public XmlCollation[]? Collations { - get { return (_uniqueCollations != null) ? _uniqueCollations.ToArray() : null; } + get { return (_uniqueCollations is not null) ? _uniqueCollations.ToArray() : null; } } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs index e1580e23a70f9b..2dce7ca41f8b31 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs @@ -31,7 +31,7 @@ public static XmlILAnnotation Write(QilNode nd) { XmlILAnnotation? ann = nd.Annotation as XmlILAnnotation; - if (ann == null) + if (ann is null) { ann = new XmlILAnnotation(nd.Annotation); nd.Annotation = ann; @@ -111,7 +111,7 @@ public OptimizerPatterns? Patterns /// public override int Count { - get { return (_annPrev != null) ? 3 : 2; } + get { return (_annPrev is not null) ? 3 : 2; } } /// @@ -121,7 +121,7 @@ public override object? this[int index] { get { - if (_annPrev != null) + if (_annPrev is not null) { if (index == 0) return _annPrev; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs index 730054b9eb521a..70c2664fca519f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs @@ -65,11 +65,11 @@ internal class XmlILConstructInfo : IQilAnnotation public static XmlILConstructInfo Read(QilNode nd) { XmlILAnnotation? ann = nd.Annotation as XmlILAnnotation; - XmlILConstructInfo? constrInfo = (ann != null) ? ann.ConstructInfo : null; + XmlILConstructInfo? constrInfo = (ann is not null) ? ann.ConstructInfo : null; - if (constrInfo == null) + if (constrInfo is null) { - if (s_default == null) + if (s_default is null) { constrInfo = new XmlILConstructInfo(QilNodeType.Unknown); constrInfo._isReadOnly = true; @@ -93,7 +93,7 @@ public static XmlILConstructInfo Write(QilNode nd) XmlILAnnotation ann = XmlILAnnotation.Write(nd); XmlILConstructInfo? constrInfo = ann.ConstructInfo; - if (constrInfo == null || constrInfo._isReadOnly) + if (constrInfo is null || constrInfo._isReadOnly) { constrInfo = new XmlILConstructInfo(nd.NodeType); ann.ConstructInfo = constrInfo; @@ -278,7 +278,7 @@ public XmlILConstructInfo? ParentElementInfo { get { - if (_parentInfo != null && _parentInfo._nodeType == QilNodeType.ElementCtor) + if (_parentInfo is not null && _parentInfo._nodeType == QilNodeType.ElementCtor) return _parentInfo; return null; @@ -363,7 +363,7 @@ public ArrayList CallersInfo { get { - if (_callersInfo == null) + if (_callersInfo is null) _callersInfo = new ArrayList(); return _callersInfo; @@ -441,14 +441,14 @@ public XmlILStateAnalyzer(QilFactory fac) /// public virtual QilNode? Analyze(QilNode? ndConstr, QilNode? ndContent) { - if (ndConstr == null) + if (ndConstr is null) { // Root expression is analyzed this.parentInfo = null; this.xstates = PossibleXmlStates.WithinSequence; this.withinElem = false; - Debug.Assert(ndContent != null); + Debug.Assert(ndContent is not null); ndContent = AnalyzeContent(ndContent); } else @@ -497,20 +497,20 @@ public XmlILStateAnalyzer(QilFactory fac) case QilNodeType.DocumentCtor: this.xstates = PossibleXmlStates.WithinContent; break; case QilNodeType.ElementCtor: this.xstates = PossibleXmlStates.EnumAttrs; break; case QilNodeType.AttributeCtor: this.xstates = PossibleXmlStates.WithinAttr; break; - case QilNodeType.NamespaceDecl: Debug.Assert(ndContent == null); break; - case QilNodeType.TextCtor: Debug.Assert(ndContent == null); break; - case QilNodeType.RawTextCtor: Debug.Assert(ndContent == null); break; + case QilNodeType.NamespaceDecl: Debug.Assert(ndContent is null); break; + case QilNodeType.TextCtor: Debug.Assert(ndContent is null); break; + case QilNodeType.RawTextCtor: Debug.Assert(ndContent is null); break; case QilNodeType.CommentCtor: this.xstates = PossibleXmlStates.WithinComment; break; case QilNodeType.PICtor: this.xstates = PossibleXmlStates.WithinPI; break; case QilNodeType.XsltCopy: this.xstates = PossibleXmlStates.Any; break; - case QilNodeType.XsltCopyOf: Debug.Assert(ndContent == null); break; + case QilNodeType.XsltCopyOf: Debug.Assert(ndContent is null); break; case QilNodeType.Function: this.xstates = this.parentInfo.InitialStates; break; case QilNodeType.RtfCtor: this.xstates = PossibleXmlStates.WithinContent; break; case QilNodeType.Choice: this.xstates = PossibleXmlStates.Any; break; default: Debug.Fail($"{ndConstr.NodeType} is not handled by XmlILStateAnalyzer."); break; } - if (ndContent != null) + if (ndContent is not null) ndContent = AnalyzeContent(ndContent); if (ndConstr.NodeType == QilNodeType.Choice) @@ -845,7 +845,7 @@ protected override void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info) if (ndCopy.NodeType == QilNodeType.AttributeCtor) { QilBinary? binaryNode = ndCopy as QilBinary; - Debug.Assert(binaryNode != null); + Debug.Assert(binaryNode is not null); AnalyzeAttributeCtor(binaryNode, info); } else @@ -864,7 +864,7 @@ private void AnalyzeAttributeCtor(QilBinary ndAttr, XmlILConstructInfo info) if (ndAttr.Left.NodeType == QilNodeType.LiteralQName) { QilName? ndName = ndAttr.Left as QilName; - Debug.Assert(ndName != null); + Debug.Assert(ndName is not null); XmlQualifiedName qname; int idx; @@ -1053,7 +1053,7 @@ private bool CheckNamespaceInScope(QilBinary nd) case QilNodeType.ElementCtor: case QilNodeType.AttributeCtor: ndName = nd.Left as QilName; - if (ndName != null) + if (ndName is not null) { prefix = ndName.Prefix; ns = ndName.NamespaceUri; 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 9d193487a007d1..252f3b9f28f1a0 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 @@ -123,7 +123,7 @@ public MethodInfo DefineMethod(string name, Type returnType, Type[] paramTypes, bool isRaw = (xmlAttrs & XmlILMethodAttributes.Raw) != 0; // Ensure that name is unique - while (_methods[name] != null) + while (_methods[name] is not null) { // Add unique id to end of name in order to make it unique within this module uniqueId++; @@ -159,7 +159,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 (paramNames[i] is not null && paramNames[i]!.Length != 0) methBldr.DefineParameter(i + (isRaw ? 1 : 2), ParameterAttributes.None, paramNames[i]); } @@ -184,11 +184,11 @@ public MethodInfo DefineMethod(string name, Type returnType, Type[] paramTypes, public static ILGenerator DefineMethodBody(MethodBase methInfo) { DynamicMethod? methDyn = methInfo as DynamicMethod; - if (methDyn != null) + if (methDyn is not null) return methDyn.GetILGenerator(); MethodBuilder? methBldr = methInfo as MethodBuilder; - if (methBldr != null) + if (methBldr is not null) return methBldr.GetILGenerator(); return ((ConstructorBuilder)methInfo).GetILGenerator(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs index e02dc3d989261a..5a0f58fd2e5402 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs @@ -89,7 +89,7 @@ public QilExpression Optimize() /// protected override QilNode Visit(QilNode nd) { - if (nd != null) + if (nd is not null) { if (this[XmlILOptimization.EliminateNamespaceDecl]) { @@ -125,12 +125,12 @@ protected override QilNode VisitReference(QilNode oldNode) { QilNode? newNode = _subs.FindReplacement(oldNode); - if (newNode == null) + if (newNode is null) newNode = oldNode; // Fold reference to constant value // This is done here because "p" currently cannot match references - if (this[XmlILOptimization.EliminateLiteralVariables] && newNode != null) + if (this[XmlILOptimization.EliminateLiteralVariables] && newNode is not null) { if (newNode.NodeType == QilNodeType.Let || newNode.NodeType == QilNodeType.For) { @@ -173,7 +173,7 @@ protected QilNode Replace(XmlILOptimization pattern, QilNode original, QilNode r { // Calculate MaybeSideEffects pattern. This is done here rather than using P because every node needs // to compute it and P has no good way of matching every node type. - if (node != null) + if (node is not null) { switch (node.NodeType) { @@ -202,7 +202,7 @@ protected QilNode Replace(XmlILOptimization pattern, QilNode original, QilNode r // If any of the visited node's children have side effects, then mark the node as also having side effects for (int i = 0; i < node.Count; i++) { - if (node[i] != null) + if (node[i] is not null) { if (OptimizerPatterns.Read(node[i]).MatchesPattern(OptimizerPatternName.MaybeSideEffects)) goto case QilNodeType.XsltInvokeLateBound; @@ -4982,7 +4982,7 @@ public int Count(QilNode expr, QilNode target) protected override QilNode Visit(QilNode n) { - if (n == null) + if (n is null) return null!; if (n == this.target) @@ -5066,7 +5066,7 @@ private class PositionOfFinder : NodeFinder /// protected override bool OnFound(QilNode expr) { - return this.parent != null && this.parent.NodeType == QilNodeType.PositionOf; + return this.parent is not null && this.parent.NodeType == QilNodeType.PositionOf; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs index c93e81f753a178..cc7c2a046d03d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs @@ -51,7 +51,7 @@ public static bool IsEnabled s_alreadyCheckedEnabled = true; } - return (s_dirName != null); + return (s_dirName is not null); } } @@ -168,7 +168,7 @@ private static void WriteQil(QilExpression qil, XmlWriter w) private static void WriteQilRewrite(QilExpression qil, XmlWriter w, string? rewriteName) { w.WriteStartElement("Diff"); - if (rewriteName != null) + if (rewriteName is not null) w.WriteAttributeString("rewrite", rewriteName); WriteQil(qil, w); w.WriteEndElement(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs index 75f097381d794f..06645390ed3553 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs @@ -90,7 +90,7 @@ private void PrepareGlobalValues(QilList globalIterators) // Get metadata for method which computes this global's value methGlobal = XmlILAnnotation.Write(iter).FunctionBinding; - Debug.Assert(methGlobal != null, "Metadata for global value should have already been computed"); + Debug.Assert(methGlobal is not null, "Metadata for global value should have already been computed"); // Create an IteratorDescriptor for this global value iterInfo = new IteratorDescriptor(_helper); @@ -140,12 +140,12 @@ private void VisitGlobalValues(QilList globalIterators) // Compute value of global value StartNestedIterator(iter); - if (param != null) + if (param is not null) { Debug.Assert(iter.XmlType == TypeFactory.ItemS, "IlGen currently only supports parameters of type item*."); // param = runtime.ExternalContext.GetParameter(localName, namespaceUri); - // if (param == null) goto LabelComputeGlobal; + // if (param is null) goto LabelComputeGlobal; LocalBuilder locParam = _helper.DeclareLocal("$$$param", typeof(object)); _helper.CallGetParameter(param.Name!.LocalName, param.Name.NamespaceUri); _helper.Emit(OpCodes.Stloc, locParam); @@ -171,7 +171,7 @@ private void VisitGlobalValues(QilList globalIterators) // LabelComputeGlobal: _helper.MarkLabel(lblComputeGlobal); - if (iter.Binding != null) + if (iter.Binding is not null) { // runtime.SetGlobalValue(idxValue, (object) value); _helper.LoadQueryRuntime(); @@ -240,11 +240,11 @@ private void Function(QilFunction ndFunc) foreach (QilIterator iter in ndFunc.Arguments) { // DebugInfo: Sequence point just before generating code for the bound expression - if (_qil.IsDebug && iter.SourceLine != null) + if (_qil.IsDebug && iter.SourceLine is not null) _helper.DebugSequencePoint(iter.SourceLine); // Calculate default value of this parameter - if (iter.Binding != null) + if (iter.Binding is not null) { Debug.Assert(iter.XmlType == TypeFactory.ItemS, "IlGen currently only supports default values in parameters of type item*."); paramId = (iter.Annotation as XmlILAnnotation)!.ArgumentPosition + 1; @@ -290,11 +290,11 @@ private void Function(QilFunction ndFunc) /// protected override QilNode Visit(QilNode nd) { - if (nd == null) + if (nd is null) return null!; // DebugInfo: Sequence point just before generating code for this expression - if (_qil.IsDebug && nd.SourceLine != null && !(nd is QilIterator)) + if (_qil.IsDebug && nd.SourceLine is not null && !(nd is QilIterator)) _helper.DebugSequencePoint(nd.SourceLine); // Expressions are constructed using one of several possible methods @@ -407,7 +407,7 @@ protected override QilNode VisitDataSource(QilDataSource ndSrc) locNav = _helper.DeclareLocal("$$$navDoc", typeof(XPathNavigator)); _helper.Emit(OpCodes.Stloc, locNav); - // if (navDoc == null) goto LabelNextCtxt; + // if (navDoc is null) goto LabelNextCtxt; _helper.Emit(OpCodes.Ldloc, locNav); _helper.Emit(OpCodes.Brfalse, _iterCurr.GetLabelNext()); @@ -972,7 +972,7 @@ protected override QilNode VisitConditional(QilTernary ndCond) /// private void ConditionalBranch(QilNode ndBranch, Type itemStorageType, LocalBuilder? locResult) { - if (locResult == null) + if (locResult is null) { Debug.Assert(ndBranch.XmlType!.IsSingleton, "Conditional must produce a singleton"); @@ -1543,7 +1543,7 @@ protected override QilNode VisitStrConcat(QilStrConcat ndStrConcat) _helper.Call(XmlILMethods.StrCatClear); // Set delimiter, if it's not empty string - if (delimiter != null) + if (delimiter is not null) { _helper.Emit(OpCodes.Ldloca, locStringConcat); NestedVisitEnsureStack(delimiter); @@ -2103,10 +2103,10 @@ private bool HandleFilterPatterns(QilLoop ndFilter) private void StartBinding(QilIterator ndIter) { OptimizerPatterns patt = OptimizerPatterns.Read(ndIter); - Debug.Assert(ndIter != null); + Debug.Assert(ndIter is not null); // DebugInfo: Sequence point just before generating code for the bound expression - if (_qil.IsDebug && ndIter.SourceLine != null) + if (_qil.IsDebug && ndIter.SourceLine is not null) _helper.DebugSequencePoint(ndIter.SourceLine); // Treat cardinality one Let iterators as if they were For iterators (no nesting necessary) @@ -2155,7 +2155,7 @@ private void StartForBinding(QilIterator ndFor, OptimizerPatterns patt) // DebugInfo: Open variable scope // DebugInfo: Ensure that for variable is stored in a local and tag it with the user-defined name - if (_qil.IsDebug && ndFor.DebugName != null) + if (_qil.IsDebug && ndFor.DebugName is not null) { _helper.DebugStartScope(); @@ -2206,7 +2206,7 @@ public void StartLetBinding(QilIterator ndLet) // DebugInfo: Open variable scope // DebugInfo: Ensure that for variable is stored in a local and tag it with the user-defined name - if (_qil.IsDebug && ndLet.DebugName != null) + if (_qil.IsDebug && ndLet.DebugName is not null) { _helper.DebugStartScope(); @@ -2227,10 +2227,10 @@ public void StartLetBinding(QilIterator ndLet) /// private void EndBinding(QilIterator ndIter) { - Debug.Assert(ndIter != null); + Debug.Assert(ndIter is not null); // Variables go out of scope here - if (_qil.IsDebug && ndIter.DebugName != null) + if (_qil.IsDebug && ndIter.DebugName is not null) _helper.DebugEndScope(); } @@ -2244,7 +2244,7 @@ protected override QilNode VisitPositionOf(QilUnary ndPos) Debug.Assert(ndIter.NodeType == QilNodeType.For); locPos = XmlILAnnotation.Write(ndIter).CachedIteratorDescriptor!.LocalPosition!; - Debug.Assert(locPos != null); + Debug.Assert(locPos is not null); _iterCurr.Storage = StorageDescriptor.Local(locPos, typeof(int), false); return ndPos; @@ -2593,7 +2593,7 @@ protected override QilNode VisitContent(QilUnary ndContent) protected override QilNode VisitAttribute(QilBinary ndAttr) { QilName? ndName = ndAttr.Right as QilName; - Debug.Assert(ndName != null, "Attribute node must have a literal QName as its second argument"); + Debug.Assert(ndName is not null, "Attribute node must have a literal QName as its second argument"); // XPathNavigator navAttr; LocalBuilder locNav = _helper.DeclareLocal("$$$navAttr", typeof(XPathNavigator)); @@ -3804,7 +3804,7 @@ protected override QilNode VisitXsltConvert(QilTargetType ndConv) } // XsltConvert.XXXToYYY(value); - if (meth != null) + if (meth is not null) _helper.Call(meth); _iterCurr.Storage = StorageDescriptor.Stack(GetItemStorageType(typDst), !typDst.IsSingleton); @@ -3882,7 +3882,7 @@ private bool GetXsltConvertMethod(XmlQueryType typSrc, XmlQueryType typDst, out else if ((object)typSrc == (object)TypeFactory.ItemS) meth = XmlILMethods.ItemsToStr; } - return meth != null; + return meth is not null; } @@ -3946,7 +3946,7 @@ private void CreateFilteredIterator(QilNode ndCtxt, string iterName, Type iterTy LoadSelectFilter(kinds, ndName); if (orSelf != TriState.Unknown) _helper.LoadBoolean(orSelf == TriState.True); - if (ndEnd != null) + if (ndEnd is not null) NestedVisitEnsureStack(ndEnd); _helper.Call(methCreate); @@ -3977,7 +3977,7 @@ private void CreateContainerIterator(QilUnary ndDod, string iterName, Type iterT LocalBuilder locIter = _helper.DeclareLocal(iterName, iterType); Label lblOnEndNested; QilLoop ndLoop = (QilLoop)ndDod.Child; - Debug.Assert(ndDod.NodeType == QilNodeType.DocOrderDistinct && ndLoop != null); + Debug.Assert(ndDod.NodeType == QilNodeType.DocOrderDistinct && ndLoop is not null); // iter.Create(filter [, orSelf]); _helper.Emit(OpCodes.Ldloca, locIter); @@ -4462,12 +4462,12 @@ private void EndWriterLoop(QilNode nd, bool hasOnEnd, Label lblOnEnd) private bool MightHaveNamespacesAfterAttributes(XmlILConstructInfo? info) { // Get parent element - if (info != null) + if (info is not null) info = info.ParentElementInfo; // If a parent element has not been statically identified, then assume that the runtime // element will have namespaces added after attributes. - if (info == null) + if (info is null) return true; return info.MightHaveNamespacesAfterAttributes; @@ -4602,7 +4602,7 @@ private XPathNodeType QilConstructorToNodeType(QilNodeType typ) /// private void LoadSelectFilter(XmlNodeKindFlags xmlTypes, QilName? ndName) { - if (ndName != null) + if (ndName is not null) { // Push NameFilter Debug.Assert(xmlTypes == XmlNodeKindFlags.Element); @@ -4644,7 +4644,7 @@ private static bool IsNodeTypeUnion(XmlNodeKindFlags xmlTypes) } /// - /// Start construction of a new nested iterator. If this.iterCurr == null, then the new iterator + /// Start construction of a new nested iterator. If this.iterCurr is null, then the new iterator /// is a top-level, or root iterator. Otherwise, the new iterator will be nested within the /// current iterator. /// @@ -4654,7 +4654,7 @@ private void StartNestedIterator(QilNode? nd) IteratorDescriptor? iterParent = _iterCurr; // Create a new, nested iterator - if (iterParent == null) + if (iterParent is null) { // Create a "root" iterator info that has no parernt _iterCurr = new IteratorDescriptor(_helper); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs index d2996cf63f3df4..e9ae1ea3aae157 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs @@ -193,7 +193,7 @@ void System.Collections.IList.Remove(object? value) private static bool IsCompatibleType(object? value) { - if ((value == null && !typeof(T).IsValueType) || (value is T)) + if ((value is null && !typeof(T).IsValueType) || (value is T)) return true; return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs index e379522b931206..90434440b0b321 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs @@ -55,7 +55,7 @@ protected override QilNode Visit(QilNode oldNode) { QilNode? newNode = null; - if (oldNode == null) + if (oldNode is null) return null!; // ShallowClone any nodes which have not yet been cloned @@ -65,7 +65,7 @@ protected override QilNode Visit(QilNode oldNode) newNode = FindClonedReference(oldNode); } - if (newNode == null) + if (newNode is null) newNode = oldNode.ShallowClone(_fac); return base.Visit(newNode); @@ -88,7 +88,7 @@ protected override QilNode VisitChildren(QilNode parent) parent[i] = VisitReference(child); // If no substutition found, then use original child - if (parent[i] == null) + if (parent[i] is null) parent[i] = child; } else @@ -107,7 +107,7 @@ protected override QilNode VisitChildren(QilNode parent) protected override QilNode VisitReference(QilNode oldNode) { QilNode? newNode = FindClonedReference(oldNode); - return base.VisitReference(newNode == null ? oldNode : newNode); + return base.VisitReference(newNode is null ? oldNode : newNode); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs index d105ee90bf45d2..c13f88fa73b9d9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs @@ -44,7 +44,7 @@ public override XmlQueryType XmlType { get { - if (this.xmlType == null) + if (this.xmlType is null) { XmlQueryType xt = XmlQueryTypeFactory.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs index 12bda6fd433566..1caea6c454123c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs @@ -95,7 +95,7 @@ public override int GetHashCode() public override bool Equals(object? other) { QilName? name = other as QilName; - if (name == null) + if (name is null) return false; return _local == name._local && _uri == name._uri; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs index c5862ec77f0942..2a2ca47f212b41 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs @@ -23,7 +23,7 @@ internal class QilPatternFactory public QilPatternFactory(QilFactory f, bool debug) { - Debug.Assert(f != null); + Debug.Assert(f is not null); _f = f; _debug = debug; } @@ -225,7 +225,7 @@ public QilNode Boolean(bool b) //----------------------------------------------- private static void CheckLogicArg(QilNode arg) { - Debug.Assert(arg != null, "Argument shouldn't be null"); + Debug.Assert(arg is not null, "Argument shouldn't be null"); Debug.Assert(arg.XmlType!.TypeCode == XmlTypeCode.Boolean && arg.XmlType.IsSingleton, "The operand must be boolean-typed" ); @@ -767,7 +767,7 @@ public QilNode TypeAssert(QilNode expr, XmlQueryType t) public QilNode IsType(QilNode expr, XmlQueryType t) { - Debug.Assert(t != null, "Type can't be null"); + Debug.Assert(t is not null, "Type can't be null"); return _f.IsType(expr, t); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs index 5701f5bba48c0e..26dba01e8a2186 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs @@ -80,7 +80,7 @@ protected virtual QilNode Replace(int pattern, QilNode original, QilNode replace /// protected override QilNode Visit(QilNode node) { - if (node == null) + if (node is null) return VisitNull()!; node = VisitChildren(node); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs index 087a0352834790..a9de9afbb39e08 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs @@ -38,7 +38,7 @@ protected override QilNode VisitChildren(QilNode parent) for (int i = 0; i < parent.Count; i++) { QilNode oldChild = parent[i], newChild; - XmlQueryType? oldChildType = oldChild != null ? oldChild.XmlType : null; + XmlQueryType? oldChildType = oldChild is not null ? oldChild.XmlType : null; // Visit child if (IsReference(parent, i)) @@ -47,7 +47,7 @@ protected override QilNode VisitChildren(QilNode parent) newChild = Visit(oldChild!); // Only replace child and recalculate type if oldChild != newChild or oldChild.XmlType != newChild.XmlType - if ((object?)oldChild != (object)newChild || (newChild != null && (object?)oldChildType != (object?)newChild.XmlType)) + if ((object?)oldChild != (object)newChild || (newChild is not null && (object?)oldChildType != (object?)newChild.XmlType)) { recalcType = true; parent[i] = newChild; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs index 2b187a375aa06f..0eaa44c8addfe3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs @@ -196,7 +196,7 @@ public XmlQueryType CheckGlobalParameterList(QilList node) foreach (QilNode child in node) { CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter); - Check(((QilParameter)child).Name != null, child, "Global parameter's name is null"); + Check(((QilParameter)child).Name is not null, child, "Global parameter's name is null"); } return node.XmlType; } @@ -283,7 +283,7 @@ public XmlQueryType CheckLet(QilIterator node) public XmlQueryType CheckParameter(QilParameter node) { - Check(node.Binding == null || node.Binding.XmlType!.IsSubtypeOf(node.XmlType!), node, "Parameter binding's xml type must be a subtype of the parameter's type"); + Check(node.Binding is null || node.Binding.XmlType!.IsSubtypeOf(node.XmlType!), node, "Parameter binding's xml type must be a subtype of the parameter's type"); return node.XmlType!; } @@ -354,7 +354,7 @@ public XmlQueryType CheckLiteralType(QilLiteral node) public XmlQueryType CheckLiteralObject(QilLiteral node) { - Check(node.Value != null, node, "Literal value is null"); + Check(node.Value is not null, node, "Literal value is null"); return XmlQueryTypeFactory.ItemS; } @@ -614,7 +614,7 @@ public XmlQueryType CheckFilter(QilLoop node) // Attempt to restrict filter's type by checking condition XmlQueryType? filterType = FindFilterType(node.Variable, node.Body); - if (filterType != null) + if (filterType is not null) return filterType; return XmlQueryTypeFactory.AtMost(node.Variable.Binding!.XmlType!, node.Variable.Binding.XmlType!.Cardinality); @@ -1084,7 +1084,7 @@ private XmlQueryType DistinctType(XmlQueryType type) case QilNodeType.And: // Both And conditions can be used to restrict filter's type leftType = FindFilterType(variable, ((QilBinary)body).Left); - if (leftType != null) + if (leftType is not null) return leftType; return FindFilterType(variable, ((QilBinary)body).Right); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs index 41c3a5765b1ba2..bbca0bd693c231 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs @@ -37,7 +37,7 @@ internal class QilValidationVisitor : QilScopedVisitor [Conditional("DEBUG")] public static void Validate(QilNode node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); new QilValidationVisitor().VisitAssumeReference(node); } @@ -62,7 +62,7 @@ protected override QilNode VisitChildren(QilNode parent) } else if (AddNode(parent)) { - if (parent.XmlType == null) + if (parent.XmlType is null) { SetError(parent, "Type information missing"); } @@ -79,7 +79,7 @@ protected override QilNode VisitChildren(QilNode parent) for (int i = 0; i < parent.Count; i++) { - if (parent[i] == null) + if (parent[i] is null) { // Allow parameter name and default value to be null if (parent.NodeType == QilNodeType.Parameter) @@ -93,7 +93,7 @@ protected override QilNode VisitChildren(QilNode parent) parent.NodeType == QilNodeType.GlobalParameterList || parent.NodeType == QilNodeType.FunctionList) { - if (((QilReference)parent[i]).DebugName == null) + if (((QilReference)parent[i]).DebugName is null) SetError(parent[i], "DebugName must not be null"); } @@ -183,7 +183,7 @@ internal static void SetError(QilNode n, string message) #endif string? s = n.Annotation as string; - if (s != null) + if (s is not null) { message = s + "\n" + message; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs index 561d83704219a4..7f94a63ab2e443 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs @@ -59,7 +59,7 @@ protected virtual bool IsReference(QilNode parent, int childNum) { QilNode child = parent[childNum]; - if (child != null) + if (child is not null) { switch (child.NodeType) { @@ -103,7 +103,7 @@ protected virtual bool IsReference(QilNode parent, int childNum) #region AUTOGENERATED protected virtual QilNode Visit(QilNode n) { - if (n == null) + if (n is null) return VisitNull()!; return n.NodeType switch @@ -241,7 +241,7 @@ protected virtual QilNode Visit(QilNode n) protected virtual QilNode VisitReference(QilNode n) { - if (n == null) + if (n is null) return VisitNull()!; return n.NodeType switch @@ -463,7 +463,7 @@ private void Check(QilNode input, int depth) for (int i = 0; i < input.Count; i++) { QilNode child = input[i]; - if (child != null) + if (child is not null) { Check(child, nextDepth); } 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 7e2b54f7ced507..d57437d2e64e5a 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 @@ -94,7 +94,7 @@ protected virtual void WriteAnnotations(object? ann) { string? s = null, name = null; - if (ann == null) + if (ann is null) { return; } @@ -114,8 +114,8 @@ protected virtual void WriteAnnotations(object? ann) return; } - if (s != null && s.Length != 0) - this.writer.WriteComment(name != null && name.Length != 0 ? name + ": " + s : s); + if (s is not null && s.Length != 0) + this.writer.WriteComment(name is not null && name.Length != 0 ? name + ": " + s : s); } /// @@ -161,7 +161,7 @@ protected override QilNode VisitChildren(QilNode node) this.writer.WriteAttributeString("id", _ngen.NameOf(node)); // Write the debug name of this reference (if it's defined) as a "name" attribute - if (reference.DebugName != null) + if (reference.DebugName is not null) this.writer.WriteAttributeString("name", reference.DebugName.ToString()); if (node.NodeType == QilNodeType.Parameter) @@ -169,7 +169,7 @@ protected override QilNode VisitChildren(QilNode node) // Don't visit parameter's name, or its default value if it is null QilParameter param = (QilParameter)node; - if (param.DefaultValue != null) + if (param.DefaultValue is not null) VisitAssumeReference(param.DefaultValue); return node; @@ -186,12 +186,12 @@ protected override QilNode VisitReference(QilNode node) { QilReference reference = (QilReference)node; string name = _ngen.NameOf(node); - if (name == null) + if (name is null) name = "OUT-OF-SCOPE REFERENCE"; this.writer.WriteStartElement("RefTo"); this.writer.WriteAttributeString("id", name); - if (reference.DebugName != null) + if (reference.DebugName is not null) this.writer.WriteAttributeString("name", reference.DebugName.ToString()); this.writer.WriteEndElement(); @@ -204,7 +204,7 @@ protected override QilNode VisitReference(QilNode node) protected override QilNode VisitQilExpression(QilExpression qil) { IList fdecls = new ForwardRefFinder().Find(qil); - if (fdecls != null && fdecls.Count > 0) + if (fdecls is not null && fdecls.Count > 0) { this.writer.WriteStartElement("ForwardDecls"); foreach (QilNode n in fdecls) @@ -294,7 +294,7 @@ protected override void BeforeVisit(QilNode node) if ((this.options & (Options.TypeInfo | Options.RoundTripTypeInfo)) != 0) WriteXmlType(node); - if ((this.options & Options.LineInfo) != 0 && node.SourceLine != null) + if ((this.options & Options.LineInfo) != 0 && node.SourceLine is not null) WriteLineInfo(node); } @@ -414,7 +414,7 @@ public string NameOf(QilNode n) object? old = n.Annotation; NameAnnotation? a = old as NameAnnotation; - if (a == null) + if (a is null) { name = NextName(); n.Annotation = new NameAnnotation(name, old); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs index 9bd4a85ac9023a..3dc33ebc690329 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs @@ -23,7 +23,7 @@ internal class QueryReaderSettings public QueryReaderSettings(XmlNameTable xmlNameTable) { - Debug.Assert(xmlNameTable != null); + Debug.Assert(xmlNameTable is not null); _xmlReaderSettings = new XmlReaderSettings(); _xmlReaderSettings.NameTable = xmlNameTable; _xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document; @@ -37,7 +37,7 @@ public QueryReaderSettings(XmlReader reader) #pragma warning disable 618 XmlValidatingReader? valReader = reader as XmlValidatingReader; #pragma warning restore 618 - if (valReader != null) + if (valReader is not null) { // Unwrap validation reader _validatingReader = true; @@ -45,7 +45,7 @@ public QueryReaderSettings(XmlReader reader) } _xmlReaderSettings = reader.Settings; - if (_xmlReaderSettings != null) + if (_xmlReaderSettings is not null) { _xmlReaderSettings = _xmlReaderSettings.Clone(); _xmlReaderSettings.NameTable = reader.NameTable; @@ -53,7 +53,7 @@ public QueryReaderSettings(XmlReader reader) _xmlReaderSettings.LineNumberOffset = 0; _xmlReaderSettings.LinePositionOffset = 0; XmlTextReaderImpl? impl = reader as XmlTextReaderImpl; - if (impl != null) + if (impl is not null) { _xmlReaderSettings.XmlResolver = impl.GetResolver(); } @@ -62,7 +62,7 @@ public QueryReaderSettings(XmlReader reader) { _xmlNameTable = reader.NameTable; XmlTextReader? xmlTextReader = reader as XmlTextReader; - if (xmlTextReader != null) + if (xmlTextReader is not null) { XmlTextReaderImpl impl = xmlTextReader.Impl; _entityHandling = impl.EntityHandling; @@ -87,7 +87,7 @@ public QueryReaderSettings(XmlReader reader) public XmlReader CreateReader(Stream stream, string baseUri) { XmlReader reader; - if (_xmlReaderSettings != null) + if (_xmlReaderSettings is not null) { reader = XmlTextReader.Create(stream, _xmlReaderSettings, baseUri); } @@ -113,7 +113,7 @@ public XmlReader CreateReader(Stream stream, string baseUri) public XmlNameTable NameTable { - get { return _xmlReaderSettings != null ? _xmlReaderSettings.NameTable! : _xmlNameTable!; } + get { return _xmlReaderSettings is not null ? _xmlReaderSettings.NameTable! : _xmlNameTable!; } } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs index 44ec8492d2224f..4d079946930aca 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs @@ -348,7 +348,7 @@ internal IteratorResult MoveNext(XPathNavigator input, bool isContent) { case IteratorState.NeedCurrent: // If there are no more input nodes, then iteration is complete - if (input == null) + if (input is null) return IteratorResult.NoMoreNodes; // Save the input node as the current node @@ -362,7 +362,7 @@ internal IteratorResult MoveNext(XPathNavigator input, bool isContent) return IteratorResult.NeedInputNode; case IteratorState.HaveCurrentNeedNext: - if (input == null) + if (input is null) { // There are no more input nodes, so enter HaveCurrentNoNext state and return Current _state = IteratorState.HaveCurrentNoNext; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs index ee3d21356c627c..237831a7b7649a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs @@ -41,7 +41,7 @@ internal class DecimalFormatter public DecimalFormatter(string formatPicture, DecimalFormat decimalFormat) { - Debug.Assert(formatPicture != null && decimalFormat != null); + Debug.Assert(formatPicture is not null && decimalFormat is not null); if (formatPicture.Length == 0) { throw XsltException.Create(SR.Xslt_InvalidFormat); @@ -236,7 +236,7 @@ public string Format(double value) NumberFormatInfo formatInfo; string subPicture; - if (value < 0 && _negFormatInfo != null) + if (value < 0 && _negFormatInfo is not null) { formatInfo = _negFormatInfo; subPicture = _negFormat; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs index f595922ebcb62d..b9bad33f98b3a1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs @@ -36,7 +36,7 @@ public int Compare(XPathNavigator navThis, XPathNavigator navThat) } // Use this.roots to impose stable ordering - if (_roots == null) + if (_roots is null) _roots = new List(); Debug.Assert(GetDocumentIndex(navThis) != GetDocumentIndex(navThat)); @@ -55,7 +55,7 @@ public int GetDocumentIndex(XPathNavigator nav) XPathNavigator navRoot; // Use this.roots to impose stable ordering - if (_roots == null) + if (_roots is null) _roots = new List(); // Position navigator to root diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs index bb82c33a8d63fd..34510eda4900e3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs @@ -42,13 +42,13 @@ public void AddSequence(IList sequence) if (sequence.Count == 0) return; - if (_firstSequence == null) + if (_firstSequence is null) { _firstSequence = sequence; } else { - if (_sequencesToMerge == null) + if (_sequencesToMerge is null) { _sequencesToMerge = new List>(); MoveAndInsertSequence(_firstSequence.GetEnumerator()); @@ -68,11 +68,11 @@ public IList MergeSequences() XmlQueryNodeSequence newSequence; // Zero sequences to merge - if (_firstSequence == null) + if (_firstSequence is null) return XmlQueryNodeSequence.Empty; // One sequence to merge - if (_sequencesToMerge == null || _sequencesToMerge.Count <= 1) + if (_sequencesToMerge is null || _sequencesToMerge.Count <= 1) return _firstSequence; // Two or more sequences to merge diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs index 9b44a9fe557d9e..b72dbf4933f64f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs @@ -17,12 +17,12 @@ internal sealed class EarlyBoundInfo public EarlyBoundInfo(string namespaceUri, Type ebType) { - Debug.Assert(namespaceUri != null && ebType != null); + Debug.Assert(namespaceUri is not null && ebType is not null); // Get the default constructor _namespaceUri = namespaceUri; _constrInfo = ebType.GetConstructor(Type.EmptyTypes); - Debug.Assert(_constrInfo != null, "The early bound object type " + ebType.FullName + " must have a public default constructor"); + Debug.Assert(_constrInfo is not null, "The early bound object type " + ebType.FullName + " must have a public default constructor"); } /// @@ -46,7 +46,7 @@ public EarlyBoundInfo(string namespaceUri, Type ebType) public override bool Equals(object obj) { EarlyBoundInfo info = obj as EarlyBoundInfo; - if (info == null) + if (info is null) return false; return _namespaceUri == info._namespaceUri && _constrInfo == info._constrInfo; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs index 8ca6025bc44e70..4f14901d410d33 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs @@ -289,7 +289,7 @@ public override XPathNavigator Clone() public override bool MoveTo(XPathNavigator other) { RtfTreeNavigator that = other as RtfTreeNavigator; - if (that != null) + if (that is not null) { _events = that._events; _constr = that._constr; @@ -400,7 +400,7 @@ public override XPathNavigator Clone() public override bool MoveTo(XPathNavigator other) { RtfTextNavigator that = other as RtfTextNavigator; - if (that != null) + if (that is not null) { _text = that._text; _baseUri = that._baseUri; @@ -427,7 +427,7 @@ internal sealed class NavigatorConstructor /// public XPathNavigator GetNavigator(XmlEventCache events, XmlNameTable nameTable) { - if (_cache == null) + if (_cache is null) { // Create XPathDocument from event cache XPathDocument doc = new XPathDocument(nameTable); @@ -449,7 +449,7 @@ public XPathNavigator GetNavigator(XmlEventCache events, XmlNameTable nameTable) /// public XPathNavigator GetNavigator(string text, string baseUri, XmlNameTable nameTable) { - if (_cache == null) + if (_cache is null) { // Create XPathDocument XPathDocument doc = new XPathDocument(nameTable); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs index 7001187ecbc35f..0808e696bbf5bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs @@ -91,15 +91,15 @@ public SetIteratorResult MoveNext(XPathNavigator nestedNavigator) } // Merge left and right nodes - if (_navCurr == null) + if (_navCurr is null) { // If both navCurr and navOther are null, then iteration is complete - if (_navOther == null) + if (_navOther is null) return SetIteratorResult.NoMoreNodes; Swap(); } - else if (_navOther != null) + else if (_navOther is not null) { int order = _runtime.ComparePosition(_navOther, _navCurr); @@ -211,12 +211,12 @@ public SetIteratorResult MoveNext(XPathNavigator nestedNavigator) case IteratorState.HaveCurrent: // Just returned left node as current, so fetch new left and right nodes - Debug.Assert(nestedNavigator == null, "null is passed to MoveNext after IteratorState.HaveCurrent has been returned."); + Debug.Assert(nestedNavigator is null, "null is passed to MoveNext after IteratorState.HaveCurrent has been returned."); _state = IteratorState.NeedLeftAndRight; return SetIteratorResult.NeedLeftNode; } - if (_navLeft == null || _navRight == null) + if (_navLeft is null || _navRight is null) { // No more nodes from either left or right iterator (or both), so iteration is complete return SetIteratorResult.NoMoreNodes; @@ -311,17 +311,17 @@ public SetIteratorResult MoveNext(XPathNavigator nestedNavigator) case IteratorState.HaveCurrent: // Just returned left node as current, so fetch new left node - Debug.Assert(nestedNavigator == null, "null is passed to MoveNext after IteratorState.HaveCurrent has been returned."); + Debug.Assert(nestedNavigator is null, "null is passed to MoveNext after IteratorState.HaveCurrent has been returned."); _state = IteratorState.NeedLeft; return SetIteratorResult.NeedLeftNode; } - if (_navLeft == null) + if (_navLeft is null) { // If navLeft is null, then difference operation is complete return SetIteratorResult.NoMoreNodes; } - else if (_navRight != null) + else if (_navRight is not null) { int order = _runtime.ComparePosition(_navLeft, _navRight); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs index f2f61ca05081e8..d33c02bce5e931 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs @@ -52,9 +52,9 @@ internal int Count /// public void Concat(string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); - if (_delimiter != null && _idxStr != 0) + if (_delimiter is not null && _idxStr != 0) { // Add delimiter ConcatNoDelimiter(_delimiter); @@ -90,7 +90,7 @@ internal void ConcatNoDelimiter(string? s) case 3: _s4 = s; break; case 4: // Calling Clear() is expensive, allocate a new List instead - int capacity = (_strList == null) ? 8 : _strList.Count; + int capacity = (_strList is null) ? 8 : _strList.Count; List strList = _strList = new List(capacity); strList.Add(_s1); strList.Add(_s2); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs index 07a9798589437b..28080cb43d155f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs @@ -104,7 +104,7 @@ public IteratorResult MoveNext(XPathNavigator input) { if (_state != IteratorState.NeedDescendant) { - if (input == null) + if (input is null) return IteratorResult.NoMoreNodes; // Descendants of the input node will be duplicates if the input node is in the subtree @@ -429,7 +429,7 @@ public IteratorResult MoveNext(XPathNavigator input) { case IteratorState.NeedCandidateCurrent: // If there are no more input nodes, then iteration is complete - if (input == null) + if (input is null) return IteratorResult.NoMoreNodes; // Save input node as current node @@ -441,7 +441,7 @@ public IteratorResult MoveNext(XPathNavigator input) case IteratorState.HaveCandidateCurrent: // If there are no more input nodes, - if (input == null) + if (input is null) { // Then candidate node has been selected, and there are no further input nodes _state = IteratorState.HaveCurrentNoNext; @@ -458,7 +458,7 @@ public IteratorResult MoveNext(XPathNavigator input) case IteratorState.HaveCurrentNeedNext: // If there are no more input nodes, - if (input == null) + if (input is null) { // Then candidate node has been selected, and there are no further input nodes _state = IteratorState.HaveCurrentNoNext; @@ -751,7 +751,7 @@ public IteratorResult MoveNext(XPathNavigator input) { case IteratorState.NeedCandidateCurrent: // If there are no more input nodes, then iteration is complete - if (input == null) + if (input is null) return IteratorResult.NoMoreNodes; // Save input node as current node @@ -763,7 +763,7 @@ public IteratorResult MoveNext(XPathNavigator input) case IteratorState.HaveCandidateCurrent: // If there are no more input nodes, - if (input == null) + if (input is null) { // Then candidate node has been selected, and there are no further input nodes _state = IteratorState.HaveCurrentNoNext; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs index 20cccb874ffb00..8258523542370c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs @@ -36,7 +36,7 @@ public WhitespaceRuleLookup(IList rules) : this() { WhitespaceRule rule; InternalWhitespaceRule ruleInternal; - Debug.Assert(rules != null); + Debug.Assert(rules is not null); for (int i = rules.Count - 1; i >= 0; i--) { @@ -44,7 +44,7 @@ public WhitespaceRuleLookup(IList rules) : this() rule = rules[i]; ruleInternal = new InternalWhitespaceRule(rule.LocalName, rule.NamespaceName, rule.PreserveSpace, -i); - if (rule.LocalName == null || rule.NamespaceName == null) + if (rule.LocalName is null || rule.NamespaceName is null) { // Wildcard, so add to wildcards array _wildcards.Add(ruleInternal); @@ -86,9 +86,9 @@ public void Atomize(XmlNameTable nameTable) public bool ShouldStripSpace(string localName, string namespaceName) { InternalWhitespaceRule qnameRule, wildcardRule; - Debug.Assert(_nameTable != null && _ruleTemp != null); - Debug.Assert(localName != null && (object)_nameTable.Get(localName) == (object)localName); - Debug.Assert(namespaceName != null && (object)_nameTable.Get(namespaceName) == (object)namespaceName); + Debug.Assert(_nameTable is not null && _ruleTemp is not null); + Debug.Assert(localName is not null && (object)_nameTable.Get(localName) == (object)localName); + Debug.Assert(namespaceName is not null && (object)_nameTable.Get(namespaceName) == (object)namespaceName); _ruleTemp.Init(localName, namespaceName, false, 0); @@ -100,7 +100,7 @@ public bool ShouldStripSpace(string localName, string namespaceName) { wildcardRule = _wildcards[pos] as InternalWhitespaceRule; - if (qnameRule != null) + if (qnameRule is not null) { // If qname priority is greater than any subsequent wildcard's priority, then we're done if (qnameRule.Priority > wildcardRule.Priority) @@ -111,9 +111,9 @@ public bool ShouldStripSpace(string localName, string namespaceName) continue; } - if (wildcardRule.LocalName == null || (object)wildcardRule.LocalName == (object)localName) + if (wildcardRule.LocalName is null || (object)wildcardRule.LocalName == (object)localName) { - if (wildcardRule.NamespaceName == null || (object)wildcardRule.NamespaceName == (object)namespaceName) + if (wildcardRule.NamespaceName is null || (object)wildcardRule.NamespaceName == (object)namespaceName) { // Found wildcard match, so we're done (since wildcards are in priority order) return !wildcardRule.PreserveSpace; @@ -121,7 +121,7 @@ public bool ShouldStripSpace(string localName, string namespaceName) } } - return (qnameRule != null && !qnameRule.PreserveSpace); + return (qnameRule is not null && !qnameRule.PreserveSpace); } private class InternalWhitespaceRule : WhitespaceRule @@ -143,7 +143,7 @@ public void Init(string localName, string namespaceName, bool preserveSpace, int base.Init(localName, namespaceName, preserveSpace); _priority = priority; - if (localName != null && namespaceName != null) + if (localName is not null && namespaceName is not null) { _hashCode = localName.GetHashCode(); } @@ -151,10 +151,10 @@ public void Init(string localName, string namespaceName, bool preserveSpace, int public void Atomize(XmlNameTable nameTable) { - if (LocalName != null) + if (LocalName is not null) LocalName = nameTable.Add(LocalName); - if (NamespaceName != null) + if (NamespaceName is not null) NamespaceName = nameTable.Add(NamespaceName); } @@ -173,8 +173,8 @@ public override bool Equals(object obj) Debug.Assert(obj is InternalWhitespaceRule); InternalWhitespaceRule that = obj as InternalWhitespaceRule; - Debug.Assert(LocalName != null && that.LocalName != null); - Debug.Assert(NamespaceName != null && that.NamespaceName != null); + Debug.Assert(LocalName is not null && that.LocalName is not null); + Debug.Assert(NamespaceName is not null && that.NamespaceName is not null); // string == operator compares object references first and if they are not the same compares contents // of the compared strings. As a result we do not have to cast strings to objects to force reference diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs index dabcd574c47751..e09f0ca4ae8b22 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs @@ -17,12 +17,12 @@ internal class WhitespaceRuleReader : XmlWrappingReader public static XmlReader CreateReader(XmlReader baseReader, WhitespaceRuleLookup wsRules) { - if (wsRules == null) + if (wsRules is null) { return baseReader; // There is no rules to process } XmlReaderSettings readerSettings = baseReader.Settings; - if (readerSettings != null) + if (readerSettings is not null) { if (readerSettings.IgnoreWhitespace) { @@ -32,12 +32,12 @@ public static XmlReader CreateReader(XmlReader baseReader, WhitespaceRuleLookup else { XmlTextReader txtReader = baseReader as XmlTextReader; - if (txtReader != null && txtReader.WhitespaceHandling == WhitespaceHandling.None) + if (txtReader is not null && txtReader.WhitespaceHandling == WhitespaceHandling.None) { return baseReader; // V1 XmlTextReader that strips all WS } XmlTextReaderImpl txtReaderImpl = baseReader as XmlTextReaderImpl; - if (txtReaderImpl != null && txtReaderImpl.WhitespaceHandling == WhitespaceHandling.None) + if (txtReaderImpl is not null && txtReaderImpl.WhitespaceHandling == WhitespaceHandling.None) { return baseReader; // XmlTextReaderImpl that strips all WS } @@ -47,7 +47,7 @@ public static XmlReader CreateReader(XmlReader baseReader, WhitespaceRuleLookup private WhitespaceRuleReader(XmlReader baseReader, WhitespaceRuleLookup wsRules) : base(baseReader) { - Debug.Assert(wsRules != null); + Debug.Assert(wsRules is not null); _val = null; _stkStrip = new BitStack(); @@ -63,7 +63,7 @@ private WhitespaceRuleReader(XmlReader baseReader, WhitespaceRuleLookup wsRules) /// public override string Value { - get { return (_val == null) ? base.Value : _val; } + get { return (_val is null) ? base.Value : _val; } } /// @@ -110,7 +110,7 @@ public override bool Read() goto case XmlNodeType.Whitespace; // If whitespace was cached, then prepend it to text or CDATA value - if (ws != null) + if (ws is not null) _val = string.Concat(ws, base.Value); // Preserve adjacent whitespace @@ -128,7 +128,7 @@ public override bool Read() if (_shouldStrip) { // Save whitespace until it can be determined whether it will be stripped - if (ws == null) + if (ws is null) ws = base.Value; else ws = string.Concat(ws, base.Value); 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 0a4560db11d681..0c7e845d698a3b 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 @@ -68,7 +68,7 @@ private void SetWrappedWriter(XmlRawWriter writer) { // If new writer might remove itself from pipeline, have it callback on this method when its ready to go IRemovableWriter removable = writer as IRemovableWriter; - if (removable != null) + if (removable is not null) removable.OnRemoveWriterEvent = SetWrappedWriter; _wrapped = writer; @@ -86,7 +86,7 @@ public override void WriteStartAttribute(string prefix, string localName, string { int hashCode; int idx = 0; - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(localName is not null && localName.Length != 0 && prefix is not null && ns is not null); // Compute hashcode based on first letter of the localName hashCode = (1 << ((int)localName[0] & 31)); @@ -143,8 +143,8 @@ internal override void WriteNamespaceDeclaration(string prefix, string ns) /// public override void WriteString(string text) { - Debug.Assert(text != null); - Debug.Assert(_arrAttrs != null && _numEntries != 0); + Debug.Assert(text is not null); + Debug.Assert(_arrAttrs is not null && _numEntries != 0); EnsureAttributeCache(); _arrAttrs[_numEntries++].Init(text); } @@ -156,7 +156,7 @@ public override void WriteString(string text) public override void WriteValue(object value) { Debug.Assert(value is XmlAtomicValue, "value should always be an XmlAtomicValue, as XmlAttributeCache is only used by XmlQueryOutput"); - Debug.Assert(_arrAttrs != null && _numEntries != 0); + Debug.Assert(_arrAttrs is not null && _numEntries != 0); EnsureAttributeCache(); _arrAttrs[_numEntries++].Init((XmlAtomicValue)value); } @@ -234,7 +234,7 @@ private void FlushAttributes() // If localName is null, then this is a duplicate attribute that has been marked as "deleted" localName = _arrAttrs[idx].LocalName; - if (localName != null) + if (localName is not null) { string prefix = _arrAttrs[idx].Prefix; string ns = _arrAttrs[idx].Namespace; @@ -246,7 +246,7 @@ private void FlushAttributes() { string text = _arrAttrs[idx].Text; - if (text != null) + if (text is not null) _wrapped.WriteString(text); else _wrapped.WriteValue(_arrAttrs[idx].Value); @@ -262,7 +262,7 @@ private void FlushAttributes() } // Notify event listener that attributes have been flushed - if (_onRemove != null) + if (_onRemove is not null) _onRemove(_wrapped); } @@ -319,7 +319,7 @@ public void Init(XmlAtomicValue value) public bool IsDuplicate(string localName, string ns, int hashCode) { // If attribute is not marked as deleted - if (_localName != null) + if (_localName is not null) { // And if hash codes match, if (_hashCode == hashCode) @@ -353,7 +353,7 @@ public bool IsDuplicate(string localName, string ns, int hashCode) /// private void EnsureAttributeCache() { - if (_arrAttrs == null) + if (_arrAttrs is null) { // Create caching array _arrAttrs = new AttrNameVal[DefaultCacheSize]; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs index 224747d64468e1..cad3c51e3b92d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs @@ -152,7 +152,7 @@ internal static XmlCollation Create(string collationLiteral) // Disregard unrecognized options. internal static XmlCollation Create(string collationLiteral, bool throwOnError) { - Debug.Assert(collationLiteral != null, "collation literal should not be null"); + Debug.Assert(collationLiteral is not null, "collation literal should not be null"); if (collationLiteral == XmlReservedNs.NsCollCodePoint) { @@ -277,7 +277,7 @@ internal static XmlCollation Create(string collationLiteral, bool throwOnError) } // new cultureinfo based on alternate sorting option - if (sort != null && cultInfo != null) + if (sort is not null && cultInfo is not null) { string cultName = cultInfo.Name; switch (sort) @@ -349,7 +349,7 @@ public override bool Equals(object obj) } XmlCollation that = obj as XmlCollation; - return that != null && + return that is not null && _options == that._options && object.Equals(_cultInfo, that._cultInfo); } @@ -357,7 +357,7 @@ public override bool Equals(object obj) public override int GetHashCode() { int hashCode = _options; - if (_cultInfo != null) + if (_cultInfo is not null) { hashCode ^= _cultInfo.GetHashCode(); } @@ -375,9 +375,9 @@ public override int GetHashCode() internal void GetObjectData(BinaryWriter writer) { // NOTE: For CultureInfo we serialize only LCID. It seems to suffice for our purposes. - Debug.Assert(_cultInfo == null || _cultInfo.Equals(new CultureInfo(_cultInfo.Name)), + Debug.Assert(_cultInfo is null || _cultInfo.Equals(new CultureInfo(_cultInfo.Name)), "Cannot serialize CultureInfo correctly"); - writer.Write(_cultInfo != null ? _cultInfo.Name : LOCALE_CURRENT); + writer.Write(_cultInfo is not null ? _cultInfo.Name : LOCALE_CURRENT); writer.Write(_options); } @@ -413,7 +413,7 @@ internal CultureInfo Culture get { // Use default thread culture if this.cultinfo = null - if (_cultInfo == null) + if (_cultInfo is null) return CultureInfo.CurrentCulture; return _cultInfo; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs index 1707aa9d560999..e1694383095ab1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs @@ -30,7 +30,7 @@ public XmlExtensionFunction Bind(string name, string namespaceUri, int numArgs, { XmlExtensionFunction func; - if (_funcCached == null) + if (_funcCached is null) _funcCached = new XmlExtensionFunction(); // If the extension function already exists in the table, then binding has already been performed @@ -192,14 +192,14 @@ public void Bind() { if (methSearch.Name.Equals(_name, comparison) && (_numArgs == -1 || methSearch.GetParameters().Length == _numArgs)) { - if (methMatch != null) + if (methMatch is not null) throw new XslTransformException(/*[XT_037]*/SR.XmlIl_AmbiguousExtensionMethod, _namespaceUri, _name, _numArgs.ToString(CultureInfo.InvariantCulture)); methMatch = methSearch; } } - if (methMatch == null) + if (methMatch is null) { methods = _objectType.GetMethods(_flags | BindingFlags.NonPublic); foreach (MethodInfo methSearch in methods) @@ -273,7 +273,7 @@ private void Bind(MethodInfo meth) /// public object Invoke(object extObj, object[] args) { - Debug.Assert(_meth != null, "Must call Bind() before calling Invoke."); + Debug.Assert(_meth is not null, "Must call Bind() before calling Invoke."); Debug.Assert(args.Length == _argClrTypes.Length, "Mismatched number of actual and formal arguments."); try @@ -300,7 +300,7 @@ public object Invoke(object extObj, object[] args) public override bool Equals(object other) { XmlExtensionFunction that = other as XmlExtensionFunction; - Debug.Assert(that != null); + Debug.Assert(that is not null); // Compare name, argument count, object type, and binding flags return (_hashCode == that._hashCode && _name == that._name && _namespaceUri == that._namespaceUri && diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs index 840a8bf7cbcf0f..a607f94c988caa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs @@ -86,7 +86,7 @@ public static IList NavigatorsToItems(IList listNavig { // Check to see if the navigator cache implements IList IList listItems = listNavigators as IList; - if (listItems != null) + if (listItems is not null) return listItems; // Create XmlQueryNodeSequence, which does implement IList @@ -97,7 +97,7 @@ public static IList ItemsToNavigators(IList listItems { // Check to see if the navigator cache implements IList IList listNavs = listItems as IList; - if (listNavs != null) + if (listNavs is not null) return listNavs; // Create XmlQueryNodeSequence, which does implement IList diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs index ee3756d2e7afe4..4306a72ee8f300 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs @@ -157,7 +157,7 @@ private static XmlNavigatorFilter[] CreateTypeFilters() /// public static XmlNavigatorFilter Create(XPathNodeType nodeType) { - Debug.Assert(s_typeFilters[(int)nodeType] != null); + Debug.Assert(s_typeFilters[(int)nodeType] is not null); return s_typeFilters[(int)nodeType]; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs index 08b530c4aba3c4..d316a56684bba5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs @@ -28,7 +28,7 @@ internal struct XmlNavigatorStack /// public void Push(XPathNavigator nav) { - if (_stkNav == null) + if (_stkNav is null) { _stkNav = new XPathNavigator[InitialStackSize]; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs index c2d3b2e3781d1d..00f11994094a5b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs @@ -64,10 +64,10 @@ internal XmlQueryContext(XmlQueryRuntime runtime, object defaultDataSource, XmlR // Load the default document from a Uri _defaultDataSource = GetDataSource(defaultDataSource as string, null); - if (_defaultDataSource == null) + if (_defaultDataSource is null) throw new XslTransformException(SR.XmlIl_UnknownDocument, defaultDataSource as string); } - else if (defaultDataSource != null) + else if (defaultDataSource is not null) { _defaultDataSource = ConstructDocument(defaultDataSource, null, null); } @@ -92,7 +92,7 @@ public XmlNameTable QueryNameTable /// public XmlNameTable DefaultNameTable { - get { return _defaultDataSource != null ? _defaultDataSource.NameTable : null; } + get { return _defaultDataSource is not null ? _defaultDataSource.NameTable : null; } } /// @@ -103,7 +103,7 @@ public XPathNavigator DefaultDataSource get { // Throw exception if there is no default data source to return - if (_defaultDataSource == null) + if (_defaultDataSource is null) throw new XslTransformException(SR.XmlIl_NoDefaultDocument, string.Empty); return _defaultDataSource; @@ -124,17 +124,17 @@ public XPathNavigator GetDataSource(string uriRelative, string uriBase) try { // If the data source has already been retrieved, then return the data source from the cache. - uriResolvedBase = (uriBase != null) ? _dataSources.ResolveUri(null, uriBase) : null; + uriResolvedBase = (uriBase is not null) ? _dataSources.ResolveUri(null, uriBase) : null; uriResolved = _dataSources.ResolveUri(uriResolvedBase, uriRelative); - if (uriResolved != null) + if (uriResolved is not null) nav = _dataSourceCache[uriResolved] as XPathNavigator; - if (nav == null) + if (nav is null) { // Get the entity from the resolver and ensure it is cached as a document input = _dataSources.GetEntity(uriResolved, null, null); - if (input != null) + if (input is not null) { // Construct a document from the entity and add the document to the cache nav = ConstructDocument(input, uriRelative, uriResolved); @@ -164,12 +164,12 @@ public XPathNavigator GetDataSource(string uriRelative, string uriBase) /// private XPathNavigator ConstructDocument(object dataSource, string uriRelative, Uri uriResolved) { - Debug.Assert(dataSource != null, "GetType() below assumes dataSource is not null"); + Debug.Assert(dataSource is not null, "GetType() below assumes dataSource is not null"); Stream stream = dataSource as Stream; - if (stream != null) + if (stream is not null) { // Create document from stream - XmlReader reader = _readerSettings.CreateReader(stream, uriResolved != null ? uriResolved.ToString() : null); + XmlReader reader = _readerSettings.CreateReader(stream, uriResolved is not null ? uriResolved.ToString() : null); try { @@ -190,13 +190,13 @@ private XPathNavigator ConstructDocument(object dataSource, string uriRelative, } else if (dataSource is IXPathNavigable) { - if (_wsRules != null) + if (_wsRules is not null) throw new XslTransformException(SR.XmlIl_CantStripNav, string.Empty); return (dataSource as IXPathNavigable).CreateNavigator(); } - Debug.Assert(uriRelative != null, "Relative URI should not be null"); + Debug.Assert(uriRelative is not null, "Relative URI should not be null"); throw new XslTransformException(SR.XmlIl_CantResolveEntity, uriRelative, dataSource.GetType().ToString()); } @@ -211,7 +211,7 @@ private XPathNavigator ConstructDocument(object dataSource, string uriRelative, /// public object GetParameter(string localName, string namespaceUri) { - return (_argList != null) ? _argList.GetParam(localName, namespaceUri) : null; + return (_argList is not null) ? _argList.GetParam(localName, namespaceUri) : null; } @@ -224,7 +224,7 @@ public object GetParameter(string localName, string namespaceUri) /// public object GetLateBoundObject(string namespaceUri) { - return (_argList != null) ? _argList.GetExtensionObject(namespaceUri) : null; + return (_argList is not null) ? _argList.GetExtensionObject(namespaceUri) : null; } /// @@ -234,11 +234,11 @@ public bool LateBoundFunctionExists(string name, string namespaceUri) { object instance; - if (_argList == null) + if (_argList is null) return false; instance = _argList.GetExtensionObject(namespaceUri); - if (instance == null) + if (instance is null) return false; return new XmlExtensionFunction(name, namespaceUri, -1, instance.GetType(), XmlQueryRuntime.LateBoundFlags).CanBind(); @@ -257,12 +257,12 @@ public IList InvokeXsltLateBoundFunction(string name, string namespac object objRet; // Get external object instance from argument list (throw if either the list or the instance doesn't exist) - instance = (_argList != null) ? _argList.GetExtensionObject(namespaceUri) : null; - if (instance == null) + instance = (_argList is not null) ? _argList.GetExtensionObject(namespaceUri) : null; + if (instance is null) throw new XslTransformException(SR.XmlIl_UnknownExtObj, namespaceUri); // Bind to a method on the instance object - if (_extFuncsLate == null) + if (_extFuncsLate is null) _extFuncsLate = new XmlExtensionFunctionTable(); // Bind to the instance, looking for a matching method (throws if no matching method) @@ -309,7 +309,7 @@ public IList InvokeXsltLateBoundFunction(string name, string namespac objRet = extFunc.Invoke(instance, objActualArgs); // 2. Convert to IList - if (objRet == null && extFunc.ClrReturnType == XsltConvert.VoidType) + if (objRet is null && extFunc.ClrReturnType == XsltConvert.VoidType) return XmlQueryNodeSequence.Empty; return (IList)_runtime.ChangeTypeXsltResult(XmlQueryTypeFactory.ItemS, objRet); @@ -325,9 +325,9 @@ public IList InvokeXsltLateBoundFunction(string name, string namespac /// public void OnXsltMessageEncountered(string message) { - XsltMessageEncounteredEventHandler onMessage = (_argList != null) ? _argList.xsltMessageEncountered : null; + XsltMessageEncounteredEventHandler onMessage = (_argList is not null) ? _argList.xsltMessageEncountered : null; - if (onMessage != null) + if (onMessage is not null) onMessage(this, new XmlILQueryEventArgs(message)); } } 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 83387e02926fcc..124d75878852b5 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 @@ -97,7 +97,7 @@ internal XmlRawWriter Writer { // If new writer might remove itself from pipeline, have it callback on this method when it's ready to go IRemovableWriter removable = value as IRemovableWriter; - if (removable != null) + if (removable is not null) removable.OnRemoveWriterEvent = SetWrappedWriter; _xwrt = value; @@ -160,7 +160,7 @@ public override void WriteDocType(string name, string pubid, string sysid, strin /// 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 is not null && localName is not null && localName.Length != 0 && ns is not null, "Invalid argument"); Debug.Assert(ValidateNames.ValidateName(prefix, localName, ns, XPathNodeType.Element, ValidateNames.Flags.All), "Name validation failed"); // Xml state transitions @@ -173,7 +173,7 @@ public override void WriteStartElement(string prefix, string localName, string n WriteNamespaceDeclarationUnchecked(prefix, ns); // Cache attributes in order to detect duplicates - if (_attrCache == null) + if (_attrCache is null) _attrCache = new XmlAttributeCache(); _attrCache.Init(Writer); @@ -220,7 +220,7 @@ public override void WriteFullEndElement() /// public override void WriteStartAttribute(string prefix, string localName, string ns) { - Debug.Assert(prefix != null && localName != null && ns != null, "Invalid argument"); + Debug.Assert(prefix is not null && localName is not null && ns is not null, "Invalid argument"); if (prefix.Length == 5 && prefix == "xmlns") { @@ -446,7 +446,7 @@ public void EndTree() public void WriteStartElementUnchecked(string prefix, string localName, string ns) { Debug.Assert(_xstate == XmlState.WithinContent, "WriteStartElement cannot be called in the " + _xstate + " state."); - if (_nsmgr != null) _nsmgr.PushScope(); + if (_nsmgr is not null) _nsmgr.PushScope(); Writer.WriteStartElement(prefix, localName, ns); //reset when enter element _usedPrefixes.Clear(); @@ -487,7 +487,7 @@ public void WriteEndElementUnchecked(string prefix, string localName, string ns) Writer.WriteEndElement(prefix, localName, ns); _xstate = XmlState.WithinContent; _depth--; - if (_nsmgr != null) _nsmgr.PopScope(); + if (_nsmgr is not null) _nsmgr.PopScope(); } /// @@ -537,7 +537,7 @@ public void WriteEndAttributeUnchecked() /// public void WriteNamespaceDeclarationUnchecked(string prefix, string ns) { - Debug.Assert(prefix != null && ns != null); + Debug.Assert(prefix is not null && ns is not null); Debug.Assert(_xstate == XmlState.EnumAttrs, "WriteNamespaceDeclaration cannot be called in the " + _xstate + " state."); // xmlns:foo="" is illegal @@ -550,7 +550,7 @@ public void WriteNamespaceDeclarationUnchecked(string prefix, string ns) return; } - if (_nsmgr == null) + if (_nsmgr is null) { // If namespace manager has no namespaces, then xmlns="" is in scope by default if (ns.Length == 0 && prefix.Length == 0) @@ -698,11 +698,11 @@ public void WriteStartAttributeComputed(XmlQualifiedName name) public void WriteNamespaceDeclaration(string prefix, string ns) { string nsExisting; - Debug.Assert(prefix != null && ns != null); + Debug.Assert(prefix is not null && ns is not null); ConstructInEnumAttrs(XPathNodeType.Namespace); - if (_nsmgr == null) + if (_nsmgr is null) { // If namespace manager has not yet been created, then there is no possibility of conflict WriteNamespaceDeclarationUnchecked(prefix, ns); @@ -720,7 +720,7 @@ public void WriteNamespaceDeclaration(string prefix, string ns) // prefix, ns, nsExisting --> Look for xmlns:foo="uri", found xmlns:foo="uri2" // If the prefix is mapped to a uri, - if (nsExisting != null) + if (nsExisting is not null) { // Then throw an error except if the prefix trying to redefine is already used if (_usedPrefixes.ContainsKey(prefix)) @@ -745,7 +745,7 @@ public void WriteNamespaceDeclaration(string prefix, string ns) /// public void WriteStartNamespace(string prefix) { - Debug.Assert(prefix != null, "Invalid argument"); + Debug.Assert(prefix is not null, "Invalid argument"); // Handle namespace attributes that are not sent directly to WriteNamespaceDeclaration ConstructInEnumAttrs(XPathNodeType.Namespace); @@ -898,7 +898,7 @@ public void XsltCopyOf(XPathNavigator navigator) { RtfNavigator navRtf = navigator as RtfNavigator; - if (navRtf != null) + if (navRtf is not null) { // Copy Rtf navRtf.CopyToWriter(this); @@ -979,7 +979,7 @@ private void AddNamespace(string prefix, string ns) /// private void WriteString(string text, bool disableOutputEscaping) { - Debug.Assert(text != null, "Invalid argument"); + Debug.Assert(text is not null, "Invalid argument"); // Xml state transitions switch (_xstate) @@ -1036,7 +1036,7 @@ private void CopyNode(XPathNavigator navigator) { XPathNodeType nodeType; int depthStart = _depth; - Debug.Assert(navigator != null); + Debug.Assert(navigator is not null); while (true) { @@ -1146,7 +1146,7 @@ private bool StartCopy(XPathNavigator navigator, bool callChk) { // Do not allow namespaces to be copied after attributes XmlAttributeCache attrCache = Writer as XmlAttributeCache; - if (attrCache != null && attrCache.Count != 0) + if (attrCache is not null && attrCache.Count != 0) throw new XslTransformException(SR.XmlIl_NmspAfterAttr, string.Empty); WriteNamespaceDeclaration(navigator.LocalName, navigator.Value); @@ -1318,7 +1318,7 @@ private void WriteCachedNamespaces() while (_cntNmsp != 0) { // Output each prefix->ns mapping pair - Debug.Assert(_nsmgr != null); + Debug.Assert(_nsmgr is not null); _cntNmsp--; _nsmgr.GetNamespaceDeclaration(_cntNmsp, out prefix, out ns); Writer.WriteNamespaceDeclaration(prefix, ns); @@ -1353,7 +1353,7 @@ private string CheckAttributePrefix(string prefix, string ns) Debug.Assert(prefix.Length != 0 && ns.Length != 0); // Ensure that this attribute's prefix does not conflict with previously declared prefixes in this scope - if (_nsmgr == null) + if (_nsmgr is null) { // If namespace manager has no namespaces, then there is no possibility of conflict WriteNamespaceDeclarationUnchecked(prefix, ns); @@ -1367,7 +1367,7 @@ private string CheckAttributePrefix(string prefix, string ns) if (nsExisting != ns) { // Then if the prefix is already mapped, - if (nsExisting != null) + if (nsExisting is not null) { // Then there is a conflict that must be resolved by finding another prefix // Always find a new prefix, even if the conflict didn't occur in the current scope @@ -1398,12 +1398,12 @@ 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 is not null && ns is not null && ns.Length != 0); - if (_conflictPrefixes == null) + if (_conflictPrefixes is null) _conflictPrefixes = new Dictionary(16); - if (_nsmgr == null) + if (_nsmgr is null) { _nsmgr = new XmlNamespaceManager(_runtime.NameTable); _nsmgr.PushScope(); @@ -1411,7 +1411,7 @@ private string RemapPrefix(string prefix, string ns, bool isElemPrefix) // Rule #1: If another in-scope prefix is already mapped to "ns", then use that genPrefix = _nsmgr.LookupPrefix(ns); - if (genPrefix != null) + if (genPrefix is not null) { // Can't use an empty prefix for an attribute if (isElemPrefix || genPrefix.Length != 0) @@ -1542,7 +1542,7 @@ private string EnsureValidName(string prefix, string localName, string ns, XPath private void PushElementNames(string prefix, string localName, string ns) { // Push the name parts onto a stack - if (_stkNames == null) + if (_stkNames is null) _stkNames = new Stack(15); _stkNames.Push(prefix); @@ -1555,7 +1555,7 @@ private void PushElementNames(string prefix, string localName, string ns) /// private void PopElementNames(out string prefix, out string localName, out string ns) { - Debug.Assert(_stkNames != null); + Debug.Assert(_stkNames is not null); ns = _stkNames.Pop(); localName = _stkNames.Pop(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index 0575e803f3ddf7..f21f5ef437b33b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -77,35 +77,35 @@ public sealed class XmlQueryRuntime /// internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) { - Debug.Assert(data != null); + Debug.Assert(data is not null); string[] names = data.Names; Int32Pair[] filters = data.Filters; WhitespaceRuleLookup wsRules; int i; // Early-Bound Library Objects - wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null; + wsRules = (data.WhitespaceRules is not null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null; _ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules); _xsltLib = null; _earlyInfo = data.EarlyBound; - _earlyObjects = (_earlyInfo != null) ? new object[_earlyInfo.Length] : null; + _earlyObjects = (_earlyInfo is not null) ? new object[_earlyInfo.Length] : null; // Global variables and parameters _globalNames = data.GlobalNames; - _globalValues = (_globalNames != null) ? new object[_globalNames.Length] : null; + _globalValues = (_globalNames is not null) ? new object[_globalNames.Length] : null; // Names _nameTableQuery = _ctxt.QueryNameTable; _atomizedNames = null; - if (names != null) + if (names is not null) { // Atomize all names in "nameTableQuery". Use names from the default data source's // name table when possible. XmlNameTable nameTableDefault = _ctxt.DefaultNameTable; _atomizedNames = new string[names.Length]; - if (nameTableDefault != _nameTableQuery && nameTableDefault != null) + if (nameTableDefault != _nameTableQuery && nameTableDefault is not null) { // Ensure that atomized names from the default data source are added to the // name table used in this query @@ -125,7 +125,7 @@ internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlR // Name filters _filters = null; - if (filters != null) + if (filters is not null) { // Construct name filters. Each pair of integers in the filters[] array specifies the // (localName, namespaceUri) of the NameFilter to be created. @@ -211,10 +211,10 @@ public void DebugSetGlobalValue(string name, object value) /// public object DebugGetXsltValue(IList seq) { - if (seq != null && seq.Count == 1) + if (seq is not null && seq.Count == 1) { XPathItem item = seq[0] as XPathItem; - if (item != null && !item.IsNode) + if (item is not null && !item.IsNode) { return item.TypedValue; } @@ -250,7 +250,7 @@ public XsltLibrary XsltFunctions { get { - if (_xsltLib == null) + if (_xsltLib is null) { _xsltLib = new XsltLibrary(this); } @@ -266,10 +266,10 @@ public XsltLibrary XsltFunctions public object GetEarlyBoundObject(int index) { object obj; - Debug.Assert(_earlyObjects != null && index < _earlyObjects.Length, "Early bound object does not exist"); + Debug.Assert(_earlyObjects is not null && index < _earlyObjects.Length, "Early bound object does not exist"); obj = _earlyObjects[index]; - if (obj == null) + if (obj is null) { // Early-bound object does not yet exist, so create it now obj = _earlyInfo[index].CreateObject(); @@ -284,7 +284,7 @@ public object GetEarlyBoundObject(int index) /// public bool EarlyBoundFunctionExists(string name, string namespaceUri) { - if (_earlyInfo == null) + if (_earlyInfo is null) return false; for (int idx = 0; idx < _earlyInfo.Length; idx++) @@ -306,7 +306,7 @@ public bool EarlyBoundFunctionExists(string name, string namespaceUri) /// public bool IsGlobalComputed(int index) { - return _globalValues[index] != null; + return _globalValues[index] is not null; } /// @@ -347,7 +347,7 @@ public XmlNameTable NameTable /// public string GetAtomizedName(int index) { - Debug.Assert(_atomizedNames != null); + Debug.Assert(_atomizedNames is not null); return _atomizedNames[index]; } @@ -356,7 +356,7 @@ public string GetAtomizedName(int index) /// public XmlNavigatorFilter GetNameFilter(int index) { - Debug.Assert(_filters != null); + Debug.Assert(_filters is not null); return _filters[index]; } @@ -409,7 +409,7 @@ public XmlQualifiedName ParseTagName(string tagName, string ns) /// internal void ParseTagName(string tagName, int idxPrefixMappings, out string prefix, out string localName, out string ns) { - Debug.Assert(_prefixMappingsList != null); + Debug.Assert(_prefixMappingsList is not null); // Parse the tagName as a prefix, localName pair ValidateNames.ParseQNameThrow(tagName, out prefix, out localName); @@ -426,7 +426,7 @@ internal void ParseTagName(string tagName, int idxPrefixMappings, out string pre } // Throw exception if prefix could not be resolved - if (ns == null) + if (ns is null) { // Check for mappings that are always in-scope if (prefix.Length == 0) @@ -476,7 +476,7 @@ public bool IsQNameEqual(XPathNavigator navigator, int indexLocalName, int index /// internal XmlQueryType GetXmlType(int idxType) { - Debug.Assert(_types != null); + Debug.Assert(_types is not null); return _types[idxType]; } @@ -553,7 +553,7 @@ internal object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type { // Node or Rtf RtfNavigator rtf = item as RtfNavigator; - if (rtf != null) + if (rtf is not null) value = rtf.ToNavigator(); else value = new XPathArrayIterator((IList)value); @@ -591,7 +591,7 @@ public object ChangeTypeXsltResult(int indexType, object value) /// internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) { - if (value == null) + if (value is null) throw new XslTransformException(SR.Xslt_ItemNull, string.Empty); switch (xmlType.TypeCode) @@ -613,7 +613,7 @@ internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) XPathArrayIterator iter = value as XPathArrayIterator; // Special-case XPathArrayIterator in order to avoid copies - if (iter != null && iter.AsList is XmlQueryNodeSequence) + if (iter is not null && iter.AsList is XmlQueryNodeSequence) { value = iter.AsList as XmlQueryNodeSequence; } @@ -623,7 +623,7 @@ internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) XmlQueryNodeSequence seq = new XmlQueryNodeSequence(); IList list = value as IList; - if (list != null) + if (list is not null) { for (int i = 0; i < list.Count; i++) seq.Add(EnsureNavigator(list[i])); @@ -680,7 +680,7 @@ internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) // Support IXPathNavigable and XPathNavigator navigable = value as IXPathNavigable; - if (navigable != null) + if (navigable is not null) { if (value is XPathNavigator) value = new XmlQueryNodeSequence((XPathNavigator)value); @@ -708,7 +708,7 @@ private static XPathNavigator EnsureNavigator(object value) { XPathNavigator nav = value as XPathNavigator; - if (nav == null) + if (nav is null) throw new XslTransformException(SR.Xslt_ItemNull, string.Empty); return nav; @@ -807,7 +807,7 @@ private XmlQueryType CreateXmlType(XPathItem item) { // Rtf RtfNavigator rtf = item as RtfNavigator; - if (rtf != null) + if (rtf is not null) return XmlQueryTypeFactory.Node; // Node @@ -816,13 +816,13 @@ private XmlQueryType CreateXmlType(XPathItem item) { case XPathNodeType.Root: case XPathNodeType.Element: - if (nav.XmlType == null) + if (nav.XmlType is null) return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), XmlSchemaComplexType.UntypedAnyType, false); return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, nav.SchemaInfo.SchemaElement.IsNillable); case XPathNodeType.Attribute: - if (nav.XmlType == null) + if (nav.XmlType is null) return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), DatatypeImplementation.UntypedAtomicType, false); return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, false); @@ -845,7 +845,7 @@ private XmlQueryType CreateXmlType(XPathItem item) /// public XmlCollation GetCollation(int index) { - Debug.Assert(_collations != null); + Debug.Assert(_collations is not null); return _collations[index]; } @@ -880,7 +880,7 @@ public IList DocOrderDistinct(IList seq) return seq; XmlQueryNodeSequence nodeSeq = (XmlQueryNodeSequence)seq; - if (nodeSeq == null) + if (nodeSeq is null) nodeSeq = new XmlQueryNodeSequence(seq); return nodeSeq.DocOrderDistinct(_docOrderCmp); @@ -908,17 +908,17 @@ public bool FindIndex(XPathNavigator context, int indexId, out XmlILIndex index) { XPathNavigator navRoot; ArrayList docIndexes; - Debug.Assert(context != null); + Debug.Assert(context is not null); // Get root of document navRoot = context.Clone(); navRoot.MoveToRoot(); // Search pre-existing indexes in order to determine whether the specified index has already been created - if (_indexes != null && indexId < _indexes.Length) + if (_indexes is not null && indexId < _indexes.Length) { docIndexes = (ArrayList)_indexes[indexId]; - if (docIndexes != null) + if (docIndexes is not null) { // Search for an index defined over the specified document for (int i = 0; i < docIndexes.Count; i += 2) @@ -945,14 +945,14 @@ public void AddNewIndex(XPathNavigator context, int indexId, XmlILIndex index) { XPathNavigator navRoot; ArrayList docIndexes; - Debug.Assert(context != null); + Debug.Assert(context is not null); // Get root of document navRoot = context.Clone(); navRoot.MoveToRoot(); // Ensure that a slot exists for the new index - if (_indexes == null) + if (_indexes is null) { _indexes = new ArrayList[indexId + 4]; } @@ -965,7 +965,7 @@ public void AddNewIndex(XPathNavigator context, int indexId, XmlILIndex index) } docIndexes = (ArrayList)_indexes[indexId]; - if (docIndexes == null) + if (docIndexes is null) { docIndexes = new ArrayList(); _indexes[indexId] = docIndexes; @@ -1079,7 +1079,7 @@ public void ThrowException(string text) /// internal static XPathNavigator SyncToNavigator(XPathNavigator navigatorThis, XPathNavigator navigatorThat) { - if (navigatorThis == null || !navigatorThis.MoveTo(navigatorThat)) + if (navigatorThis is null || !navigatorThis.MoveTo(navigatorThat)) return navigatorThat.Clone(); return navigatorThis; @@ -1093,7 +1093,7 @@ public static int OnCurrentNodeChanged(XPathNavigator currentNode) IXmlLineInfo lineInfo = currentNode as IXmlLineInfo; // In case of a namespace node, check whether it is inherited or locally defined - if (lineInfo != null && !(currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode))) + if (lineInfo is not null && !(currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode))) { OnCurrentNodeChanged2(currentNode.BaseURI, lineInfo.LineNumber, lineInfo.LinePosition); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs index b43ecb531ad8d8..9bdc8253188b05 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs @@ -38,7 +38,7 @@ public class XmlQuerySequence : IList, System.Collections.IList /// public static XmlQuerySequence CreateOrReuse(XmlQuerySequence seq) { - if (seq != null) + if (seq is not null) { seq.Clear(); return seq; @@ -53,7 +53,7 @@ public static XmlQuerySequence CreateOrReuse(XmlQuerySequence seq) /// public static XmlQuerySequence CreateOrReuse(XmlQuerySequence seq, T item) { - if (seq != null) + if (seq is not null) { seq.Clear(); seq.Add(item); @@ -429,7 +429,7 @@ public sealed class XmlQueryItemSequence : XmlQuerySequence /// public static XmlQueryItemSequence CreateOrReuse(XmlQueryItemSequence seq) { - if (seq != null) + if (seq is not null) { seq.Clear(); return seq; @@ -444,7 +444,7 @@ public static XmlQueryItemSequence CreateOrReuse(XmlQueryItemSequence seq) /// public static XmlQueryItemSequence CreateOrReuse(XmlQueryItemSequence seq, XPathItem item) { - if (seq != null) + if (seq is not null) { seq.Clear(); seq.Add(item); @@ -503,7 +503,7 @@ public sealed class XmlQueryNodeSequence : XmlQuerySequence, ILi /// public static XmlQueryNodeSequence CreateOrReuse(XmlQueryNodeSequence seq) { - if (seq != null) + if (seq is not null) { seq.Clear(); return seq; @@ -518,7 +518,7 @@ public static XmlQueryNodeSequence CreateOrReuse(XmlQueryNodeSequence seq) /// public static XmlQueryNodeSequence CreateOrReuse(XmlQueryNodeSequence seq, XPathNavigator navigator) { - if (seq != null) + if (seq is not null) { seq.Clear(); seq.Add(navigator); @@ -599,7 +599,7 @@ public XmlQueryNodeSequence DocOrderDistinct(IComparer comparer) int iEach, iDistinct; XPathNavigator[] sortArray; - if (_docOrderDistinct != null) + if (_docOrderDistinct is not null) return _docOrderDistinct; if (Count <= 1) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs index 0cd1738310d883..b9acd6816a0909 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs @@ -41,7 +41,7 @@ internal class XmlQueryStaticData /// public XmlQueryStaticData(XmlWriterSettings defaultWriterSettings, IList whitespaceRules, StaticDataManager staticData) { - Debug.Assert(defaultWriterSettings != null && staticData != null); + Debug.Assert(defaultWriterSettings is not null && staticData is not null); _defaultWriterSettings = defaultWriterSettings; _whitespaceRules = whitespaceRules; _names = staticData.Names; @@ -203,7 +203,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) _defaultWriterSettings.GetObjectData(dataWriter); // IList whitespaceRules; - if (_whitespaceRules == null) + if (_whitespaceRules is null) { dataWriter.Write(0); } @@ -217,7 +217,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // string[] names; - if (_names == null) + if (_names is null) { dataWriter.Write(0); } @@ -231,7 +231,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // StringPair[][] prefixMappingsList; - if (_prefixMappingsList == null) + if (_prefixMappingsList is null) { dataWriter.Write(0); } @@ -250,7 +250,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // Int32Pair[] filters; - if (_filters == null) + if (_filters is null) { dataWriter.Write(0); } @@ -265,7 +265,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // XmlQueryType[] types; - if (_types == null) + if (_types is null) { dataWriter.Write(0); } @@ -279,7 +279,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // XmlCollation[] collations; - if (_collations == null) + if (_collations is null) { dataWriter.Write(0); } @@ -293,7 +293,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // string[] globalNames; - if (_globalNames == null) + if (_globalNames is null) { dataWriter.Write(0); } @@ -307,7 +307,7 @@ public void GetObjectData(out byte[] data, out Type[] ebTypes) } // EarlyBoundInfo[] earlyBound; - if (_earlyBound == null) + if (_earlyBound is null) { dataWriter.Write(0); ebTypes = null; @@ -443,8 +443,8 @@ public XmlQueryDataWriter(Stream output) : base(output) { } /// public void WriteStringQ(string value) { - Write(value != null); - if (value != null) + Write(value is not null); + if (value is not null) { Write(value); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs index fe94d265fb8855..c51869de1c7454 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs @@ -29,7 +29,7 @@ public int Priority // All linked keys have same priority XmlSortKey key = this; - while (key != null) + while (key is not null) { key._priority = value; key = key._nextKey; @@ -44,7 +44,7 @@ public int Priority /// public XmlSortKey AddSortKey(XmlSortKey sortKey) { - if (_nextKey != null) + if (_nextKey is not null) { // Add to end of list--this is not it _nextKey.AddSortKey(sortKey); @@ -65,10 +65,10 @@ public XmlSortKey AddSortKey(XmlSortKey sortKey) /// protected int BreakSortingTie(XmlSortKey that) { - if (_nextKey != null) + if (_nextKey is not null) { // There are multiple keys, so break tie using next key - Debug.Assert(_nextKey != null && that._nextKey != null); + Debug.Assert(_nextKey is not null && that._nextKey is not null); return _nextKey.CompareTo(that._nextKey); } @@ -83,7 +83,7 @@ protected int BreakSortingTie(XmlSortKey that) protected int CompareToEmpty(object obj) { XmlEmptySortKey that = obj as XmlEmptySortKey; - Debug.Assert(that != null && !(this is XmlEmptySortKey)); + Debug.Assert(that is not null && !(this is XmlEmptySortKey)); return that.IsEmptyGreatest ? -1 : 1; } @@ -120,7 +120,7 @@ public override int CompareTo(object obj) { XmlEmptySortKey that = obj as XmlEmptySortKey; - if (that == null) + if (that is null) { // Empty compared to non-empty Debug.Assert(obj is XmlSortKey); @@ -151,7 +151,7 @@ public override int CompareTo(object obj) XmlDecimalSortKey that = obj as XmlDecimalSortKey; int cmp; - if (that == null) + if (that is null) return CompareToEmpty(obj); cmp = decimal.Compare(_decVal, that._decVal); @@ -180,7 +180,7 @@ public override int CompareTo(object obj) { XmlIntegerSortKey that = obj as XmlIntegerSortKey; - if (that == null) + if (that is null) return CompareToEmpty(obj); if (_longVal == that._longVal) @@ -208,7 +208,7 @@ public override int CompareTo(object obj) { XmlIntSortKey that = obj as XmlIntSortKey; - if (that == null) + if (that is null) return CompareToEmpty(obj); if (_intVal == that._intVal) @@ -244,18 +244,18 @@ public override int CompareTo(object obj) XmlStringSortKey that = obj as XmlStringSortKey; int idx, cntCmp, result; - if (that == null) + if (that is null) return CompareToEmpty(obj); // Compare either using SortKey.Compare or byte arrays - if (_sortKey != null) + if (_sortKey is not null) { - Debug.Assert(that._sortKey != null, "Both keys must have non-null sortKey field"); + Debug.Assert(that._sortKey is not null, "Both keys must have non-null sortKey field"); result = SortKey.Compare(_sortKey, that._sortKey); } else { - Debug.Assert(_sortKeyBytes != null && that._sortKeyBytes != null, "Both keys must have non-null sortKeyBytes field"); + Debug.Assert(_sortKeyBytes is not null && that._sortKeyBytes is not null, "Both keys must have non-null sortKeyBytes field"); cntCmp = (_sortKeyBytes.Length < that._sortKeyBytes.Length) ? _sortKeyBytes.Length : that._sortKeyBytes.Length; for (idx = 0; idx < cntCmp; idx++) @@ -322,7 +322,7 @@ public override int CompareTo(object obj) { XmlDoubleSortKey that = obj as XmlDoubleSortKey; - if (that == null) + if (that is null) { // Compare to empty sequence if (_isNaN) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs index 29fc8c76b2dff6..8a761a52305c45 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs @@ -29,7 +29,7 @@ public struct XmlSortKeyAccumulator /// public void Create() { - if (_keys == null) + if (_keys is null) _keys = new XmlSortKey[DefaultSortKeyCount]; _pos = 0; @@ -97,7 +97,7 @@ private void AppendSortKey(XmlSortKey key) // Ensure that sort will be stable by setting index of key key.Priority = _pos; - if (_keys[_pos] == null) + if (_keys[_pos] is null) _keys[_pos] = key; else _keys[_pos].AddSortKey(key); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs index 4673961e6b7b20..c3bdf17033784a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs @@ -25,7 +25,7 @@ private TokenInfo() [Conditional("DEBUG")] public void AssertSeparator(bool isSeparator) { - Debug.Assert(isSeparator == (formatString != null), "AssertSeparator"); + Debug.Assert(isSeparator == (formatString is not null), "AssertSeparator"); } // Creates a TokenInfo for a separator token. @@ -196,7 +196,7 @@ public string FormatSequence(IList val) } } - if (_tokens == null) + if (_tokens is null) { // Special case of the default format for (int idx = 0; idx < val.Count; idx++) @@ -225,7 +225,7 @@ public string FormatSequence(IList val) TokenInfo periodicSeparator = 2 < cFormats ? _tokens[cFormats - 2] : s_defaultSeparator; TokenInfo periodicFormat = 0 < cFormats ? _tokens[cFormats - 1] : s_defaultFormat; - if (prefix != null) + if (prefix is not null) { prefix.AssertSeparator(true); sb.Append(prefix.formatString, prefix.startIdx, prefix.length); @@ -249,7 +249,7 @@ public string FormatSequence(IList val) FormatItem(sb, val[i], thisFormat.startChar, thisFormat.length); } - if (suffix != null) + if (suffix is not null) { suffix.AssertSeparator(true); sb.Append(suffix.formatString, suffix.startIdx, suffix.length); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs index 26b902273ee77e..b93bb21fe76c90 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs @@ -161,7 +161,7 @@ public static XPathNavigator ToNode(XPathItem item) } RtfNavigator rtf = item as RtfNavigator; - if (rtf != null) + if (rtf is not null) return rtf.ToNavigator(); return (XPathNavigator)item; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs index 2d45c788d2f9dc..b536e03ea76e5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs @@ -119,7 +119,7 @@ public static string NormalizeSpace(string value) else if (value[idx] != ' ' || idxSpace == idx) { // Space was previous character or this is a non-space character - if (sb == null) + if (sb is null) sb = new StringBuilder(value.Length); else sb.Append(' '); @@ -140,7 +140,7 @@ public static string NormalizeSpace(string value) } } - if (sb == null) + if (sb is null) { // Check for string that is entirely composed of whitespace if (idxStart == idx) return string.Empty; @@ -248,7 +248,7 @@ public static string BaseUri(XPathNavigator navigator) public static string OuterXml(XPathNavigator navigator) { RtfNavigator rtf = navigator as RtfNavigator; - if (rtf == null) + if (rtf is null) { return navigator.OuterXml; } @@ -345,9 +345,9 @@ public static double MSNumber(IList value) } } - Debug.Assert(stringValue != null); + Debug.Assert(stringValue is not null); double d; - if (XmlConvert.TryToDouble(stringValue, out d) != null) + if (XmlConvert.TryToDouble(stringValue, out d) is not null) { d = double.NaN; } @@ -517,7 +517,7 @@ public static string MSNamespaceUri(string name, XPathNavigator currentNode) return string.Empty; } string ns = currentNode.LookupNamespace(prefix); - if (ns != null) + if (ns is not null) { return ns; } @@ -535,7 +535,7 @@ public static string MSNamespaceUri(string name, XPathNavigator currentNode) private static CultureInfo GetCultureInfo(string lang) { - Debug.Assert(lang != null); + Debug.Assert(lang is not null); if (lang.Length == 0) { return CultureInfo.CurrentCulture; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs index ccf04eb9d09b5a..5b7b74f26a57f2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs @@ -72,14 +72,14 @@ internal static class XsltMethods public static MethodInfo GetMethod(Type className, string methName) { MethodInfo methInfo = className.GetMethod(methName); - Debug.Assert(methInfo != null, "Method " + className.Name + "." + methName + " not found"); + Debug.Assert(methInfo is not null, "Method " + className.Name + "." + methName + " not found"); return methInfo; } public static MethodInfo GetMethod(Type className, string methName, params Type[] args) { MethodInfo methInfo = className.GetMethod(methName, args); - Debug.Assert(methInfo != null, "Method " + className.Name + "." + methName + " not found"); + Debug.Assert(methInfo is not null, "Method " + className.Name + "." + methName + " not found"); return methInfo; } } @@ -110,7 +110,7 @@ public string FormatMessage(string res, IList args) public int CheckScriptNamespace(string nsUri) { // Check that extension and script namespaces do not clash - if (_runtime.ExternalContext.GetLateBoundObject(nsUri) != null) + if (_runtime.ExternalContext.GetLateBoundObject(nsUri) is not null) { throw new XslTransformException(SR.Xslt_ScriptAndExtensionClash, nsUri); } @@ -126,14 +126,14 @@ public bool ElementAvailable(XmlQualifiedName name) // Spec: http://www.w3.org/TR/xslt#function-function-available public bool FunctionAvailable(XmlQualifiedName name) { - if (_functionsAvail == null) + if (_functionsAvail is null) { _functionsAvail = new HybridDictionary(); } else { object obj = _functionsAvail[name]; - if (obj != null) + if (obj is not null) { return (bool)obj; } @@ -170,7 +170,7 @@ private bool FunctionAvailableHelper(XmlQualifiedName name) public int RegisterDecimalFormat(XmlQualifiedName name, string infinitySymbol, string nanSymbol, string characters) { - if (_decimalFormats == null) + if (_decimalFormats is null) { _decimalFormats = new Dictionary(); } @@ -196,7 +196,7 @@ private DecimalFormat CreateDecimalFormat(string infinitySymbol, string nanSymbo public double RegisterDecimalFormatter(string formatPicture, string infinitySymbol, string nanSymbol, string characters) { - if (_decimalFormatters == null) + if (_decimalFormatters is null) { _decimalFormatters = new List(); } @@ -214,7 +214,7 @@ public string FormatNumberStatic(double value, double decimalFormatterIndex) public string FormatNumberDynamic(double value, string formatPicture, XmlQualifiedName decimalFormatName, string errorMessageName) { DecimalFormat format; - if (_decimalFormats == null || !_decimalFormats.TryGetValue(decimalFormatName, out format)) + if (_decimalFormats is null || !_decimalFormats.TryGetValue(decimalFormatName, out format)) { throw new XslTransformException(SR.Xslt_NoDecimalFormat, errorMessageName); } @@ -243,14 +243,14 @@ internal static int LangToLcidInternal(string lang, bool forwardCompatibility, I { int lcid = InvariantCultureLcid; - if (lang != null) + if (lang is not null) { // The value of the 'lang' attribute must be a non-empty nmtoken if (lang.Length == 0) { if (!forwardCompatibility) { - if (errorHelper != null) + if (errorHelper is not null) { errorHelper.ReportError(SR.Xslt_InvalidAttrValue, nameof(lang), lang); } @@ -271,7 +271,7 @@ internal static int LangToLcidInternal(string lang, bool forwardCompatibility, I { if (!forwardCompatibility) { - if (errorHelper != null) + if (errorHelper is not null) { errorHelper.ReportError(SR.Xslt_InvalidLanguage, lang); } @@ -292,14 +292,14 @@ internal static string LangToNameInternal(string lang, bool forwardCompatibility { string cultName = InvariantCultureName; - if (lang != null) + if (lang is not null) { // The value of the 'lang' attribute must be a non-empty nmtoken if (lang.Length == 0) { if (!forwardCompatibility) { - if (errorHelper != null) + if (errorHelper is not null) { errorHelper.ReportError(/*[XT_032]*/SR.Xslt_InvalidAttrValue, nameof(lang), lang); } @@ -320,7 +320,7 @@ internal static string LangToNameInternal(string lang, bool forwardCompatibility { if (!forwardCompatibility) { - if (errorHelper != null) + if (errorHelper is not null) { errorHelper.ReportError(/*[XT_033]*/SR.Xslt_InvalidLanguage, lang); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs index d0b14c713385a6..d96efcf199a0c5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs @@ -81,7 +81,7 @@ public static void Validate(ISourceLineInfo lineInfo) // Returns file path for local and network URIs. Used for PDB generating and error reporting. public static string GetFileName(string uriString) { - Debug.Assert(uriString != null); + Debug.Assert(uriString is not null); Uri? uri; if (uriString.Length != 0 && diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs index 0be02ffcb2f7bd..85ab29713aed76 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs @@ -73,7 +73,7 @@ public virtual void StartBuild() [return: NotNullIfNotNull("result")] public virtual QilNode? EndBuild(QilNode? result) { - if (result == null) + if (result is null) { // special door to clean builder state in exception handlers _inTheBuild = false; return result; @@ -116,7 +116,7 @@ public virtual QilNode Operator(XPathOperator op, QilNode? left, QilNode? right) Debug.Assert(op != XPathOperator.Unknown); XPathOperatorGroup opGroup = s_operatorGroup[(int)op]; - Debug.Assert((opGroup != XPathOperatorGroup.Negate && right != null) || (opGroup == XPathOperatorGroup.Negate && right == null)); + Debug.Assert((opGroup != XPathOperatorGroup.Negate && right is not null) || (opGroup == XPathOperatorGroup.Negate && right is null)); switch (opGroup) { @@ -300,7 +300,7 @@ private QilNode ArithmeticOperator(XPathOperator op, QilNode left, QilNode right private QilNode UnionOperator(XPathOperator op, QilNode? left, QilNode right) { Debug.Assert(op == XPathOperator.Union); - if (left == null) + if (left is null) { return _f.EnsureNodeSet(right); } @@ -357,20 +357,20 @@ private QilNode BuildAxisFilter(QilNode qilAxis, XPathAxis xpathAxis, XPathNodeT { QilLoop filter = (QilLoop)qilAxis; filter.Body = _f.And(filter.Body, - name != null && nsUri != null ? _f.Eq(_f.NameOf(itr), _f.QName(name, nsUri)) : // ns:bar || bar - nsUri != null ? _f.Eq(_f.NamespaceUriOf(itr), _f.String(nsUri)) : // ns:* - name != null ? _f.Eq(_f.LocalNameOf(itr), _f.String(name)) : // *:foo - /*name == nsUri == null*/ _f.True() // * + name is not null && nsUri is not null ? _f.Eq(_f.NameOf(itr), _f.QName(name, nsUri)) : // ns:bar || bar + nsUri is not null ? _f.Eq(_f.NamespaceUriOf(itr), _f.String(nsUri)) : // ns:* + name is not null ? _f.Eq(_f.LocalNameOf(itr), _f.String(name)) : // *:foo + /*name == nsUri is null*/ _f.True() // * ); return filter; } } return _f.Filter(itr = _f.For(qilAxis), - name != null && nsUri != null ? _f.Eq(_f.NameOf(itr), _f.QName(name, nsUri)) : // ns:bar || bar - nsUri != null ? _f.Eq(_f.NamespaceUriOf(itr), _f.String(nsUri)) : // ns:* - name != null ? _f.Eq(_f.LocalNameOf(itr), _f.String(name)) : // *:foo - /*name == nsUri == null*/ _f.True() // * + name is not null && nsUri is not null ? _f.Eq(_f.NameOf(itr), _f.QName(name, nsUri)) : // ns:bar || bar + nsUri is not null ? _f.Eq(_f.NamespaceUriOf(itr), _f.String(nsUri)) : // ns:* + name is not null ? _f.Eq(_f.LocalNameOf(itr), _f.String(name)) : // *:foo + /*name == nsUri is null*/ _f.True() // * ); } @@ -432,7 +432,7 @@ private QilNode BuildAxis(XPathAxis xpathAxis, XPathNodeType nodeType, string? n public virtual QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? prefix, string? name) { - string? nsUri = prefix == null ? null : _environment.ResolvePrefix(prefix); + string? nsUri = prefix is null ? null : _environment.ResolvePrefix(prefix); return BuildAxis(xpathAxis, nodeType, nsUri, name); } @@ -851,7 +851,7 @@ public QilNode Fixup(QilNode inExpr, QilIterator current, QilNode? last) QilDepthChecker.Check(inExpr); _current = current; _last = last; - Debug.Assert(current != null); + Debug.Assert(current is not null); _justCount = false; _environment = null; numCurrent = numPosition = numLast = 0; @@ -864,7 +864,7 @@ public QilNode Fixup(QilNode inExpr, QilIterator current, QilNode? last) public QilNode Fixup(QilNode inExpr, IXPathEnvironment environment) { - Debug.Assert(environment != null); + Debug.Assert(environment is not null); QilDepthChecker.Check(inExpr); _justCount = false; _current = null; @@ -894,11 +894,11 @@ protected override QilNode VisitUnknown(QilNode unknown) numCurrent++; if (!_justCount) { - if (_environment != null) + if (_environment is not null) { unknown = _environment.GetCurrent()!; } - else if (_current != null) + else if (_current is not null) { unknown = _current; } @@ -909,11 +909,11 @@ protected override QilNode VisitUnknown(QilNode unknown) numPosition++; if (!_justCount) { - if (_environment != null) + if (_environment is not null) { unknown = _environment.GetPosition(); } - else if (_current != null) + else if (_current is not null) { // position can be in predicate only and in predicate current olways an iterator unknown = f.XsltConvert(f.PositionOf((QilIterator)_current), T.DoubleX); @@ -925,18 +925,18 @@ protected override QilNode VisitUnknown(QilNode unknown) numLast++; if (!_justCount) { - if (_environment != null) + if (_environment is not null) { unknown = _environment.GetLast(); } - else if (_current != null) + else if (_current is not null) { - Debug.Assert(_last != null); + Debug.Assert(_last is not null); unknown = _last; } } } - Debug.Assert(unknown != null); + Debug.Assert(unknown is not null); return unknown; } @@ -970,7 +970,7 @@ void SetStopVisitMark(QilNode n, bool stop) { } } bool GetStopVisitMark(QilNode n) { - return XsltAnnotation.Write(n)[0] != null; + return XsltAnnotation.Write(n)[0] is not null; } #endif } @@ -986,7 +986,7 @@ internal class FunctionInfo public FunctionInfo(T id, int minArgs, int maxArgs, XmlTypeCode[]? argTypes) { - Debug.Assert(maxArgs == 0 || maxArgs == Infinity || argTypes != null && argTypes.Length == maxArgs); + Debug.Assert(maxArgs == 0 || maxArgs == Infinity || argTypes is not null && argTypes.Length == maxArgs); this.id = id; this.minArgs = minArgs; this.maxArgs = maxArgs; @@ -1044,7 +1044,7 @@ public void CastArguments(IList args, string name, XPathQilFactory f) } else { - Debug.Assert(args.Count == 0 || argTypes != null); + Debug.Assert(args.Count == 0 || argTypes is not null); for (int i = 0; i < args.Count; i++) { if (argTypes![i] == XmlTypeCode.Node && f.CannotBeNodeSet(args[i])) 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 6b2e67550a4c13..6b0ed5b35a2c92 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 @@ -81,7 +81,7 @@ private static void AppendTrimmed(StringBuilder sb, string value, int startIndex internal string? MarkOutError() { - if (queryString == null || queryString.Trim(' ').Length == 0) + if (queryString is null || queryString.Trim(' ').Length == 0) { return null; } @@ -107,7 +107,7 @@ internal override string FormatDetailedMessage() string message = Message; string? error = MarkOutError(); - if (error != null && error.Length > 0) + if (error is not null && error.Length > 0) { if (message.Length > 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs index f1b073d2e95aff..b6e857e0c9d7ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs @@ -64,13 +64,13 @@ internal class XPathContext { // Methods that deal with XPath context. Xslt.QilGenerator calls these method as well: public static QilNode GetCurrentNode(QilTuple context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); Debug.Assert(GetTuple(context).For.Type == QilNodeType.For); return GetTuple(context).For; } public static QilNode GetCurrentPosition(QilFactory f, QilTuple context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); if (context.Where.Type != QilNodeType.True) { Debug.Assert(context.For.Type == QilNodeType.For); // convert context (1) --> (2) @@ -87,7 +87,7 @@ public static QilNode GetLastPosition(QilFactory f, QilTuple context) { } public static QilTuple GetTuple(QilTuple context) { - Debug.Assert(context != null); + Debug.Assert(context is not null); if (context.For.Type == QilNodeType.Let) { Debug.Assert(context.Where.Type == QilNodeType.True); Debug.Assert(context.Return.Type == QilNodeType.OldTuple); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs index 5208144246306e..748a10b969dae1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs @@ -24,8 +24,8 @@ internal class XPathParser public Node Parse(XPathScanner scanner, IXPathBuilder builder, LexKind endLex) { - Debug.Assert(_scanner == null && _builder == null); - Debug.Assert(scanner != null && builder != null); + Debug.Assert(_scanner is null && _builder is null); + Debug.Assert(scanner is not null && builder is not null); Node result = default(Node); _scanner = scanner; @@ -40,7 +40,7 @@ public Node Parse(XPathScanner scanner, IXPathBuilder builder, LexKind end } catch (XPathCompileException e) { - if (e.queryString == null) + if (e.queryString is null) { e.queryString = scanner.Source; PopPosInfo(out e.startChar, out e.endChar); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs index 879e8d997c7c2e..12c549aa9c4bad 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs @@ -46,43 +46,43 @@ public bool IsAnyType(QilNode n) [Conditional("DEBUG")] public void CheckNode(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSingleton && n.XmlType.IsNode, "Must be a singleton node"); + Debug.Assert(n is not null && n.XmlType!.IsSingleton && n.XmlType.IsNode, "Must be a singleton node"); } [Conditional("DEBUG")] public void CheckNodeSet(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsNode, "Must be a node-set"); + Debug.Assert(n is not null && n.XmlType!.IsNode, "Must be a node-set"); } [Conditional("DEBUG")] public void CheckNodeNotRtf(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSingleton && n.XmlType.IsNode && n.XmlType.IsNotRtf, "Must be a singleton node and not an Rtf"); + Debug.Assert(n is not null && n.XmlType!.IsSingleton && n.XmlType.IsNode && n.XmlType.IsNotRtf, "Must be a singleton node and not an Rtf"); } [Conditional("DEBUG")] public void CheckString(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.StringX), "Must be a singleton string"); + Debug.Assert(n is not null && n.XmlType!.IsSubtypeOf(T.StringX), "Must be a singleton string"); } [Conditional("DEBUG")] public void CheckStringS(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.StringXS), "Must be a sequence of strings"); + Debug.Assert(n is not null && n.XmlType!.IsSubtypeOf(T.StringXS), "Must be a sequence of strings"); } [Conditional("DEBUG")] public void CheckDouble(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.DoubleX), "Must be a singleton Double"); + Debug.Assert(n is not null && n.XmlType!.IsSubtypeOf(T.DoubleX), "Must be a singleton Double"); } [Conditional("DEBUG")] public void CheckBool(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.BooleanX), "Must be a singleton Bool"); + Debug.Assert(n is not null && n.XmlType!.IsSubtypeOf(T.BooleanX), "Must be a singleton Bool"); } // Return true if inferred type of the given expression is never a subtype of T.NodeS @@ -308,7 +308,7 @@ public QilNode ConvertToNodeSet(QilNode n) public QilNode EnsureNodeSet(QilNode n) { QilNode? result = TryEnsureNodeSet(n); - if (result == null) + if (result is null) { throw new XPathCompileException(SR.XPath_NodeSetExpected); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs index b78f74bdf67bba..2a010e9e063fbf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs @@ -75,7 +75,7 @@ public XPathScanner(string xpathExpr) : this(xpathExpr, 0) { } public XPathScanner(string xpathExpr, int startFrom) { - Debug.Assert(xpathExpr != null); + Debug.Assert(xpathExpr is not null); _xpathExpr = xpathExpr; _kind = LexKind.Unknown; SetSourceIndex(startFrom); @@ -115,7 +115,7 @@ public string Name get { Debug.Assert(_kind == LexKind.Name); - Debug.Assert(_name != null); + Debug.Assert(_name is not null); return _name; } } @@ -125,7 +125,7 @@ public string Prefix get { Debug.Assert(_kind == LexKind.Name); - Debug.Assert(_prefix != null); + Debug.Assert(_prefix is not null); return _prefix; } } @@ -150,7 +150,7 @@ public string StringValue get { Debug.Assert(_kind == LexKind.String); - Debug.Assert(_stringValue != null); + Debug.Assert(_stringValue is not null); return _stringValue; } } @@ -421,8 +421,8 @@ private bool CheckOperator(bool star) } else { - Debug.Assert(_prefix != null); - Debug.Assert(_name != null); + Debug.Assert(_prefix is not null); + Debug.Assert(_name is not null); if (_prefix.Length != 0 || _name.Length > 3) return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs index b23f0a37223a74..7da85f245f6824 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs @@ -2019,7 +2019,7 @@ public void ShiftRight(int cbit) public int CompareTo(object? obj) { - Debug.Assert(obj != null); + Debug.Assert(obj is not null); BigInteger bi = (BigInteger)obj; AssertValid(); bi.AssertValid(); @@ -3109,7 +3109,7 @@ public static unsafe double StringToDouble(string s) LGetRight: Debug.Assert(ch == '.'); ch = *pch++; - if (pchFirstDig == null) + if (pchFirstDig is null) { // Count fractional leading zeros (e.g. six zeros in '0.0000005') while (ch == '0') @@ -3143,11 +3143,11 @@ public static unsafe double StringToDouble(string s) return 0.0; } - Debug.Assert(pchFirstDig != null); + Debug.Assert(pchFirstDig is not null); if (expAdj == 0) { - // Assert(StrRChrW(pchFirstDig, &pchFirstDig[numDig], '.') == null); + // Assert(StrRChrW(pchFirstDig, &pchFirstDig[numDig], '.') is null); // Detect special case where number is an integer if (numDig <= 9) @@ -3167,7 +3167,7 @@ public static unsafe double StringToDouble(string s) { // The number has a fractional part Debug.Assert(expAdj < 0); - // Assert(StrRChrW(pchStart, pch, '.') != null); + // Assert(StrRChrW(pchStart, pch, '.') is not null); } // Limit to 50 digits (double is only precise up to 17 or so digits) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs index bb0adf57e3d907..b2b0f3125694f0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs @@ -26,7 +26,7 @@ internal class XmlILCommand /// public XmlILCommand(ExecuteDelegate delExec, XmlQueryStaticData staticData) { - Debug.Assert(delExec != null && staticData != null); + Debug.Assert(delExec is not null && staticData is not null); _delExec = delExec; _staticData = staticData; } @@ -46,7 +46,7 @@ public XmlQueryStaticData StaticData /// provided name. The results are output to the provided XmlWriter. /// public override void Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter results) { - if (results == null) + if (results is null) throw new ArgumentNullException(nameof(results)); Execute(contextDocument, dataSources, argumentList, results, false); @@ -58,7 +58,7 @@ public override void Execute(XmlReader contextDocument, XmlResolver dataSources, /// provided name. The results are output to the provided TextWriter. /// public override void Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, TextWriter results) { - if (results == null) + if (results is null) throw new ArgumentNullException(nameof(results)); Execute(contextDocument, dataSources, argumentList, XmlWriter.Create(results, this.staticData.DefaultWriterSettings), true); @@ -70,7 +70,7 @@ public override void Execute(XmlReader contextDocument, XmlResolver dataSources, /// provided name. The results are output to the provided Stream. /// public override void Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, Stream results) { - if (results == null) + if (results is null) throw new ArgumentNullException(nameof(results)); Execute(contextDocument, dataSources, argumentList, XmlWriter.Create(results, this.staticData.DefaultWriterSettings), true); @@ -104,8 +104,8 @@ public void Execute(object defaultDocument, XmlResolver? dataSources, XsltArgume // Try to extract a RawWriter XmlWellFormedWriter? wellFormedWriter = writer as XmlWellFormedWriter; - if (wellFormedWriter != null && - wellFormedWriter.RawWriter != null && + if (wellFormedWriter is not null && + wellFormedWriter.RawWriter is not null && wellFormedWriter.WriteState == WriteState.Start && wellFormedWriter.Settings.ConformanceLevel != ConformanceLevel.Document) { @@ -129,10 +129,10 @@ public void Execute(object defaultDocument, XmlResolver? dataSources, XsltArgume /// private void Execute(object defaultDocument, XmlResolver? dataSources, XsltArgumentList? argumentList, XmlSequenceWriter results) { - Debug.Assert(results != null); + Debug.Assert(results is not null); // Ensure that dataSources is always non-null - if (dataSources == null) + if (dataSources is null) dataSources = XmlNullResolver.Singleton; _delExec(new XmlQueryRuntime(_staticData, defaultDocument, dataSources, argumentList, results)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs index 16d19e0e1a84cb..060b7af3ba2937 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs @@ -77,7 +77,7 @@ public XmlILGenerator() bool useLRE = ( !_qil.IsDebug && - (typeBldr == null) + (typeBldr is null) #if DEBUG && !XmlILTrace.IsEnabled // Dump assembly to disk; can't do this when using LRE #endif @@ -108,7 +108,7 @@ public XmlILGenerator() #endif // Create module in which methods will be generated - if (typeBldr != null) + if (typeBldr is not null) { _module = new XmlILModule(typeBldr); } @@ -129,8 +129,8 @@ public XmlILGenerator() // Create metadata for the root expression // public void Root() - Debug.Assert(_qil.Root != null); - XmlILMethodAttributes methAttrs = (_qil.Root.SourceLine == null) ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; + Debug.Assert(_qil.Root is not null); + XmlILMethodAttributes methAttrs = (_qil.Root.SourceLine is null) ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; MethodInfo methRoot = _module.DefineMethod("Root", typeof(void), Array.Empty(), Array.Empty(), methAttrs); // Declare all early bound function objects @@ -161,7 +161,7 @@ public XmlILGenerator() ); // Create static constructor that initializes XmlQueryStaticData instance at runtime - if (typeBldr != null) + if (typeBldr is not null) { CreateTypeInitializer(staticData); @@ -209,7 +209,7 @@ private void CreateFunctionMetadata(IList funcList) paramTypes[arg] = XmlILTypeHelper.GetStorageType(ndParam.XmlType!); // Get the name of each argument - if (ndParam.DebugName != null) + if (ndParam.DebugName is not null) paramNames[arg] = ndParam.DebugName; } @@ -226,7 +226,7 @@ private void CreateFunctionMetadata(IList funcList) } // Create the method metadata - methAttrs = ndFunc.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; + methAttrs = ndFunc.SourceLine is null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; methInfo = _module!.DefineMethod(ndFunc.DebugName!, typReturn, paramTypes, paramNames, methAttrs); for (int arg = 0; arg < ndFunc.Arguments.Count; arg++) @@ -253,7 +253,7 @@ private void CreateGlobalValueMetadata(IList globalList) { // public T GlobalValue() typReturn = XmlILTypeHelper.GetStorageType(ndRef.XmlType!); - methAttrs = ndRef.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; + methAttrs = ndRef.SourceLine is null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; methInfo = _module!.DefineMethod(ndRef.DebugName!.ToString(), typReturn, Array.Empty(), Array.Empty(), methAttrs); // Annotate function with MethodBuilder @@ -299,7 +299,7 @@ private void CreateHelperFunctions() _helper!.MethodBegin(meth, null, false); - // if (navigatorThis != null && navigatorThis.MoveTo(navigatorThat)) + // if (navigatorThis is not null && navigatorThis.MoveTo(navigatorThat)) // return navigatorThis; lblClone = _helper.DefineLabel(); _helper.Emit(OpCodes.Ldarg_0); @@ -334,7 +334,7 @@ private void EvaluateGlobalValues(IList iterList) { // Get MethodInfo that evaluates the global value and discard its return value methInfo = XmlILAnnotation.Write(ndIter).FunctionBinding; - Debug.Assert(methInfo != null, "MethodInfo for global value should have been created previously."); + Debug.Assert(methInfo is not null, "MethodInfo for global value should have been created previously."); _helper!.LoadQueryRuntime(); _helper.Call(methInfo); @@ -369,7 +369,7 @@ public void CreateTypeInitializer(XmlQueryStaticData staticData) _helper.Call(XmlILMethods.InitializeArray); _helper.Emit(OpCodes.Stsfld, fldData); - if (ebTypes != null) + if (ebTypes is not null) { // Type[] types = new Type[s_ebTypes.Length]; LocalBuilder locTypes = _helper.DeclareLocal("$$$types", typeof(Type[])); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs index b140fc567eac50..2f30a69c5c1073 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs @@ -48,13 +48,13 @@ private XmlQualifiedNameTest(string? name, string? ns, bool exclude) : base(name /// public static XmlQualifiedNameTest New(string? name, string? ns) { - if (ns == null && name == null) + if (ns is null && name is null) { return Wildcard; } else { - return new XmlQualifiedNameTest(name == null ? wildcard : name, ns == null ? wildcard : ns, false); + return new XmlQualifiedNameTest(name is null ? wildcard : name, ns is null ? wildcard : ns, false); } } @@ -158,7 +158,7 @@ public static XmlQualifiedNameTest New(XmlQualifiedName name) { /// Construct new "exclusion" name test /// public static XmlQualifiedNameTest New(string ns, bool exclude) { - Debug.Assert(ns != null); + Debug.Assert(ns is not null); return new XmlQualifiedNameTest(wildcard, ns, exclude); } @@ -177,7 +177,7 @@ public XmlQualifiedNameTest Intersect(XmlQualifiedNameTest other) { if ((object)namespaceFrom == (object)nameFrom) { return namespaceFrom; } - else if (namespaceFrom == null || nameFrom == null) { + else if (namespaceFrom is null || nameFrom is null) { return null; } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs index 0883d4d5846aa5..b714ff6828ca1f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs @@ -169,7 +169,7 @@ public bool NeverSubtypeOf(XmlQueryType baseType) /// public bool Equals(XmlQueryType? that) { - if (that == null) + if (that is null) return false; // Check cardinality and DocOrderDistinct property @@ -322,7 +322,7 @@ public override bool Equals(object? obj) { XmlQueryType? that = obj as XmlQueryType; - if (that == null) + if (that is null) return false; return Equals(that); @@ -343,7 +343,7 @@ public override int GetHashCode() unchecked { - if (schemaType != null) + if (schemaType is not null) hash += (hash << 7) ^ schemaType.GetHashCode(); hash += (hash << 7) ^ (int)NodeKinds; @@ -496,7 +496,7 @@ private bool IsSubtypeOfItemType(XmlQueryType baseType) // If type codes are not the same, then IsSubtypeOf can return true *only* if "baseType" is a built-in type XmlSchemaType builtInType = XmlSchemaType.GetBuiltInSimpleType(baseType.TypeCode); - if (builtInType != null && baseSchemaType != builtInType) + if (builtInType is not null && baseSchemaType != builtInType) return false; // Now check whether TypeCode is derived from baseType.TypeCode diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs index ce571c9932ec52..c2e23b0e1ff349 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs @@ -501,8 +501,8 @@ public static XmlQueryType Create(XmlTypeCode code, XmlQualifiedNameTest nameTes /// private ItemType(XmlTypeCode code, XmlQualifiedNameTest nameTest, XmlSchemaType schemaType, bool isNillable, bool isStrict, bool isNotRtf) { - Debug.Assert(nameTest != null, "nameTest cannot be null"); - Debug.Assert(schemaType != null, "schemaType cannot be null"); + Debug.Assert(nameTest is not null, "nameTest cannot be null"); + Debug.Assert(schemaType is not null, "schemaType cannot be null"); _code = code; _nameTest = nameTest; _schemaType = schemaType; @@ -735,7 +735,7 @@ public static XmlQueryType Create(List members) /// private ChoiceType(List members) { - Debug.Assert(members != null && members.Count != 1, "ChoiceType must contain a list with 0 or >1 types."); + Debug.Assert(members is not null && members.Count != 1, "ChoiceType must contain a list with 0 or >1 types."); _members = members; @@ -965,7 +965,7 @@ private sealed class SequenceType : XmlQueryType /// public static XmlQueryType Create(XmlQueryType prime, XmlQueryCardinality card) { - Debug.Assert(prime != null, "SequenceType can only modify the cardinality of a non-null XmlQueryType."); + Debug.Assert(prime is not null, "SequenceType can only modify the cardinality of a non-null XmlQueryType."); Debug.Assert(prime.IsSingleton, "Prime type must have cardinality one."); if (prime.TypeCode == XmlTypeCode.None) @@ -1340,7 +1340,7 @@ public XmlQueryType DataOn(XmlQueryType source) { card = XmlQueryCardinality.ZeroOrMore; } else { - if (sourceSchemaType.Datatype == null) { + if (sourceSchemaType.Datatype is null) { // Complex content adds anyAtomicType* if mixed XmlSchemaComplexType complexType = (XmlSchemaComplexType)sourceItem.SchemaType; if (complexType.ContentType == XmlSchemaContentType.Mixed) { @@ -1434,7 +1434,7 @@ public XmlQueryType ChildrenOf(XmlQueryType source, XmlQueryType filter) { itemCard = (AddFilteredPrime(list, UntypedElement, filter) * XmlQueryCardinality.ZeroOrMore); itemCard += AddFilteredPrime(list, Text, filter); } - else if (sourceSchemaType.Datatype != null) { + else if (sourceSchemaType.Datatype is not null) { // Text is the only child node simple type can have itemCard = AddFilteredPrime(list, Text, filter, true) * XmlQueryCardinality.ZeroOrOne; } @@ -1491,7 +1491,7 @@ public XmlQueryType AttributesOf(XmlQueryType source, XmlQueryType filter) { else { // Only complex type can have attributes XmlSchemaComplexType type = sourceSchemaType as XmlSchemaComplexType; - if (type != null) { + if (type is not null) { card |= AddAttributes(list, type.AttributeUses, type.AttributeWildcard, filter); } } @@ -1533,7 +1533,7 @@ public XmlQueryType ParentOf(XmlQueryType source, XmlQueryType filter) { case XmlTypeCode.Comment: case XmlTypeCode.Text: case XmlTypeCode.Element: - if (schemaSet == null) { + if (schemaSet is null) { card |= AddFilteredPrime(list, UntypedDocument, filter) * XmlQueryCardinality.ZeroOrOne; card |= AddFilteredPrime(list, UntypedElement, filter) * XmlQueryCardinality.ZeroOrOne; } @@ -1545,7 +1545,7 @@ public XmlQueryType ParentOf(XmlQueryType source, XmlQueryType filter) { case XmlTypeCode.Namespace: case XmlTypeCode.Attribute: - if (schemaSet == null) { + if (schemaSet is null) { card |= (AddFilteredPrime(list, UntypedElement, filter) * XmlQueryCardinality.ZeroOrOne); } else { @@ -1586,7 +1586,7 @@ public XmlQueryType DescendantsOf(XmlQueryType source, XmlQueryType filter) { if ((filter.NodeKinds & (XmlNodeKindFlags.Element | XmlNodeKindFlags.Text)) != 0) { Dictionary allTypes = new Dictionary(); XmlSchemaType sourceSchemaType = sourceItem.SchemaType; - if (sourceSchemaType == null) { + if (sourceSchemaType is null) { Debug.Assert(sourceItem.TypeCode == XmlTypeCode.Node); sourceSchemaType = XmlSchemaComplexType.AnyType; } @@ -1634,7 +1634,7 @@ public XmlQueryType AncestorsOf(XmlQueryType source, XmlQueryType filter) { case XmlTypeCode.Element: case XmlTypeCode.Namespace: case XmlTypeCode.Attribute: - if (schemaSet == null) { + if (schemaSet is null) { card |= (AddFilteredPrime(list, UntypedDocument, filter) * XmlQueryCardinality.ZeroOrOne) + (AddFilteredPrime(list, UntypedElement, filter) * XmlQueryCardinality.ZeroOrMore); } @@ -1659,7 +1659,7 @@ public XmlQueryType AncestorsOf(XmlQueryType source, XmlQueryType filter) { private XmlQueryCardinality AddAttributes(List list, XmlSchemaObjectTable attributeUses, XmlSchemaAnyAttribute attributeWildcard, XmlQueryType filter) { XmlQueryCardinality card = XmlQueryCardinality.Zero; - if (attributeWildcard != null) { + if (attributeWildcard is not null) { XmlSchemaType attributeSchemaType = attributeWildcard.ProcessContentsCorrect == XmlSchemaContentProcessing.Skip ? DatatypeImplementation.UntypedAtomicType : DatatypeImplementation.AnySimpleType; // wildcard will match more then one attribute @@ -1701,7 +1701,7 @@ private XmlQueryType CreateAttributeType(string ns, bool exclude, XmlSchemaType private XmlQueryCardinality AddDescendantParticle(List list, Dictionary allTypes, XmlSchemaParticle particle, XmlQueryType filter) { XmlQueryCardinality card = XmlQueryCardinality.None; XmlSchemaElement element = particle as XmlSchemaElement; - if (element != null) { + if (element is not null) { // Single element XmlQueryType elementType = CreateElementType(element); @@ -1713,7 +1713,7 @@ private XmlQueryCardinality AddDescendantParticle(List list, Dicti } else { XmlSchemaAny any = particle as XmlSchemaAny; - if (any != null) { + if (any is not null) { // Descendants of any card = AddFilteredPrime(list, Element, filter); } @@ -1743,7 +1743,7 @@ private XmlQueryCardinality AddElementOrTextDescendants(List list, card = AddFilteredPrime(list, UntypedElement, filter) * XmlQueryCardinality.ZeroOrMore; card += AddFilteredPrime(list, Text, filter); } - else if (sourceSchemaType.Datatype != null) { + else if (sourceSchemaType.Datatype is not null) { // Text is the only child node simple content of complext type card = AddFilteredPrime(list, Text, filter, true) * XmlQueryCardinality.ZeroOrOne; } @@ -1782,14 +1782,14 @@ private XmlQueryType CreateElementType(string ns, bool exclude, XmlSchemaType sc private XmlQueryCardinality AddChildParticle(List list, XmlSchemaParticle particle, XmlQueryType filter) { XmlQueryCardinality card = XmlQueryCardinality.None; XmlSchemaElement element = particle as XmlSchemaElement; - if (element != null) { + if (element is not null) { // Single element card = AddFilteredPrime(list, CreateElementType(element), filter); } else { // XmlSchemaAny matches more then one element XmlSchemaAny any = particle as XmlSchemaAny; - if (any != null) { + if (any is not null) { XmlSchemaType elementSchemaType = any.ProcessContentsCorrect == XmlSchemaContentProcessing.Skip ? XmlSchemaComplexType.UntypedAnyType : XmlSchemaComplexType.AnyType; switch (any.NamespaceList.Type) { case NamespaceList.ListType.Set: @@ -1904,7 +1904,7 @@ private XmlQueryType IntersectItemTypes(XmlQueryType left, XmlQueryType right) { // right is a subtype of left return right return right; } - else if (nameTest != null && type != null) { + else if (nameTest is not null && type is not null) { // create a new type return ItemType.Create(left.TypeCode, nameTest, type, isNillable); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs index da6068cb4bf7cd..a648e166f0bf44 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs @@ -35,7 +35,7 @@ internal static string CreateMessage(string res, params string?[]? args) try { - if (args == null) + if (args is null) { message = res; } @@ -48,13 +48,13 @@ internal static string CreateMessage(string res, params string?[]? args) { } - if (message != null) + if (message is not null) { return message; } StringBuilder sb = new StringBuilder(res); - if (args != null && args.Length > 0) + if (args is not null && args.Length > 0) { Debug.Fail("Resource string '" + res + "' was not found"); sb.Append('('); @@ -79,15 +79,15 @@ public override string ToString() { string result = this.GetType().FullName!; string info = FormatDetailedMessage(); - if (info != null && info.Length > 0) + if (info is not null && info.Length > 0) { result += ": " + info; } - if (InnerException != null) + if (InnerException is not null) { result += " ---> " + InnerException.ToString() + Environment.NewLine + " " + CreateMessage(SR.Xml_EndOfInnerExceptionStack); } - if (StackTrace != null) + if (StackTrace is not null) { result += Environment.NewLine + StackTrace; } @@ -157,16 +157,16 @@ internal XslLoadException(CompilerError error) internal void SetSourceLineInfo(ISourceLineInfo? lineInfo) { - Debug.Assert(lineInfo == null || lineInfo.Uri != null); + Debug.Assert(lineInfo is null || lineInfo.Uri is not null); _lineInfo = lineInfo; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("hasLineInfo", _lineInfo != null); + info.AddValue("hasLineInfo", _lineInfo is not null); - if (_lineInfo != null) + if (_lineInfo is not null) { info.AddValue("Uri", _lineInfo.Uri, typeof(string)); info.AddValue("StartLine", _lineInfo.Start.Line, typeof(int)); @@ -178,26 +178,26 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont public override string? SourceUri { - get { return _lineInfo != null ? _lineInfo.Uri : null; } + get { return _lineInfo is not null ? _lineInfo.Uri : null; } } public override int LineNumber { - get { return _lineInfo != null ? _lineInfo.Start.Line : 0; } + get { return _lineInfo is not null ? _lineInfo.Start.Line : 0; } } public override int LinePosition { - get { return _lineInfo != null ? _lineInfo.Start.Pos : 0; } + get { return _lineInfo is not null ? _lineInfo.Start.Pos : 0; } } private static string AppendLineInfoMessage(string message, ISourceLineInfo? lineInfo) { - if (lineInfo != null) + if (lineInfo is not null) { string fileName = SourceLineInfo.GetFileName(lineInfo.Uri!); string lineInfoMessage = CreateMessage(SR.Xml_ErrorFilePosition, fileName, lineInfo.Start.Line.ToString(CultureInfo.InvariantCulture), lineInfo.Start.Pos.ToString(CultureInfo.InvariantCulture)); - if (lineInfoMessage != null && lineInfoMessage.Length > 0) + if (lineInfoMessage is not null && lineInfoMessage.Length > 0) { if (message.Length > 0 && !XmlCharType.IsWhiteSpace(message[message.Length - 1])) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs index 1105a03cae9ced..263a0e572168a1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs @@ -67,7 +67,7 @@ internal class Compiler public Compiler(XsltSettings settings, bool debug, string? scriptAssemblyPath) { - Debug.Assert(CompilerErrorColl == null, "Compiler cannot be reused"); + Debug.Assert(CompilerErrorColl is null, "Compiler cannot be reused"); Settings = settings; IsDebug = settings.IncludeDebugInformation | debug; @@ -79,8 +79,8 @@ public Compiler(XsltSettings settings, bool debug, string? scriptAssemblyPath) public CompilerErrorCollection Compile(object stylesheet, XmlResolver? xmlResolver, out QilExpression qil) { - Debug.Assert(stylesheet != null); - Debug.Assert(Root == null, "Compiler cannot be reused"); + Debug.Assert(stylesheet is not null); + Debug.Assert(Root is null, "Compiler cannot be reused"); new XsltLoader().Load(this, stylesheet, xmlResolver); qil = QilGenerator.CompileStylesheet(this); @@ -132,7 +132,7 @@ public bool SetNsAlias(string ssheetNsUri, string resultNsUri, string? resultPre // Recover by choosing the declaration that occurs later in the stylesheet } NsAliases[ssheetNsUri] = new NsAlias(resultNsUri, resultPrefix, importPrecedence); - return oldNsAlias != null; + return oldNsAlias is not null; } private void MergeWhitespaceRules(Stylesheet sheet) @@ -205,7 +205,7 @@ public static string ConstructQName(string prefix, string localName) public bool ParseQName(string qname, out string prefix, out string localName, IErrorHelper errorHelper) { - Debug.Assert(qname != null); + Debug.Assert(qname is not null); try { ValidateNames.ParseQNameThrow(qname, out prefix, out localName); @@ -222,7 +222,7 @@ public bool ParseQName(string qname, out string prefix, out string localName, IE public bool ParseNameTest(string nameTest, out string? prefix, out string? localName, IErrorHelper errorHelper) { - Debug.Assert(nameTest != null); + Debug.Assert(nameTest is not null); try { ValidateNames.ParseNameTestThrow(nameTest, out prefix, out localName); @@ -239,7 +239,7 @@ public bool ParseNameTest(string nameTest, out string? prefix, out string? local public void ValidatePiName(string name, IErrorHelper errorHelper) { - Debug.Assert(name != null); + Debug.Assert(name is not null); try { ValidateNames.ValidateNameThrow( @@ -376,10 +376,10 @@ public int Compare(CompilerError? x, CompilerError? y) if ((object?)x == (object?)y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; int result = _moduleOrder[x.FileName].CompareTo(_moduleOrder[y.FileName]); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs index fa10fd9a2480f3..84b9de2560ed37 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs @@ -37,7 +37,7 @@ public CompilerErrorCollection() { } public void AddRange(CompilerError[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs index 744793ab723c7f..e1f1a6ff7d7172 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs @@ -104,14 +104,14 @@ public bool EnterScope(NsDecl? nsDecl) bool hasNamespaces = false; bool excludeAll = false; - for (; nsDecl != null; nsDecl = nsDecl.Prev) + for (; nsDecl is not null; nsDecl = nsDecl.Prev) { - if (nsDecl.NsUri == null) + if (nsDecl.NsUri is null) { - Debug.Assert(nsDecl.Prefix == null, "NS may be null only when prefix is null where it is used for extension-element-prefixes='#all'"); + Debug.Assert(nsDecl.Prefix is null, "NS may be null only when prefix is null where it is used for extension-element-prefixes='#all'"); excludeAll = true; } - else if (nsDecl.Prefix == null) + else if (nsDecl.Prefix is null) { AddExNamespace(nsDecl.NsUri); } @@ -147,7 +147,7 @@ private void AddRecord() private void AddRecord(ScopeFlags flag, string? ncName, string? uri, [AllowNull] V value) { Debug.Assert(flag == (flag & ScopeFlags.ExclusiveFlags) && (flag & (flag - 1)) == 0 && flag != 0, "One exclusive flag"); - Debug.Assert(uri != null || ncName == null, "null, null means exclude '#all'"); + Debug.Assert(uri is not null || ncName is null, "null, null means exclude '#all'"); ScopeFlags flags = _records[_lastRecord].flags; bool canReuseLastRecord = (_lastScopes == 0) && (flags & ScopeFlags.ExclusiveFlags) == 0; @@ -198,7 +198,7 @@ private void SetFlag(ScopeFlags flag, bool value) // Add variable to the current scope. Returns false in case of duplicates. public void AddVariable(QilName varName, V value) { - Debug.Assert(varName.LocalName != null && varName.NamespaceUri != null); + Debug.Assert(varName.LocalName is not null && varName.NamespaceUri is not null); AddRecord(ScopeFlags.Variable, varName.LocalName, varName.NamespaceUri, value); } @@ -206,7 +206,7 @@ public void AddVariable(QilName varName, V value) // If interval is empty (from < to), the function returns null. private string? LookupNamespace(string prefix, int from, int to) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); for (int record = from; to <= record; --record) { string? recPrefix, recNsUri; @@ -246,7 +246,7 @@ public void AddExNamespace(string? nsUri) public bool IsExNamespace(string nsUri) { - Debug.Assert(nsUri != null); + Debug.Assert(nsUri is not null); int exAll = 0; for (int record = _lastRecord; 0 <= record; record--) { @@ -254,12 +254,12 @@ public bool IsExNamespace(string nsUri) ScopeFlags flags = GetName(ref _records[record], out recPrefix, out recNsUri); if ((flags & ScopeFlags.NsExcl) != 0) { - Debug.Assert(recPrefix == null); + Debug.Assert(recPrefix is null); if (recNsUri == nsUri) { return true; // This namespace is excluded } - if (recNsUri == null) + if (recNsUri is null) { exAll = record; // #all namespaces below are excluded } @@ -298,7 +298,7 @@ public bool IsExNamespace(string nsUri) private int SearchVariable(string localName, string uri) { - Debug.Assert(localName != null); + Debug.Assert(localName is not null); for (int record = _lastRecord; 0 <= record; --record) { string? recLocal, recNsUri; @@ -362,7 +362,7 @@ internal System.Collections.Generic.IEnumerable GetActiveRecords() if (_records[currentRecord].IsNamespace) { // This is a namespace declaration - if (LookupNamespace(_records[currentRecord].ncName!, _lastRecord, currentRecord + 1) != null) + if (LookupNamespace(_records[currentRecord].ncName!, _lastRecord, currentRecord + 1) is not null) { continue; } @@ -397,7 +397,7 @@ public bool MoveNext() if (_scope._records[_currentRecord].IsNamespace) { // This is a namespace declaration - if (_scope.LookupNamespace(_scope._records[_currentRecord].ncName!, _lastRecord, _currentRecord + 1) == null) + if (_scope.LookupNamespace(_scope._records[_currentRecord].ncName!, _lastRecord, _currentRecord + 1) is null) { // Its prefix has not been redefined later in [currentRecord + 1, lastRecord] return true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs index cce691ba93b540..b8c922938c0b78 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs @@ -51,7 +51,7 @@ public void SetFocus(SingletonFocusType focusType) public void SetFocus(QilIterator? current) { - if (current != null) + if (current is not null) { _focusType = SingletonFocusType.Iterator; _current = current; @@ -77,7 +77,7 @@ public QilNode GetCurrent() case SingletonFocusType.InitialDocumentNode: return _f.Root(_f.XmlContext()); case SingletonFocusType.InitialContextNode: return _f.XmlContext(); default: - Debug.Assert(_focusType == SingletonFocusType.Iterator && _current != null, "Unexpected singleton focus type"); + Debug.Assert(_focusType == SingletonFocusType.Iterator && _current is not null, "Unexpected singleton focus type"); return _current; } } @@ -134,19 +134,19 @@ public bool IsFocusSet public QilNode GetCurrent() { - Debug.Assert(_current != null, "Naked current() is not expected in this function"); + Debug.Assert(_current is not null, "Naked current() is not expected in this function"); return _current; } public QilNode GetPosition() { - Debug.Assert(_position != null, "Naked position() is not expected in this function"); + Debug.Assert(_position is not null, "Naked position() is not expected in this function"); return _position; } public QilNode GetLast() { - Debug.Assert(_last != null, "Naked last() is not expected in this function"); + Debug.Assert(_last is not null, "Naked last() is not expected in this function"); return _last; } } @@ -170,7 +170,7 @@ public void SetFocus(QilIterator current) public bool IsFocusSet { - get { return _current != null; } + get { return _current is not null; } } public QilNode? GetCurrent() @@ -185,7 +185,7 @@ public QilNode GetPosition() public QilNode GetLast() { - if (_last == null) + if (_last is null) { // Create a let that will be fixed up later in ConstructLoop or by LastFixupVisitor _last = _f.Let(_f.Double(0)); @@ -195,7 +195,7 @@ public QilNode GetLast() public void EnsureCache() { - if (_cached == null) + if (_cached is null) { _cached = _f.Let(_current!.Binding!); _current.Binding = _cached; @@ -204,7 +204,7 @@ public void EnsureCache() public void Sort(QilNode? sortKeys) { - if (sortKeys != null) + if (sortKeys is not null) { // If sorting is required, cache the input node-set to support last() within sort key expressions EnsureCache(); @@ -216,7 +216,7 @@ public void Sort(QilNode? sortKeys) public QilLoop ConstructLoop(QilNode body) { QilLoop result; - if (_last != null) + if (_last is not null) { // last() encountered either in the sort keys or in the body of the current loop EnsureCache(); @@ -224,11 +224,11 @@ public QilLoop ConstructLoop(QilNode body) } result = _f.BaseFactory.Loop(_current!, body); - if (_last != null) + if (_last is not null) { result = _f.BaseFactory.Loop(_last, result); } - if (_cached != null) + if (_cached is not null) { result = _f.BaseFactory.Loop(_cached, result); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs index 6e15fc5605a9da..e07390ae30078e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs @@ -52,14 +52,14 @@ public QilNode GenerateInvoke(QilFunction func, IList actualArgs) QilNode? invokeArg = FindActualArg(formalArg, actualArgs); // If actual value was not specified, use the default value and copy its debug comment - if (invokeArg == null) + if (invokeArg is null) { if (_debug) { if (formalArg.Name!.NamespaceUri == XmlReservedNs.NsXslDebug) { Debug.Assert(formalArg.Name.LocalName == "namespaces", "Cur,Pos,Last don't have default values and should be always added to by caller in AddImplicitArgs()"); - Debug.Assert(formalArg.DefaultValue != null, "PrecompileProtoTemplatesHeaders() set it"); + Debug.Assert(formalArg.DefaultValue is not null, "PrecompileProtoTemplatesHeaders() set it"); invokeArg = Clone(formalArg.DefaultValue); } else @@ -102,7 +102,7 @@ public QilNode GenerateInvoke(QilFunction func, IList actualArgs) private QilNode? FindActualArg(QilParameter formalArg, IList actualArgs) { QilName? argName = formalArg.Name; - Debug.Assert(argName != null); + Debug.Assert(argName is not null); foreach (XslNode actualArg in actualArgs) { if (actualArg.Name!.Equals(argName)) @@ -120,7 +120,7 @@ protected override QilNode VisitReference(QilNode n) QilNode? replacement = FindClonedReference(n); // If the reference is internal for the subtree being cloned, return it as is - if (replacement != null) + if (replacement is not null) { return replacement; } @@ -130,8 +130,8 @@ protected override QilNode VisitReference(QilNode n) // xsl:param's) must be taken care of. for (int prevArg = 0; prevArg < _curArg; prevArg++) { - Debug.Assert(_formalArgs![prevArg] != null, "formalArg must be in the list"); - Debug.Assert(_invokeArgs![prevArg] != null, "This arg should be compiled already"); + Debug.Assert(_formalArgs![prevArg] is not null, "formalArg must be in the list"); + Debug.Assert(_invokeArgs![prevArg] is not null, "This arg should be compiled already"); // Is this a reference to prevArg? if (n == _formalArgs[prevArg]) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs index b7a110a2e6023e..b54c4a9b035b96 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs @@ -39,7 +39,7 @@ public override void StartBuild() { _depth--; Debug.Assert(0 <= _depth && _depth <= 1, "this shouldn't happen"); - if (result == null) + if (result is null) { // special door to clean builder state in exception handlers return base.EndBuild(result); } @@ -74,8 +74,8 @@ public PathConvertor(XPathQilFactory f) : base(f.BaseFactory) public QilNode ConvertReletive2Absolute(QilNode node, QilNode fixup) { QilDepthChecker.Check(node); - Debug.Assert(node != null); - Debug.Assert(fixup != null); + Debug.Assert(node is not null); + Debug.Assert(fixup is not null); _fixup = fixup; return this.Visit(node); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs index 3e16e60d002d8b..b02996247b19c3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs @@ -133,7 +133,7 @@ public TemplateMatch(Template template, QilLoop filter) NipOffTypeNameCheck(); Debug.Assert( - _qname == null || + _qname is null || _nodeKind == XmlNodeKindFlags.Element || _nodeKind == XmlNodeKindFlags.Attribute || _nodeKind == XmlNodeKindFlags.PI, "qname may be not null only for element, attribute, or PI patterns" ); @@ -190,7 +190,7 @@ private void NipOffTypeNameCheck() _nodeKind = nodeKinds; QilBinary lastAnd = leftPath[idx & 3]; - if (lastAnd != null && lastAnd.Right.NodeType == QilNodeType.Eq) + if (lastAnd is not null && lastAnd.Right.NodeType == QilNodeType.Eq) { QilBinary eq = (QilBinary)lastAnd.Right; @@ -210,11 +210,11 @@ private void NipOffTypeNameCheck() QilBinary and1 = leftPath[idx & 3]; QilBinary and2 = leftPath[--idx & 3]; - if (and2 != null) + if (and2 is not null) { and2.Left = and1.Right; } - else if (and1 != null) + else if (and1 is not null) { _condition = and1.Right; } @@ -276,7 +276,7 @@ public void Add(Pattern pattern) QilName? qname = pattern.Match.QName; List? list; - if (qname == null) + if (qname is null) { list = NonFixedNamePatterns; } @@ -382,7 +382,7 @@ public void CollectPatterns(StylesheetLevel sheet, QilName mode) private QilNode MatchPattern(QilIterator it, TemplateMatch match) { QilNode? cond = match.Condition; - if (cond == null) + if (cond is null) { return _f.True(); } @@ -550,7 +550,7 @@ public QilNode BuildMatcher(QilIterator it, IList actualArgs, QilNode o QilName qname = match.QName; QilNode cond = match.Condition; - if (cond != null) { + if (cond is not null) { // We have to clone, because the same pattern may be used // in many different xsl:apply-templates/imports functions cond = cond.DeepClone(f.BaseFactory); @@ -569,14 +569,14 @@ public QilNode BuildMatcher(QilIterator it, IList actualArgs, QilNode o default : nodeType = null ; break; } - Debug.Assert(nodeType != null, "Unexpected nodeKind: " + nodeKind); + Debug.Assert(nodeType is not null, "Unexpected nodeKind: " + nodeKind); QilNode typeNameCheck = f.IsType(it, nodeType); - if (qname != null) { + if (qname is not null) { typeNameCheck = f.And(typeNameCheck, f.Eq(f.NameOf(it), qname.ShallowClone(f.BaseFactory))); } - cond = (cond == null) ? typeNameCheck : f.And(typeNameCheck, cond); + cond = (cond is null) ? typeNameCheck : f.And(typeNameCheck, cond); } result = f.Conditional(cond, diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs index ffcbe6d8e387c7..147e225f92487b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs @@ -54,11 +54,11 @@ public void PopScope() } } - // This can be ns declaration or ns exclussion. Las one when prefix == null; + // This can be ns declaration or ns exclussion. Las one when prefix is null; public void AddNamespace(string prefix, string uri) { - Debug.Assert(prefix != null); - Debug.Assert(uri != null); + Debug.Assert(prefix is not null); + Debug.Assert(uri is not null); // uri = nameTable.Add(uri); AddRecord(prefix, uri); } @@ -99,8 +99,8 @@ private void AddRecord(string? prefix, string? uri) //// We need following methods: //public void InvalidatePrefix(string prefix) { - // Debug.Assert(prefix != null); - // if (LookupNamespace(prefix) == null) { // This is optimisation. May be better just add this record? + // Debug.Assert(prefix is not null); + // if (LookupNamespace(prefix) is null) { // This is optimisation. May be better just add this record? // return; // } // AddRecord(prefix, null); @@ -108,7 +108,7 @@ private void AddRecord(string? prefix, string? uri) public void InvalidateAllPrefixes() { - if (_records[_lastRecord].prefix == null) + if (_records[_lastRecord].prefix is null) { return; // Averything was invalidated already. Nothing to do. } @@ -118,7 +118,7 @@ public void InvalidateAllPrefixes() public void InvalidateNonDefaultPrefixes() { string? defaultNs = LookupNamespace(string.Empty); - if (defaultNs == null) + if (defaultNs is null) { // We don't know default NS anyway. InvalidateAllPrefixes(); } @@ -126,7 +126,7 @@ public void InvalidateNonDefaultPrefixes() { if ( _records[_lastRecord].prefix!.Length == 0 && - _records[_lastRecord - 1].prefix == null + _records[_lastRecord - 1].prefix is null ) { return; // Averything was already done @@ -139,10 +139,10 @@ public void InvalidateNonDefaultPrefixes() public string? LookupNamespace(string prefix) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); for ( int record = _lastRecord; // from last record - _records[record].prefix != null; // till lookup barrier + _records[record].prefix is not null; // till lookup barrier --record // in reverce direction ) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs index d7d3d3740534d8..4b802b38731921 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs @@ -134,7 +134,7 @@ private bool IsDebug private QilExpression Compile(Compiler compiler) { - Debug.Assert(compiler != null); + Debug.Assert(compiler is not null); _compiler = compiler; _functions = _f.FunctionList(); _extPars = _f.GlobalParameterList(); @@ -200,7 +200,7 @@ private QilExpression Compile(Compiler compiler) List ebTypes = new List(scriptClasses.Count); foreach (KeyValuePair pair in scriptClasses) { - if (pair.Value != null) + if (pair.Value is not null) { ebTypes.Add(new EarlyBoundInfo(pair.Key, pair.Value)); } @@ -476,7 +476,7 @@ private void PrecompileProtoTemplatesHeaders() foreach (ProtoTemplate tmpl in _compiler.AllTemplates) { - Debug.Assert(tmpl != null && tmpl.Function == null); + Debug.Assert(tmpl is not null && tmpl.Function is null); Debug.Assert(tmpl.NodeType == XslNodeType.AttributeSet || tmpl.NodeType == XslNodeType.Template); QilList args = _f.FormalParameterList(); XslFlags flags = !IsDebug ? tmpl.Flags : XslFlags.FullFocus; @@ -494,17 +494,17 @@ private void PrecompileProtoTemplatesHeaders() { args.Add(CreateXslParam(CloneName(_nameLast), T.DoubleX)); } - if (IsDebug && nsList != null) + if (IsDebug && nsList is not null) { // AttributeSet doesn't need this logic because: 1) it doesn't have args; 2) we merge them. - // SimplifiedStylesheet has nsList == null as well. + // SimplifiedStylesheet has nsList is null as well. QilParameter ns = CreateXslParam(CloneName(_nameNamespaces), T.NamespaceS); ns.DefaultValue = GetNsVar(nsList); args.Add(ns); } Template? template = tmpl as Template; - if (template != null) + if (template is not null) { Debug.Assert(tmpl.NodeType == XslNodeType.Template); @@ -570,7 +570,7 @@ private void PrecompileProtoTemplatesHeaders() paramFunc.DebugName = ""; param.DefaultValue = _f.Invoke(paramFunc, paramActual); // store VarPar here to compile it on next pass: - if (paramWithCalls == null) + if (paramWithCalls is null) { paramWithCalls = new List(); paramToTemplate = new Dictionary(); @@ -600,13 +600,13 @@ private void PrecompileProtoTemplatesHeaders() tmpl is AttributeSet ? T.AttributeS : T.NodeNotRtfS ); tmpl.Function.DebugName = tmpl.GetDebugName(); - Debug.Assert((template != null) == (tmpl.SourceLine != null), "Templates must have line information, and attribute sets must not"); + Debug.Assert((template is not null) == (tmpl.SourceLine is not null), "Templates must have line information, and attribute sets must not"); SetLineInfo(tmpl.Function, tmpl.SourceLine ?? SourceLineInfo.NoSource); _functions.Add(tmpl.Function); } // foreach (ProtoTemplate tmpl in compiler.AllTemplates) // Finish compiling postponed parameters (those having calls in their default values) - if (paramWithCalls != null) + if (paramWithCalls is not null) { Debug.Assert(!IsDebug, "In debug mode we don't generate parumWithCalls functions. Otherwise focus flags should be adjusted"); foreach (VarPar par in paramWithCalls) @@ -641,7 +641,7 @@ private QilParameter CreateXslParam(QilName name, XmlQueryType xt) private void CompileProtoTemplate(ProtoTemplate tmpl) { - Debug.Assert(tmpl != null && tmpl.Function != null && tmpl.Function.Definition.NodeType == QilNodeType.Unknown); + Debug.Assert(tmpl is not null && tmpl.Function is not null && tmpl.Function.Definition.NodeType == QilNodeType.Unknown); EnterScope(tmpl); @@ -654,7 +654,7 @@ private void CompileProtoTemplate(ProtoTemplate tmpl) Debug.Assert(tmpl is Template, "Only templates can have explicit arguments"); if (IsDebug) { - Debug.Assert(arg.DefaultValue == null, "Argument must not be compiled yet"); + Debug.Assert(arg.DefaultValue is null, "Argument must not be compiled yet"); VarPar xslParam = (VarPar)arg.Annotation!; QilList? nsListParam = EnterScope(xslParam); arg.DefaultValue = CompileVarParValue(xslParam); @@ -698,7 +698,7 @@ private QilNode CompileInstructions(IList instructions, QilList content private QilNode CompileInstructions(IList instructions, int from, QilList content) { - Debug.Assert(instructions != null); + Debug.Assert(instructions is not null); for (int i = from; i < instructions.Count; i++) { XslNode node = instructions[i]; @@ -745,7 +745,7 @@ private QilNode CompileInstructions(IList instructions, int from, QilLi } ExitScope(); - Debug.Assert(result != null, "Result of compilation should not be null"); + Debug.Assert(result is not null, "Result of compilation should not be null"); if (result.NodeType == QilNodeType.Sequence && result.Count == 0) { continue; @@ -874,14 +874,14 @@ private QilNode CompileElement(NodeCtor node) QilNode qilName = CompileStringAvt(node.NameAvt); QilNode qname; - if (qilName.NodeType == QilNodeType.LiteralString && (qilNs == null || qilNs.NodeType == QilNodeType.LiteralString)) + if (qilName.NodeType == QilNodeType.LiteralString && (qilNs is null || qilNs.NodeType == QilNodeType.LiteralString)) { string name = (string)(QilLiteral)qilName; string prefix, local, nsUri; bool isValid = _compiler.ParseQName(name, out prefix, out local, (IErrorHelper)this); - if (qilNs == null) + if (qilNs is null) { nsUri = isValid ? ResolvePrefix(/*ignoreDefaultNs:*/false, prefix) : _compiler.CreatePhantomNamespace(); } @@ -893,7 +893,7 @@ private QilNode CompileElement(NodeCtor node) } else { // Process AVT - if (qilNs != null) + if (qilNs is not null) { qname = _f.StrParseQName(qilName, qilNs); } @@ -933,14 +933,14 @@ private QilNode CompileAttribute(NodeCtor node) QilNode qname; bool explicitNamespace = false; - if (qilName.NodeType == QilNodeType.LiteralString && (qilNs == null || qilNs.NodeType == QilNodeType.LiteralString)) + if (qilName.NodeType == QilNodeType.LiteralString && (qilNs is null || qilNs.NodeType == QilNodeType.LiteralString)) { string name = (string)(QilLiteral)qilName; string prefix, local, nsUri; bool isValid = _compiler.ParseQName(name, out prefix, out local, (IErrorHelper)this); - if (qilNs == null) + if (qilNs is null) { nsUri = isValid ? ResolvePrefix(/*ignoreDefaultNs:*/true, prefix) : _compiler.CreatePhantomNamespace(); } @@ -960,7 +960,7 @@ private QilNode CompileAttribute(NodeCtor node) else { // Process AVT - if (qilNs != null) + if (qilNs is not null) { qname = _f.StrParseQName(qilName, qilNs); } @@ -1037,7 +1037,7 @@ private QilNode CompileAvt(string source) while (pos < source.Length) { QilNode? fixedPart = ExtractText(source, ref pos); - if (fixedPart != null) + if (fixedPart is not null) { result.Add(fixedPart); } @@ -1060,7 +1060,7 @@ private QilNode CompileAvt(string source) [return: NotNullIfNotNull("avt")] private QilNode? CompileStringAvt(string? avt) { - if (avt == null) + if (avt is null) { return null; } @@ -1073,7 +1073,7 @@ private QilNode CompileAvt(string source) private QilNode CompileTextAvt(string avt) { - Debug.Assert(avt != null); + Debug.Assert(avt is not null); if (avt.IndexOfAny(s_curlyBraces) == -1) { return _f.TextCtor(_f.String(avt)); @@ -1177,7 +1177,7 @@ private QilNode CompileApplyTemplates(XslNodeEx node) for (int i = 0; i < content.Count; i++) { VarPar? withParam = content[i] as VarPar; - if (withParam != null) + if (withParam is not null) { Debug.Assert(withParam.NodeType == XslNodeType.WithParam); CompileWithParam(withParam); @@ -1246,7 +1246,7 @@ private QilNode CompileCallTemplate(XslNodeEx node) Template? tmpl; if (_compiler.NamedTemplates.TryGetValue(node.Name!, out tmpl)) { - Debug.Assert(tmpl.Function != null, "All templates should be already compiled"); + Debug.Assert(tmpl.Function is not null, "All templates should be already compiled"); result = _invkGen.GenerateInvoke(tmpl.Function, AddRemoveImplicitArgs(node.Content, tmpl.Flags)!); } else @@ -1281,7 +1281,7 @@ private QilNode CompileUseAttributeSet(XslNode node) AttributeSet? attSet; if (_compiler.AttributeSets.TryGetValue(node.Name!, out attSet)) { - Debug.Assert(attSet.Function != null, "All templates should be already compiled"); + Debug.Assert(attSet.Function is not null, "All templates should be already compiled"); return _invkGen.GenerateInvoke(attSet.Function, AddRemoveImplicitArgs(node.Content, attSet.Flags)!); } else @@ -1421,7 +1421,7 @@ private QilNode CompileChoose(XslNode node) QilList? nsList = EnterScope(when); if (when.NodeType == XslNodeType.Otherwise) { - Debug.Assert(result == null, "xsl:otherwise must be the last child of xsl:choose"); + Debug.Assert(result is null, "xsl:otherwise must be the last child of xsl:choose"); result = CompileInstructions(when.Content); } else @@ -1432,7 +1432,7 @@ private QilNode CompileChoose(XslNode node) SetLineInfoCheck(result, when.SourceLine); result = SetDebugNs(result, nsList); } - if (result == null) + if (result is null) { return _f.Sequence(); } @@ -1478,7 +1478,7 @@ private QilNode CompileVarParValue(XslNode node) string? select = node.Select; QilNode varValue; - if (select != null) + if (select is not null) { // In case of incorrect stylesheet, variable or parameter may have both a 'select' attribute and non-empty content QilList list = InstructionList(); @@ -1502,7 +1502,7 @@ private QilNode CompileVarParValue(XslNode node) // In debug mode every variable/param must be of type 'any' varValue = _f.TypeAssert(varValue, T.ItemS); } - Debug.Assert(varValue.SourceLine == null); + Debug.Assert(varValue.SourceLine is null); return varValue; } @@ -1528,7 +1528,7 @@ private void CompileWithParam(VarPar withParam) while (i < content.Count) { Sort? sort = content[i] as Sort; - if (sort != null) + if (sort is not null) { CompileSort(sort, keyList, ref parentLoop); content.RemoveAt(i); @@ -1549,7 +1549,7 @@ private void CompileWithParam(VarPar withParam) { QilNode? result = CompileStringAvt(attValue); - if (result == null) + if (result is null) { // Do nothing } @@ -1583,7 +1583,7 @@ private QilNode CompileLangAttributeToLcid(string? attValue, bool fwdCompat) private QilNode CompileLangToLcid(QilNode? lang, bool fwdCompat) { - if (lang == null) + if (lang is null) { return _f.Double(XsltLibrary.InvariantCultureLcid); } @@ -1602,7 +1602,7 @@ private void CompileDataTypeAttribute(string? attValue, bool fwdCompat, ref QilN const string DtText = "text"; const string DtNumber = "number"; QilNode? result = CompileStringAvt(attValue); - if (result != null) + if (result is not null) { if (result.NodeType == QilNodeType.LiteralString) { @@ -1685,7 +1685,7 @@ private void CompileDataTypeAttribute(string? attValue, bool fwdCompat, ref QilN private QilNode CompileOrderAttribute(string attName, string? attValue, string value0, string value1, bool fwdCompat) { QilNode? result = CompileStringAvt(attValue); - if (result != null) + if (result is not null) { if (result.NodeType == QilNodeType.LiteralString) { @@ -1733,7 +1733,7 @@ private void CompileSort(Sort sort, QilList keyList, ref LoopFocus parentLoop) select = CompileXPathExpression(sort.Select); - if (sort.Lang != null || sort.DataType != null || sort.Order != null || sort.CaseOrder != null) + if (sort.Lang is not null || sort.DataType is not null || sort.Order is not null || sort.CaseOrder is not null) { // Calculate these attributes in the context of the parent loop LoopFocus curLoopSaved = _curLoop; @@ -1774,14 +1774,14 @@ private void CompileSort(Sort sort, QilList keyList, ref LoopFocus parentLoop) _strConcat.Append(lang); char separator = '?'; - if (order != null) + if (order is not null) { _strConcat.Append(separator); _strConcat.Append("descendingOrder="); _strConcat.Append(order); separator = '&'; } - if (caseOrder != null) + if (caseOrder is not null) { _strConcat.Append(separator); _strConcat.Append("upperFirst="); @@ -1795,7 +1795,7 @@ private void CompileSort(Sort sort, QilList keyList, ref LoopFocus parentLoop) // Line information is not copied keyList.Add(result); - if (select2 != null) + if (select2 is not null) { result = _f.SortKey(select2, collation.DeepClone(_f.BaseFactory)); // Line information is not copied @@ -1844,7 +1844,7 @@ private QilNode MatchCountPattern(QilNode? countPattern, QilIterator testNode) with the same node kind as the context node and, if the context node has an expanded-QName, with the same expanded-QName as the context node. */ - if (countPattern != null) + if (countPattern is not null) { return MatchPattern(countPattern, testNode); } @@ -1909,7 +1909,7 @@ private QilNode PlaceMarker(QilNode? countPattern, QilNode? fromPattern, bool mu QilNode countMatches, fromMatches, A, F, AF; QilIterator i, j; - countPattern2 = (countPattern != null) ? countPattern.DeepClone(_f.BaseFactory) : null; + countPattern2 = (countPattern is not null) ? countPattern.DeepClone(_f.BaseFactory) : null; countMatches = _f.Filter(i = _f.For(_f.AncestorOrSelf(GetCurrentNode())), MatchCountPattern(countPattern, i)); if (multiple) { @@ -1920,7 +1920,7 @@ private QilNode PlaceMarker(QilNode? countPattern, QilNode? fromPattern, bool mu A = _f.Filter(i = _f.For(countMatches), _f.Eq(_f.PositionOf(i), _f.Int32(1))); } - if (fromPattern == null) + if (fromPattern is null) { AF = A; } @@ -1959,7 +1959,7 @@ private QilNode PlaceMarkerAny(QilNode? countPattern, QilNode? fromPattern) QilNode range, fromMatches, F, AF; QilIterator i, j, k; - if (fromPattern == null) + if (fromPattern is null) { // According to XSLT 2.0 spec, if the 'from' attribute is omitted, matches-from() returns true // only for the root node. It means $F is a sequence of length one containing the root node, @@ -1994,7 +1994,7 @@ private QilNode CompileLetterValueAttribute(string? attValue, bool fwdCompat) string letterValue; QilNode? result = CompileStringAvt(attValue); - if (result != null) + if (result is not null) { if (result.NodeType == QilNodeType.LiteralString) { @@ -2032,7 +2032,7 @@ private QilNode CompileGroupingSeparatorAttribute(string? attValue, bool fwdComp { QilNode? result = CompileStringAvt(attValue); - if (result == null) + if (result is null) { // NOTE: string.Empty value denotes unspecified attribute result = _f.String(string.Empty); @@ -2066,7 +2066,7 @@ private QilNode CompileGroupingSizeAttribute(string? attValue, bool fwdCompat) { QilNode? result = CompileStringAvt(attValue); - if (result == null) + if (result is null) { return _f.Double(0); } @@ -2101,7 +2101,7 @@ private QilNode CompileNumber(Number num) { QilNode value; - if (num.Value != null) + if (num.Value is not null) { // REVIEW: We may want to report a warning if any of 'level', 'count' and 'from' attributes // specified together with 'value'. It is ERR XT0975 in XSLT 2.0. @@ -2109,8 +2109,8 @@ private QilNode CompileNumber(Number num) } else { - QilNode? countPattern = (num.Count != null) ? CompileNumberPattern(num.Count) : null; - QilNode? fromPattern = (num.From != null) ? CompileNumberPattern(num.From) : null; + QilNode? countPattern = (num.Count is not null) ? CompileNumberPattern(num.Count) : null; + QilNode? fromPattern = (num.From is not null) ? CompileNumberPattern(num.From) : null; switch (num.Level) { @@ -2141,7 +2141,7 @@ private void CompileAndSortMatches(Stylesheet sheet) foreach (Template template in sheet.Templates) { - if (template.Match != null) + if (template.Match is not null) { EnterScope(template); QilNode result = CompileMatchPattern(template.Match); @@ -2276,7 +2276,7 @@ private QilIterator CompileGlobalVarPar(VarPar varPar) private void ReportErrorInXPath(XslLoadException e) { XPathCompileException? ex = e as XPathCompileException; - string errorText = (ex != null) ? ex.FormatDetailedMessage() : e.Message; + string errorText = (ex is not null) ? ex.FormatDetailedMessage() : e.Message; _compiler.ReportError(_lastScope!.SourceLine!, SR.Xml_UserException, errorText); } @@ -2298,7 +2298,7 @@ private QilNode CompileXPathExpression(string? expr) QilNode result; SetEnvironmentFlags(/*allowVariables:*/true, /*allowCurrent:*/true, /*allowKey:*/true); - if (expr == null) + if (expr is null) { result = PhantomXPathExpression(); } @@ -2329,7 +2329,7 @@ private QilNode CompileXPathExpression(string? expr) private QilNode CompileNodeSetExpression(string expr) { QilNode? result = _f.TryEnsureNodeSet(CompileXPathExpression(expr)); - if (result == null) + if (result is null) { // The expression is never a node-set XPathCompileException e = new XPathCompileException(expr, 0, expr.Length, SR.XPath_NodeSetExpected, null); @@ -2344,7 +2344,7 @@ private QilNode CompileNodeSetExpression(string expr) private QilNode CompileXPathExpressionWithinAvt(string expr, ref int pos) { - Debug.Assert(expr != null); + Debug.Assert(expr is not null); XPathScanner scanner; QilNode result; @@ -2373,7 +2373,7 @@ private QilNode CompileXPathExpressionWithinAvt(string expr, ref int pos) private QilNode CompileMatchPattern(string pttrn) { - Debug.Assert(pttrn != null); + Debug.Assert(pttrn is not null); XPathScanner scanner; QilNode result; @@ -2399,7 +2399,7 @@ private QilNode CompileMatchPattern(string pttrn) private QilNode CompileNumberPattern(string pttrn) { - Debug.Assert(pttrn != null); + Debug.Assert(pttrn is not null); XPathScanner scanner; QilNode result; @@ -2425,12 +2425,12 @@ private QilNode CompileKeyMatch(string? pttrn) XPathScanner scanner; QilNode result; - if (_keyMatchBuilder == null) + if (_keyMatchBuilder is null) { _keyMatchBuilder = new KeyMatchBuilder((IXPathEnvironment)this); } SetEnvironmentFlags(/*allowVariables:*/false, /*allowCurrent:*/false, /*allowKey:*/false); - if (pttrn == null) + if (pttrn is null) { result = PhantomKeyMatch(); } @@ -2460,7 +2460,7 @@ private QilNode CompileKeyUse(Key key) QilNode result; SetEnvironmentFlags(/*allowVariables:*/false, /*allowCurrent:*/true, /*allowKey:*/false); - if (expr == null) + if (expr is null) { result = _f.Error(_f.String(XslLoadException.CreateMessage(key.SourceLine, SR.Xslt_MissingAttribute, "use"))); } @@ -2551,7 +2551,7 @@ private void SetArg(IList args, int pos, QilName name, QilNode value) } if ((flags & XslFlags.FocusFilter) != 0) { - if (args == null || args.IsReadOnly) + if (args is null || args.IsReadOnly) { args = new List(3); } @@ -2605,7 +2605,7 @@ private bool FillupInvokeArgs(IList formalArgs, IList actualAr } } } - if (arg == null) + if (arg is null) { // Formal argument has not been found among actual arguments return false; @@ -2655,7 +2655,7 @@ private QilNode InvokeApplyFunction(StylesheetLevel sheet, QilName mode, IList defList, QilNode key, IFocus env) { - Debug.Assert(defList != null && defList.Count > 0); + Debug.Assert(defList is not null && defList.Count > 0); if (defList.Count == 1) { return _f.Invoke(defList[0].Function!, _f.ActualParameterList(env.GetCurrent()!, key)); @@ -453,7 +453,7 @@ private QilNode CompileSingleKey(List defList, QilNode key, IFocus env) private QilNode CompileSingleKey(List defList, QilIterator key, QilIterator context) { - Debug.Assert(defList != null && defList.Count > 0); + Debug.Assert(defList is not null && defList.Count > 0); QilList result = _f.BaseFactory.Sequence(); QilNode? keyRef = null; @@ -511,14 +511,14 @@ private QilNode CompileFnDocument(QilNode uris, QilNode? baseNode) else { u = _f.Let(uris); - j = (baseNode != null) ? _f.Let(baseNode) : null; + j = (baseNode is not null) ? _f.Let(baseNode) : null; result = _f.Conditional(_f.Not(_f.IsType(u, T.AnyAtomicType)), _f.DocOrderDistinct(_f.Loop(i = _f.For(_f.TypeAssert(u, T.NodeS)), CompileSingleDocument(_f.ConvertToString(i), j ?? i) )), CompileSingleDocument(_f.XsltConvert(u, T.StringX), j) ); - result = (baseNode != null) ? _f.Loop(j!, result) : result; + result = (baseNode is not null) ? _f.Loop(j!, result) : result; result = _f.Loop(u, result); } return result; @@ -529,7 +529,7 @@ private QilNode CompileSingleDocument(QilNode uri, QilNode? baseNode) _f.CheckString(uri); QilNode baseUri; - if (baseNode == null) + if (baseNode is null) { baseUri = _f.String(_lastScope!.SourceLine!.Uri); } @@ -560,7 +560,7 @@ private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNod _f.CheckString(formatPicture); XmlQualifiedName? resolvedName; - if (formatName == null) + if (formatName is null) { resolvedName = new XmlQualifiedName(); // formatName must be non-null in the f.InvokeFormatNumberDynamic() call below @@ -579,7 +579,7 @@ private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNod } } - if (resolvedName != null) + if (resolvedName is not null) { DecimalFormatDecl format; if (_compiler.DecimalFormats.Contains(resolvedName)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs index 32c71b7e352211..6beb9513413406 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs @@ -33,7 +33,7 @@ public void Reset() private void FlushBuilder() { - if (_concat == null) + if (_concat is null) { _concat = _f.BaseFactory.Sequence(); } @@ -59,7 +59,7 @@ public void Append(char value) public void Append(QilNode? value) { Debug.Assert(_inUse, "Reset() wasn't called"); - if (value != null) + if (value is not null) { Debug.Assert(value.XmlType!.TypeCode == XmlTypeCode.String); if (value.NodeType == QilNodeType.LiteralString) @@ -78,7 +78,7 @@ public QilNode ToQil() { Debug.Assert(_inUse); // If we want allow multiple calls to ToQil() this logic should be changed _inUse = false; - if (_concat == null) + if (_concat is null) { return _f.String(_builder.ToString()); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs index 011862c1ff00af..421e9438b776f6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs @@ -84,7 +84,7 @@ public void AddWhitespaceRule(int index, WhitespaceRule rule) public bool AddVarPar(VarPar var) { Debug.Assert(var.NodeType == XslNodeType.Variable || var.NodeType == XslNodeType.Param); - Debug.Assert(var.Name!.NamespaceUri != null, "Name must be resolved in XsltLoader"); + Debug.Assert(var.Name!.NamespaceUri is not null, "Name must be resolved in XsltLoader"); foreach (XslNode prevVar in GlobalVarPars!) { if (prevVar.Name!.Equals(var.Name)) @@ -108,7 +108,7 @@ public bool AddTemplate(Template template) _compiler.AllTemplates.Add(template); - if (template.Name != null) + if (template.Name is not null) { Template? old; if (!_compiler.NamedTemplates.TryGetValue(template.Name, out old)) @@ -125,7 +125,7 @@ public bool AddTemplate(Template template) } } - if (template.Match != null) + if (template.Match is not null) { Templates.Add(template); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs index 663a96bbd6d886..ba1c0087fef6b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs @@ -26,7 +26,7 @@ internal class XPathPatternBuilder : XPathPatternParser.IPatternBuilder public XPathPatternBuilder(IXPathEnvironment environment) { - Debug.Assert(environment != null); + Debug.Assert(environment is not null); _environment = environment; _f = environment.Factory; _predicateEnvironment = new XPathPredicateEnvironment(environment); @@ -66,7 +66,7 @@ private void FixupFilterBinding(QilLoop filter, QilNode newBinding) public virtual QilNode? EndBuild(QilNode? result) { Debug.Assert(_inTheBuild, "StartBuild() wasn't called"); - if (result == null) + if (result is null) { // Special door to clean builder state in exception handlers } @@ -83,8 +83,8 @@ private void FixupFilterBinding(QilLoop filter, QilNode newBinding) public QilNode Operator(XPathOperator op, QilNode? left, QilNode? right) { Debug.Assert(op == XPathOperator.Union); - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); // It is important to not create nested lists here Debug.Assert(right.NodeType == QilNodeType.Filter, "LocationPathPattern must be compiled into a filter"); if (left.NodeType == QilNodeType.Sequence) @@ -102,10 +102,10 @@ public QilNode Operator(XPathOperator op, QilNode? left, QilNode? right) private static QilLoop BuildAxisFilter(QilPatternFactory f, QilIterator itr, XPathAxis xpathAxis, XPathNodeType nodeType, string? name, string? nsUri) { QilNode nameTest = ( - name != null && nsUri != null ? f.Eq(f.NameOf(itr), f.QName(name, nsUri)) : // ns:bar || bar - nsUri != null ? f.Eq(f.NamespaceUriOf(itr), f.String(nsUri)) : // ns:* - name != null ? f.Eq(f.LocalNameOf(itr), f.String(name)) : // *:foo - /*name == nsUri == null*/ f.True() // * + name is not null && nsUri is not null ? f.Eq(f.NameOf(itr), f.QName(name, nsUri)) : // ns:bar || bar + nsUri is not null ? f.Eq(f.NamespaceUriOf(itr), f.String(nsUri)) : // ns:* + name is not null ? f.Eq(f.LocalNameOf(itr), f.String(name)) : // *:foo + /*name == nsUri is null*/ f.True() // * ); XmlNodeKindFlags intersection = XPathBuilder.AxisTypeMask(itr.XmlType!.NodeKinds, nodeType, xpathAxis); @@ -135,7 +135,7 @@ public QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? prefix, switch (xpathAxis) { case XPathAxis.DescendantOrSelf: - Debug.Assert(nodeType == XPathNodeType.All && prefix == null && name == null, " // is the only d-o-s axes that we can have in pattern"); + Debug.Assert(nodeType == XPathNodeType.All && prefix is null && name is null, " // is the only d-o-s axes that we can have in pattern"); return _f.Nop(_fixupNode); // We using Nop as a flag that DescendantOrSelf exis was used between steps. case XPathAxis.Root: QilIterator i; @@ -143,19 +143,19 @@ public QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? prefix, priority = 0.5; break; default: - string? nsUri = prefix == null ? null : _environment.ResolvePrefix(prefix); + string? nsUri = prefix is null ? null : _environment.ResolvePrefix(prefix); result = BuildAxisFilter(_f, _f.For(_fixupNode), xpathAxis, nodeType, name, nsUri); switch (nodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: - if (name != null) + if (name is not null) { priority = 0; } else { - if (prefix != null) + if (prefix is not null) { priority = -0.25; } @@ -166,7 +166,7 @@ public QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? prefix, } break; case XPathNodeType.ProcessingInstruction: - priority = name != null ? 0 : -0.5; + priority = name is not null ? 0 : -0.5; break; default: priority = -0.5; @@ -192,8 +192,8 @@ public QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? prefix, // -> Filter('b' & Ancestor(Filter('a'))) public QilNode JoinStep(QilNode left, QilNode right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); if (left.NodeType == QilNodeType.Nop) { QilUnary nop = (QilUnary)left; @@ -211,13 +211,13 @@ public QilNode JoinStep(QilNode left, QilNode right) { ancestor = true; QilUnary nop = (QilUnary)right; - Debug.Assert(nop.Child != null); + Debug.Assert(nop.Child is not null); right = nop.Child; } } Debug.Assert(right.NodeType == QilNodeType.Filter); QilLoop? lastParent = GetLastParent(right); - Debug.Assert(lastParent != null); + Debug.Assert(lastParent is not null); FixupFilterBinding(parentFilter, ancestor ? _f.Ancestor(lastParent.Variable) : _f.Parent(lastParent.Variable)); lastParent.Body = _f.And(lastParent.Body, _f.Not(_f.IsEmpty(parentFilter))); @@ -378,7 +378,7 @@ public static void CleanAnnotation(QilNode node) public IXPathBuilder GetPredicateBuilder(QilNode ctx) { QilLoop context = (QilLoop)ctx; - Debug.Assert(context != null, "Predicate always has step so it can't have context == null"); + Debug.Assert(context is not null, "Predicate always has step so it can't have context is null"); Debug.Assert(context.Variable.NodeType == QilNodeType.For, "It shouldn't be Let, becaus predicates in PatternBuilder don't produce cached tuples."); return _predicateBuilder; } @@ -432,7 +432,7 @@ private class XsltFunctionFocus : IFocus public XsltFunctionFocus(QilIterator current) { - Debug.Assert(current != null); + Debug.Assert(current is not null); _current = current; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternParser.cs index 2f9c06bafc1e0b..b8d44407f94a81 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternParser.cs @@ -25,8 +25,8 @@ public interface IPatternBuilder : IXPathBuilder public QilNode Parse(XPathScanner scanner, IPatternBuilder ptrnBuilder) { - Debug.Assert(_scanner == null && _ptrnBuilder == null); - Debug.Assert(scanner != null && ptrnBuilder != null); + Debug.Assert(_scanner is null && _ptrnBuilder is null); + Debug.Assert(scanner is not null && ptrnBuilder is not null); QilNode? result = null; ptrnBuilder.StartBuild(); try @@ -230,7 +230,7 @@ private QilNode ParseStepPattern() opnd = _ptrnBuilder!.Axis(axis, nodeType, nodePrefix, nodeName); XPathPatternBuilder? xpathPatternBuilder = _ptrnBuilder as XPathPatternBuilder; - if (xpathPatternBuilder != null) + if (xpathPatternBuilder is not null) { //for XPathPatternBuilder, get all predicates and then build them List predicates = new List(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs index 6c6b0912c552a8..6c5f92c52f4ad9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs @@ -66,7 +66,7 @@ internal class NsDecl public NsDecl(NsDecl? prev, string? prefix, string? nsUri) { - Debug.Assert(nsUri != null || Prefix == null); + Debug.Assert(nsUri is not null || Prefix is null); this.Prev = prev; this.Prefix = prefix; this.NsUri = nsUri; @@ -117,8 +117,8 @@ public void SetContent(List? content) public void AddContent(XslNode node) { - Debug.Assert(node != null); - if (_content == null) + Debug.Assert(node is not null); + if (_content is null) { _content = new List(); } @@ -127,7 +127,7 @@ public void AddContent(XslNode node) public void InsertContent(IEnumerable collection) { - if (_content == null) + if (_content is null) { _content = new List(collection); } @@ -153,19 +153,19 @@ internal string? TraceName _ => NodeType.ToString(), }; sb.Append(nodeTypeName); - if (Name != null) + if (Name is not null) { sb.Append(' '); sb.Append(Name.QualifiedName); } ISourceLineInfo? lineInfo = SourceLine; - if (lineInfo == null && NodeType == XslNodeType.AttributeSet) + if (lineInfo is null && NodeType == XslNodeType.AttributeSet) { lineInfo = Content[0].SourceLine; - Debug.Assert(lineInfo != null); + Debug.Assert(lineInfo is not null); } - if (lineInfo != null) + if (lineInfo is not null) { string fileName = SourceLineInfo.GetFileName(lineInfo.Uri!); int idx = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1; @@ -215,7 +215,7 @@ public override string GetDebugName() public new void AddContent(XslNode node) { - Debug.Assert(node != null && node.NodeType == XslNodeType.List); + Debug.Assert(node is not null && node.NodeType == XslNodeType.List); base.AddContent(node); } @@ -245,13 +245,13 @@ public override string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("> { protected override QilName GetKeyForItem(List list) { - Debug.Assert(list != null && list.Count > 0); + Debug.Assert(list is not null && list.Count > 0); return list[0].Name!; } } @@ -318,7 +318,7 @@ public Key(QilName name, string? match, string? use, XslVersion xslVer) : base(XslNodeType.Key, name, null, xslVer) { // match and use can be null in case of incorrect stylesheet - Debug.Assert(name != null); + Debug.Assert(name is not null); this.Match = match; this.Use = use; } @@ -330,13 +330,13 @@ public string GetDebugName() dbgName.Append(Name!.QualifiedName); dbgName.Append('"'); - if (Match != null) + if (Match is not null) { dbgName.Append(" match=\""); dbgName.Append(Match); dbgName.Append('"'); } - if (Use != null) + if (Use is not null) { dbgName.Append(" use=\""); dbgName.Append(Use); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs index 2f0ffada81514f..d14d3dc6498efe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs @@ -60,7 +60,7 @@ internal class Graph : Dictionary?> public IEnumerable GetAdjList(V v) { List? adjList; - if (TryGetValue(v, out adjList) && adjList != null) + if (TryGetValue(v, out adjList) && adjList is not null) { return adjList; } @@ -76,7 +76,7 @@ public void AddEdge(V v1, V v2) } List? adjList; - if (!TryGetValue(v1, out adjList) || adjList == null) + if (!TryGetValue(v1, out adjList) || adjList is null) { adjList = this[v1] = new List(); } @@ -284,7 +284,7 @@ private void FillModeFlags(Dictionary parentModeFlags, Styles // 2. Add ModeFlags of my templates to my parent foreach (Template tmpl in sheet.Templates) { - Debug.Assert(tmpl.Match != null); + Debug.Assert(tmpl.Match is not null); XslFlags templateFlags = tmpl.Flags & (XslFlags.FocusFilter | XslFlags.SideEffects); if (templateFlags != 0) { @@ -305,7 +305,7 @@ protected override XslFlags Visit(XslNode node) _scope.ExitScope(); // Local variables and parameters must be added to the outer scope - if (_currentTemplate != null && (node.NodeType == XslNodeType.Variable || node.NodeType == XslNodeType.Param)) + if (_currentTemplate is not null && (node.NodeType == XslNodeType.Variable || node.NodeType == XslNodeType.Param)) { _scope.AddVariable(node.Name!, (VarPar)node); } @@ -354,7 +354,7 @@ protected override XslFlags VisitApplyImports(XslNode node) protected override XslFlags VisitApplyTemplates(XslNode node) { - Debug.Assert(node.Select != null, "Absent @select should be replaced with 'node()' in XsltLoader"); + Debug.Assert(node.Select is not null, "Absent @select should be replaced with 'node()' in XsltLoader"); XslFlags result = ProcessExpr(node.Select); foreach (XslNode instr in node.Content) @@ -370,7 +370,7 @@ protected override XslFlags VisitApplyTemplates(XslNode node) modePar = _applyTemplatesParams[mn] = AstFactory.WithParam(instr.Name!); } - if (_typeDonor != null) + if (_typeDonor is not null) { _dataFlow!.AddEdge(_typeDonor, modePar); } @@ -381,7 +381,7 @@ protected override XslFlags VisitApplyTemplates(XslNode node) } } - if (_currentTemplate != null) + if (_currentTemplate is not null) { AddApplyTemplatesEdge(/*mode:*/node.Name!, _currentTemplate); } @@ -406,8 +406,8 @@ protected override XslFlags VisitCallTemplate(XslNode node) if (_compiler!.NamedTemplates.TryGetValue(node.Name!, out target)) { - Debug.Assert(target != null); - if (_currentTemplate != null) + Debug.Assert(target is not null); + if (_currentTemplate is not null) { if (_forEachDepth == 0) { @@ -437,7 +437,7 @@ protected override XslFlags VisitCallTemplate(XslNode node) // b) if value of xsl:with-param is a VarPar reference, add an edge connecting it with xsl:param // to the data flow graph. - if (target != null) + if (target is not null) { foreach (XslNode instr in target.Content) { @@ -466,10 +466,10 @@ protected override XslFlags VisitCallTemplate(XslNode node) idx++; } - if (found != null) + if (found is not null) { // Found corresponding xsl:with-param, check its type - if (_typeDonor != null) + if (_typeDonor is not null) { // add an edge from its type donor to xsl:param _dataFlow!.AddEdge(_typeDonor, par); @@ -588,7 +588,7 @@ protected override XslFlags VisitNumber(Number node) XslFlags.Rtf | ProcessPattern(node.Count) | ProcessPattern(node.From) | - (node.Value != null ? ProcessExpr(node.Value) : XslFlags.Current) | + (node.Value is not null ? ProcessExpr(node.Value) : XslFlags.Current) | ProcessAvt(node.Format) | ProcessAvt(node.Lang) | ProcessAvt(node.LetterValue) | @@ -628,7 +628,7 @@ protected override XslFlags VisitText(Text node) protected override XslFlags VisitUseAttributeSet(XslNode node) { - if (_compiler!.AttributeSets.TryGetValue(node.Name!, out AttributeSet? attSet) && _currentTemplate != null) + if (_compiler!.AttributeSets.TryGetValue(node.Name!, out AttributeSet? attSet) && _currentTemplate is not null) { if (_forEachDepth == 0) { @@ -658,7 +658,7 @@ protected override XslFlags VisitValueOfDoe(XslNode node) protected override XslFlags VisitParam(VarPar node) { Template? tmpl = _currentTemplate as Template; - if (tmpl != null && tmpl.Match != null) + if (tmpl is not null && tmpl.Match is not null) { // This template has 'match' attribute and might be called from built-in template rules, // all xsl:param's will be defaulted in that case @@ -699,7 +699,7 @@ private XslFlags ProcessVarPar(VarPar node) } #endif - if (node.Select != null) + if (node.Select is not null) { if (node.Content.Count != 0) { @@ -712,7 +712,7 @@ private XslFlags ProcessVarPar(VarPar node) { result = _xpathAnalyzer!.Analyze(node.Select); _typeDonor = _xpathAnalyzer.TypeDonor; - if (_typeDonor != null && node.NodeType != XslNodeType.WithParam) + if (_typeDonor is not null && node.NodeType != XslNodeType.WithParam) { _dataFlow!.AddEdge(_typeDonor, node); } @@ -826,7 +826,7 @@ private void DepthFirstSearch(ProtoTemplate t) } Template? template = t as Template; if ( - template != null && // This ProteTemplate is Template + template is not null && // This ProteTemplate is Template _revApplyTemplatesGraph!.TryGetValue(template.Mode, out list) // list - ProtoTemplates that have apply-templatess mode="{template.Mode}" ) { @@ -878,7 +878,7 @@ public XPathAnalyzer(Compiler compiler, CompilerScopeManager scope) public XslFlags Analyze(string? xpathExpr) { _typeDonor = null; - if (xpathExpr == null) + if (xpathExpr is null) { return XslFlags.None; } @@ -903,7 +903,7 @@ public XslFlags Analyze(string? xpathExpr) public XslFlags AnalyzeAvt(string? source) { _typeDonor = null; - if (source == null) + if (source is null) { return XslFlags.None; } @@ -948,7 +948,7 @@ public XslFlags AnalyzeAvt(string? source) private VarPar? ResolveVariable(string prefix, string name) { string? ns = ResolvePrefix(prefix); - if (ns == null) + if (ns is null) { return null; } @@ -1020,7 +1020,7 @@ public virtual XslFlags Operator(XPathOperator op, XslFlags left, XslFlags right public virtual XslFlags Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? prefix, string? name) { _typeDonor = null; - if (xpathAxis == XPathAxis.Self && nodeType == XPathNodeType.All && prefix == null && name == null) + if (xpathAxis == XPathAxis.Self && nodeType == XPathNodeType.All && prefix is null && name is null) { return XslFlags.Current | XslFlags.Node; } @@ -1047,7 +1047,7 @@ public virtual XslFlags Predicate(XslFlags nodeset, XslFlags predicate, bool isR public virtual XslFlags Variable(string prefix, string name) { _typeDonor = ResolveVariable(prefix, name); - if (_typeDonor == null) + if (_typeDonor is null) { return XslFlags.AnyType; } @@ -1132,10 +1132,10 @@ public virtual XslFlags Function(string prefix, string name, IList arg { // Unknown function. Can be script function or extension function funcFlags = XslFlags.AnyType; - if (_compiler.Settings.EnableScript && ns != null) + if (_compiler.Settings.EnableScript && ns is not null) { XmlExtensionFunction? scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, default(NullErrorHelper)); - if (scrFunc != null) + if (scrFunc is not null) { XmlQueryType xt = scrFunc.XmlReturnType; if (xt == TypeFactory.StringX) @@ -1269,7 +1269,7 @@ public void Rewrite(Compiler compiler) private static int NodeCostForXPath(string? xpath) { int cost = 0; - if (xpath != null) + if (xpath is not null) { // Every XPath expression needs at least one iterator cost = IteratorNodeCost; @@ -1431,7 +1431,7 @@ private void Refactor(XslNode parent, int split) if (!scoperecord.IsVariable) { // The scope record is either a namespace declaration or an exclusion namespace - Debug.Assert(scoperecord.IsNamespace || scoperecord.ncName == null); + Debug.Assert(scoperecord.IsNamespace || scoperecord.ncName is null); Debug.Assert(!_compiler.IsPhantomNamespace(scoperecord.nsUri!)); newtemplate.Namespaces = new NsDecl(newtemplate.Namespaces, scoperecord.ncName, scoperecord.nsUri); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltInput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltInput.cs index a92349ad85fb45..1637a14b356cf1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltInput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltInput.cs @@ -40,15 +40,15 @@ internal class XsltInput : IErrorHelper public XsltInput(XmlReader reader, Compiler compiler, KeywordsTable atoms) { - Debug.Assert(reader != null); - Debug.Assert(atoms != null); + Debug.Assert(reader is not null); + Debug.Assert(atoms is not null); EnsureExpandEntities(reader); IXmlLineInfo? xmlLineInfo = reader as IXmlLineInfo; _atoms = atoms; _reader = reader; _reatomize = reader.NameTable != atoms.NameTable; - _readerLineInfo = (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) ? xmlLineInfo : null; + _readerLineInfo = (xmlLineInfo is not null && xmlLineInfo.HasLineInfo()) ? xmlLineInfo : null; _topLevelReader = reader.ReadState == ReadState.Initial; _scopeManager = new CompilerScopeManager(atoms); _compiler = compiler; @@ -72,9 +72,9 @@ public XsltInput(XmlReader reader, Compiler compiler, KeywordsTable atoms) private static void EnsureExpandEntities(XmlReader reader) { XmlTextReader? tr = reader as XmlTextReader; - if (tr != null && tr.EntityHandling != EntityHandling.ExpandEntities) + if (tr is not null && tr.EntityHandling != EntityHandling.ExpandEntities) { - Debug.Assert(tr.Settings == null, "XmlReader created with XmlReader.Create should always expand entities."); + Debug.Assert(tr.Settings is null, "XmlReader created with XmlReader.Create should always expand entities."); tr.EntityHandling = EntityHandling.ExpandEntities; } } @@ -113,7 +113,7 @@ public bool FindStylesheetElement() { // This may be an embedded stylesheet - store namespaces in scope IXmlNamespaceResolver? nsResolver = _reader as IXmlNamespaceResolver; - if (nsResolver != null) + if (nsResolver is not null) { namespacesInScope = nsResolver.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); } @@ -127,13 +127,13 @@ public bool FindStylesheetElement() // If namespacesInScope is not null then the stylesheet being read is an embedded stylesheet that can have namespaces // defined outside of xsl:stylesheet instruction. In this case the namespace definitions collected above have to be added // to the element scope. - if (namespacesInScope != null) + if (namespacesInScope is not null) { foreach (KeyValuePair prefixNamespacePair in namespacesInScope) { // The namespace could be redefined on the element we just read. If this is the case scopeManager already has // namespace definition for this prefix and the old definition must not be added to the scope. - if (_scopeManager.LookupNamespace(prefixNamespacePair.Key) == null) + if (_scopeManager.LookupNamespace(prefixNamespacePair.Key) is null) { string nsAtomizedValue = _atoms.NameTable.Add(prefixNamespacePair.Value); _scopeManager.AddNsDeclaration(prefixNamespacePair.Key, nsAtomizedValue); @@ -178,7 +178,7 @@ private void FillupRecord(ref Record rec) rec.prefix = _atoms.NameTable.Add(rec.prefix); } - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType)); } @@ -186,7 +186,7 @@ private void FillupRecord(ref Record rec) private void SetRecordEnd(ref Record rec) { - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType)); if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.start)) @@ -208,7 +208,7 @@ private void FillupTextRecord(ref Record rec) rec.value = _reader.Value; rec.baseUri = _reader.BaseURI; - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { bool isCDATA = (_reader.NodeType == XmlNodeType.CDATA); int line = _readerLineInfo.LineNumber; @@ -249,7 +249,7 @@ private void FillupCharacterEntityRecord(ref Record rec) rec.prefix = string.Empty; rec.baseUri = _reader.BaseURI; - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - 1); } @@ -259,7 +259,7 @@ private void FillupCharacterEntityRecord(ref Record rec) rec.value = _reader.Value; _reader.Read(); Debug.Assert(_reader.NodeType == XmlNodeType.EndEntity); - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + 1); } @@ -298,7 +298,7 @@ private bool ReadAttribute(ref Record rec) SetRecordEnd(ref rec); return true; } - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { int correction = (_reader.NodeType == XmlNodeType.EntityReference) ? -2 : -1; rec.valueStart = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction); @@ -327,7 +327,7 @@ private bool ReadAttribute(ref Record rec) } } while (_reader.ReadAttributeValue()); rec.value = _strConcat.GetResult(); - if (_readerLineInfo != null) + if (_readerLineInfo is not null) { Debug.Assert(_reader.NodeType != XmlNodeType.EntityReference); int correction = ((_reader.NodeType == XmlNodeType.EndEntity) ? 1 : lastText.Length) + 1; @@ -551,7 +551,7 @@ public bool MoveToLiteralAttribute(int attNum) public bool MoveToXsltAttribute(int attNum, string attName) { - Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error."); + Debug.Assert(_attributes is not null && _attributes[attNum].name == attName, "Attribute numbering error."); _currentRecord = _xsltAttributeNumber[attNum]; return _currentRecord != 0; } @@ -563,7 +563,7 @@ public bool IsRequiredAttribute(int attNum) public bool AttributeExists(int attNum, string attName) { - Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error."); + Debug.Assert(_attributes is not null && _attributes[attNum].name == attName, "Attribute numbering error."); return _xsltAttributeNumber[attNum] != 0; } @@ -980,7 +980,7 @@ private void InsertExNamespaces(int attExPrefixes, ContextInfo ctxInfo, bool ext for (int idx = 0; idx < list.Length; idx++) { - if (list[idx] != null) + if (list[idx] is not null) { ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, list[idx]); // null means that this Exlusion NS if (extensions) @@ -1015,7 +1015,7 @@ private void SetDefaultCollation(int attCollation) int col; for (col = 0; col < list.Length; col++) { - if (System.Xml.Xsl.Runtime.XmlCollation.Create(list[col], /*throw:*/false) != null) + if (System.Xml.Xsl.Runtime.XmlCollation.Create(list[col], /*throw:*/false) is not null) { break; } @@ -1055,7 +1055,7 @@ public ISourceLineInfo BuildLineInfo() public ISourceLineInfo BuildNameLineInfo() { - if (_readerLineInfo == null) + if (_readerLineInfo is null) { return BuildLineInfo(); } @@ -1065,7 +1065,7 @@ public ISourceLineInfo BuildNameLineInfo() // LocalName (and other cached properties) can be null only if nothing has been read from the reader. // This happens for instance when a reader which has already been closed or a reader positioned // on the very last node of the document is passed to the ctor. - if (LocalName == null) + if (LocalName is null) { // Fill up the current record to set all the properties used below. FillupRecord(ref _records[_currentRecord]); @@ -1081,7 +1081,7 @@ public ISourceLineInfo BuildReaderLineInfo() { Location loc; - if (_readerLineInfo != null) + if (_readerLineInfo is not null) loc = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition); else loc = new Location(0, 0); @@ -1092,9 +1092,9 @@ public ISourceLineInfo BuildReaderLineInfo() // Resolve prefix, return null and report an error if not found public string? LookupXmlNamespace(string prefix) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); string? nsUri = _scopeManager.LookupNamespace(prefix); - if (nsUri != null) + if (nsUri is not null) { Debug.Assert(Ref.Equal(_atoms.NameTable.Get(nsUri), nsUri), "Namespaces must be atomized"); return nsUri; 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 da0c17a1febeb2..d5088eaf659efa 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 @@ -41,12 +41,12 @@ internal class XsltLoader : IErrorHelper public void Load(Compiler compiler, object stylesheet, XmlResolver? xmlResolver) { - Debug.Assert(compiler != null); + Debug.Assert(compiler is not null); _compiler = compiler; _xmlResolver = xmlResolver ?? XmlNullResolver.Singleton; XmlReader? reader = stylesheet as XmlReader; - if (reader != null) + if (reader is not null) { _readerSettings = new QueryReaderSettings(reader); Load(reader); @@ -56,14 +56,14 @@ public void Load(Compiler compiler, object stylesheet, XmlResolver? xmlResolver) // We should take DefaultReaderSettings from Compiler.Settings.DefaultReaderSettings. string? uri = stylesheet as string; - if (uri != null) + if (uri is not null) { - // If xmlResolver == null, then the original uri will be resolved using XmlUrlResolver + // If xmlResolver is null, then the original uri will be resolved using XmlUrlResolver XmlResolver origResolver = xmlResolver!; - if (xmlResolver == null || xmlResolver == XmlNullResolver.Singleton) + if (xmlResolver is null || xmlResolver == XmlNullResolver.Singleton) origResolver = new XmlUrlResolver(); Uri resolvedUri = origResolver.ResolveUri(null, uri); - if (resolvedUri == null) + if (resolvedUri is null) { throw new XslLoadException(SR.Xslt_CantResolve, uri); } @@ -77,7 +77,7 @@ public void Load(Compiler compiler, object stylesheet, XmlResolver? xmlResolver) else { IXPathNavigable? navigable = stylesheet as IXPathNavigable; - if (navigable != null) + if (navigable is not null) { reader = XPathNavigatorReader.Create(navigable.CreateNavigator()!); _readerSettings = new QueryReaderSettings(reader.NameTable); @@ -89,7 +89,7 @@ public void Load(Compiler compiler, object stylesheet, XmlResolver? xmlResolver) } } } - Debug.Assert(compiler.Root != null); + Debug.Assert(compiler.Root is not null); compiler.StartApplyTemplates = f.ApplyTemplates(nullMode); ProcessOutputSettings(); foreach (AttributeSet attSet in compiler.AttributeSets.Values) @@ -180,7 +180,7 @@ private Uri ResolveUri(string relativeUri, string baseUri) { Uri? resolvedBaseUri = (baseUri.Length != 0) ? _xmlResolver.ResolveUri(null, baseUri) : null; Uri resolvedUri = _xmlResolver.ResolveUri(resolvedBaseUri, relativeUri); - if (resolvedUri == null) + if (resolvedUri is null) { throw new XslLoadException(SR.Xslt_CantResolve, relativeUri); } @@ -192,24 +192,24 @@ private XmlReader CreateReader(Uri uri, XmlResolver xmlResolver) object? input = xmlResolver.GetEntity(uri, null, null); Stream? stream = input as Stream; - if (stream != null) + if (stream is not null) { return _readerSettings.CreateReader(stream, uri.ToString()); } XmlReader? reader = input as XmlReader; - if (reader != null) + if (reader is not null) { return reader; } IXPathNavigable? navigable = input as IXPathNavigable; - if (navigable != null) + if (navigable is not null) { return XPathNavigatorReader.Create(navigable.CreateNavigator()!); } - throw new XslLoadException(SR.Xslt_CannotLoadStylesheet, uri.ToString(), input == null ? "null" : input.GetType().ToString()); + throw new XslLoadException(SR.Xslt_CannotLoadStylesheet, uri.ToString(), input is null ? "null" : input.GetType().ToString()); } private Stylesheet LoadStylesheet(Uri uri, bool include) @@ -260,10 +260,10 @@ private Stylesheet LoadStylesheet(XmlReader reader, bool include) { throw; } - // Note that XmlResolver or XmlReader may throw XmlException with SourceUri == null. + // Note that XmlResolver or XmlReader may throw XmlException with SourceUri is null. // In that case we report current line information from XsltInput. XmlException? ex = e as XmlException; - ISourceLineInfo lineInfo = (ex != null && ex.SourceUri != null ? + ISourceLineInfo lineInfo = (ex is not null && ex.SourceUri is not null ? new SourceLineInfo(ex.SourceUri, ex.LineNumber, ex.LinePosition, ex.LineNumber, ex.LinePosition) : _input.BuildReaderLineInfo() ); @@ -311,7 +311,7 @@ private void LoadDocument() private void LoadSimplifiedStylesheet() { Debug.Assert(!_input.IsXsltNamespace()); - Debug.Assert(_curTemplate == null); + Debug.Assert(_curTemplate is null); // Prefix will be fixed later in LoadLiteralResultElement() _curTemplate = f.Template(/*name:*/null, /*match:*/"/", /*mode:*/nullMode, /*priority:*/double.NaN, _input.XslVersion); @@ -319,7 +319,7 @@ private void LoadSimplifiedStylesheet() // This template has mode=null match="/" and no imports _input.CanHaveApplyImports = true; XslNode lre = LoadLiteralResultElement(/*asStylesheet:*/true); - if (lre != null) + if (lre is not null) { SetLineInfo(_curTemplate, lre.SourceLine); @@ -576,7 +576,7 @@ private void LoadOutput() TriState triState; QilName? name = ParseQNameAttribute(0); - if (name != null) ReportNYI("xsl:output/@name"); + if (name is not null) ReportNYI("xsl:output/@name"); if (_input.MoveToXsltAttribute(1, "method")) { @@ -585,7 +585,7 @@ private void LoadOutput() _compiler.EnterForwardsCompatible(); XmlOutputMethod outputMethod; XmlQualifiedName? method = ParseOutputMethod(_input.Value, out outputMethod); - if (_compiler.ExitForwardsCompatible(_input.ForwardCompatibility) && method != null) + if (_compiler.ExitForwardsCompatible(_input.ForwardCompatibility) && method is not null) { if (currentPrec == output.MethodPrec && !output.Method!.Equals(method)) { @@ -812,7 +812,7 @@ private void CheckUseAttrubuteSetInList(IList list) private void CheckAttributeSetsDfs(AttributeSet attSet) { - Debug.Assert(attSet != null); + Debug.Assert(attSet is not null); switch (attSet.CycleCheck) { case CycleCheck.NotStarted: @@ -824,7 +824,7 @@ private void CheckAttributeSetsDfs(AttributeSet attSet) break; default: Debug.Assert(attSet.CycleCheck == CycleCheck.Processing); - Debug.Assert(attSet.Content[0].SourceLine != null); + Debug.Assert(attSet.Content[0].SourceLine is not null); _compiler.ReportError(/*[XT0720]*/attSet.Content[0].SourceLine!, SR.Xslt_CircularAttributeSet, attSet.Name!.QualifiedName); break; } @@ -852,7 +852,7 @@ private void LoadKey(NsDecl? stylesheetNsList) if (V1) { - if (use == null) + if (use is null) { _input.SkipNode(); } @@ -869,13 +869,13 @@ private void LoadKey(NsDecl? stylesheetNsList) { content = LoadEndTag(content); } - if ((use == null) == (content.Count == 0)) + if ((use is null) == (content.Count == 0)) { ReportError(/*[XTSE1205]*/SR.Xslt_KeyCntUse); } else { - if (use == null) ReportNYI("xsl:key[count(@use) = 0]"); + if (use is null) ReportNYI("xsl:key[count(@use) = 0]"); } } @@ -1031,7 +1031,7 @@ private void LoadNamespaceAlias(NsDecl? stylesheetNsList) CheckNoContent(); - if (stylesheetNsUri == null || resultNsUri == null) + if (stylesheetNsUri is null || resultNsUri is null) { // At least one of attributes is missing or invalid return; @@ -1054,7 +1054,7 @@ private void LoadAttributeSet(NsDecl? stylesheetNsList) ctxInfo.nsList = MergeNamespaces(ctxInfo.nsList, stylesheetNsList); QilName? setName = ParseQNameAttribute(0); - Debug.Assert(setName != null, "Required attribute always != null"); + Debug.Assert(setName is not null, "Required attribute always is not null"); AttributeSet? set; if (!_curStylesheet!.AttributeSets!.TryGetValue(setName, out set)) @@ -1110,7 +1110,7 @@ private void LoadAttributeSet(NsDecl? stylesheetNsList) private void LoadGlobalVariableOrParameter(NsDecl? stylesheetNsList, XslNodeType nodeType) { - Debug.Assert(_curTemplate == null); + Debug.Assert(_curTemplate is null); Debug.Assert(_input.CanHaveApplyImports == false); VarPar var = XslVarPar(); // Preserving namespaces to parse content later @@ -1128,7 +1128,7 @@ private void LoadGlobalVariableOrParameter(NsDecl? stylesheetNsList, XslNodeType }; private void LoadTemplate(NsDecl? stylesheetNsList) { - Debug.Assert(_curTemplate == null); + Debug.Assert(_curTemplate is null); ContextInfo ctxInfo = _input.GetAttributes(_templateAttributes); ctxInfo.nsList = MergeNamespaces(ctxInfo.nsList, stylesheetNsList); @@ -1145,7 +1145,7 @@ private void LoadTemplate(NsDecl? stylesheetNsList) } QilName mode = V1 ? ParseModeAttribute(3) : ParseModeListAttribute(3); - if (match == null) + if (match is null) { CheckError(!_input.AttributeExists(1, "name"), /*[XT_007]*/SR.Xslt_BothMatchNameAbsent); CheckError(_input.AttributeExists(3, "mode"), /*[XT_008]*/SR.Xslt_ModeWithoutMatch); @@ -1171,7 +1171,7 @@ private void LoadTemplate(NsDecl? stylesheetNsList) _curTemplate = f.Template(name, match, mode, priority, _input.XslVersion); // Template without match considered to not have mode and can't call xsl:apply-imports - _input.CanHaveApplyImports = (match != null); + _input.CanHaveApplyImports = (match is not null); SetInfo(_curTemplate, LoadEndTag(LoadInstructions(InstructionFlags.AllowParam)), ctxInfo @@ -1239,7 +1239,7 @@ private void LoadCharacterMap(NsDecl stylesheetNsList) { new XsltAttribute("override", V2Opt) }; private void LoadFunction(NsDecl stylesheetNsList) { - Debug.Assert(curTemplate == null); + Debug.Assert(curTemplate is null); ContextInfo ctxInfo = input.GetAttributes(functionAttributes); ctxInfo.nsList = MergeNamespaces(ctxInfo.nsList, stylesheetNsList); @@ -1296,12 +1296,12 @@ private void LoadMsScript(NsDecl? stylesheetNsList) } } - if (scriptNs == null) + if (scriptNs is null) { scriptNs = _compiler.CreatePhantomNamespace(); } string? language = ParseStringAttribute(1, "language"); - if (language == null) + if (language is null) { language = "jscript"; } @@ -1391,7 +1391,7 @@ private List LoadInstructions(List content, InstructionFlags f !atTop ? /*[XT_014]*/SR.Xslt_NotAtTop : /*else*/ null ); - if (error != null) + if (error is not null) { ReportError(error, _input.QualifiedName, parentName); atTop = false; @@ -1556,7 +1556,7 @@ private XslNode XslApplyTemplates() ContextInfo ctxInfo = _input.GetAttributes(_applyTemplatesAttributes); string? select = ParseStringAttribute(0, "select"); - if (select == null) + if (select is null) { select = "node()"; } @@ -1702,7 +1702,7 @@ private XslNode XslChoose() } } } - if (node == null) + if (node is null) { ReportError(/*[XT_020]*/SR.Xslt_UnexpectedElement, _input.QualifiedName, parentName); _input.SkipNode(); @@ -1766,7 +1766,7 @@ private XslNode XslMessage() { content = LoadEndTag(content); } - if (select != null) + if (select is not null) { content.Insert(0, f.CopyOf(select, _input.XslVersion)); } @@ -1795,7 +1795,7 @@ private XslNode XslNumber() string? value = ParseStringAttribute(0, "value"); string? select = ParseStringAttribute(1, "select"); - if (select != null) ReportNYI("xsl:number/@select"); + if (select is not null) ReportNYI("xsl:number/@select"); NumberLevel level = NumberLevel.Single; if (_input.MoveToXsltAttribute(2, "level")) { @@ -1823,7 +1823,7 @@ private XslNode XslNumber() string? groupingSize = ParseStringAttribute(10, "grouping-size"); // Default values for xsl:number : level="single" format="1" - if (format == null) + if (format is null) { format = "1"; } @@ -1852,11 +1852,11 @@ private XslNode XslValueOf() string? separator = ParseStringAttribute(1, "separator"); bool doe = ParseYesNoAttribute(2, /*attName:*/"disable-output-escaping") == TriState.True; - if (separator == null) + if (separator is null) { if (!_input.BackwardCompatibility) { - separator = select != null ? " " : string.Empty; + separator = select is not null ? " " : string.Empty; } } else @@ -1868,7 +1868,7 @@ private XslNode XslValueOf() if (V1) { - if (select == null) + if (select is null) { _input.SkipNode(); return SetInfo(f.Error(XslLoadException.CreateMessage(ctxInfo.lineInfo, SR.Xslt_MissingAttribute, "select")), null, ctxInfo); @@ -1877,8 +1877,8 @@ private XslNode XslValueOf() } else { - content = LoadContent(select != null); - CheckError(select == null && content.Count == 0, /*[???]*/SR.Xslt_NoSelectNoContent, _input.ElementName); + content = LoadContent(select is not null); + CheckError(select is null && content.Count == 0, /*[???]*/SR.Xslt_NoSelectNoContent, _input.ElementName); if (content.Count != 0) { ReportNYI("xsl:value-of/*"); @@ -1943,7 +1943,7 @@ private VarPar XslVarPar() TriState required = ParseYesNoAttribute(3, "required"); if (required == TriState.True) ReportNYI("xsl:param/@required == true()"); - if (asType != null) + if (asType is not null) { ReportNYI("xsl:param/@as"); } @@ -1951,7 +1951,7 @@ private VarPar XslVarPar() TriState tunnel = ParseYesNoAttribute(4, "tunnel"); if (tunnel != TriState.Unknown) { - if (nodeType == XslNodeType.Param && _curTemplate == null) + if (nodeType == XslNodeType.Param && _curTemplate is null) { if (!_input.ForwardCompatibility) { @@ -1964,8 +1964,8 @@ private VarPar XslVarPar() } } - List content = LoadContent(select != null); - CheckError((required == TriState.True) && (select != null || content.Count != 0), /*[???]*/SR.Xslt_RequiredAndSelect, name!.ToString()); + List content = LoadContent(select is not null); + CheckError((required == TriState.True) && (select is not null || content.Count != 0), /*[???]*/SR.Xslt_RequiredAndSelect, name!.ToString()); VarPar result = f.VarPar(nodeType, name, select, _input.XslVersion); SetInfo(result, content, ctxInfo); @@ -1981,9 +1981,9 @@ private XslNode XslComment() { ContextInfo ctxInfo = _input.GetAttributes(_commentAttributes); string? select = ParseStringAttribute(0, "select"); - if (select != null) ReportNYI("xsl:comment/@select"); + if (select is not null) ReportNYI("xsl:comment/@select"); - return SetInfo(f.Comment(), LoadContent(select != null), ctxInfo); + return SetInfo(f.Comment(), LoadContent(select is not null), ctxInfo); } private List LoadContent(bool hasSelect) @@ -2010,9 +2010,9 @@ private XslNode XslProcessingInstruction() ContextInfo ctxInfo = _input.GetAttributes(_processingInstructionAttributes); string name = ParseNCNameAttribute(0); string? select = ParseStringAttribute(1, "select"); - if (select != null) ReportNYI("xsl:processing-instruction/@select"); + if (select is not null) ReportNYI("xsl:processing-instruction/@select"); - return SetInfo(f.PI(name, _input.XslVersion), LoadContent(select != null), ctxInfo); + return SetInfo(f.PI(name, _input.XslVersion), LoadContent(select is not null), ctxInfo); } // http://www.w3.org/TR/xslt#section-Creating-Text @@ -2108,15 +2108,15 @@ private XslNode XslAttribute() CheckError(ns == XmlReservedNs.NsXmlNs, /*[XT_024]*/SR.Xslt_ReservedNS, ns); string? select = ParseStringAttribute(2, "select"); - if (select != null) ReportNYI("xsl:attribute/@select"); + if (select is not null) ReportNYI("xsl:attribute/@select"); string? separator = ParseStringAttribute(3, "separator"); - if (separator != null) ReportNYI("xsl:attribute/@separator"); - separator = separator != null ? separator : (select != null ? " " : string.Empty); + if (separator is not null) ReportNYI("xsl:attribute/@separator"); + separator = separator is not null ? separator : (select is not null ? " " : string.Empty); ParseTypeAttribute(4); ParseValidationAttribute(5, /*defVal:*/false); - return SetInfo(f.Attribute(name, ns, _input.XslVersion), LoadContent(select != null), ctxInfo); + return SetInfo(f.Attribute(name, ns, _input.XslVersion), LoadContent(select is not null), ctxInfo); } // http://www.w3.org/TR/xslt#sorting @@ -2154,7 +2154,7 @@ private XslNode XslSort(int sortNumber) } else { - content = LoadContent(select != null); + content = LoadContent(select is not null); if (content.Count != 0) { ReportNYI("xsl:sort/*"); @@ -2162,7 +2162,7 @@ private XslNode XslSort(int sortNumber) } } - if (select == null /*&& content.Count == 0*/) + if (select is null /*&& content.Count == 0*/) { select = "."; } @@ -2203,7 +2203,7 @@ private XslNode XslAnalyzeString() { string select = ParseStringAttribute(0, "select"); string regex = ParseStringAttribute(1, "regex" ); string flags = ParseStringAttribute(2, "flags" ); - if (flags == null) { + if (flags is null) { flags = ""; } @@ -2218,14 +2218,14 @@ private XslNode XslAnalyzeString() { case XmlNodeType.Element: if (input.IsXsltKeyword(atoms.MatchingSubstring)) { ContextInfo ctxInfoChld = input.GetAttributes(); - CheckError(nonMatching != null, /*[???]*/SR.Xslt_AnalyzeStringChildOrder); - CheckError(matching != null, /*[???]*/SR.Xslt_AnalyzeStringDupChild, atoms.MatchingSubstring); + CheckError(nonMatching is not null, /*[???]*/SR.Xslt_AnalyzeStringChildOrder); + CheckError(matching is not null, /*[???]*/SR.Xslt_AnalyzeStringDupChild, atoms.MatchingSubstring); // The current template rule becomes null, so we must not allow xsl:apply-import's within this element input.CanHaveApplyImports = false; matching = SetInfo(f.List(), LoadInstructions(), ctxInfoChld); } else if (input.IsXsltKeyword(atoms.NonMatchingSubstring)) { ContextInfo ctxInfoChld = input.GetAttributes(); - CheckError(nonMatching != null, /*[???]*/SR.Xslt_AnalyzeStringDupChild, atoms.NonMatchingSubstring); + CheckError(nonMatching is not null, /*[???]*/SR.Xslt_AnalyzeStringDupChild, atoms.NonMatchingSubstring); input.CanHaveApplyImports = false; nonMatching = SetInfo(f.List(), LoadInstructions(), ctxInfoChld); } else if (input.IsXsltKeyword(atoms.Fallback)) { @@ -2262,8 +2262,8 @@ private XslNode XslNamespace() { string name = ParseNCNameAttribute(0); string select= ParseStringAttribute(1, "select"); - List content = LoadContent(select != null); - CheckError(select == null && content.Count == 0, /*[???]*/SR.Xslt_NoSelectNoContent, input.ElementName); + List content = LoadContent(select is not null); + CheckError(select is null && content.Count == 0, /*[???]*/SR.Xslt_NoSelectNoContent, input.ElementName); ReportNYI("xsl:namespace"); @@ -2281,7 +2281,7 @@ private XslNode XslPerformSort() { List content = LoadInstructions(InstructionFlags.AllowSort); ctxInfo.SaveExtendedLineInfo(input); - if (select != null) { + if (select is not null) { foreach (XslNode node in content) { if (node.NodeType != XslNodeType.Sort) { ReportError(SR.Xslt_PerformSortCntSel); @@ -2425,9 +2425,9 @@ private XslNode XslResultDocument() { ReportNYI("xsl:result-document"); - if (format != null) ReportNYI("xsl:result-document/@format"); + if (format is not null) ReportNYI("xsl:result-document/@format"); - if (href == null) { + if (href is null) { href = string.Empty; } // attHref is a BaseUri of new output tree. It should be resolved relative to "base output URI" @@ -2469,23 +2469,23 @@ private XslNode XslResultDocument() { if (byteOrderMask != TriState.Unknown) ReportNYI("xsl:result-document/@byte-order-mark"); if (!escapeUriAttributes) ReportNYI("xsl:result-document/@escape-uri-attributes == flase()"); if (!includeContentType) ReportNYI("xsl:output/@include-content-type == flase()"); - if (normalizationForm != null) ReportNYI("xsl:result-document/@normalization-form"); + if (normalizationForm is not null) ReportNYI("xsl:result-document/@normalization-form"); if (undeclarePrefixes) ReportNYI("xsl:result-document/@undeclare-prefixes == true()"); - if (docTypePublic != null) { + if (docTypePublic is not null) { settings.DocTypePublic = docTypePublic; } - if (docTypeSystem != null) { + if (docTypeSystem is not null) { settings.DocTypeSystem = docTypeSystem; } - if (mediaType != null) { + if (mediaType is not null) { settings.MediaType = mediaType; } - if (useCharacterMaps != null) ReportNYI("xsl:result-document/@use-character-maps"); + if (useCharacterMaps is not null) ReportNYI("xsl:result-document/@use-character-maps"); - if (outputVersion != null) { + if (outputVersion is not null) { // BUGBUG: Check that version is a valid nmtoken // ignore version since we support only one version for both xml (1.0) and html (4.0) ReportNYI("xsl:result-document/@output-version"); @@ -2542,7 +2542,7 @@ private XslNode LoadLiteralResultElement(bool asStylesheet) private void CheckWithParam(List content, XslNode withParam) { - Debug.Assert(content != null && withParam != null); + Debug.Assert(content is not null && withParam is not null); Debug.Assert(withParam.NodeType == XslNodeType.WithParam); foreach (XslNode node in content) { @@ -2556,8 +2556,8 @@ private void CheckWithParam(List content, XslNode withParam) private static void AddInstruction(List content, XslNode? instruction) { - Debug.Assert(content != null); - if (instruction != null) + Debug.Assert(content is not null); + if (instruction is not null) { content.Add(instruction); } @@ -2565,7 +2565,7 @@ private static void AddInstruction(List content, XslNode? instruction) private List LoadEndTag(List content) { - Debug.Assert(content != null); + Debug.Assert(content is not null); if (_compiler.IsDebug && !_input.IsEmptyElement) { AddInstruction(content, SetLineInfo(f.Nop(), _input.BuildLineInfo())); @@ -2760,7 +2760,7 @@ private QilName ParseModeListAttribute(int attNum) // Does not suppress errors private bool ResolveQName(bool ignoreDefaultNs, string qname, out string localName, out string namespaceName, out string prefix) { - if (qname == null) + if (qname is null) { // That means stylesheet is incorrect prefix = _compiler.PhantomNCName; @@ -2780,7 +2780,7 @@ private bool ResolveQName(bool ignoreDefaultNs, string qname, out string localNa else { namespaceName = _input.LookupXmlNamespace(prefix)!; - if (namespaceName == null) + if (namespaceName is null) { namespaceName = _compiler.CreatePhantomNamespace(); return false; @@ -2810,7 +2810,7 @@ private bool ResolveQName(bool ignoreDefaultNs, string qname, out string localNa { _compiler.ExitForwardsCompatible(_input.ForwardCompatibility); } - if (result == null && required) + if (result is null && required) { result = f.QName(_compiler.PhantomNCName, _compiler.CreatePhantomNamespace(), _compiler.PhantomNCName); } @@ -2846,7 +2846,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 (elements is not null && elements.Length != 0) { string[] tokens = XmlConvert.SplitString(elements); for (int i = 0; i < tokens.Length; i++) @@ -2856,21 +2856,21 @@ private void ParseWhitespaceRules(string elements, bool preserveSpace) { namespaceName = _compiler.CreatePhantomNamespace(); } - else if (prefix == null || prefix.Length == 0) + else if (prefix is null || prefix.Length == 0) { namespaceName = prefix; } else { namespaceName = _input.LookupXmlNamespace(prefix); - if (namespaceName == null) + if (namespaceName is null) { namespaceName = _compiler.CreatePhantomNamespace(); } } int index = ( - (localName == null ? 1 : 0) + - (namespaceName == null ? 1 : 0) + (localName is null ? 1 : 0) + + (namespaceName is null ? 1 : 0) ); _curStylesheet!.AddWhitespaceRule(index, new WhitespaceRule(localName, namespaceName, preserveSpace)); } @@ -2914,7 +2914,7 @@ private void ParseWhitespaceRules(string elements, bool preserveSpace) private void AddUseAttributeSets(List list) { Debug.Assert(_input.LocalName == "use-attribute-sets", "we are positioned on this attribute"); - Debug.Assert(list != null && list.Count == 0, "It happened that we always add use-attribute-sets first. Otherwise we can't call list.Clear()"); + Debug.Assert(list is not null && list.Count == 0, "It happened that we always add use-attribute-sets first. Otherwise we can't call list.Clear()"); _compiler.EnterForwardsCompatible(); foreach (string qname in XmlConvert.SplitString(_input.Value)) @@ -3042,7 +3042,7 @@ private void ParseInputTypeAnnotationsAttribute(int attNum) break; case "strip": case "preserve": - if (_compiler.inputTypeAnnotations == null) + if (_compiler.inputTypeAnnotations is null) { _compiler.inputTypeAnnotations = value; } @@ -3067,7 +3067,7 @@ private void CheckNoContent() QName parentName = _input.ElementName; ISourceLineInfo? errorLineInfo = SkipEmptyContent(); - if (errorLineInfo != null) + if (errorLineInfo is not null) { _compiler.ReportError(errorLineInfo, /*[XT0260]*/SR.Xslt_NotEmptyContents, parentName); } @@ -3086,7 +3086,7 @@ private void CheckNoContent() // NOTE: XmlNodeType.SignificantWhitespace is not allowed here if (_input.NodeType != XmlNodeType.Whitespace) { - if (result == null) + if (result is null) { result = _input.BuildNameLineInfo(); } @@ -3099,15 +3099,15 @@ private void CheckNoContent() private static XslNode SetLineInfo(XslNode node, ISourceLineInfo? lineInfo) { - Debug.Assert(node != null); + Debug.Assert(node is not null); node.SourceLine = lineInfo; return node; } private static void SetContent(XslNode node, List? content) { - Debug.Assert(node != null); - if (content != null && content.Count == 0) + Debug.Assert(node is not null); + if (content is not null && content.Count == 0) { content = null; // Actualy we can reuse this ArrayList. } @@ -3116,7 +3116,7 @@ private static void SetContent(XslNode node, List? content) internal static XslNode SetInfo(XslNode to, List? content, ContextInfo info) { - Debug.Assert(to != null); + Debug.Assert(to is not null); to.Namespaces = info.nsList; SetContent(to, content); SetLineInfo(to, info.lineInfo); @@ -3132,22 +3132,22 @@ internal static XslNode SetInfo(XslNode to, List? content, ContextInfo // we should copy NsDecls of stylesheet locally in toplevel elements. private static NsDecl? MergeNamespaces(NsDecl? thisList, NsDecl? parentList) { - if (parentList == null) + if (parentList is null) { return thisList; } - if (thisList == null) + if (thisList is null) { return parentList; } // Clone all nodes and attache them to nodes of thisList; - while (parentList != null) + while (parentList is not null) { bool duplicate = false; - for (NsDecl? tmp = thisList; tmp != null; tmp = tmp.Prev) + for (NsDecl? tmp = thisList; tmp is not null; tmp = tmp.Prev) { if (Ref.Equal(tmp.Prefix, parentList.Prefix) && ( - tmp.Prefix != null || // Namespace declaration + tmp.Prefix is not null || // Namespace declaration tmp.NsUri == parentList.NsUri // Extension or excluded namespace )) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs index 909d0f8a7cade8..088dd62b675f78 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs @@ -43,7 +43,7 @@ public void CheckXsltType(QilNode n) [Conditional("DEBUG")] public void CheckQName(QilNode n) { - Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.QNameX), "Must be a singleton QName"); + Debug.Assert(n is not null && n.XmlType!.IsSubtypeOf(T.QNameX), "Must be a singleton QName"); } // We use a value of XmlQualifiedName type to denote a missing parameter @@ -119,7 +119,7 @@ public QilNode InvokeLangToLcid(QilNode n, bool fwdCompat) public QilNode InvokeNumberFormat(QilNode value, QilNode format, QilNode lang, QilNode letterValue, QilNode groupingSeparator, QilNode groupingSize) { - Debug.Assert(value != null && ( + Debug.Assert(value is not null && ( value.XmlType!.IsSubtypeOf(T.IntXS) || value.XmlType.IsSubtypeOf(T.DoubleX)), "Value must be either a sequence of ints, or a double singleton" @@ -138,7 +138,7 @@ public QilNode InvokeNumberFormat(QilNode value, QilNode format, public QilNode InvokeRegisterDecimalFormat(DecimalFormatDecl format) { - Debug.Assert(format != null); + Debug.Assert(format is not null); return XsltInvokeEarlyBound(QName("register-decimal-format"), XsltMethods.RegisterDecimalFormat, T.IntX, new QilNode[] { @@ -151,7 +151,7 @@ public QilNode InvokeRegisterDecimalFormat(DecimalFormatDecl format) public QilNode InvokeRegisterDecimalFormatter(QilNode formatPicture, DecimalFormatDecl format) { CheckString(formatPicture); - Debug.Assert(format != null); + Debug.Assert(format is not null); return XsltInvokeEarlyBound(QName("register-decimal-formatter"), XsltMethods.RegisterDecimalFormatter, T.DoubleX, new QilNode[] { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs index 083e1e7da48a9d..2d28c4e2855c2c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs @@ -60,7 +60,7 @@ internal XPathNavigator? Node { get { - if (_nodeSet != null) + if (_nodeSet is not null) { return _nodeSet.Current; } @@ -97,19 +97,19 @@ internal void AllocateVariables(int count) internal object GetVariable(int index) { - Debug.Assert(_variables != null && index < _variables.Length); + Debug.Assert(_variables is not null && index < _variables.Length); return _variables[index]; } internal void SetVariable(int index, object value) { - Debug.Assert(_variables != null && index < _variables.Length); + Debug.Assert(_variables is not null && index < _variables.Length); _variables[index] = value; } internal void SetParameter(XmlQualifiedName name, object value) { - if (_withParams == null) + if (_withParams is null) { _withParams = new Hashtable(); } @@ -119,13 +119,13 @@ internal void SetParameter(XmlQualifiedName name, object value) internal void ResetParams() { - if (_withParams != null) + if (_withParams is not null) _withParams.Clear(); } internal object? GetParameter(XmlQualifiedName name) { - if (_withParams != null) + if (_withParams is not null) { return _withParams[name]; } @@ -134,14 +134,14 @@ internal void ResetParams() internal void InitNodeSet(XPathNodeIterator nodeSet) { - Debug.Assert(nodeSet != null); + Debug.Assert(nodeSet is not null); _nodeSet = nodeSet; } [MemberNotNull(nameof(_newNodeSet))] internal void InitNewNodeSet(XPathNodeIterator nodeSet) { - Debug.Assert(nodeSet != null); + Debug.Assert(nodeSet is not null); _newNodeSet = nodeSet; } @@ -189,7 +189,7 @@ internal void Finished() internal void Inherit(ActionFrame parent) { - Debug.Assert(parent != null); + Debug.Assert(parent is not null); _variables = parent._variables; } @@ -243,7 +243,7 @@ internal void Exit() [MemberNotNullWhen(false, nameof(_action))] internal bool Execute(Processor processor) { - if (_action == null) + if (_action is null) { return true; } @@ -255,7 +255,7 @@ internal bool Execute(Processor processor) if (State == Action.Finished) { // Advanced to next action - if (_container != null) + if (_container is not null) { _currentAction++; _action = _container.GetAction(_currentAction); @@ -265,7 +265,7 @@ internal bool Execute(Processor processor) { _action = null; } - return _action == null; + return _action is null; } return false; // Do not pop, unless specified otherwise diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyImportsAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyImportsAction.cs index c63f6e5d76787d..63e3a6c1edff65 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyImportsAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyImportsAction.cs @@ -26,7 +26,7 @@ internal override void Compile(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyTemplatesAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyTemplatesAction.cs index 52709c6f59dd36..67af3f083f79bd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyTemplatesAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ApplyTemplatesAction.cs @@ -29,20 +29,20 @@ internal class ApplyTemplatesAction : ContainerAction internal static ApplyTemplatesAction BuiltInRule() { - Debug.Assert(s_BuiltInRule != null); + Debug.Assert(s_BuiltInRule is not null); return s_BuiltInRule; } internal static ApplyTemplatesAction BuiltInRule(XmlQualifiedName? mode) { - return (mode == null || mode.IsEmpty) ? BuiltInRule() : new ApplyTemplatesAction(mode); + return (mode is null || mode.IsEmpty) ? BuiltInRule() : new ApplyTemplatesAction(mode); } internal ApplyTemplatesAction() { } private ApplyTemplatesAction(XmlQualifiedName mode) { - Debug.Assert(mode != null); + Debug.Assert(mode is not null); _mode = mode; } @@ -62,7 +62,7 @@ internal override bool CompileAttribute(Compiler compiler) } else if (Ref.Equal(name, compiler.Atoms.Mode)) { - Debug.Assert(_mode == null); + Debug.Assert(_mode is null); if (compiler.AllowBuiltInMode && value == "*") { _mode = Compiler.BuiltInMode; @@ -137,14 +137,14 @@ private void CompileContent(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: processor.ResetParams(); processor.InitSortArray(); - if (this.containedActions != null && this.containedActions.Count > 0) + if (this.containedActions is not null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); frame.State = ProcessedChildren; @@ -174,7 +174,7 @@ internal override void Execute(Processor processor, ActionFrame frame) case ProcessNextNode: Debug.Assert(frame.State == ProcessNextNode); - Debug.Assert(frame.NewNodeSet != null); + Debug.Assert(frame.NewNodeSet is not null); if (frame.NewNextNode(processor)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs index 1dc8f92828cff8..a6b29b4e0f1067 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs @@ -34,7 +34,7 @@ internal class AttributeAction : ContainerAction PrefixQName qname = new PrefixQName(); qname.SetQName(name); - qname.Namespace = nsUri != null ? nsUri : manager!.ResolveXPathNamespace(qname.Prefix); + qname.Namespace = nsUri is not null ? nsUri : manager!.ResolveXPathNamespace(qname.Prefix); if (qname.Prefix.StartsWith("xml", StringComparison.Ordinal)) { @@ -74,7 +74,7 @@ internal override void Compile(Compiler compiler) _nsUri = PrecalculateAvt(ref _nsAvt); // if both name and ns are not AVT we can calculate qname at compile time and will not need namespace manager anymore - if (_nameAvt == null && _nsAvt == null) + if (_nameAvt is null && _nsAvt is null) { if (_name != "xmlns") { @@ -115,23 +115,23 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - if (_qname != null) + if (_qname is not null) { frame.CalulatedName = _qname; } else { frame.CalulatedName = CreateAttributeQName( - _nameAvt == null ? _name! : _nameAvt.Evaluate(processor, frame), - _nsAvt == null ? _nsUri : _nsAvt.Evaluate(processor, frame), + _nameAvt is null ? _name! : _nameAvt.Evaluate(processor, frame), + _nsAvt is null ? _nsUri : _nsAvt.Evaluate(processor, frame), _manager ); - if (frame.CalulatedName == null) + if (frame.CalulatedName is null) { // name == "xmlns" case. Ignore xsl:attribute frame.Finished(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs index 037e44f0fa85c4..4518bc1f95d62c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs @@ -31,7 +31,7 @@ internal override bool CompileAttribute(Compiler compiler) string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Name)) { - Debug.Assert(this.name == null); + Debug.Assert(this.name is null); this.name = compiler.CreateXPathQName(value); } else if (Ref.Equal(name, compiler.Atoms.UseAttributeSets)) @@ -99,7 +99,7 @@ internal void Merge(AttributeSetAction attributeAction) Action? action; int i = 0; - while ((action = attributeAction.GetAction(i)) != null) + while ((action = attributeAction.GetAction(i)) is not null) { AddAction(action); i++; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Avt.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Avt.cs index fc78f2af4a37f9..71a74f2f40693b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Avt.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Avt.cs @@ -18,13 +18,13 @@ internal sealed class Avt private Avt(string constAvt) { - Debug.Assert(constAvt != null); + Debug.Assert(constAvt is not null); _constAvt = constAvt; } private Avt(ArrayList eventList) { - Debug.Assert(eventList != null); + Debug.Assert(eventList is not null); _events = new TextEvent[eventList.Count]; for (int i = 0; i < eventList.Count; i++) { @@ -35,19 +35,19 @@ private Avt(ArrayList eventList) [MemberNotNullWhen(false, nameof(_events))] public bool IsConstant { - get { return _events == null; } + get { return _events is null; } } internal string Evaluate(Processor? processor, ActionFrame? frame) { if (IsConstant) { - Debug.Assert(_constAvt != null); + Debug.Assert(_constAvt is not null); return _constAvt; } else { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); StringBuilder builder = processor.GetSharedStringBuilder(); @@ -62,8 +62,8 @@ internal string Evaluate(Processor? processor, ActionFrame? frame) internal static Avt CompileAvt(Compiler compiler, string avtText) { - Debug.Assert(compiler != null); - Debug.Assert(avtText != null); + Debug.Assert(compiler is not null); + Debug.Assert(avtText is not null); bool constant; ArrayList list = compiler.CompileAvt(avtText, out constant); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BeginEvent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BeginEvent.cs index 9c3adf6d817b70..144fd26cc150c8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BeginEvent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BeginEvent.cs @@ -23,7 +23,7 @@ internal class BeginEvent : Event public BeginEvent(Compiler compiler) { NavigatorInput input = compiler.Input; - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(input.NodeType != XPathNodeType.Namespace); _nodeType = input.NodeType; _namespaceUri = input.NamespaceURI; @@ -51,10 +51,10 @@ public override void ReplaceNamespaceAlias(Compiler compiler) return; // '#default' aren't apply to attributes. } NamespaceInfo? ResultURIInfo = compiler.FindNamespaceAlias(_namespaceUri); - if (ResultURIInfo != null) + if (ResultURIInfo is not null) { _namespaceUri = ResultURIInfo.nameSpace!; - if (ResultURIInfo.prefix != null) + if (ResultURIInfo.prefix is not null) { _prefix = ResultURIInfo.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 028752efcf66e0..856ace00604e5c 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 @@ -90,12 +90,12 @@ internal string Name { get { - if (_name == null) + if (_name is null) { string prefix = Prefix; string localName = LocalName; - if (prefix != null && 0 < prefix.Length) + if (prefix is not null && 0 < prefix.Length) { if (localName.Length > 0) { @@ -147,14 +147,14 @@ internal string Value for (int i = 0; i < this.TextInfoCount; i++) { string? ti = this.TextInfo[i]; - if (ti == null) continue; // ignore disableEscaping + if (ti is null) continue; // ignore disableEscaping size += ti.Length; } StringBuilder sb = new StringBuilder(size); for (int i = 0; i < this.TextInfoCount; i++) { string? ti = this.TextInfo[i]; - if (ti == null) continue; // ignore disableEscaping + if (ti is null) continue; // ignore disableEscaping sb.Append(ti); } return sb.ToString(); @@ -169,7 +169,7 @@ internal string Value internal void ValueAppend(string? s, bool disableEscaping) { - if (s == null || s.Length == 0) + if (s is null || s.Length == 0) { return; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs index aa1fb7d0bfde4f..c965b6d73a8bf1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs @@ -27,7 +27,7 @@ internal override bool CompileAttribute(Compiler compiler) string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Name)) { - Debug.Assert(_name == null); + Debug.Assert(_name is null); _name = compiler.CreateXPathQName(value); } else @@ -81,12 +81,12 @@ private void CompileContent(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: processor.ResetParams(); - if (this.containedActions != null && this.containedActions.Count > 0) + if (this.containedActions is not null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); frame.State = ProcessedChildren; @@ -95,7 +95,7 @@ internal override void Execute(Processor processor, ActionFrame frame) goto case ProcessedChildren; case ProcessedChildren: TemplateAction? action = processor.Stylesheet.FindTemplate(_name!); - if (action != null) + if (action is not null) { frame.State = ProcessedTemplate; processor.PushActionFrame(action, frame.NodeSet); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CommentAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CommentAction.cs index 0b80fcc9019c99..ac9578c22ec7c6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CommentAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CommentAction.cs @@ -23,7 +23,7 @@ internal override void Compile(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs index e0357b481bcf9b..afbf2789730044 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs @@ -58,7 +58,7 @@ public void CompileAttributes(Compiler compiler) internal static string? PrecalculateAvt(ref Avt? avt) { string? result = null; - if (avt != null && avt.IsConstant) + if (avt is not null && avt.IsConstant) { result = avt.Evaluate(null, null); avt = null; @@ -92,7 +92,7 @@ public void CheckEmpty(Compiler compiler) public void CheckRequiredAttribute(Compiler compiler, object? attrValue, string attrName) { - CheckRequiredAttribute(compiler, attrValue != null, attrName); + CheckRequiredAttribute(compiler, attrValue is not null, attrName); } public void CheckRequiredAttribute(Compiler compiler, bool attr, string attrName) 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 9b6c4195395962..9ea6bbfc804e79 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 @@ -98,7 +98,7 @@ internal KeywordsTable Atoms { get { - Debug.Assert(_atoms != null); + Debug.Assert(_atoms is not null); return _atoms; } } @@ -121,19 +121,19 @@ internal NavigatorInput Input internal bool Advance() { - Debug.Assert(Document != null); + Debug.Assert(Document is not null); return Document.Advance(); } internal bool Recurse() { - Debug.Assert(Document != null); + Debug.Assert(Document is not null); return Document.Recurse(); } internal bool ToParent() { - Debug.Assert(Document != null); + Debug.Assert(Document is not null); return Document.ToParent(); } @@ -147,9 +147,9 @@ internal RootAction RootAction get { return _rootAction; } set { - Debug.Assert(_rootAction == null); + Debug.Assert(_rootAction is null); _rootAction = value; - Debug.Assert(_currentTemplate == null); + Debug.Assert(_currentTemplate is null); _currentTemplate = _rootAction; } } @@ -172,9 +172,9 @@ internal string GetUnicRtfId() // internal void Compile(NavigatorInput input, XmlResolver xmlResolver) { - Debug.Assert(input != null); - Debug.Assert(xmlResolver != null); - Debug.Assert(_input == null && _atoms == null); + Debug.Assert(input is not null); + Debug.Assert(xmlResolver is not null); + Debug.Assert(_input is null && _atoms is null); _xmlResolver = xmlResolver; PushInputDocument(input); @@ -186,7 +186,7 @@ internal void Compile(NavigatorInput input, XmlResolver xmlResolver) this.rootStylesheet = new Stylesheet(); PushStylesheet(this.rootStylesheet); - Debug.Assert(_input != null && _atoms != null); + Debug.Assert(_input is not null && _atoms is not null); try { @@ -205,7 +205,7 @@ internal void Compile(NavigatorInput input, XmlResolver xmlResolver) _rootAction.PorcessAttributeSets(this.rootStylesheet); this.stylesheet.SortWhiteSpace(); - if (_globalNamespaceAliasTable != null) + if (_globalNamespaceAliasTable is not null) { this.stylesheet.ReplaceNamespaceAlias(this); _rootAction.ReplaceNamespaceAlias(this); @@ -216,10 +216,10 @@ internal void Compile(NavigatorInput input, XmlResolver xmlResolver) PopInputDocument(); } - Debug.Assert(_rootAction != null); - Debug.Assert(this.stylesheet != null); - Debug.Assert(_queryStore != null); - Debug.Assert(_input == null && _atoms == null); + Debug.Assert(_rootAction is not null); + Debug.Assert(this.stylesheet is not null); + Debug.Assert(_queryStore is not null); + Debug.Assert(_input is null && _atoms is null); } // @@ -241,7 +241,7 @@ internal bool CanHaveApplyImports internal void InsertExtensionNamespace(string value) { string[]? nsList = ResolvePrefixes(value); - if (nsList != null) + if (nsList is not null) { _scopeManager.InsertExtensionNamespaces(nsList); } @@ -250,7 +250,7 @@ internal void InsertExtensionNamespace(string value) internal void InsertExcludedNamespace(string value) { string[]? nsList = ResolvePrefixes(value); - if (nsList != null) + if (nsList is not null) { _scopeManager.InsertExcludedNamespaces(nsList); } @@ -327,18 +327,18 @@ internal int InsertVariable(VariableAction variable) InputScope varScope; if (variable.IsGlobal) { - Debug.Assert(_rootAction != null); + Debug.Assert(_rootAction is not null); varScope = _rootScope!; } else { - Debug.Assert(_currentTemplate != null); + Debug.Assert(_currentTemplate is not null); Debug.Assert(variable.VarType == VariableType.LocalVariable || variable.VarType == VariableType.LocalParameter || variable.VarType == VariableType.WithParameter); varScope = _scopeManager.VariableScope; } VariableAction? oldVar = varScope.ResolveVariable(variable.Name!); - if (oldVar != null) + if (oldVar is not null) { // Other variable with this name is visible in this scope if (oldVar.IsGlobal) @@ -381,12 +381,12 @@ internal int InsertVariable(VariableAction variable) internal void AddNamespaceAlias(string StylesheetURI, NamespaceInfo AliasInfo) { - if (_globalNamespaceAliasTable == null) + if (_globalNamespaceAliasTable is null) { _globalNamespaceAliasTable = new Hashtable(); } NamespaceInfo? duplicate = _globalNamespaceAliasTable[StylesheetURI] as NamespaceInfo; - if (duplicate == null || AliasInfo.stylesheetId <= duplicate.stylesheetId) + if (duplicate is null || AliasInfo.stylesheetId <= duplicate.stylesheetId) { _globalNamespaceAliasTable[StylesheetURI] = AliasInfo; } @@ -394,7 +394,7 @@ internal void AddNamespaceAlias(string StylesheetURI, NamespaceInfo AliasInfo) internal bool IsNamespaceAlias(string StylesheetURI) { - if (_globalNamespaceAliasTable == null) + if (_globalNamespaceAliasTable is null) { return false; } @@ -403,7 +403,7 @@ internal bool IsNamespaceAlias(string StylesheetURI) internal NamespaceInfo? FindNamespaceAlias(string StylesheetURI) { - if (_globalNamespaceAliasTable != null) + if (_globalNamespaceAliasTable is not null) { return (NamespaceInfo?)_globalNamespaceAliasTable[StylesheetURI]; } @@ -443,7 +443,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 (tokens is null || tokens.Length == 0) { return null; } @@ -473,7 +473,7 @@ internal void AddDecimalFormat(XmlQualifiedName name, DecimalFormat formatinfo) internal bool GetYesNo(string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert((object)value == (object)Input!.Value); // this is always true. Why we passing value to this function. if (value == "yes") { @@ -517,7 +517,7 @@ internal string GetSingleAttribute(string attributeAtom) input.ToParent(); } - if (value == null) + if (value is null) { throw XsltException.Create(SR.Xslt_MissingAttribute, attributeAtom); } @@ -577,10 +577,10 @@ internal bool IsCircularReference(string href) internal Uri ResolveUri(string relativeUri) { - Debug.Assert(_xmlResolver != null); + Debug.Assert(_xmlResolver is not null); string baseUri = this.Input!.BaseURI; Uri uri = _xmlResolver.ResolveUri((baseUri.Length != 0) ? _xmlResolver.ResolveUri(null, baseUri) : null, relativeUri); - if (uri == null) + if (uri is null) { throw XsltException.Create(SR.Xslt_CantResolve, relativeUri); } @@ -589,7 +589,7 @@ internal Uri ResolveUri(string relativeUri) internal NavigatorInput ResolveDocument(Uri absoluteUri) { - Debug.Assert(_xmlResolver != null); + Debug.Assert(_xmlResolver is not null); object? input = _xmlResolver.GetEntity(absoluteUri, null, null); string resolved = absoluteUri.ToString(); @@ -614,7 +614,7 @@ internal NavigatorInput ResolveDocument(Uri absoluteUri) internal void PushInputDocument(NavigatorInput newInput) { - Debug.Assert(newInput != null); + Debug.Assert(newInput is not null); string inputUri = newInput.Href; AddDocumentURI(inputUri); @@ -627,7 +627,7 @@ internal void PushInputDocument(NavigatorInput newInput) internal void PopInputDocument() { - Debug.Assert(_input != null); + Debug.Assert(_input is not null); Debug.Assert(_input.Atoms == _atoms); NavigatorInput lastInput = _input; @@ -635,7 +635,7 @@ internal void PopInputDocument() _input = lastInput.Next!; lastInput.Next = null; - if (_input != null) + if (_input is not null) { _atoms = _input.Atoms; _scopeManager = _input.InputScopeManager; @@ -691,7 +691,7 @@ internal void AddTemplate(TemplateAction template) internal void BeginTemplate(TemplateAction template) { - Debug.Assert(_currentTemplate != null); + Debug.Assert(_currentTemplate is not null); _currentTemplate = template; _currentMode = template.Mode; this.CanHaveApplyImports = template.MatchKey != Compiler.InvalidQueryKey; @@ -699,7 +699,7 @@ internal void BeginTemplate(TemplateAction template) internal void EndTemplate() { - Debug.Assert(_currentTemplate != null); + Debug.Assert(_currentTemplate is not null); _currentTemplate = _rootAction; } @@ -718,7 +718,7 @@ internal int AddQuery(string xpathQuery) internal int AddQuery(string xpathQuery, bool allowVar, bool allowKey, bool isPattern) { - Debug.Assert(_queryStore != null); + Debug.Assert(_queryStore is not null); CompiledXpathExpr expr; try @@ -931,7 +931,7 @@ private static bool GetNextAvtLex(string avt, ref int start, StringBuilder lex, internal ArrayList CompileAvt(string avtText, out bool constant) { - Debug.Assert(avtText != null); + Debug.Assert(avtText is not null); ArrayList list = new ArrayList(); constant = true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs index aaa95f7190d2db..8369de32327a9c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs @@ -98,12 +98,12 @@ internal void CompileStylesheetAttributes(Compiler compiler) input.ToParent(); } - if (version == null) + if (version is null) { throw XsltException.Create(SR.Xslt_MissingAttribute, "version"); } - if (badAttribute != null && !compiler.ForwardCompatibility) + if (badAttribute is not null && !compiler.ForwardCompatibility) { throw XsltException.Create(SR.Xslt_InvalidAttribute, badAttribute, element); } @@ -136,7 +136,7 @@ internal void CompileSingleTemplate(Compiler compiler) input.ToParent(); } - if (version == null) + if (version is null) { if (Ref.Equal(input.LocalName, input.Atoms.Stylesheet) && input.NamespaceURI == XmlReservedNs.NsWdXsl) @@ -227,7 +227,7 @@ private void CompileImports(Compiler compiler) for (int i = imports.Count - 1; 0 <= i; i--) { // Imports should be compiled in reverse order Uri? uri = imports[i] as Uri; - Debug.Assert(uri != null); + Debug.Assert(uri is not null); imports[i] = CompileImport(compiler, uri, ++_maxid); } compiler.Stylesheetid = saveStylesheetId; @@ -355,7 +355,7 @@ internal void CompileKey(Compiler compiler) CheckRequiredAttribute(compiler, MatchKey != Compiler.InvalidQueryKey, "match"); CheckRequiredAttribute(compiler, UseKey != Compiler.InvalidQueryKey, "use"); - CheckRequiredAttribute(compiler, Name != null, "name"); + CheckRequiredAttribute(compiler, Name is not null, "name"); // It is a breaking change to check for emptiness, SQLBUDT 324364 //CheckEmpty(compiler); @@ -435,7 +435,7 @@ protected void CompileDecimalFormat(Compiler compiler) input.ToParent(); } info.NegativeInfinitySymbol = string.Concat(info.NegativeSign, info.PositiveInfinitySymbol); - if (Name == null) + if (Name is null) { Name = new XmlQualifiedName(); } @@ -570,7 +570,7 @@ protected void CompileTopLevelElements(Compiler compiler) else if (Ref.Equal(name, input.Atoms.Variable)) { VariableAction? action = compiler.CreateVariableAction(VariableType.GlobalVariable); - if (action != null) + if (action is not null) { AddAction(action); } @@ -578,7 +578,7 @@ protected void CompileTopLevelElements(Compiler compiler) else if (Ref.Equal(name, input.Atoms.Param)) { VariableAction? action = compiler.CreateVariableAction(VariableType.GlobalParameter); - if (action != null) + if (action is not null) { AddAction(action); } @@ -759,7 +759,7 @@ private void CompileInstruction(Compiler compiler) throw compiler.UnexpectedKeyword(); } - Debug.Assert(action != null); + Debug.Assert(action is not null); AddAction(action); } @@ -861,7 +861,7 @@ private void CompileOutput(Compiler compiler) internal void AddAction(Action? action) { - if (this.containedActions == null) + if (this.containedActions is null) { this.containedActions = new ArrayList(); } @@ -872,7 +872,7 @@ internal void AddAction(Action? action) [MemberNotNull(nameof(lastCopyCodeAction))] private void EnsureCopyCodeAction() { - if (lastCopyCodeAction == null) + if (lastCopyCodeAction is null) { CopyCodeAction copyCode = new CopyCodeAction(); AddAction(copyCode); @@ -943,7 +943,7 @@ private void AddScript(Compiler compiler) while (input.MoveToNextAttribute()); input.ToParent(); } - if (implementsNamespace == null) + if (implementsNamespace is null) { throw XsltException.Create(SR.Xslt_MissingAttribute, input.Atoms.ImplementsPrefix); } @@ -957,12 +957,12 @@ private void AddScript(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - if (this.containedActions != null && this.containedActions.Count > 0) + if (this.containedActions is not null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); frame.State = ProcessingChildren; @@ -985,9 +985,9 @@ internal override void Execute(Processor processor, ActionFrame frame) internal Action? GetAction(int actionIndex) { - Debug.Assert(actionIndex == 0 || this.containedActions != null); + Debug.Assert(actionIndex == 0 || this.containedActions is not null); - if (this.containedActions != null && actionIndex < this.containedActions.Count) + if (this.containedActions is not null && actionIndex < this.containedActions.Count) { return (Action)this.containedActions[actionIndex]!; } @@ -999,12 +999,12 @@ internal override void Execute(Processor processor, ActionFrame frame) internal void CheckDuplicateParams(XmlQualifiedName name) { - if (this.containedActions != null) + if (this.containedActions is not null) { foreach (CompiledAction action in this.containedActions) { WithParamAction? param = action as WithParamAction; - if (param != null && param.Name == name) + if (param is not null && param.Name == name) { throw XsltException.Create(SR.Xslt_DuplicateWithParam, name.ToString()); } @@ -1014,7 +1014,7 @@ internal void CheckDuplicateParams(XmlQualifiedName name) internal override void ReplaceNamespaceAlias(Compiler compiler) { - if (this.containedActions == null) + if (this.containedActions is null) { return; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAction.cs index 2a08aa6320f451..5bf6aeea53da49 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAction.cs @@ -29,7 +29,7 @@ internal override void Compile(Compiler compiler) CompileTemplate(compiler); compiler.ToParent(); } - if (this.containedActions == null) + if (this.containedActions is null) _empty = true; } @@ -49,7 +49,7 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); while (processor.CanContinue) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAttributesAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAttributesAction.cs index 4868b2c20c1110..556ee88d4c74bc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAttributesAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyAttributesAction.cs @@ -19,13 +19,13 @@ internal sealed class CopyAttributesAction : Action internal static CopyAttributesAction GetAction() { - Debug.Assert(s_Action != null); + Debug.Assert(s_Action is not null); return s_Action; } internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); while (processor.CanContinue) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyCodeAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyCodeAction.cs index 3234ebc3ae9c03..32138efdc26690 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyCodeAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyCodeAction.cs @@ -28,7 +28,7 @@ internal void AddEvent(Event copyEvent) internal void AddEvents(ArrayList copyEvents) { - Debug.Assert(copyEvents != null); + Debug.Assert(copyEvents is not null); _copyEvents.AddRange(copyEvents); } @@ -43,8 +43,8 @@ internal override void ReplaceNamespaceAlias(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); - Debug.Assert(_copyEvents != null && _copyEvents.Count > 0); + Debug.Assert(processor is not null && frame is not null); + Debug.Assert(_copyEvents is not null && _copyEvents.Count > 0); switch (frame.State) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNamespacesAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNamespacesAction.cs index 843091df52c6be..380843901acd27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNamespacesAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNamespacesAction.cs @@ -16,13 +16,13 @@ internal sealed class CopyNamespacesAction : Action internal static CopyNamespacesAction GetAction() { - Debug.Assert(s_Action != null); + Debug.Assert(s_Action is not null); return s_Action; } internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); while (processor.CanContinue) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNodeSetAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNodeSetAction.cs index b7f3df9edcc2c7..b0bb6d56cca58a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNodeSetAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyNodeSetAction.cs @@ -21,13 +21,13 @@ internal sealed class CopyNodeSetAction : Action internal static CopyNodeSetAction GetAction() { - Debug.Assert(s_Action != null); + Debug.Assert(s_Action is not null); return s_Action; } internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); while (processor.CanContinue) { switch (frame.State) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs index 5aa6fb72955e1d..136bb540fc471c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs @@ -41,12 +41,12 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - Debug.Assert(frame.NodeSet != null); + Debug.Assert(frame.NodeSet is not null); Query query = processor.GetValueQuery(_selectKey); object result = query.Evaluate(frame.NodeSet); @@ -60,7 +60,7 @@ internal override void Execute(Processor processor, ActionFrame frame) } XPathNavigator? nav = result as XPathNavigator; - if (nav != null) + if (nav is not null) { processor.PushActionFrame(CopyNodeSetAction.GetAction(), new XPathSingletonIterator(nav)); frame.State = NodeSetCopied; @@ -80,7 +80,7 @@ internal override void Execute(Processor processor, ActionFrame frame) break; case ResultStored: - Debug.Assert(frame.StoredOutput != null); + Debug.Assert(frame.StoredOutput is not null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DbgCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DbgCompiler.cs index 02668f7a9c511b..57fafe6cb1451c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DbgCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DbgCompiler.cs @@ -58,8 +58,8 @@ public virtual VariableAction[] GlobalVariables { get { - Debug.Assert(this.Debugger != null); - if (_globalVarsCache == null) + Debug.Assert(this.Debugger is not null); + if (_globalVarsCache is null) { _globalVarsCache = (VariableAction[])_globalVars.ToArray(typeof(VariableAction)); } @@ -70,8 +70,8 @@ public virtual VariableAction[] LocalVariables { get { - Debug.Assert(this.Debugger != null); - if (_localVarsCache == null) + Debug.Assert(this.Debugger is not null); + if (_localVarsCache is null) { _localVarsCache = (VariableAction[])_localVars.ToArray(typeof(VariableAction)); } @@ -81,7 +81,7 @@ public virtual VariableAction[] LocalVariables private void DefineVariable(VariableAction variable) { - Debug.Assert(this.Debugger != null); + Debug.Assert(this.Debugger is not null); if (variable.IsGlobal) { for (int i = 0; i < _globalVars.Count; i++) @@ -589,9 +589,9 @@ internal override void Compile(Compiler compiler) _dbgData = new DbgData(compiler); base.Compile(compiler); - Debug.Assert(compiler.Debugger != null); + Debug.Assert(compiler.Debugger is not null); string builtIn = compiler.Debugger.GetBuiltInTemplatesUri(); - if (builtIn != null && builtIn.Length != 0) + if (builtIn is not null && builtIn.Length != 0) { compiler.AllowBuiltInMode = true; builtInSheet = compiler.RootAction.CompileImport(compiler, compiler.ResolveUri(builtIn), int.MaxValue); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DocumentScope.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DocumentScope.cs index 77a971882770b3..21070562d063a7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DocumentScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/DocumentScope.cs @@ -25,13 +25,13 @@ internal NamespaceDecl AddNamespace(string prefix, string uri, string prevDefaul internal string? ResolveAtom(string prefix) { - Debug.Assert(prefix != null && prefix.Length > 0); + Debug.Assert(prefix is not null && prefix.Length > 0); - for (NamespaceDecl? scope = this.scopes; scope != null; scope = scope.Next) + for (NamespaceDecl? scope = this.scopes; scope is not null; scope = scope.Next) { if (Ref.Equal(scope.Prefix, prefix)) { - Debug.Assert(scope.Uri != null); + Debug.Assert(scope.Uri is not null); return scope.Uri; } } @@ -41,13 +41,13 @@ internal NamespaceDecl AddNamespace(string prefix, string uri, string prevDefaul internal string? ResolveNonAtom(string prefix) { - Debug.Assert(prefix != null && prefix.Length > 0); + Debug.Assert(prefix is not null && prefix.Length > 0); - for (NamespaceDecl? scope = this.scopes; scope != null; scope = scope.Next) + for (NamespaceDecl? scope = this.scopes; scope is not null; scope = scope.Next) { if (scope.Prefix == prefix) { - Debug.Assert(scope.Uri != null); + Debug.Assert(scope.Uri is not null); return scope.Uri; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs index d32b9d4c0626c6..dccb9718f509b6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs @@ -33,7 +33,7 @@ private static PrefixQName CreateElementQName(string name, string? nsUri, InputS PrefixQName qname = new PrefixQName(); qname.SetQName(name); - if (nsUri == null) + if (nsUri is null) { qname.Namespace = manager!.ResolveXmlNamespace(qname.Prefix); } @@ -53,7 +53,7 @@ internal override void Compile(Compiler compiler) _nsUri = PrecalculateAvt(ref _nsAvt); // if both name and ns are not AVT we can calculate qname at compile time and will not need namespace manager anymore - if (_nameAvt == null && _nsAvt == null) + if (_nameAvt is null && _nsAvt is null) { if (_name != "xmlns") { @@ -71,7 +71,7 @@ internal override void Compile(Compiler compiler) CompileTemplate(compiler); compiler.ToParent(); } - _empty = (this.containedActions == null); + _empty = (this.containedActions is null); } internal override bool CompileAttribute(Compiler compiler) @@ -100,20 +100,20 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - if (_qname != null) + if (_qname is not null) { frame.CalulatedName = _qname; } else { frame.CalulatedName = CreateElementQName( - _nameAvt == null ? _name! : _nameAvt.Evaluate(processor, frame), - _nsAvt == null ? _nsUri : _nsAvt.Evaluate(processor, frame), + _nameAvt is null ? _name! : _nameAvt.Evaluate(processor, frame), + _nsAvt is null ? _nsUri : _nsAvt.Evaluate(processor, frame), _manager ); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Event.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Event.cs index 566f0774e06d27..8a792f0f4604eb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Event.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Event.cs @@ -16,8 +16,8 @@ public virtual void ReplaceNamespaceAlias(Compiler compiler) { } internal void OnInstructionExecute(Processor processor) { - Debug.Assert(processor.Debugger != null, "We don't generate calls this function if ! debugger"); - Debug.Assert(DbgData.StyleSheet != null, "We call this function from *EventDbg only"); + Debug.Assert(processor.Debugger is not null, "We don't generate calls this function if ! debugger"); + Debug.Assert(DbgData.StyleSheet is not null, "We call this function from *EventDbg only"); processor.OnInstructionExecute(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs index e367d52acaa20c..fa9dbbec6cbb50 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs @@ -51,12 +51,12 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - if (_sortContainer != null) + if (_sortContainer is not null) { processor.InitSortArray(); processor.PushActionFrame(_sortContainer, frame.NodeSet!); @@ -66,7 +66,7 @@ internal override void Execute(Processor processor, ActionFrame frame) goto case ProcessedSort; case ProcessedSort: frame.InitNewNodeSet(processor.StartQuery(frame.NodeSet!, _selectKey)); - if (_sortContainer != null) + if (_sortContainer is not null) { Debug.Assert(processor.SortArray.Count != 0); frame.SortNewNodeSet(processor, processor.SortArray); @@ -76,7 +76,7 @@ internal override void Execute(Processor processor, ActionFrame frame) case ProcessNextNode: Debug.Assert(frame.State == ProcessNextNode); - Debug.Assert(frame.NewNodeSet != null); + Debug.Assert(frame.NewNodeSet is not null); if (frame.NewNextNode(processor)) { @@ -111,7 +111,7 @@ protected void CompileSortElements(Compiler compiler) if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl) && Ref.Equal(input.LocalName, input.Atoms.Sort)) { - if (_sortContainer == null) + if (_sortContainer is null) { _sortContainer = new ContainerAction(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/HtmlProps.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/HtmlProps.cs index 7ae3808c591854..378198225c93f1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/HtmlProps.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/HtmlProps.cs @@ -48,7 +48,7 @@ public static HtmlElementProps Create(bool empty, bool abrParent, bool uriParent HtmlElementProps? result = (HtmlElementProps?)s_table[name]; return result; // We can do this but in case of Xml/Html mixed output this doesn't have big sence. - // return result != null ? result : s_otherElements; + // return result is not null ? result : s_otherElements; } private static Hashtable CreatePropsTable() @@ -159,7 +159,7 @@ public static HtmlAttributeProps Create(bool abr, bool uri, bool name) HtmlAttributeProps? result = (HtmlAttributeProps?)s_table[name]; return result; // We can do this but in case of Xml/Html mixed output this doesn't have big sence. - // return result != null ? result : s_otherElements; + // return result is not null ? result : s_otherElements; } private static Hashtable CreatePropsTable() diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs index b067309f69cf13..0d4115ec2b3c3e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs @@ -62,7 +62,7 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { @@ -85,7 +85,7 @@ internal override void Execute(Processor processor, ActionFrame frame) case ProcessingChildren: if (_type == ConditionType.ConditionWhen || _type == ConditionType.ConditionOtherwise) { - Debug.Assert(frame.Container != null); + Debug.Assert(frame.Container is not null); frame.Exit(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs index 93601bbb1908f1..4196c2370e392b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs @@ -50,7 +50,7 @@ internal void Init(InputScope? parent) this.scopes = null; _parent = parent; - if (_parent != null) + if (_parent is not null) { _forwardCompatibility = _parent._forwardCompatibility; _canHaveApplyImports = _parent._canHaveApplyImports; @@ -59,7 +59,7 @@ internal void Init(InputScope? parent) internal void InsertExtensionNamespace(string nspace) { - if (_extensionNamespaces == null) + if (_extensionNamespaces is null) { _extensionNamespaces = new Hashtable(); } @@ -68,7 +68,7 @@ internal void InsertExtensionNamespace(string nspace) internal bool IsExtensionNamespace(string nspace) { - if (_extensionNamespaces == null) + if (_extensionNamespaces is null) { return false; } @@ -77,7 +77,7 @@ internal bool IsExtensionNamespace(string nspace) internal void InsertExcludedNamespace(string nspace) { - if (_excludedNamespaces == null) + if (_excludedNamespaces is null) { _excludedNamespaces = new Hashtable(); } @@ -86,7 +86,7 @@ internal void InsertExcludedNamespace(string nspace) internal bool IsExcludedNamespace(string nspace) { - if (_excludedNamespaces == null) + if (_excludedNamespaces is null) { return false; } @@ -95,9 +95,9 @@ internal bool IsExcludedNamespace(string nspace) internal void InsertVariable(VariableAction variable) { - Debug.Assert(variable != null); + Debug.Assert(variable is not null); - if (_variables == null) + if (_variables is null) { _variables = new Hashtable(); } @@ -106,7 +106,7 @@ internal void InsertVariable(VariableAction variable) internal int GetVeriablesCount() { - if (_variables == null) + if (_variables is null) { return 0; } @@ -115,12 +115,12 @@ internal int GetVeriablesCount() public VariableAction? ResolveVariable(XmlQualifiedName qname) { - for (InputScope? inputScope = this; inputScope != null; inputScope = inputScope.Parent) + for (InputScope? inputScope = this; inputScope is not null; inputScope = inputScope.Parent) { - if (inputScope.Variables != null) + if (inputScope.Variables is not null) { VariableAction? variable = (VariableAction?)inputScope.Variables[qname]; - if (variable != null) + if (variable is not null) { return variable; } @@ -132,7 +132,7 @@ internal int GetVeriablesCount() public VariableAction? ResolveGlobalVariable(XmlQualifiedName qname) { InputScope? prevScope = null; - for (InputScope? inputScope = this; inputScope != null; inputScope = inputScope.Parent) + for (InputScope? inputScope = this; inputScope is not null; inputScope = inputScope.Parent) { prevScope = inputScope; } 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 25acce1c6ae401..c16b7eb23dce68 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 @@ -29,8 +29,8 @@ internal InputScope VariableScope { get { - Debug.Assert(_scopeStack != null); - Debug.Assert(_scopeStack.Parent != null); + Debug.Assert(_scopeStack is not null); + Debug.Assert(_scopeStack.Parent is not null); return _scopeStack.Parent; } } @@ -56,13 +56,13 @@ internal InputScope PushScope() internal void PopScope() { - Debug.Assert(_scopeStack != null, "Push/Pop disbalance"); - if (_scopeStack == null) + Debug.Assert(_scopeStack is not null, "Push/Pop disbalance"); + if (_scopeStack is null) { return; } - for (NamespaceDecl? scope = _scopeStack.Scopes; scope != null; scope = scope.Next) + for (NamespaceDecl? scope = _scopeStack.Scopes; scope is not null; scope = scope.Next) { _defaultNS = scope.PrevDefaultNsUri; } @@ -72,12 +72,12 @@ internal void PopScope() internal void PushNamespace(string prefix, string nspace) { - Debug.Assert(_scopeStack != null, "PushScope wasn't called"); - Debug.Assert(prefix != null); - Debug.Assert(nspace != null); + Debug.Assert(_scopeStack is not null, "PushScope wasn't called"); + Debug.Assert(prefix is not null); + Debug.Assert(nspace is not null); _scopeStack.AddNamespace(prefix, nspace, _defaultNS); - if (prefix == null || prefix.Length == 0) + if (prefix is null || prefix.Length == 0) { _defaultNS = nspace; } @@ -92,7 +92,7 @@ public string DefaultNamespace private string ResolveNonEmptyPrefix(string prefix) { - Debug.Assert(_scopeStack != null, "PushScope wasn't called"); + Debug.Assert(_scopeStack is not null, "PushScope wasn't called"); Debug.Assert(!string.IsNullOrEmpty(prefix)); if (prefix == "xml") { @@ -103,10 +103,10 @@ private string ResolveNonEmptyPrefix(string prefix) return XmlReservedNs.NsXmlNs; } - for (InputScope? inputScope = _scopeStack; inputScope != null; inputScope = inputScope.Parent) + for (InputScope? inputScope = _scopeStack; inputScope is not null; inputScope = inputScope.Parent) { string? nspace = inputScope.ResolveNonAtom(prefix); - if (nspace != null) + if (nspace is not null) { return nspace; } @@ -116,7 +116,7 @@ private string ResolveNonEmptyPrefix(string prefix) public string ResolveXmlNamespace(string prefix) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); if (prefix.Length == 0) { return _defaultNS; @@ -126,7 +126,7 @@ public string ResolveXmlNamespace(string prefix) public string ResolveXPathNamespace(string prefix) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); if (prefix.Length == 0) { return string.Empty; @@ -136,8 +136,8 @@ public string ResolveXPathNamespace(string prefix) internal void InsertExtensionNamespaces(string[] nsList) { - Debug.Assert(_scopeStack != null, "PushScope wasn't called"); - Debug.Assert(nsList != null); + Debug.Assert(_scopeStack is not null, "PushScope wasn't called"); + Debug.Assert(nsList is not null); for (int idx = 0; idx < nsList.Length; idx++) { _scopeStack.InsertExtensionNamespace(nsList[idx]); @@ -146,8 +146,8 @@ internal void InsertExtensionNamespaces(string[] nsList) internal bool IsExtensionNamespace(string nspace) { - Debug.Assert(_scopeStack != null, "PushScope wasn't called"); - for (InputScope? inputScope = _scopeStack; inputScope != null; inputScope = inputScope.Parent) + Debug.Assert(_scopeStack is not null, "PushScope wasn't called"); + for (InputScope? inputScope = _scopeStack; inputScope is not null; inputScope = inputScope.Parent) { if (inputScope.IsExtensionNamespace(nspace)) { @@ -159,8 +159,8 @@ internal bool IsExtensionNamespace(string nspace) internal void InsertExcludedNamespaces(string[] nsList) { - Debug.Assert(_scopeStack != null, "PushScope wasn't called"); - Debug.Assert(nsList != null); + Debug.Assert(_scopeStack is not null, "PushScope wasn't called"); + Debug.Assert(nsList is not null); for (int idx = 0; idx < nsList.Length; idx++) { _scopeStack.InsertExcludedNamespace(nsList[idx]); @@ -169,8 +169,8 @@ internal void InsertExcludedNamespaces(string[] nsList) internal bool IsExcludedNamespace(string nspace) { - Debug.Assert(_scopeStack != null, "PushScope wasn't called"); - for (InputScope? inputScope = _scopeStack; inputScope != null; inputScope = inputScope.Parent) + Debug.Assert(_scopeStack is not null, "PushScope wasn't called"); + for (InputScope? inputScope = _scopeStack; inputScope is not null; inputScope = inputScope.Parent) { if (inputScope.IsExcludedNamespace(nspace)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/MessageAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/MessageAction.cs index 4dd349725890d3..d826adf6aad8a9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/MessageAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/MessageAction.cs @@ -43,7 +43,7 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: @@ -55,7 +55,7 @@ internal override void Execute(Processor processor, ActionFrame frame) case ProcessingChildren: TextOnlyOutput? recOutput = processor.PopOutput() as TextOnlyOutput; - Debug.Assert(recOutput != null); + Debug.Assert(recOutput is not null); if (_Terminate) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NameSpaceEvent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NameSpaceEvent.cs index 57002bcfac1a74..86ba50c9204711 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NameSpaceEvent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NameSpaceEvent.cs @@ -15,7 +15,7 @@ internal class NamespaceEvent : Event public NamespaceEvent(NavigatorInput input) { - Debug.Assert(input != null); + Debug.Assert(input is not null); Debug.Assert(input.NodeType == XPathNodeType.Namespace); _namespaceUri = input.Value; _name = input.LocalName; @@ -26,10 +26,10 @@ public override void ReplaceNamespaceAlias(Compiler compiler) if (_namespaceUri.Length != 0) { // Do we need to check this for namespace? NamespaceInfo? ResultURIInfo = compiler.FindNamespaceAlias(_namespaceUri); - if (ResultURIInfo != null) + if (ResultURIInfo is not null) { _namespaceUri = ResultURIInfo.nameSpace!; - if (ResultURIInfo.prefix != null) + if (ResultURIInfo.prefix is not null) { _name = ResultURIInfo.prefix; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs index e149f0118fc5e6..642b85debb19c9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs @@ -206,15 +206,15 @@ internal bool MoveToNextNamespace() // internal NavigatorInput(XPathNavigator navigator, string baseUri, InputScope? rootScope) { - if (navigator == null) + if (navigator is null) { throw new ArgumentNullException(nameof(navigator)); } - if (baseUri == null) + if (baseUri is null) { throw new ArgumentNullException(nameof(baseUri)); } - Debug.Assert(navigator.NameTable != null); + Debug.Assert(navigator.NameTable is not null); _Next = null; _Href = baseUri; _Atoms = new KeywordsTable(navigator.NameTable); @@ -239,7 +239,7 @@ internal NavigatorInput(XPathNavigator navigator) : this(navigator, navigator.Ba [MemberNotNull(nameof(_Navigator))] internal void AssertInput() { - Debug.Assert(_Navigator != null); + Debug.Assert(_Navigator is not null); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorOutput.cs index c4471b42795735..c18a4c5a72db4b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorOutput.cs @@ -25,7 +25,7 @@ internal NavigatorOutput(string baseUri) public Processor.OutputResult RecordDone(RecordBuilder record) { - Debug.Assert(record != null); + Debug.Assert(record is not null); BuilderInfo mainNode = record.MainNode; _documentIndex++; 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 26b54dd0ca7718..b660f40ddd9640 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 @@ -114,7 +114,7 @@ private static string ConvertToArabic(double val, int minLength, int groupSize, { string str; - if (groupSize != 0 && groupSeparator != null) + if (groupSize != 0 && groupSeparator is not null) { NumberFormatInfo NumberFormat = new NumberFormatInfo(); NumberFormat.NumberGroupSizes = new int[] { groupSize }; @@ -231,7 +231,7 @@ internal override void Compile(Compiler compiler) _letter = ParseLetter(PrecalculateAvt(ref _letterAvt)); _lang = PrecalculateAvt(ref _langAvt); _groupingSep = PrecalculateAvt(ref _groupingSepAvt); - if (_groupingSep != null && _groupingSep.Length > 1) + if (_groupingSep is not null && _groupingSep.Length > 1) { throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator"); } @@ -382,7 +382,7 @@ private static object SimplifyValue(object value) if (Type.GetTypeCode(value.GetType()) == TypeCode.Object) { XPathNodeIterator? nodeset = value as XPathNodeIterator; - if (nodeset != null) + if (nodeset is not null) { if (nodeset.MoveNext()) { @@ -391,7 +391,7 @@ private static object SimplifyValue(object value) return string.Empty; } XPathNavigator? nav = value as XPathNavigator; - if (nav != null) + if (nav is not null) { return nav.Value; } @@ -401,13 +401,13 @@ private static object SimplifyValue(object value) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); ArrayList list = processor.NumberList; switch (frame.State) { case Initialized: - Debug.Assert(frame != null); - Debug.Assert(frame.NodeSet != null); + Debug.Assert(frame is not null); + Debug.Assert(frame.NodeSet is not null); list.Clear(); if (_valueKey != Compiler.InvalidQueryKey) { @@ -446,15 +446,15 @@ internal override void Execute(Processor processor, ActionFrame frame) /*CalculatingFormat:*/ frame.StoredOutput = Format(list, - _formatAvt == null ? _formatTokens : ParseFormat(_formatAvt.Evaluate(processor, frame)), - _langAvt == null ? _lang : _langAvt.Evaluate(processor, frame), - _letterAvt == null ? _letter : ParseLetter(_letterAvt.Evaluate(processor, frame)), - _groupingSepAvt == null ? _groupingSep : _groupingSepAvt.Evaluate(processor, frame), - _groupingSizeAvt == null ? _groupingSize : _groupingSizeAvt.Evaluate(processor, frame) + _formatAvt is null ? _formatTokens : ParseFormat(_formatAvt.Evaluate(processor, frame)), + _langAvt is null ? _lang : _langAvt.Evaluate(processor, frame), + _letterAvt is null ? _letter : ParseLetter(_letterAvt.Evaluate(processor, frame)), + _groupingSepAvt is null ? _groupingSep : _groupingSepAvt.Evaluate(processor, frame), + _groupingSizeAvt is null ? _groupingSize : _groupingSizeAvt.Evaluate(processor, frame) ); goto case OutputNumber; case OutputNumber: - Debug.Assert(frame.StoredOutput != null); + Debug.Assert(frame.StoredOutput is not null); if (!processor.TextEvent(frame.StoredOutput)) { frame.State = OutputNumber; @@ -502,13 +502,13 @@ private static string Format(ArrayList numberlist, List? tokens, st { StringBuilder result = new StringBuilder(); int cFormats = 0; - if (tokens != null) + if (tokens is not null) { cFormats = tokens.Count; } NumberingFormat numberingFormat = new NumberingFormat(); - if (groupingSize != null) + if (groupingSize is not null) { try { @@ -517,7 +517,7 @@ private static string Format(ArrayList numberlist, List? tokens, st catch (System.FormatException) { } catch (System.OverflowException) { } } - if (groupingSep != null) + if (groupingSep is not null) { if (groupingSep.Length > 1) { @@ -529,7 +529,7 @@ private static string Format(ArrayList numberlist, List? tokens, st if (0 < cFormats) { FormatInfo? prefix = tokens![0]; - Debug.Assert(prefix == null || prefix.isSeparator); + Debug.Assert(prefix is null || prefix.isSeparator); FormatInfo? sufix = null; if (cFormats % 2 == 1) { @@ -538,7 +538,7 @@ private static string Format(ArrayList numberlist, List? tokens, st } FormatInfo periodicSeparator = 2 < cFormats ? tokens[cFormats - 2]! : s_defaultSeparator; FormatInfo periodicFormat = 0 < cFormats ? tokens[cFormats - 1]! : s_defaultFormat; - if (prefix != null) + if (prefix is not null) { result.Append(prefix.formatString); } @@ -565,7 +565,7 @@ private static string Format(ArrayList numberlist, List? tokens, st result.Append(numberingFormat.FormatItem(numberlist[i]!)); } - if (sufix != null) + if (sufix is not null) { result.Append(sufix.formatString); } @@ -700,7 +700,7 @@ Parse format string into format tokens (alphanumeric) and separators [return: NotNullIfNotNull("formatString")] private static List? ParseFormat(string? formatString) { - if (formatString == null || formatString.Length == 0) + if (formatString is null || formatString.Length == 0) { return null; } @@ -752,7 +752,7 @@ Parse format string into format tokens (alphanumeric) and separators private string? ParseLetter(string? letter) { - if (letter == null || letter == "traditional" || letter == "alphabetic") + if (letter is null || letter == "traditional" || letter == "alphabetic") { return letter; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs index 813f36473c3fe4..94d8e9b73ca11b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs @@ -14,7 +14,7 @@ internal class OutKeywords #endif internal OutKeywords(XmlNameTable nameTable) { - Debug.Assert(nameTable != null); + Debug.Assert(nameTable is not null); #if DEBUG _NameTable = nameTable; #endif @@ -111,7 +111,7 @@ internal string XmlnsNamespace private void CheckKeyword(string keyword) { #if DEBUG - Debug.Assert(keyword != null); + Debug.Assert(keyword is not null); Debug.Assert((object)keyword == (object?)_NameTable.Get(keyword)); #endif } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScope.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScope.cs index c978824e636692..7f2c82b2a0a1b8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScope.cs @@ -82,12 +82,12 @@ internal void Init(string name, string nspace, string prefix, XmlSpace space, st internal bool FindPrefix(string urn, out string prefix) { - Debug.Assert(urn != null); + Debug.Assert(urn is not null); - for (NamespaceDecl? scope = this.scopes; scope != null; scope = scope.Next) + for (NamespaceDecl? scope = this.scopes; scope is not null; scope = scope.Next) { if (Ref.Equal(scope.Uri, urn) && - scope.Prefix != null && + scope.Prefix is not null && scope.Prefix.Length > 0) { prefix = scope.Prefix; 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 12cb0001644946..bfce99f3e99833 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 @@ -27,7 +27,7 @@ internal OutputScope CurrentElementScope { get { - Debug.Assert(_elementScopesStack.Peek() != null); // We adding rootElementScope to garantee this + Debug.Assert(_elementScopesStack.Peek() is not null); // We adding rootElementScope to garantee this return (OutputScope)_elementScopesStack.Peek()!; } } @@ -44,18 +44,18 @@ internal string XmlLang internal OutputScopeManager(XmlNameTable nameTable, OutKeywords atoms) { - Debug.Assert(nameTable != null); - Debug.Assert(atoms != null); + Debug.Assert(nameTable is not null); + Debug.Assert(atoms is not null); _elementScopesStack = new HWStack(STACK_INCREMENT); _nameTable = nameTable; _atoms = atoms; _defaultNS = _atoms.Empty; - // We always adding rootElementScope to garantee that CurrentElementScope != null + // We always adding rootElementScope to garantee that CurrentElementScope is not null // This context is active between PI and first element for example OutputScope rootElementScope = (OutputScope)_elementScopesStack.Push(); - if (rootElementScope == null) + if (rootElementScope is null) { rootElementScope = new OutputScope(); _elementScopesStack.AddToTop(rootElementScope); @@ -65,11 +65,11 @@ internal OutputScopeManager(XmlNameTable nameTable, OutKeywords atoms) internal void PushNamespace(string prefix, string nspace) { - Debug.Assert(prefix != null); - Debug.Assert(nspace != null); + Debug.Assert(prefix is not null); + Debug.Assert(nspace is not null); CurrentElementScope.AddNamespace(prefix, nspace, _defaultNS); - if (prefix == null || prefix.Length == 0) + if (prefix is null || prefix.Length == 0) { _defaultNS = nspace; } @@ -77,19 +77,19 @@ internal void PushNamespace(string prefix, string nspace) internal void PushScope(string name, string nspace, string prefix) { - Debug.Assert(name != null); - Debug.Assert(nspace != null); - Debug.Assert(prefix != null); + Debug.Assert(name is not null); + Debug.Assert(nspace is not null); + Debug.Assert(prefix is not null); OutputScope parentScope = CurrentElementScope; OutputScope elementScope = (OutputScope)_elementScopesStack.Push(); - if (elementScope == null) + if (elementScope is null) { elementScope = new OutputScope(); _elementScopesStack.AddToTop(elementScope); } - Debug.Assert(elementScope != null); + Debug.Assert(elementScope is not null); elementScope.Init(name, nspace, prefix, parentScope.Space, parentScope.Lang, parentScope.Mixed); } @@ -97,9 +97,9 @@ internal void PopScope() { OutputScope? elementScope = (OutputScope?)_elementScopesStack.Pop(); - Debug.Assert(elementScope != null); // We're adding rootElementScope to gurantee this + Debug.Assert(elementScope is not null); // We're adding rootElementScope to gurantee this - for (NamespaceDecl? scope = elementScope.Scopes; scope != null; scope = scope.Next) + for (NamespaceDecl? scope = elementScope.Scopes; scope is not null; scope = scope.Next) { _defaultNS = scope.PrevDefaultNsUri; } @@ -113,10 +113,10 @@ internal void PopScope() internal string? ResolveNamespace(string prefix, out bool thisScope) { - Debug.Assert(prefix != null); + Debug.Assert(prefix is not null); thisScope = true; - if (prefix == null || prefix.Length == 0) + if (prefix is null || prefix.Length == 0) { return _defaultNS; } @@ -137,7 +137,7 @@ internal void PopScope() OutputScope elementScope = (OutputScope)_elementScopesStack[i]; string? nspace = elementScope.ResolveAtom(prefix); - if (nspace != null) + if (nspace is not null) { thisScope = (i == _elementScopesStack.Length - 1); return nspace; @@ -150,7 +150,7 @@ internal void PopScope() internal bool FindPrefix(string nspace, out string? prefix) { - Debug.Assert(nspace != null); + Debug.Assert(nspace is not null); for (int i = _elementScopesStack.Length - 1; 0 <= i; i--) { Debug.Assert(_elementScopesStack[i] is OutputScope); @@ -160,7 +160,7 @@ internal bool FindPrefix(string nspace, out string? prefix) if (elementScope.FindPrefix(nspace, out pfx)) { string? testNspace = ResolveNamespace(pfx); - if (testNspace != null && Ref.Equal(testNspace, nspace)) + if (testNspace is not null && Ref.Equal(testNspace, nspace)) { prefix = pfx; return true; @@ -182,7 +182,7 @@ internal string GeneratePrefix(string format) do { prefix = string.Format(CultureInfo.InvariantCulture, format, _prefixIndex++); - } while (_nameTable.Get(prefix) != null); + } while (_nameTable.Get(prefix) is not null); return _nameTable.Add(prefix); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/PrefixQName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/PrefixQName.cs index e5dfaecce95959..570ef91593d02a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/PrefixQName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/PrefixQName.cs @@ -33,7 +33,7 @@ internal void SetQName(string qname) public static void ParseQualifiedName(string qname, out string prefix, out string local) { - Debug.Assert(qname != null); + Debug.Assert(qname is not null); prefix = string.Empty; local = string.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs index 814a496e92d266..832ba88d4f5110 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs @@ -65,15 +65,15 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - if (_nameAvt == null) + if (_nameAvt is null) { frame.StoredOutput = _name; - if (_name == null) + if (_name is null) { // name was static but was bad; frame.Finished(); @@ -92,7 +92,7 @@ internal override void Execute(Processor processor, ActionFrame frame) goto case NameReady; case NameReady: - Debug.Assert(frame.StoredOutput != null); + Debug.Assert(frame.StoredOutput is not null); if (processor.BeginEvent(XPathNodeType.ProcessingInstruction, string.Empty, frame.StoredOutput, string.Empty, false) == false) { // Come back later @@ -121,7 +121,7 @@ internal override void Execute(Processor processor, ActionFrame frame) internal static bool IsProcessingInstructionName(string? name) { - if (name == null) + if (name is null) { return false; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs index 8ef9fb4acef42e..7177498bf1490e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs @@ -114,7 +114,7 @@ internal XPathNavigator? Current get { ActionFrame? frame = (ActionFrame?)_actionStack.Peek(); - return frame != null ? frame.Node : null; + return frame is not null ? frame.Node : null; } } @@ -138,7 +138,7 @@ internal XmlResolver Resolver { get { - Debug.Assert(_resolver != null, "Constructor should create it if null passed"); + Debug.Assert(_resolver is not null, "Constructor should create it if null passed"); return _resolver; } } @@ -147,7 +147,7 @@ internal ArrayList SortArray { get { - Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); + Debug.Assert(_sortArray is not null, "InitSortArray() wasn't called"); return _sortArray; } } @@ -160,10 +160,10 @@ internal Key[]? KeyList internal XPathNavigator GetNavigator(Uri ruri) { XPathNavigator? result = null; - if (_documentCache != null) + if (_documentCache is not null) { result = _documentCache[ruri] as XPathNavigator; - if (result != null) + if (result is not null) { return result.Clone(); } @@ -198,13 +198,13 @@ internal XPathNavigator GetNavigator(Uri ruri) internal void AddSort(Sort sortinfo) { - Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); + Debug.Assert(_sortArray is not null, "InitSortArray() wasn't called"); _sortArray.Add(sortinfo); } internal void InitSortArray() { - if (_sortArray == null) + if (_sortArray is null) { _sortArray = new ArrayList(); } @@ -217,7 +217,7 @@ internal void InitSortArray() internal object? GetGlobalParameter(XmlQualifiedName qname) { object? parameter = _args.GetParam(qname.Name, qname.Namespace); - if (parameter == null) + if (parameter is null) { return null; } @@ -276,7 +276,7 @@ internal StringBuilder GetSharedStringBuilder() #if DEBUG Debug.Assert(!_stringBuilderLocked); #endif - if (_sharedStringBuilder == null) + if (_sharedStringBuilder is null) { _sharedStringBuilder = new StringBuilder(); } @@ -302,7 +302,7 @@ internal ArrayList NumberList { get { - if (_numberList == null) + if (_numberList is null) { _numberList = new ArrayList(); } @@ -353,14 +353,14 @@ public Processor( _resolver = resolver ?? XmlNullResolver.Singleton; _args = args ?? new XsltArgumentList(); _debugger = debugger; - if (_debugger != null) + if (_debugger is not null) { _debuggerStack = new HWStack(StackIncrement, /*limit:*/1000); _templateLookup = new TemplateLookupActionDbg(); } // Clone the compile-time KeyList - if (_rootAction.KeyList != null) + if (_rootAction.KeyList is not null) { _keyList = new Key[_rootAction.KeyList.Count]; for (int i = 0; i < _keyList.Length; i++) @@ -374,7 +374,7 @@ public Processor( foreach (DictionaryEntry entry in _stylesheet.ScriptObjectTypes) { string namespaceUri = (string)entry.Key; - if (GetExtensionObject(namespaceUri) != null) + if (GetExtensionObject(namespaceUri) is not null) { throw XsltException.Create(SR.Xslt_ScriptDub, namespaceUri); } @@ -444,15 +444,15 @@ public void Execute(XmlWriter writer) // internal void Execute() { - Debug.Assert(_actionStack != null); + Debug.Assert(_actionStack is not null); while (_execResult == ExecResult.Continue) { ActionFrame? frame = (ActionFrame?)_actionStack.Peek(); - if (frame == null) + if (frame is null) { - Debug.Assert(_builder != null); + Debug.Assert(_builder is not null); _builder.TheEnd(); ExecutionResult = ExecResult.Done; break; @@ -479,14 +479,14 @@ internal ActionFrame PushNewFrame() { ActionFrame? prent = (ActionFrame?)_actionStack.Peek(); ActionFrame frame = (ActionFrame)_actionStack.Push(); - if (frame == null) + if (frame is null) { frame = new ActionFrame(); _actionStack.AddToTop(frame); } - Debug.Assert(frame != null); + Debug.Assert(frame is not null); - if (prent != null) + if (prent is not null) { frame.Inherit(prent); } @@ -513,7 +513,7 @@ internal void PushActionFrame(ActionFrame container, XPathNodeIterator? nodeSet) internal void PushTemplateLookup(XPathNodeIterator? nodeSet, XmlQualifiedName? mode, Stylesheet? importsOf) { - Debug.Assert(_templateLookup != null); + Debug.Assert(_templateLookup is not null); _templateLookup.Initialize(mode, importsOf); PushActionFrame(_templateLookup, nodeSet); } @@ -546,7 +546,7 @@ internal Query GetValueQuery(int key, XsltCompileContext? context) theQuery.CompiledQuery.CheckErrors(); Query expr = _queryList[key]; - if (context == null) + if (context is null) { context = new XsltCompileContext(theQuery._ScopeManager, this); } @@ -561,7 +561,7 @@ internal Query GetValueQuery(int key, XsltCompileContext? context) private XsltCompileContext GetValueOfContext() { - if (_valueOfContext == null) + if (_valueOfContext is null) { _valueOfContext = new XsltCompileContext(); } @@ -571,7 +571,7 @@ private XsltCompileContext GetValueOfContext() [Conditional("DEBUG")] private void RecycleValueOfContext() { - if (_valueOfContext != null) + if (_valueOfContext is not null) { _valueOfContext.Recycle(); } @@ -579,7 +579,7 @@ private void RecycleValueOfContext() private XsltCompileContext GetMatchesContext() { - if (_matchesContext == null) + if (_matchesContext is null) { _matchesContext = new XsltCompileContext(); } @@ -589,7 +589,7 @@ private XsltCompileContext GetMatchesContext() [Conditional("DEBUG")] private void RecycleMatchesContext() { - if (_matchesContext != null) + if (_matchesContext is not null) { _matchesContext.Recycle(); } @@ -604,7 +604,7 @@ private void RecycleMatchesContext() if (value is XPathNodeIterator) { XPathNavigator? n = query.Advance(); - result = n != null ? ValueOf(n) : string.Empty; + result = n is not null ? ValueOf(n) : string.Empty; } else { @@ -677,7 +677,7 @@ internal object RunQuery(ActionFrame context, int key) Query query = GetCompiledQuery(key); object value = query.Evaluate(context.NodeSet!); XPathNodeIterator? it = value as XPathNodeIterator; - if (it != null) + if (it is not null) { return new XPathArrayIterator(it); } @@ -689,9 +689,9 @@ internal string EvaluateString(ActionFrame context, int key) { object objValue = Evaluate(context, key); string? value = null; - if (objValue != null) + if (objValue is not null) value = XmlConvert.ToXPathString(objValue); - if (value == null) + if (value is null) value = string.Empty; return value; } @@ -700,10 +700,10 @@ internal bool EvaluateBoolean(ActionFrame context, int key) { object objValue = Evaluate(context, key); - if (objValue != null) + if (objValue is not null) { XPathNavigator? nav = objValue as XPathNavigator; - return nav != null ? Convert.ToBoolean(nav.Value, CultureInfo.InvariantCulture) : Convert.ToBoolean(objValue, CultureInfo.InvariantCulture); + return nav is not null ? Convert.ToBoolean(nav.Value, CultureInfo.InvariantCulture) : Convert.ToBoolean(objValue, CultureInfo.InvariantCulture); } else { @@ -718,7 +718,7 @@ internal bool Matches(XPathNavigator? context, int key) try { - bool result = query.MatchNode(context) != null; + bool result = query.MatchNode(context) is not null; RecycleMatchesContext(); return result; @@ -750,7 +750,7 @@ internal bool ExecutionDone internal void ResetOutput() { - Debug.Assert(_builder != null); + Debug.Assert(_builder is not null); _builder.Reset(); } internal bool BeginEvent(XPathNodeType nodeType, string? prefix, string? name, string? nspace, bool empty) @@ -760,7 +760,7 @@ internal bool BeginEvent(XPathNodeType nodeType, string? prefix, string? name, s internal bool BeginEvent(XPathNodeType nodeType, string? prefix, string? name, string? nspace, bool empty, object? htmlProps, bool search) { - Debug.Assert(_xsm != null); + Debug.Assert(_xsm is not null); int stateOutlook = _xsm.BeginOutlook(nodeType); @@ -803,7 +803,7 @@ internal bool TextEvent(string? text) internal bool TextEvent(string? text, bool disableOutputEscaping) { - Debug.Assert(_xsm != null); + Debug.Assert(_xsm is not null); if (_ignoreLevel > 0) { @@ -838,7 +838,7 @@ internal bool TextEvent(string? text, bool disableOutputEscaping) internal bool EndEvent(XPathNodeType nodeType) { - Debug.Assert(_xsm != null); + Debug.Assert(_xsm is not null); if (_ignoreLevel > 0) { @@ -962,7 +962,7 @@ internal bool CopyEndEvent(XPathNavigator node) internal static bool IsRoot(XPathNavigator navigator) { - Debug.Assert(navigator != null); + Debug.Assert(navigator is not null); if (navigator.NodeType == XPathNodeType.Root) { @@ -985,7 +985,7 @@ internal static bool IsRoot(XPathNavigator navigator) // internal void PushOutput(IRecordOutput output) { - Debug.Assert(output != null); + Debug.Assert(output is not null); _builder!.OutputState = _xsm.State; RecordBuilder lastBuilder = _builder; _builder = new RecordBuilder(output, _nameTable); @@ -996,7 +996,7 @@ internal void PushOutput(IRecordOutput output) internal IRecordOutput PopOutput() { - Debug.Assert(_builder != null); + Debug.Assert(_builder is not null); RecordBuilder topBuilder = _builder; _builder = topBuilder.Next!; @@ -1028,7 +1028,7 @@ internal object GetVariableValue(VariableAction variable) { throw XsltException.Create(SR.Xslt_CircularReference, variable.NameStr); } - if (result != null) + if (result is not null) { return result; } @@ -1047,7 +1047,7 @@ internal object GetVariableValue(VariableAction variable) } while (saveStackSize < _actionStack.Length); Debug.Assert(saveStackSize == _actionStack.Length); result = rootFrame.GetVariable(variablekey); - Debug.Assert(result != null, "Variable was just calculated and result can't be null"); + Debug.Assert(result is not null, "Variable was just calculated and result can't be null"); return result; } else @@ -1086,9 +1086,9 @@ internal class DebuggerFrame internal void PushDebuggerStack() { - Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); + Debug.Assert(this.Debugger is not null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack!.Push(); - if (dbgFrame == null) + if (dbgFrame is null) { dbgFrame = new DebuggerFrame(); _debuggerStack.AddToTop(dbgFrame); @@ -1098,29 +1098,29 @@ internal void PushDebuggerStack() internal void PopDebuggerStack() { - Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); + Debug.Assert(this.Debugger is not null, "We don't generate calls this function if ! debugger"); _debuggerStack!.Pop(); } internal void OnInstructionExecute() { - Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); + Debug.Assert(this.Debugger is not null, "We don't generate calls this function if ! debugger"); DebuggerFrame? dbgFrame = (DebuggerFrame?)_debuggerStack!.Peek(); - Debug.Assert(dbgFrame != null, "PushDebuggerStack() wasn't ever called"); + Debug.Assert(dbgFrame is not null, "PushDebuggerStack() wasn't ever called"); dbgFrame.actionFrame = (ActionFrame?)_actionStack.Peek(); this.Debugger.OnInstructionExecute((IXsltProcessor)this); } internal XmlQualifiedName? GetPreviousMode() { - Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); + Debug.Assert(this.Debugger is not null, "We don't generate calls this function if ! debugger"); Debug.Assert(2 <= _debuggerStack!.Length); return ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 2]!).currentMode; } internal void SetCurrentMode(XmlQualifiedName? mode) { - Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); + Debug.Assert(this.Debugger is not null, "We don't generate calls this function if ! debugger"); ((DebuggerFrame)_debuggerStack![_debuggerStack.Length - 1]).currentMode = mode; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs index 0deeabd95fdcfc..dd1bb55854b6f0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs @@ -40,8 +40,8 @@ internal sealed class ReaderOutput : XmlReader, IRecordOutput internal ReaderOutput(Processor processor) { - Debug.Assert(processor != null); - Debug.Assert(processor.NameTable != null); + Debug.Assert(processor is not null); + Debug.Assert(processor.NameTable is not null); _processor = processor; _nameTable = processor.NameTable; @@ -67,7 +67,7 @@ public override string Name string prefix = Prefix; string localName = LocalName; - if (prefix != null && prefix.Length > 0) + if (prefix is not null && prefix.Length > 0) { if (localName.Length > 0) { @@ -167,12 +167,12 @@ public override bool IsDefault public override XmlSpace XmlSpace { - get { return _manager != null ? _manager.XmlSpace : XmlSpace.None; } + get { return _manager is not null ? _manager.XmlSpace : XmlSpace.None; } } public override string XmlLang { - get { return _manager != null ? _manager.XmlLang : string.Empty; } + get { return _manager is not null ? _manager.XmlLang : string.Empty; } } // Attribute Accessors @@ -307,7 +307,7 @@ public override bool MoveToElement() public override bool Read() { - Debug.Assert(_processor != null || _state == ReadState.Closed); + Debug.Assert(_processor is not null || _state == ReadState.Closed); if (_state != ReadState.Interactive) { @@ -420,7 +420,7 @@ public override string ReadString() } else { - if (sb == null) + if (sb is null) { sb = new StringBuilder(result); } @@ -430,7 +430,7 @@ public override string ReadString() throw new InvalidOperationException(SR.Xml_InvalidOperation); break; default: - return (sb == null) ? result : sb.ToString(); + return (sb is null) ? result : sb.ToString(); } } } @@ -448,7 +448,7 @@ public override string ReadInnerXml() Read(); // skeep begin Element while (depth < Depth) { // process content - Debug.Assert(_builder != null); + Debug.Assert(_builder is not null); output.RecordDone(_builder); Read(); } @@ -486,7 +486,7 @@ public override string ReadOuterXml() // process internal elements & text nodes while (depth < Depth) { - Debug.Assert(_builder != null); + Debug.Assert(_builder is not null); output.RecordDone(_builder); Read(); } @@ -520,7 +520,7 @@ public override XmlNameTable NameTable { get { - Debug.Assert(_nameTable != null); + Debug.Assert(_nameTable is not null); return _nameTable; } } @@ -529,7 +529,7 @@ public override XmlNameTable NameTable { string? atomizedPrefix = _nameTable.Get(prefix); - if (_manager != null && atomizedPrefix != null) + if (_manager is not null && atomizedPrefix is not null) { return _manager.ResolveNamespace(atomizedPrefix); } @@ -553,7 +553,7 @@ public override bool ReadAttributeValue() return false; } - if (_attributeValue == null) + if (_attributeValue is null) { _attributeValue = new BuilderInfo(); _attributeValue.NodeType = XmlNodeType.Text; @@ -628,11 +628,11 @@ private BuilderInfo GetBuilderInfo(int attrib) private bool FindAttribute(string? localName, string? namespaceURI, out int attrIndex) { - if (namespaceURI == null) + if (namespaceURI is null) { namespaceURI = string.Empty; } - if (localName == null) + if (localName is null) { localName = string.Empty; } @@ -655,7 +655,7 @@ private bool FindAttribute(string? localName, string? namespaceURI, out int attr private bool FindAttribute(string? name, out int attrIndex) { - if (name == null) + if (name is null) { name = string.Empty; } @@ -689,8 +689,8 @@ private void Reset() [System.Diagnostics.Conditional("DEBUG")] private void CheckCurrentInfo() { - Debug.Assert(_currentInfo != null); - Debug.Assert(_attributeCount == 0 || _attributeList != null); + Debug.Assert(_currentInfo is not null); + Debug.Assert(_attributeCount == 0 || _attributeList is not null); Debug.Assert((_currentIndex == -1) == (_currentInfo == _mainNode)); Debug.Assert((_currentIndex == -1) || (_currentInfo == _attributeValue || _attributeList![_currentIndex] is BuilderInfo && _attributeList[_currentIndex] == _currentInfo)); } @@ -710,7 +710,7 @@ private void Init() public string AttributeInnerXml(string value) { - if (_encoder == null) Init(); + if (_encoder is null) Init(); _buffer!.Length = 0; // clean buffer _encoder.StartAttribute(/*save:*/false); _encoder.Write(value); @@ -720,7 +720,7 @@ public string AttributeInnerXml(string value) public string AttributeOuterXml(string name, string value) { - if (_encoder == null) Init(); + if (_encoder is null) Init(); _buffer!.Length = 0; // clean buffer _buffer.Append(name); _buffer.Append('='); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs index 5e5c646ffe3f13..4fd03b340c2d93 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs @@ -52,9 +52,9 @@ internal sealed class RecordBuilder internal RecordBuilder(IRecordOutput output, XmlNameTable? nameTable) { - Debug.Assert(output != null); + Debug.Assert(output is not null); _output = output; - _nameTable = nameTable != null ? nameTable : new NameTable(); + _nameTable = nameTable is not null ? nameTable : new NameTable(); _atoms = new OutKeywords(_nameTable); _scopeManager = new OutputScopeManager(_nameTable, _atoms); } @@ -137,9 +137,9 @@ internal Processor.OutputResult BeginEvent(int state, XPathNodeType nodeType, st ResetRecord(state); PopElementScope(); - prefix = (prefix != null) ? _nameTable.Add(prefix) : _atoms.Empty; - name = (name != null) ? _nameTable.Add(name) : _atoms.Empty; - nspace = (nspace != null) ? _nameTable.Add(nspace) : _atoms.Empty; + prefix = (prefix is not null) ? _nameTable.Add(prefix) : _atoms.Empty; + name = (name is not null) ? _nameTable.Add(name) : _atoms.Empty; + nspace = (nspace is not null) ? _nameTable.Add(nspace) : _atoms.Empty; switch (nodeType) { @@ -258,7 +258,7 @@ private int FindAttribute(string name, string nspace, ref string prefix) for (int attrib = 0; attrib < _attributeCount; attrib++) { - Debug.Assert(_attributeList[attrib] != null && _attributeList[attrib] is BuilderInfo); + Debug.Assert(_attributeList[attrib] is not null && _attributeList[attrib] is BuilderInfo); BuilderInfo attribute = (BuilderInfo)_attributeList[attrib]!; @@ -324,7 +324,7 @@ private void BeginAttribute(string prefix, string name, string nspace, object? h attrib = NewAttribute(); } - Debug.Assert(_attributeList[attrib] != null && _attributeList[attrib] is BuilderInfo); + Debug.Assert(_attributeList[attrib] is not null && _attributeList[attrib] is BuilderInfo); BuilderInfo attribute = (BuilderInfo)_attributeList[attrib]!; attribute.Initialize(prefix, name, nspace); @@ -358,7 +358,7 @@ private void BeginNamespace(string name, string nspace) else { string? nspaceDeclared = _scopeManager.ResolveNamespace(name, out thisScope); - if (nspaceDeclared != null) + if (nspaceDeclared is not null) { if (!Ref.Equal(nspace, nspaceDeclared)) { @@ -473,7 +473,7 @@ private Processor.OutputResult CheckRecordEnd(int state) private void SetEmptyFlag(int state) { - Debug.Assert(_mainNode != null); + Debug.Assert(_mainNode is not null); if ((state & StateMachine.BeginChild) != 0) { @@ -531,7 +531,7 @@ private void FixupElement() { bool thisScope = false; string? nspace = _scopeManager.ResolveNamespace(_mainNode.Prefix, out thisScope); - if (nspace != null) + if (nspace is not null) { if (!Ref.Equal(_mainNode.NamespaceURI, nspace)) { @@ -577,7 +577,7 @@ private void FixupAttributes(int attributeCount) { bool thisScope = false; string? nspace = _scopeManager.ResolveNamespace(info.Prefix, out thisScope); - if (nspace != null) + if (nspace is not null) { if (!Ref.Equal(info.NamespaceURI, nspace)) { @@ -626,7 +626,7 @@ private void AnalyzeComment() case s_Minus: if (minus) { - if (newComment == null) + if (newComment is null) newComment = new StringBuilder(comment, begin, index, 2 * comment.Length); else newComment.Append(comment, begin, index - begin); @@ -642,7 +642,7 @@ private void AnalyzeComment() } } - if (newComment != null) + if (newComment is not null) { if (begin < comment.Length) newComment.Append(comment, begin, comment.Length - begin); @@ -678,7 +678,7 @@ private void AnalyzeProcessingInstruction() case s_Greater: if (question) { - if (newPI == null) + if (newPI is null) { newPI = new StringBuilder(pi, begin, index, 2 * pi.Length); } @@ -697,7 +697,7 @@ private void AnalyzeProcessingInstruction() } } - if (newPI != null) + if (newPI is not null) { if (begin < pi.Length) { @@ -743,7 +743,7 @@ private void DeclareNamespace(string nspace, string prefix) { int index = NewNamespace(); - Debug.Assert(_namespaceList[index] != null && _namespaceList[index] is BuilderInfo); + Debug.Assert(_namespaceList[index] is not null && _namespaceList[index] is BuilderInfo); BuilderInfo ns = (BuilderInfo)_namespaceList[index]!; if (prefix == _atoms.Empty) @@ -774,7 +774,7 @@ internal string GetPrefixForNamespace(string nspace) if (_scopeManager.FindPrefix(nspace, out prefix)) { - Debug.Assert(prefix != null && prefix.Length > 0); + Debug.Assert(prefix is not null && prefix.Length > 0); return prefix; } else diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs index d1b684a3f0ee70..d30c06bc6ede79 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs @@ -35,7 +35,7 @@ public Key(XmlQualifiedName name, int matchkey, int usekey) public void AddKey(XPathNavigator root, Hashtable table) { - if (_keyNodes == null) + if (_keyNodes is null) { _keyNodes = new ArrayList(); } @@ -44,7 +44,7 @@ public void AddKey(XPathNavigator root, Hashtable table) public Hashtable? GetKeys(XPathNavigator root) { - if (_keyNodes != null) + if (_keyNodes is not null) { for (int i = 0; i < _keyNodes.Count; i++) { @@ -93,7 +93,7 @@ internal XsltOutput Output { get { - if (_output == null) + if (_output is null) { _output = new XsltOutput(); } @@ -111,7 +111,7 @@ internal override void Compile(Compiler compiler) internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey) { - if (_keyList == null) + if (_keyList is null) { _keyList = new List(); } @@ -121,7 +121,7 @@ internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey) internal AttributeSetAction GetAttributeSet(XmlQualifiedName name) { AttributeSetAction? action = (AttributeSetAction?)_attributeSetTable[name]; - if (action == null) + if (action is null) { throw XsltException.Create(SR.Xslt_NoAttributeSet, name.ToString()); } @@ -136,7 +136,7 @@ public void PorcessAttributeSets(Stylesheet rootStylesheet) // As we mentioned we need to invert all lists. foreach (AttributeSetAction attSet in _attributeSetTable.Values) { - if (attSet.containedActions != null) + if (attSet.containedActions is not null) { attSet.containedActions.Reverse(); } @@ -150,13 +150,13 @@ private void MirgeAttributeSets(Stylesheet stylesheet) { // mirge stylesheet.AttributeSetTable to this.AttributeSetTable - if (stylesheet.AttributeSetTable != null) + if (stylesheet.AttributeSetTable is not null) { foreach (AttributeSetAction srcAttSet in stylesheet.AttributeSetTable.Values) { ArrayList? srcAttList = srcAttSet.containedActions; AttributeSetAction? dstAttSet = (AttributeSetAction?)_attributeSetTable[srcAttSet.Name!]; - if (dstAttSet == null) + if (dstAttSet is null) { dstAttSet = new AttributeSetAction(); { @@ -169,7 +169,7 @@ private void MirgeAttributeSets(Stylesheet stylesheet) ArrayList? dstAttList = dstAttSet.containedActions; // We adding attributes in reverse order for purpuse. In the mirged list most importent attset shoud go last one // so we'll need to invert dstAttList finaly. - if (srcAttList != null) + if (srcAttList is not null) { for (int src = srcAttList.Count - 1; 0 <= src; src--) { @@ -204,7 +204,7 @@ private void CheckAttributeSets_RecurceInList(Hashtable markTable, ICollection s } else { - Debug.Assert(mark == null); + Debug.Assert(mark is null); markTable[qname] = (object)PROCESSING; CheckAttributeSets_RecurceInContainer(markTable, GetAttributeSet(qname)); @@ -215,7 +215,7 @@ private void CheckAttributeSets_RecurceInList(Hashtable markTable, ICollection s private void CheckAttributeSets_RecurceInContainer(Hashtable markTable, ContainerAction container) { - if (container.containedActions == null) + if (container.containedActions is null) { return; } @@ -235,7 +235,7 @@ private void CheckAttributeSets_RecurceInContainer(Hashtable markTable, Containe internal void AddDecimalFormat(XmlQualifiedName name, DecimalFormat formatinfo) { DecimalFormat? exist = (DecimalFormat?)_decimalFormatTable[name]; - if (exist != null) + if (exist is not null) { NumberFormatInfo info = exist.info; NumberFormatInfo newinfo = formatinfo.info; @@ -269,7 +269,7 @@ internal List? KeyList internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { @@ -279,7 +279,7 @@ internal override void Execute(Processor processor, ActionFrame frame) root.MoveToRoot(); frame.InitNodeSet(new XPathSingletonIterator(root)); - if (this.containedActions != null && this.containedActions.Count > 0) + if (this.containedActions is not null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); } @@ -289,7 +289,7 @@ internal override void Execute(Processor processor, ActionFrame frame) Debug.Assert(frame.State == QueryInitialized); frame.NextNode(processor); Debug.Assert(Processor.IsRoot(frame.Node!)); - if (processor.Debugger != null) + if (processor.Debugger is not null) { // this is like apply-templates, but we don't have it on stack. // Pop the stack, otherwise last instruction will be on it. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs index f19259e508374b..7afb8a5f8c9d28 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs @@ -82,7 +82,7 @@ private void CacheOuptutProps(XsltOutput output) _isHtmlOutput = _output.Method == XsltOutput.OutputMethod.Html; _cdataElements = _output.CDataElements; _indentOutput = _output.Indent; - _outputDoctype = _output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null); + _outputDoctype = _output.DoctypeSystem is not null || (_isHtmlOutput && _output.DoctypePublic is not null); _outputXmlDecl = _isXmlOutput && !_output.OmitXmlDeclaration && !_omitXmlDeclCalled; } @@ -114,7 +114,7 @@ private void WriteStartElement(RecordBuilder record) if (mainNode.Prefix.Length == 0) { htmlProps = mainNode.htmlProps; - if (htmlProps == null && mainNode.search) + if (htmlProps is null && mainNode.search) { htmlProps = HtmlElementProps.GetProps(mainNode.LocalName); } @@ -128,7 +128,7 @@ private void WriteStartElement(RecordBuilder record) { if ( _secondRoot && ( - _output.DoctypeSystem != null || + _output.DoctypeSystem is not null || _output.Standalone ) ) @@ -145,7 +145,7 @@ private void WriteStartElement(RecordBuilder record) _outputDoctype = false; } - if (_cdataElements != null && _cdataElements.Contains(new XmlQualifiedName(mainNode.LocalName, mainNode.NamespaceURI)) && _isXmlOutput) + if (_cdataElements is not null && _cdataElements.Contains(new XmlQualifiedName(mainNode.LocalName, mainNode.NamespaceURI)) && _isXmlOutput) { record.Manager.CurrentElementScope.ToCData = true; } @@ -159,7 +159,7 @@ private void WriteStartElement(RecordBuilder record) if (mainNode.IsEmptyTag) { - Debug.Assert(!_isHtmlOutput || mainNode.Prefix != null, "Html can't have abbreviated elements"); + Debug.Assert(!_isHtmlOutput || mainNode.Prefix is not null, "Html can't have abbreviated elements"); Write(s_SlashGreaterThan); } else @@ -167,7 +167,7 @@ private void WriteStartElement(RecordBuilder record) Write(s_GreaterThan); } - if (htmlProps != null && htmlProps.Head) + if (htmlProps is not null && htmlProps.Head) { mainNode.Depth++; Indent(record); @@ -187,7 +187,7 @@ private void WriteTextNode(RecordBuilder record) scope.Mixed = true; - if (scope.HtmlElementProps != null && scope.HtmlElementProps.NoEntities) + if (scope.HtmlElementProps is not null && scope.HtmlElementProps.NoEntities) { // script or stile Write(mainNode.Value); @@ -207,7 +207,7 @@ private void WriteTextNode(BuilderInfo node) for (int i = 0; i < node.TextInfoCount; i++) { string? text = node.TextInfo[i]; - if (text == null) + if (text is null) { // disableEscaping marker i++; Debug.Assert(i < node.TextInfoCount, "disableEscaping marker can't be last TextInfo record"); @@ -230,7 +230,7 @@ private void WriteCDataSection(string value) private void WriteDoctype(BuilderInfo mainNode) { Debug.Assert(_outputDoctype == true, "It supposed to check this condition before actual call"); - Debug.Assert(_output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null), "We set outputDoctype == true only if"); + Debug.Assert(_output.DoctypeSystem is not null || (_isHtmlOutput && _output.DoctypePublic is not null), "We set outputDoctype == true only if"); Indent(0); Write(s_DocType); if (_isXmlOutput) @@ -242,7 +242,7 @@ private void WriteDoctype(BuilderInfo mainNode) WriteName(string.Empty, "html"); } Write(s_Space); - if (_output.DoctypePublic != null) + if (_output.DoctypePublic is not null) { Write(s_Public); Write(s_Quote); @@ -253,7 +253,7 @@ private void WriteDoctype(BuilderInfo mainNode) { Write(s_System); } - if (_output.DoctypeSystem != null) + if (_output.DoctypeSystem is not null) { Write(s_Quote); Write(_output.DoctypeSystem); @@ -272,7 +272,7 @@ private void WriteXmlDeclaration() Write(s_LessThanQuestion); WriteName(string.Empty, "xml"); Write(s_VersionAll); - if (this.encoding != null) + if (this.encoding is not null) { Write(s_EncodingStart); Write(this.encoding.WebName); @@ -314,7 +314,7 @@ private void WriteEndElement(RecordBuilder record) { HtmlElementProps? htmlProps = record.Manager.CurrentElementScope.HtmlElementProps; - if (htmlProps != null && htmlProps.Empty) + if (htmlProps is not null && htmlProps.Empty) { return; } @@ -390,7 +390,7 @@ private bool DecideDefaultOutput(BuilderInfo node) private void CacheRecord(RecordBuilder record) { - if (_outputCache == null) + if (_outputCache is null) { _outputCache = new ArrayList(); } @@ -400,7 +400,7 @@ private void CacheRecord(RecordBuilder record) private void OutputCachedRecords() { - if (_outputCache == null) + if (_outputCache is null) { return; } @@ -519,10 +519,10 @@ private void OutputRecord(BuilderInfo node) private void WriteName(string prefix, string name) { - if (prefix != null && prefix.Length > 0) + if (prefix is not null && prefix.Length > 0) { Write(prefix); - if (name != null && name.Length > 0) + if (name is not null && name.Length > 0) { Write(s_Colon); } @@ -536,13 +536,13 @@ private void WriteName(string prefix, string name) private void WriteXmlAttributeValue(string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); WriteWithReplace(value, s_XmlAttributeValueFind, s_XmlAttributeValueReplace); } private void WriteHtmlAttributeValue(string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); int length = value.Length; int i = 0; @@ -574,7 +574,7 @@ private void WriteHtmlAttributeValue(string value) private void WriteHtmlUri(string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(_isHtmlOutput); int length = value.Length; @@ -607,7 +607,7 @@ private void WriteHtmlUri(string value) default: if (127 < ch) { - if (_utf8Encoding == null) + if (_utf8Encoding is null) { _utf8Encoding = Encoding.UTF8; _byteBuffer = new byte[_utf8Encoding.GetMaxByteCount(1)]; @@ -630,7 +630,7 @@ private void WriteHtmlUri(string value) private void WriteWithReplace(string value, char[] find, string[] replace) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(find.Length == replace.Length); int length = value.Length; @@ -681,7 +681,7 @@ private void WriteWithReplace(string value, char[] find, string[] replace) private void WriteCData(string value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Write(value.Replace(s_CDataEnd, s_CDataSplit)); } @@ -695,14 +695,14 @@ private void WriteAttributes(ArrayList list, int count, HtmlElementProps? htmlEl string attrValue = attribute.Value; bool abr = false, uri = false; { - if (htmlElementsProps != null && attribute.Prefix.Length == 0) + if (htmlElementsProps is not null && attribute.Prefix.Length == 0) { HtmlAttributeProps? htmlAttrProps = attribute.htmlAttrProps; - if (htmlAttrProps == null && attribute.search) + if (htmlAttrProps is null && attribute.search) { htmlAttrProps = HtmlAttributeProps.GetProps(attribute.LocalName); } - if (htmlAttrProps != null) + if (htmlAttrProps is not null) { abr = htmlElementsProps.AbrParent && htmlAttrProps.Abr; uri = htmlElementsProps.UriParent && (htmlAttrProps.Uri || diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs index b03f30517b9fad..8bec7116af63e6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs @@ -27,7 +27,7 @@ internal class SortAction : CompiledAction private string? ParseLang(string? value) { - if (value == null) + if (value is null) { // Avt is not constant, or attribute wasn't defined return null; } @@ -36,7 +36,7 @@ internal class SortAction : CompiledAction // change exception types for some stylesheets. CultureInfo cultInfo = new CultureInfo(value); if (!XmlComplianceUtil.IsValidLanguageID(value.ToCharArray(), 0, value.Length) - && (value.Length == 0 || cultInfo == null) + && (value.Length == 0 || cultInfo is null) ) { if (_forwardCompatibility) @@ -50,7 +50,7 @@ internal class SortAction : CompiledAction private XmlDataType ParseDataType(string? value, InputScopeManager manager) { - if (value == null) + if (value is null) { // Avt is not constant, or attribute wasn't defined return XmlDataType.Text; } @@ -74,7 +74,7 @@ private XmlDataType ParseDataType(string? value, InputScopeManager manager) private XmlSortOrder ParseOrder(string? value) { - if (value == null) + if (value is null) { // Avt is not constant, or attribute wasn't defined return XmlSortOrder.Ascending; } @@ -95,7 +95,7 @@ private XmlSortOrder ParseOrder(string? value) private XmlCaseOrder ParseCaseOrder(string? value) { - if (value == null) + if (value is null) { // Avt is not constant, or attribute wasn't defined return XmlCaseOrder.None; } @@ -131,7 +131,7 @@ internal override void Compile(Compiler compiler) _order = ParseOrder(PrecalculateAvt(ref _orderAvt)); _caseOrder = ParseCaseOrder(PrecalculateAvt(ref _caseOrderAvt)); - if (_langAvt == null && _dataTypeAvt == null && _orderAvt == null && _caseOrderAvt == null) + if (_langAvt is null && _dataTypeAvt is null && _orderAvt is null && _caseOrderAvt is null) { _sort = new Sort(_selectKey, _lang, _dataType, _order, _caseOrder); } @@ -171,17 +171,17 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); Debug.Assert(frame.State == Initialized); - processor.AddSort(_sort != null ? + processor.AddSort(_sort is not null ? _sort : new Sort( _selectKey, - _langAvt == null ? _lang : ParseLang(_langAvt.Evaluate(processor, frame)), - _dataTypeAvt == null ? _dataType : ParseDataType(_dataTypeAvt.Evaluate(processor, frame), _manager!), - _orderAvt == null ? _order : ParseOrder(_orderAvt.Evaluate(processor, frame)), - _caseOrderAvt == null ? _caseOrder : ParseCaseOrder(_caseOrderAvt.Evaluate(processor, frame)) + _langAvt is null ? _lang : ParseLang(_langAvt.Evaluate(processor, frame)), + _dataTypeAvt is null ? _dataType : ParseDataType(_dataTypeAvt.Evaluate(processor, frame), _manager!), + _orderAvt is null ? _order : ParseOrder(_orderAvt.Evaluate(processor, frame)), + _caseOrderAvt is null ? _caseOrder : ParseCaseOrder(_caseOrderAvt.Evaluate(processor, frame)) ) ); frame.Finished(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs index 189e27543b14da..d87f88d77f29b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs @@ -65,7 +65,7 @@ internal void ReplaceValue(bool PreserveSpace) internal void AddSpace(Compiler compiler, string query, double Priority, bool PreserveSpace) { WhitespaceElement elem; - if (_queryKeyTable != null) + if (_queryKeyTable is not null) { if (_queryKeyTable.Contains(query)) { @@ -87,7 +87,7 @@ internal void AddSpace(Compiler compiler, string query, double Priority, bool Pr internal void SortWhiteSpace() { - if (_queryKeyTable != null) + if (_queryKeyTable is not null) { for (int i = 0; i < _whitespaceList!.Count; i++) { @@ -105,7 +105,7 @@ internal void SortWhiteSpace() } _whitespace = true; } - if (_imports != null) + if (_imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { @@ -122,7 +122,7 @@ internal void SortWhiteSpace() internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node) { // last one should win. I.E. We starting from the end. I.E. Lowest priority should go first - if (_whitespaceList != null) + if (_whitespaceList is not null) { for (int i = _whitespaceList.Count - 1; 0 <= i; i--) { @@ -133,7 +133,7 @@ internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node) } } } - if (_imports != null) + if (_imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { @@ -147,12 +147,12 @@ internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node) internal void AddAttributeSet(AttributeSetAction attributeSet) { - Debug.Assert(attributeSet.Name != null); - if (_attributeSetTable == null) + Debug.Assert(attributeSet.Name is not null); + if (_attributeSetTable is null) { _attributeSetTable = new Hashtable(); } - Debug.Assert(_attributeSetTable != null); + Debug.Assert(_attributeSetTable is not null); if (_attributeSetTable.ContainsKey(attributeSet.Name) == false) { @@ -173,9 +173,9 @@ internal void AddTemplate(TemplateAction template) // Ensure template has a unique name // - Debug.Assert(_templateNameTable != null); + Debug.Assert(_templateNameTable is not null); - if (template.Name != null) + if (template.Name is not null) { if (_templateNameTable.ContainsKey(template.Name) == false) { @@ -190,20 +190,20 @@ internal void AddTemplate(TemplateAction template) if (template.MatchKey != Compiler.InvalidQueryKey) { - if (_modeManagers == null) + if (_modeManagers is null) { _modeManagers = new Hashtable(); } - Debug.Assert(_modeManagers != null); + Debug.Assert(_modeManagers is not null); - if (mode == null) + if (mode is null) { mode = XmlQualifiedName.Empty; } TemplateManager? manager = (TemplateManager?)_modeManagers[mode]; - if (manager == null) + if (manager is null) { manager = new TemplateManager(this, mode); @@ -211,11 +211,11 @@ internal void AddTemplate(TemplateAction template) if (mode.IsEmpty) { - Debug.Assert(_templates == null); + Debug.Assert(_templates is null); _templates = manager; } } - Debug.Assert(manager != null); + Debug.Assert(manager is not null); template.TemplateId = ++_templateCount; manager.AddTemplate(template); @@ -224,7 +224,7 @@ internal void AddTemplate(TemplateAction template) internal void ProcessTemplates() { - if (_modeManagers != null) + if (_modeManagers is not null) { IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator(); while (enumerator.MoveNext()) @@ -235,13 +235,13 @@ internal void ProcessTemplates() } } - if (_imports != null) + if (_imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet? stylesheet = (Stylesheet?)_imports[importIndex]; - Debug.Assert(stylesheet != null); + Debug.Assert(stylesheet is not null); // // Process templates in imported stylesheet @@ -255,13 +255,13 @@ internal void ProcessTemplates() internal void ReplaceNamespaceAlias(Compiler compiler) { - if (_modeManagers != null) + if (_modeManagers is not null) { IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator(); while (enumerator.MoveNext()) { TemplateManager manager = (TemplateManager)enumerator.Value!; - if (manager.templates != null) + if (manager.templates is not null) { for (int i = 0; i < manager.templates.Count; i++) { @@ -271,7 +271,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) } } } - if (_templateNameTable != null) + if (_templateNameTable is not null) { IDictionaryEnumerator enumerator = _templateNameTable.GetEnumerator(); while (enumerator.MoveNext()) @@ -280,7 +280,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) template.ReplaceNamespaceAlias(compiler); } } - if (_imports != null) + if (_imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { @@ -292,18 +292,18 @@ internal void ReplaceNamespaceAlias(Compiler compiler) internal TemplateAction? FindTemplate(Processor processor, XPathNavigator navigator, XmlQualifiedName mode) { - Debug.Assert(processor != null && navigator != null); - Debug.Assert(mode != null); + Debug.Assert(processor is not null && navigator is not null); + Debug.Assert(mode is not null); TemplateAction? action = null; // // Try to find template within this stylesheet first // - if (_modeManagers != null) + if (_modeManagers is not null) { TemplateManager? manager = (TemplateManager?)_modeManagers[mode]; - if (manager != null) + if (manager is not null) { Debug.Assert(manager.Mode.Equals(mode)); action = manager.FindTemplate(processor, navigator); @@ -314,7 +314,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // If unsuccessful, search in imported documents from backwards // - if (action == null) + if (action is null) { action = FindTemplateImports(processor, navigator, mode); } @@ -330,13 +330,13 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // Do we have imported stylesheets? // - if (_imports != null) + if (_imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet? stylesheet = (Stylesheet?)_imports[importIndex]; - Debug.Assert(stylesheet != null); + Debug.Assert(stylesheet is not null); // // Search in imported stylesheet @@ -344,7 +344,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) action = stylesheet.FindTemplate(processor, navigator, mode); - if (action != null) + if (action is not null) { return action; } @@ -356,8 +356,8 @@ internal void ReplaceNamespaceAlias(Compiler compiler) internal TemplateAction? FindTemplate(Processor processor, XPathNavigator navigator) { - Debug.Assert(processor != null && navigator != null); - Debug.Assert(_templates == null && _modeManagers == null || _templates == _modeManagers![XmlQualifiedName.Empty]); + Debug.Assert(processor is not null && navigator is not null); + Debug.Assert(_templates is null && _modeManagers is null || _templates == _modeManagers![XmlQualifiedName.Empty]); TemplateAction? action = null; @@ -365,7 +365,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // Try to find template within this stylesheet first // - if (_templates != null) + if (_templates is not null) { action = _templates.FindTemplate(processor, navigator); } @@ -374,7 +374,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // If unsuccessful, search in imported documents from backwards // - if (action == null) + if (action is null) { action = FindTemplateImports(processor, navigator); } @@ -384,7 +384,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) internal TemplateAction? FindTemplate(XmlQualifiedName name) { - //Debug.Assert(this.templateNameTable == null); + //Debug.Assert(this.templateNameTable is null); TemplateAction? action = null; @@ -392,7 +392,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // Try to find template within this stylesheet first // - if (_templateNameTable != null) + if (_templateNameTable is not null) { action = (TemplateAction?)_templateNameTable[name]; } @@ -401,13 +401,13 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // If unsuccessful, search in imported documents from backwards // - if (action == null && _imports != null) + if (action is null && _imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet? stylesheet = (Stylesheet?)_imports[importIndex]; - Debug.Assert(stylesheet != null); + Debug.Assert(stylesheet is not null); // // Search in imported stylesheet @@ -415,7 +415,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) action = stylesheet.FindTemplate(name); - if (action != null) + if (action is not null) { return action; } @@ -433,13 +433,13 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // Do we have imported stylesheets? // - if (_imports != null) + if (_imports is not null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet? stylesheet = (Stylesheet?)_imports[importIndex]; - Debug.Assert(stylesheet != null); + Debug.Assert(stylesheet is not null); // // Search in imported stylesheet @@ -447,7 +447,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) action = stylesheet.FindTemplate(processor, navigator); - if (action != null) + if (action is not null) { return action; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs index b05f02a64ff5d8..a5a14d9a9c1689 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs @@ -55,11 +55,11 @@ internal override void Compile(Compiler compiler) CompileAttributes(compiler); if (_matchKey == Compiler.InvalidQueryKey) { - if (_name == null) + if (_name is null) { throw XsltException.Create(SR.Xslt_TemplateNoAttrib); } - if (_mode != null) + if (_mode is not null) { throw XsltException.Create(SR.Xslt_InvalidModeAttribute); } @@ -98,7 +98,7 @@ internal override bool CompileAttribute(Compiler compiler) } else if (Ref.Equal(name, compiler.Atoms.Name)) { - Debug.Assert(_name == null); + Debug.Assert(_name is null); _name = compiler.CreateXPathQName(value); } else if (Ref.Equal(name, compiler.Atoms.Priority)) @@ -112,7 +112,7 @@ internal override bool CompileAttribute(Compiler compiler) } else if (Ref.Equal(name, compiler.Atoms.Mode)) { - Debug.Assert(_mode == null); + Debug.Assert(_mode is null); if (compiler.AllowBuiltInMode && value == "*") { _mode = Compiler.BuiltInMode; @@ -141,7 +141,7 @@ private void AnalyzePriority(Compiler compiler) CompiledXpathExpr expr = (CompiledXpathExpr)theQuery.CompiledQuery; Query query = expr.QueryTree; UnionExpr? union; - while ((union = query as UnionExpr) != null) + while ((union = query as UnionExpr) is not null) { Debug.Assert(!(union.qy2 is UnionExpr), "only qy1 can be union"); TemplateAction copy = this.CloneWithoutName(); @@ -229,7 +229,7 @@ internal override void ReplaceNamespaceAlias(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { @@ -238,7 +238,7 @@ internal override void Execute(Processor processor, ActionFrame frame) { frame.AllocateVariables(this.variableCount); } - if (this.containedActions != null && this.containedActions.Count > 0) + if (this.containedActions is not null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); frame.State = ProcessingChildren; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs index 8715505643d70a..1b6f100f7f5621 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs @@ -22,32 +22,32 @@ internal void Initialize(XmlQualifiedName? mode, Stylesheet? importsOf) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); Debug.Assert(frame.State == Initialized); Action? action = null; - if (this.mode != null) + if (this.mode is not null) { - action = importsOf == null + action = importsOf is null ? processor.Stylesheet.FindTemplate(processor, frame.Node!, this.mode) : importsOf.FindTemplateImports(processor, frame.Node!, this.mode); } else { - action = importsOf == null + action = importsOf is null ? processor.Stylesheet.FindTemplate(processor, frame.Node!) : importsOf.FindTemplateImports(processor, frame.Node!); } // Built-int template rules - if (action == null) + if (action is null) { action = BuiltInTemplate(frame.Node!); } // Jump - if (action != null) + if (action is not null) { frame.SetAction(action); } @@ -59,7 +59,7 @@ internal override void Execute(Processor processor, ActionFrame frame) internal Action? BuiltInTemplate(XPathNavigator node) { - Debug.Assert(node != null); + Debug.Assert(node is not null); Action? action = null; switch (node.NodeType) @@ -98,9 +98,9 @@ internal class TemplateLookupActionDbg : TemplateLookupAction { internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); Debug.Assert(frame.State == Initialized); - Debug.Assert(processor.Debugger != null); + Debug.Assert(processor.Debugger is not null); Action? action = null; @@ -112,31 +112,31 @@ internal override void Execute(Processor processor, ActionFrame frame) } processor.SetCurrentMode(this.mode); - if (this.mode != null) + if (this.mode is not null) { - action = importsOf == null + action = importsOf is null ? processor.Stylesheet.FindTemplate(processor, frame.Node!, this.mode) : importsOf.FindTemplateImports(processor, frame.Node!, this.mode); } else { - action = importsOf == null + action = importsOf is null ? processor.Stylesheet.FindTemplate(processor, frame.Node!) : importsOf.FindTemplateImports(processor, frame.Node!); } // Built-int template rules - if (action == null && processor.RootAction!.builtInSheet != null) + if (action is null && processor.RootAction!.builtInSheet is not null) { action = processor.RootAction.builtInSheet.FindTemplate(processor, frame.Node!, Compiler.BuiltInMode); } - if (action == null) + if (action is null) { action = BuiltInTemplate(frame.Node!); } // Jump - if (action != null) + if (action is not null) { frame.SetAction(action); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs index 4567404439567c..6b201f54398032 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs @@ -19,8 +19,8 @@ private class TemplateComparer : IComparer { public int Compare(object? x, object? y) { - Debug.Assert(x != null && x is TemplateAction); - Debug.Assert(y != null && y is TemplateAction); + Debug.Assert(x is not null && x is TemplateAction); + Debug.Assert(y is not null && y is TemplateAction); TemplateAction tx = (TemplateAction)x; TemplateAction ty = (TemplateAction)y; @@ -55,14 +55,14 @@ internal TemplateManager(Stylesheet stylesheet, XmlQualifiedName mode) internal void AddTemplate(TemplateAction template) { - Debug.Assert(template != null); + Debug.Assert(template is not null); Debug.Assert( ((object)_mode == (object?)template.Mode) || - (template.Mode == null && _mode.Equals(XmlQualifiedName.Empty)) || + (template.Mode is null && _mode.Equals(XmlQualifiedName.Empty)) || _mode.Equals(template.Mode) ); - if (this.templates == null) + if (this.templates is null) { this.templates = new ArrayList(); } @@ -72,7 +72,7 @@ internal void AddTemplate(TemplateAction template) internal void ProcessTemplates() { - if (this.templates != null) + if (this.templates is not null) { this.templates.Sort(s_TemplateComparer); } @@ -80,12 +80,12 @@ internal void ProcessTemplates() internal TemplateAction? FindTemplate(Processor processor, XPathNavigator navigator) { - if (this.templates == null) + if (this.templates is null) { return null; } - Debug.Assert(this.templates != null); + Debug.Assert(this.templates is not null); for (int templateIndex = this.templates.Count - 1; templateIndex >= 0; templateIndex--) { TemplateAction action = (TemplateAction)this.templates[templateIndex]!; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextAction.cs index bd912f7749b9ef..94d00c472c32f2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextAction.cs @@ -66,7 +66,7 @@ private void CompileContent(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextEvent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextEvent.cs index dc8ed73b13a215..a95ee9ad131f0b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextEvent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextEvent.cs @@ -16,7 +16,7 @@ protected TextEvent() { } public TextEvent(string text) { - Debug.Assert(text != null); + Debug.Assert(text is not null); _text = text; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs index da293c56478dec..9ade5e81551faa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs @@ -26,7 +26,7 @@ public TextWriter Writer internal TextOnlyOutput(Processor processor, Stream stream) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -37,7 +37,7 @@ internal TextOnlyOutput(Processor processor, Stream stream) internal TextOnlyOutput(Processor processor, TextWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs index bed1a25a468c32..0ba28c05215854 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs @@ -16,7 +16,7 @@ internal class TextOutput : SequentialOutput internal TextOutput(Processor processor, Stream stream) : base(processor) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -28,7 +28,7 @@ internal TextOutput(Processor processor, Stream stream) internal TextOutput(Processor processor, TextWriter writer) : base(processor) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/UseAttributeSetsAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/UseAttributeSetsAction.cs index b38b9e86acb71d..0db33f9141b1d9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/UseAttributeSetsAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/UseAttributeSetsAction.cs @@ -26,7 +26,7 @@ internal override void Compile(Compiler compiler) Debug.Assert(Ref.Equal(compiler.Input.LocalName, compiler.Atoms.UseAttributeSets)); _useString = compiler.Input.Value; - Debug.Assert(_useAttributeSets == null); + Debug.Assert(_useAttributeSets is null); if (_useString.Length == 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs index 719b0c747bce01..5bd4b69a38a3fd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs @@ -19,7 +19,7 @@ internal class ValueOfAction : CompiledAction internal static Action BuiltInRule() { - Debug.Assert(s_BuiltInRule != null); + Debug.Assert(s_BuiltInRule is not null); return s_BuiltInRule; } @@ -53,13 +53,13 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - Debug.Assert(frame != null); - Debug.Assert(frame.NodeSet != null); + Debug.Assert(frame is not null); + Debug.Assert(frame.NodeSet is not null); string? value = processor.ValueOf(frame, _selectKey); @@ -75,7 +75,7 @@ internal override void Execute(Processor processor, ActionFrame frame) break; case ResultStored: - Debug.Assert(frame.StoredOutput != null); + Debug.Assert(frame.StoredOutput is not null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; @@ -92,13 +92,13 @@ internal class BuiltInRuleTextAction : Action private const int ResultStored = 2; internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { case Initialized: - Debug.Assert(frame != null); - Debug.Assert(frame.NodeSet != null); + Debug.Assert(frame is not null); + Debug.Assert(frame.NodeSet is not null); string value = processor.ValueOf(frame.NodeSet.Current!); @@ -114,7 +114,7 @@ internal override void Execute(Processor processor, ActionFrame frame) break; case ResultStored: - Debug.Assert(frame.StoredOutput != null); + Debug.Assert(frame.StoredOutput is not null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs index 3703e24b949998..b63eecafb36ce6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs @@ -71,12 +71,12 @@ internal override void Compile(Compiler compiler) CompileTemplate(compiler); compiler.ToParent(); - if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions != null) + if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions is not null) { throw XsltException.Create(SR.Xslt_VariableCntSel2, this.nameStr); } } - if (this.containedActions != null) + if (this.containedActions is not null) { baseUri = baseUri + '#' + compiler.GetUnicRtfId(); } @@ -95,7 +95,7 @@ internal override bool CompileAttribute(Compiler compiler) if (Ref.Equal(name, compiler.Atoms.Name)) { - Debug.Assert(this.name == null && this.nameStr == null); + Debug.Assert(this.name is null && this.nameStr is null); this.nameStr = value; this.name = compiler.CreateXPathQName(this.nameStr); } @@ -113,7 +113,7 @@ internal override bool CompileAttribute(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null && frame.State != ValueCalculated); + Debug.Assert(processor is not null && frame is not null && frame.State != ValueCalculated); object? value = null; switch (frame.State) @@ -121,7 +121,7 @@ internal override void Execute(Processor processor, ActionFrame frame) case Initialized: if (IsGlobal) { - if (frame.GetVariable(_varKey) != null) + if (frame.GetVariable(_varKey) is not null) { // This var was calculated already frame.Finished(); break; @@ -138,7 +138,7 @@ internal override void Execute(Processor processor, ActionFrame frame) { value = processor.GetParameter(this.name!); } - if (value != null) + if (value is not null) { goto case ValueCalculated; } @@ -151,7 +151,7 @@ internal override void Execute(Processor processor, ActionFrame frame) } // If there is no 'select' attribute and the content is empty, use the empty string - if (this.containedActions == null) + if (this.containedActions is null) { value = string.Empty; goto case ValueCalculated; @@ -171,7 +171,7 @@ internal override void Execute(Processor processor, ActionFrame frame) goto case ValueCalculated; case ValueCalculated: - Debug.Assert(value != null); + Debug.Assert(value is not null); frame.SetVariable(_varKey, value); frame.Finished(); break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs index d9a28c1f57cc3f..25f70b0abe91b2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs @@ -22,7 +22,7 @@ internal override void Compile(Compiler compiler) CompileTemplate(compiler); compiler.ToParent(); - if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions != null) + if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions is not null) { throw XsltException.Create(SR.Xslt_VariableCntSel2, this.nameStr); } @@ -31,7 +31,7 @@ internal override void Compile(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); object ParamValue; switch (frame.State) { @@ -44,7 +44,7 @@ internal override void Execute(Processor processor, ActionFrame frame) } else { - if (this.containedActions == null) + if (this.containedActions is null) { processor.SetParameter(this.name!, string.Empty); frame.Finished(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs index ae66561a5e3cdc..9dac43f8babac7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs @@ -13,7 +13,7 @@ internal sealed class WriterOutput : IRecordOutput internal WriterOutput(Processor processor, XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs index e09e8f9ec14061..79526868acd62a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs @@ -69,7 +69,7 @@ public override IXsltContextVariable ResolveVariable(string prefix, string name) string namespaceURI = this.LookupNamespace(prefix); XmlQualifiedName qname = new XmlQualifiedName(name, namespaceURI); IXsltContextVariable? variable = _manager!.VariableScope.ResolveVariable(qname); - if (variable == null) + if (variable is null) { throw XsltException.Create(SR.Xslt_InvalidVariable, qname.ToString()); } @@ -79,16 +79,16 @@ public override IXsltContextVariable ResolveVariable(string prefix, string name) internal object EvaluateVariable(VariableAction variable) { object result = _processor!.GetVariableValue(variable); - if (result == null && !variable.IsGlobal) + if (result is null && !variable.IsGlobal) { // This was uninitialized local variable. May be we have sutable global var too? VariableAction? global = _manager!.VariableScope.ResolveGlobalVariable(variable.Name!); - if (global != null) + if (global is not null) { result = _processor.GetVariableValue(global); } } - if (result == null) + if (result is null) { throw XsltException.Create(SR.Xslt_InvalidVariable, variable.Name!.ToString()); } @@ -129,7 +129,7 @@ public override bool PreserveWhitespace(XPathNavigator node) // this is the only place we returning null in this function return null; } - if (argTypes == null) + if (argTypes is null) { // without arg types we can't do more detailed search return methods[0]; @@ -187,10 +187,10 @@ public override bool PreserveWhitespace(XPathNavigator node) { FuncExtension? result = null; extension = _processor!.GetScriptObject(ns); - if (extension != null) + if (extension is not null) { MethodInfo? method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/true, /*publicOnly:*/false, name, argTypes); - if (method != null) + if (method is not null) { result = new FuncExtension(extension, method); } @@ -198,10 +198,10 @@ public override bool PreserveWhitespace(XPathNavigator node) } extension = _processor.GetExtensionObject(ns); - if (extension != null) + if (extension is not null) { MethodInfo? method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/false, /*publicOnly:*/true, name, argTypes); - if (method != null) + if (method is not null) { result = new FuncExtension(extension, method); } @@ -229,13 +229,13 @@ public override IXsltContextFunction ResolveFunction(string prefix, string name, { object? extension; func = GetExtentionMethod(ns, name, argTypes, out extension); - if (extension == null) + if (extension is null) { throw XsltException.Create(SR.Xslt_ScriptInvalidPrefix, prefix); // BugBug: It's better to say that method 'name' not found } } } - if (func == null) + if (func is null) { throw XsltException.Create(SR.Xslt_UnknownXsltFunction, name); } @@ -251,7 +251,7 @@ public override IXsltContextFunction ResolveFunction(string prefix, string name, // private Uri ComposeUri(string thisUri, string baseUri) { - Debug.Assert(thisUri != null && baseUri != null); + Debug.Assert(thisUri is not null && baseUri is not null); XmlResolver resolver = _processor!.Resolver; Uri? uriBase = null; if (baseUri.Length != 0) @@ -264,7 +264,7 @@ private Uri ComposeUri(string thisUri, string baseUri) private XPathNodeIterator Document(object arg0, string? baseUri) { XPathNodeIterator? it = arg0 as XPathNodeIterator; - if (it != null) + if (it is not null) { ArrayList list = new ArrayList(); Hashtable documents = new Hashtable(); @@ -318,7 +318,7 @@ private Hashtable BuildKeyTable(Key key, XPathNavigator root) private static void AddKeyValue(Hashtable keyTable, string key, XPathNavigator value, bool checkDuplicates) { ArrayList? list = (ArrayList?)keyTable[key]; - if (list == null) + if (list is null) { list = new ArrayList(); keyTable.Add(key, list); @@ -353,7 +353,7 @@ private static void EvaluateKey(XPathNavigator? node, Query matchExpr, string ma { try { - if (matchExpr.MatchNode(node) == null) + if (matchExpr.MatchNode(node) is null) { return; } @@ -364,7 +364,7 @@ private static void EvaluateKey(XPathNavigator? node, Query matchExpr, string ma } object result = useExpr.Evaluate(new XPathSingletonIterator(node!, /*moved:*/true)); XPathNodeIterator? it = result as XPathNodeIterator; - if (it != null) + if (it is not null) { bool checkDuplicates = false; while (it.MoveNext()) @@ -383,16 +383,16 @@ private static void EvaluateKey(XPathNavigator? node, Query matchExpr, string ma private DecimalFormat ResolveFormatName(string? formatName) { string ns = string.Empty, local = string.Empty; - if (formatName != null) + if (formatName is not null) { string prefix; PrefixQName.ParseQualifiedName(formatName, out prefix, out local); ns = LookupNamespace(prefix); } DecimalFormat? formatInfo = _processor!.RootAction!.GetDecimalFormat(new XmlQualifiedName(local, ns)); - if (formatInfo == null) + if (formatInfo is null) { - if (formatName != null) + if (formatName is not null) { throw XsltException.Create(SR.Xslt_NoDecimalFormat, formatName); } @@ -477,21 +477,21 @@ private bool FunctionAvailable(string qname) name == "ceiling" || name == "round" || // XSLT functions: - (s_FunctionTable[name] != null && name != "unparsed-entity-uri") + (s_FunctionTable[name] is not null && name != "unparsed-entity-uri") ); } else { // Is this script or extention function? object? extension; - return GetExtentionMethod(ns, name, /*argTypes*/null, out extension) != null; + return GetExtentionMethod(ns, name, /*argTypes*/null, out extension) is not null; } } private XPathNodeIterator Current() { XPathNavigator? nav = _processor!.Current; - if (nav != null) + if (nav is not null) { return new XPathSingletonIterator(nav.Clone()); } @@ -526,7 +526,7 @@ private string SystemProperty(string qname) } else { - if (urn == null && prefix != null) + if (urn is null && prefix is not null) { // if prefix exist it has to be mapped to namespace. // Can it be "" here ? @@ -628,7 +628,7 @@ protected void Init(int minArgs, int maxArgs, XPathResultType returnType, XPathR public static XPathNodeIterator ToIterator(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; - if (it == null) + if (it is null) { throw XsltException.Create(SR.Xslt_NoNodeSetConversion); } @@ -638,7 +638,7 @@ public static XPathNodeIterator ToIterator(object argument) public static XPathNavigator ToNavigator(object argument) { XPathNavigator? nav = argument as XPathNavigator; - if (nav == null) + if (nav is null) { throw XsltException.Create(SR.Xslt_NoNavigatorConversion); } @@ -647,7 +647,7 @@ public static XPathNavigator ToNavigator(object argument) private static string IteratorToString(XPathNodeIterator it) { - Debug.Assert(it != null); + Debug.Assert(it is not null); if (it.MoveNext()) { return it.Current!.Value; @@ -659,7 +659,7 @@ private static string IteratorToString(XPathNodeIterator it) public static string? ToString(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; - if (it != null) + if (it is not null) { return IteratorToString(it); } @@ -672,12 +672,12 @@ private static string IteratorToString(XPathNodeIterator it) public static bool ToBoolean(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; - if (it != null) + if (it is not null) { return Convert.ToBoolean(IteratorToString(it), CultureInfo.InvariantCulture); } XPathNavigator? nav = argument as XPathNavigator; - if (nav != null) + if (nav is not null) { return Convert.ToBoolean(nav.ToString(), CultureInfo.InvariantCulture); } @@ -687,12 +687,12 @@ public static bool ToBoolean(object argument) public static double ToNumber(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; - if (it != null) + if (it is not null) { return XmlConvert.ToXPathDouble(IteratorToString(it)); } XPathNavigator? nav = argument as XPathNavigator; - if (nav != null) + if (nav is not null) { return XmlConvert.ToXPathDouble(nav.ToString()); } @@ -866,14 +866,14 @@ public override object Invoke(XsltContext xsltContext, object[] args, XPathNavig if (key.Name == keyName) { Hashtable? keyTable = key.GetKeys(root); - if (keyTable == null) + if (keyTable is null) { keyTable = xsltCompileContext.BuildKeyTable(key, root); key.AddKey(root, keyTable); } XPathNodeIterator? it = args[1] as XPathNodeIterator; - if (it != null) + if (it is not null) { it = it.Clone(); while (it.MoveNext()) @@ -887,7 +887,7 @@ public override object Invoke(XsltContext xsltContext, object[] args, XPathNavig } } } - if (resultCollection == null) + if (resultCollection is null) { return XPathEmptyIterator.Instance; } @@ -903,11 +903,11 @@ public override object Invoke(XsltContext xsltContext, object[] args, XPathNavig private static ArrayList? AddToList(ArrayList? resultCollection, ArrayList? newList) { - if (newList == null) + if (newList is null) { return resultCollection; } - if (resultCollection == null) + if (resultCollection is null) { return newList; } @@ -953,8 +953,8 @@ private class FuncExtension : XsltFunctionImpl public FuncExtension(object extension, MethodInfo method) { - Debug.Assert(extension != null); - Debug.Assert(method != null); + Debug.Assert(extension is not null); + Debug.Assert(method is not null); _extension = extension; _method = method; XPathResultType returnType = GetXPathType(method.ReturnType); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs index ee25af73522321..69a0da4cf524cf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs @@ -144,7 +144,7 @@ internal override bool CompileAttribute(Compiler compiler) } catch (System.NotSupportedException) { } catch (System.ArgumentException) { } - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); } } else if (Ref.Equal(name, compiler.Atoms.OmitXmlDeclaration)) @@ -199,7 +199,7 @@ internal override bool CompileAttribute(Compiler compiler) { string[] qnames = XmlConvert.SplitString(value); - if (_cdataElements == null) + if (_cdataElements is null) { _cdataElements = new Hashtable(qnames.Length); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/newinstructionaction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/newinstructionaction.cs index f17f23ba4cf073..4e8579521e79b9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/newinstructionaction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/newinstructionaction.cs @@ -48,7 +48,7 @@ internal void CompileSelectiveTemplate(Compiler compiler) internal override void Execute(Processor processor, ActionFrame frame) { - Debug.Assert(processor != null && frame != null); + Debug.Assert(processor is not null && frame is not null); switch (frame.State) { @@ -57,7 +57,7 @@ internal override void Execute(Processor processor, ActionFrame frame) { throw XsltException.Create(SR.Xslt_UnknownExtensionElement, _name); } - if (this.containedActions != null && this.containedActions.Count > 0) + if (this.containedActions is not null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); frame.State = ProcessingChildren; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs index df1a0223c41af5..aa7a87e87c01c7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs @@ -132,7 +132,7 @@ public void Load(IXPathNavigable stylesheet, XsltSettings? settings, XmlResolver public void Load(string stylesheetUri) { Reset(); - if (stylesheetUri == null) + if (stylesheetUri is null) { throw new ArgumentNullException(nameof(stylesheetUri)); } @@ -142,7 +142,7 @@ public void Load(string stylesheetUri) public void Load(string stylesheetUri, XsltSettings? settings, XmlResolver? stylesheetResolver) { Reset(); - if (stylesheetUri == null) + if (stylesheetUri is null) { throw new ArgumentNullException(nameof(stylesheetUri)); } @@ -151,17 +151,17 @@ public void Load(string stylesheetUri, XsltSettings? settings, XmlResolver? styl private CompilerErrorCollection LoadInternal(object stylesheet, XsltSettings? settings, XmlResolver? stylesheetResolver) { - if (stylesheet == null) + if (stylesheet is null) { throw new ArgumentNullException(nameof(stylesheet)); } - if (settings == null) + if (settings is null) { settings = XsltSettings.Default; } CompileXsltToQil(stylesheet, settings, stylesheetResolver); CompilerError? error = GetFirstError(); - if (error != null) + if (error is not null) { throw new XslLoadException(error); } @@ -213,14 +213,14 @@ public void Load(Type compiledStylesheet) { #if FEATURE_COMPILED_XSL Reset(); - if (compiledStylesheet == null) + if (compiledStylesheet is null) throw new ArgumentNullException(nameof(compiledStylesheet)); object[] customAttrs = compiledStylesheet.GetCustomAttributes(typeof(GeneratedCodeAttribute), /*inherit:*/false); GeneratedCodeAttribute? generatedCodeAttr = customAttrs.Length > 0 ? (GeneratedCodeAttribute)customAttrs[0] : null; // If GeneratedCodeAttribute is not there, it is not a compiled stylesheet class - if (generatedCodeAttr != null && generatedCodeAttr.Tool == typeof(XslCompiledTransform).FullName) + if (generatedCodeAttr is not null && generatedCodeAttr.Tool == typeof(XslCompiledTransform).FullName) { if (s_version < Version.Parse(generatedCodeAttr.Version!)) { @@ -231,12 +231,12 @@ public void Load(Type compiledStylesheet) FieldInfo? fldTypes = compiledStylesheet.GetField(XmlQueryStaticData.TypesFieldName, BindingFlags.Static | BindingFlags.NonPublic); // If private fields are not there, it is not a compiled stylesheet class - if (fldData != null && fldTypes != null) + if (fldData is not null && fldTypes is not null) { // Retrieve query static data from the type byte[]? queryData = fldData.GetValue(/*this:*/null) as byte[]; - if (queryData != null) + if (queryData is not null) { MethodInfo? executeMethod = compiledStylesheet.GetMethod("Execute", BindingFlags.Static | BindingFlags.NonPublic); Type[]? earlyBoundTypes = (Type[]?)fldTypes.GetValue(/*this:*/null); @@ -249,7 +249,7 @@ public void Load(Type compiledStylesheet) } // Throw an exception if the command was not loaded - if (_command == null) + if (_command is null) throw new ArgumentException(SR.Format(SR.Xslt_NotCompiledStylesheet, compiledStylesheet.FullName), nameof(compiledStylesheet)); #else throw new PlatformNotSupportedException(SR.Xslt_NotSupported); @@ -261,15 +261,15 @@ public void Load(MethodInfo executeMethod, byte[] queryData, Type[]? earlyBoundT #if FEATURE_COMPILED_XSL Reset(); - if (executeMethod == null) + if (executeMethod is null) throw new ArgumentNullException(nameof(executeMethod)); - if (queryData == null) + if (queryData is null) throw new ArgumentNullException(nameof(queryData)); DynamicMethod? dm = executeMethod as DynamicMethod; - Delegate delExec = (dm != null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : executeMethod.CreateDelegate(typeof(ExecuteDelegate)); + Delegate delExec = (dm is not null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : executeMethod.CreateDelegate(typeof(ExecuteDelegate)); _command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes)); _outputSettings = _command.StaticData.DefaultWriterSettings; #else @@ -398,10 +398,10 @@ public void Transform(string inputUri, XsltArgumentList? arguments, Stream resul public void Transform(string inputUri, string resultsFile) { - if (inputUri == null) + if (inputUri is null) throw new ArgumentNullException(nameof(inputUri)); - if (resultsFile == null) + if (resultsFile is null) throw new ArgumentNullException(nameof(resultsFile)); // SQLBUDT 276415: Prevent wiping out the content of the input file if the output file is the same @@ -449,19 +449,19 @@ public void Transform(IXPathNavigable input, XsltArgumentList? arguments, XmlWri private static void CheckArguments(object input, object results) { - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); - if (results == null) + if (results is null) throw new ArgumentNullException(nameof(results)); } private static void CheckArguments(string inputUri, object results) { - if (inputUri == null) + if (inputUri is null) throw new ArgumentNullException(nameof(inputUri)); - if (results == null) + if (results is null) throw new ArgumentNullException(nameof(results)); } @@ -469,7 +469,7 @@ private static void CheckArguments(string inputUri, object results) private void CheckCommand() { #if FEATURE_COMPILED_XSL - if (_command == null) + if (_command is null) { throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded); } @@ -503,7 +503,7 @@ private QilExpression TestCompile(object stylesheet, XsltSettings settings, XmlR private void TestGenerate(XsltSettings settings) { - Debug.Assert(_qil != null, "You must compile to Qil first"); + Debug.Assert(_qil is not null, "You must compile to Qil first"); CompileQilToMsil(settings); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs index 28cda9fa635654..e6bee3257095d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs @@ -53,7 +53,7 @@ public void Load(XmlReader stylesheet) } public void Load(XmlReader stylesheet, XmlResolver? resolver) { - if (stylesheet == null) + if (stylesheet is null) { throw new ArgumentNullException(nameof(stylesheet)); } @@ -66,7 +66,7 @@ public void Load(IXPathNavigable stylesheet) } public void Load(IXPathNavigable stylesheet, XmlResolver? resolver) { - if (stylesheet == null) + if (stylesheet is null) { throw new ArgumentNullException(nameof(stylesheet)); } @@ -75,7 +75,7 @@ public void Load(IXPathNavigable stylesheet, XmlResolver? resolver) public void Load(XPathNavigator stylesheet) { - if (stylesheet == null) + if (stylesheet is null) { throw new ArgumentNullException(nameof(stylesheet)); } @@ -84,7 +84,7 @@ public void Load(XPathNavigator stylesheet) public void Load(XPathNavigator stylesheet, XmlResolver? resolver) { - if (stylesheet == null) + if (stylesheet is null) { throw new ArgumentNullException(nameof(stylesheet)); } @@ -112,13 +112,13 @@ public void Load(string url, XmlResolver? resolver) [MemberNotNull(nameof(_RootAction))] private void CheckCommand() { - if (_CompiledStylesheet == null) + if (_CompiledStylesheet is null) { throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded); } - Debug.Assert(_QueryStore != null); - Debug.Assert(_RootAction != null); + Debug.Assert(_QueryStore is not null); + Debug.Assert(_RootAction is not null); } public XmlReader Transform(XPathNavigator input, XsltArgumentList? args, XmlResolver? resolver) @@ -172,7 +172,7 @@ public void Transform(XPathNavigator input, XsltArgumentList? args, TextWriter o public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args, XmlResolver? resolver) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -181,7 +181,7 @@ public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args, XmlRes public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -189,7 +189,7 @@ public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args) } public void Transform(IXPathNavigable input, XsltArgumentList? args, TextWriter output, XmlResolver? resolver) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -198,7 +198,7 @@ public void Transform(IXPathNavigable input, XsltArgumentList? args, TextWriter public void Transform(IXPathNavigable input, XsltArgumentList? args, TextWriter output) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -207,7 +207,7 @@ public void Transform(IXPathNavigable input, XsltArgumentList? args, TextWriter public void Transform(IXPathNavigable input, XsltArgumentList? args, Stream output, XmlResolver? resolver) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -216,7 +216,7 @@ public void Transform(IXPathNavigable input, XsltArgumentList? args, Stream outp public void Transform(IXPathNavigable input, XsltArgumentList? args, Stream output) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -225,7 +225,7 @@ public void Transform(IXPathNavigable input, XsltArgumentList? args, Stream outp public void Transform(IXPathNavigable input, XsltArgumentList? args, XmlWriter output, XmlResolver? resolver) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -234,7 +234,7 @@ public void Transform(IXPathNavigable input, XsltArgumentList? args, XmlWriter o public void Transform(IXPathNavigable input, XsltArgumentList? args, XmlWriter output) { - if (input == null) + if (input is null) { throw new ArgumentNullException(nameof(input)); } @@ -253,7 +253,7 @@ public void Transform(string inputfile, string outputfile, XmlResolver? resolver } finally { - if (fs != null) + if (fs is not null) { fs.Dispose(); } @@ -269,15 +269,15 @@ public void Transform(string inputfile, string outputfile) private void Compile(XPathNavigator stylesheet, XmlResolver? resolver) { - Debug.Assert(stylesheet != null); + Debug.Assert(stylesheet is not null); Compiler compiler = new Compiler(); NavigatorInput input = new NavigatorInput(stylesheet); compiler.Compile(input, resolver ?? XmlNullResolver.Singleton); - Debug.Assert(compiler.CompiledStylesheet != null); - Debug.Assert(compiler.QueryStore != null); - Debug.Assert(compiler.RootAction != null); + Debug.Assert(compiler.CompiledStylesheet is not null); + Debug.Assert(compiler.QueryStore is not null); + Debug.Assert(compiler.RootAction is not null); _CompiledStylesheet = compiler.CompiledStylesheet; _QueryStore = compiler.QueryStore; _RootAction = compiler.RootAction; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs index 34ed4a5367fd92..68738577d03710 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs @@ -86,7 +86,7 @@ public void Clear() private static void CheckArgumentNull(object param, string paramName) { - if (param == null) + if (param is null) { throw new ArgumentNullException(paramName); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltException.cs index 3136e02340e08f..c3309fafb8b748 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltException.cs @@ -19,8 +19,8 @@ public class XsltException : SystemException private readonly int _lineNumber; private readonly int _linePosition; - // message != null for V1 & V2 exceptions deserialized in Whidbey - // message == null for created V2 exceptions; the exception message is stored in Exception._message + // message is not null for V1 & V2 exceptions deserialized in Whidbey + // message is null for created V2 exceptions; the exception message is stored in Exception._message private readonly string? _message; protected XsltException(SerializationInfo info, StreamingContext context) : base(info, context) @@ -41,7 +41,7 @@ protected XsltException(SerializationInfo info, StreamingContext context) : base } } - if (version == null) + if (version is null) { // deserializing V1 exception _message = CreateMessage(_res, _args, _sourceUri, _lineNumber, _linePosition); @@ -137,7 +137,7 @@ private static string CreateMessage(string res, string?[]? args, string? sourceU private static string? FormatMessage(string? key, params string?[]? args) { string? message = key; - if (message != null && args != null) + if (message is not null && args is not null) { message = string.Format(CultureInfo.InvariantCulture, message, args); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs index c78e0e401d4e73..87efed52cfebbd 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs @@ -17,7 +17,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust CustomType baseMember = type.BaseType as CustomType; - if (baseMember == null) + if (baseMember is null) return CollectionServices.IEnumerableToArray(attributes, attributeFilterType); // GetAttributeUsage is expensive and should be put off as much as possible. @@ -43,7 +43,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust CombineCustomAttributes(results, inheritedAttributes, attributeFilterType, inherited, allowMultiple); baseMember = type.BaseType as CustomType; - } while (baseMember != null); + } while (baseMember is not null); return CollectionServices.ConvertListToArray(results, attributeFilterType); } @@ -57,7 +57,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust CustomMethodInfo baseMember = method.GetBaseDefinition() as CustomMethodInfo; - if (baseMember == null || baseMember.Equals(method)) + if (baseMember is null || baseMember.Equals(method)) return CollectionServices.IEnumerableToArray(attributes, attributeFilterType); // GetAttributeUsage is expensive and should be put off as much as possible. @@ -83,7 +83,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust CombineCustomAttributes(results, inheritedAttributes, attributeFilterType, inherited, allowMultiple); baseMember = method.GetBaseDefinition() as CustomMethodInfo; - } while (baseMember != null && !baseMember.Equals(method)); + } while (baseMember is not null && !baseMember.Equals(method)); return CollectionServices.ConvertListToArray(results, attributeFilterType); } @@ -131,7 +131,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust public static bool IsDefined(ICustomAttributeProvider provider, Type attributeType, bool inherit) { object[] attributes = provider.GetCustomAttributes(attributeType, inherit); - return attributes != null && attributes.Length > 0; + return attributes is not null && attributes.Length > 0; } private static IEnumerable GetFilteredAttributes(CustomReflectionContext context, MemberInfo member, Type attributeFilterType) @@ -178,7 +178,7 @@ private static void GetAttributeUsage(Type attributeFilterType, out bool inherit { AttributeUsageAttribute[] usageAttributes = (AttributeUsageAttribute[])attributeFilterType.GetCustomAttributes(typeof(AttributeUsageAttribute), false); - if (usageAttributes == null || usageAttributes.Length == 0) + if (usageAttributes is null || usageAttributes.Length == 0) { // The default AttributeUsageAttribute. inherited = true; @@ -198,7 +198,7 @@ internal static IEnumerable FilterCustomAttributes(IEnumerable a { foreach (object attr in attributes) { - if (attr == null) + if (attr is null) throw new InvalidOperationException(SR.InvalidOperation_NullAttribute); if (attributeFilterType.IsInstanceOfType(attr)) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs index bf6d6ffd60a964..65c9c94fc3a5af 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs @@ -65,7 +65,7 @@ public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) if (!getDeclaredOnly) { CustomType baseType = BaseType as CustomType; - while (baseType != null) + while (baseType is not null) { IEnumerable newProperties = baseType.NewProperties; @@ -97,11 +97,11 @@ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindin return property; // Adding indexer properties is currently not supported. - if (types != null && types.Length > 0) + if (types is not null && types.Length > 0) return property; List matchingProperties = new List(); - if (property != null) + if (property is not null) matchingProperties.Add(property); // If the ReflectionContext adds two or more properties with the same name and type, @@ -120,7 +120,7 @@ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindin if (!getDeclaredOnly) { - while ((type = type.BaseType as CustomType) != null) + while ((type = type.BaseType as CustomType) is not null) { foreach (PropertyInfo newBaseProperty in type.NewProperties) { @@ -133,7 +133,7 @@ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindin if (matchingProperties.Count == 0) return null; - if (binder == null) + if (binder is null) binder = Type.DefaultBinder; return binder.SelectProperty(bindingAttr, matchingProperties.ToArray(), returnType, types, modifiers); @@ -164,7 +164,7 @@ public override MethodInfo[] GetMethods(BindingFlags bindingAttr) if (!getDeclaredOnly) { CustomType baseType = BaseType as CustomType; - while (baseType != null) + while (baseType is not null) { // We shouldn't add a base type method directly on a subtype. // A new method with a different ReflectedType should be used. @@ -204,10 +204,10 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt if (name.Length > 4) { // Right now we don't support adding fabricated indexers on types - getPropertyGetter = (types == null || types.Length == 0) && name.StartsWith("get_", comparison); + getPropertyGetter = (types is null || types.Length == 0) && name.StartsWith("get_", comparison); if (!getPropertyGetter) - getPropertySetter = (types == null || types.Length == 1) && name.StartsWith("set_", comparison); + getPropertySetter = (types is null || types.Length == 1) && name.StartsWith("set_", comparison); } // not a property getter or setter @@ -218,7 +218,7 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt string targetPropertyName = name.Substring(4); List matchingMethods = new List(); - if (method != null) + if (method is not null) matchingMethods.Add(method); // in runtime reflection hidden methods are always returned in GetMethods @@ -227,7 +227,7 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt if (string.Equals(newDeclaredProperty.Name, targetPropertyName, comparison)) { MethodInfo accessor = getPropertyGetter ? newDeclaredProperty.GetGetMethod() : newDeclaredProperty.GetSetMethod(); - if (accessor != null) + if (accessor is not null) matchingMethods.Add(accessor); } } @@ -237,7 +237,7 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt { CustomType baseType = BaseType as CustomType; - while (baseType != null) + while (baseType is not null) { // We shouldn't add a base type method directly on a subtype. // A new method with a different ReflectedType should be used. @@ -248,7 +248,7 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt PropertyInfo inheritedProperty = new InheritedPropertyInfo(newBaseProperty, this); MethodInfo accessor = getPropertyGetter ? inheritedProperty.GetGetMethod() : inheritedProperty.GetSetMethod(); - if (accessor != null) + if (accessor is not null) matchingMethods.Add(accessor); } } @@ -261,9 +261,9 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt if (matchingMethods.Count == 0) return null; - if (types == null || getPropertyGetter) + if (types is null || getPropertyGetter) { - Debug.Assert(types == null || types.Length == 0); + Debug.Assert(types is null || types.Length == 0); // matches any signature if (matchingMethods.Count == 1) @@ -273,9 +273,9 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt } else { - Debug.Assert(getPropertySetter && types != null && types.Length == 1); + Debug.Assert(getPropertySetter && types is not null && types.Length == 1); - if (binder == null) + if (binder is null) binder = Type.DefaultBinder; return (MethodInfo)binder.SelectMethod(bindingAttr, matchingMethods.ToArray(), types, modifiers); @@ -286,7 +286,7 @@ private IEnumerable NewProperties { get { - if (_newProperties == null) + if (_newProperties is null) { _newProperties = ReflectionContext.GetNewPropertiesForType(this); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.Projector.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.Projector.cs index 6e4f4870d13ba7..c488d1f5f59041 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.Projector.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.Projector.cs @@ -23,7 +23,7 @@ public TypeInfo ProjectTypeIfNeeded(TypeInfo value) if (NeedsProjection(value)) { // Map the assembly to the underlying context first - Debug.Assert(ReflectionContext.SourceContext != null); + Debug.Assert(ReflectionContext.SourceContext is not null); value = ReflectionContext.SourceContext.MapType(value); return ProjectType(value); } @@ -36,7 +36,7 @@ public Assembly ProjectAssemblyIfNeeded(Assembly value) if (NeedsProjection(value)) { // Map the assembly to the underlying context first - Debug.Assert(ReflectionContext.SourceContext != null); + Debug.Assert(ReflectionContext.SourceContext is not null); value = ReflectionContext.SourceContext.MapAssembly(value); return ProjectAssembly(value); @@ -47,7 +47,7 @@ public Assembly ProjectAssemblyIfNeeded(Assembly value) public override TypeInfo ProjectType(Type value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -57,7 +57,7 @@ public override TypeInfo ProjectType(Type value) public override Assembly ProjectAssembly(Assembly value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -67,7 +67,7 @@ public override Assembly ProjectAssembly(Assembly value) public override Module ProjectModule(Module value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -77,7 +77,7 @@ public override Module ProjectModule(Module value) public override FieldInfo ProjectField(FieldInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -87,7 +87,7 @@ public override FieldInfo ProjectField(FieldInfo value) public override EventInfo ProjectEvent(EventInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -97,7 +97,7 @@ public override EventInfo ProjectEvent(EventInfo value) public override ConstructorInfo ProjectConstructor(ConstructorInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -107,7 +107,7 @@ public override ConstructorInfo ProjectConstructor(ConstructorInfo value) public override MethodInfo ProjectMethod(MethodInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -117,15 +117,15 @@ public override MethodInfo ProjectMethod(MethodInfo value) public override MethodBase ProjectMethodBase(MethodBase value) { - if (value == null) + if (value is null) return null; MethodInfo method = value as MethodInfo; - if (method != null) + if (method is not null) return ProjectMethod(method); ConstructorInfo constructor = value as ConstructorInfo; - if (constructor != null) + if (constructor is not null) return ProjectConstructor(constructor); throw new InvalidOperationException(SR.Format(SR.InvalidOperation_InvalidMethodType, value.GetType())); @@ -133,7 +133,7 @@ public override MethodBase ProjectMethodBase(MethodBase value) public override PropertyInfo ProjectProperty(PropertyInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -143,7 +143,7 @@ public override PropertyInfo ProjectProperty(PropertyInfo value) public override ParameterInfo ProjectParameter(ParameterInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -153,7 +153,7 @@ public override ParameterInfo ProjectParameter(ParameterInfo value) public override MethodBody ProjectMethodBody(MethodBody value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -163,7 +163,7 @@ public override MethodBody ProjectMethodBody(MethodBody value) public override LocalVariableInfo ProjectLocalVariable(LocalVariableInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -173,7 +173,7 @@ public override LocalVariableInfo ProjectLocalVariable(LocalVariableInfo value) public override ExceptionHandlingClause ProjectExceptionHandlingClause(ExceptionHandlingClause value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -183,7 +183,7 @@ public override ExceptionHandlingClause ProjectExceptionHandlingClause(Exception public override CustomAttributeData ProjectCustomAttributeData(CustomAttributeData value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -193,7 +193,7 @@ public override CustomAttributeData ProjectCustomAttributeData(CustomAttributeDa public override ManifestResourceInfo ProjectManifestResource(ManifestResourceInfo value) { - if (value == null) + if (value is null) return null; Debug.Assert(NeedsProjection(value)); @@ -203,7 +203,7 @@ public override ManifestResourceInfo ProjectManifestResource(ManifestResourceInf public override MemberInfo ProjectMember(MemberInfo value) { - if (value == null) + if (value is null) return null; MemberInfo output = null; diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs index 2676cf631b558a..13ceffa2c1f37b 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs @@ -28,7 +28,7 @@ protected CustomReflectionContext(ReflectionContext source) public override Assembly MapAssembly(Assembly assembly) { - if (assembly == null) + if (assembly is null) { throw new ArgumentNullException(nameof(assembly)); } @@ -38,7 +38,7 @@ public override Assembly MapAssembly(Assembly assembly) public override TypeInfo MapType(TypeInfo type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -112,14 +112,14 @@ internal IEnumerable GetNewPropertiesForType(CustomType type) // Setting DeclaringType on the user provided virtual properties. foreach (PropertyInfo prop in newProperties) { - if (prop == null) + if (prop is null) throw new InvalidOperationException(SR.InvalidOperation_AddNullProperty); VirtualPropertyBase vp = prop as VirtualPropertyBase; - if (vp == null || vp.ReflectionContext != this) + if (vp is null || vp.ReflectionContext != this) throw new InvalidOperationException(SR.InvalidOperation_AddPropertyDifferentContext); - if (vp.DeclaringType == null) + if (vp.DeclaringType is null) vp.SetDeclaringType(type); else if (!vp.DeclaringType.Equals(type)) throw new InvalidOperationException(SR.InvalidOperation_AddPropertyDifferentType); diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingAssembly.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingAssembly.cs index 689c85667228d5..174aa69bc28e63 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingAssembly.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingAssembly.cs @@ -16,7 +16,7 @@ internal class DelegatingAssembly : Assembly public DelegatingAssembly(Assembly assembly) { - Debug.Assert(null != assembly); + Debug.Assert(assembly is not null); UnderlyingAssembly = assembly; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingConstructorInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingConstructorInfo.cs index 516aefaec69e27..4a609a52d6888a 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingConstructorInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingConstructorInfo.cs @@ -11,7 +11,7 @@ internal class DelegatingConstructorInfo : ConstructorInfo { public DelegatingConstructorInfo(ConstructorInfo constructor) { - Debug.Assert(null != constructor); + Debug.Assert(constructor is not null); UnderlyingConstructor = constructor; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingCustomAttributeData.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingCustomAttributeData.cs index d4f798155841c4..c6dfaeada7e5b1 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingCustomAttributeData.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingCustomAttributeData.cs @@ -10,7 +10,7 @@ internal class DelegatingCustomAttributeData : CustomAttributeData { public DelegatingCustomAttributeData(CustomAttributeData attribute) { - Debug.Assert(null != attribute); + Debug.Assert(attribute is not null); UnderlyingAttribute = attribute; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingExceptionHandlingClause.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingExceptionHandlingClause.cs index 2d0585a5f9183e..89b6f17356dec4 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingExceptionHandlingClause.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingExceptionHandlingClause.cs @@ -11,7 +11,7 @@ internal class DelegatingExceptionHandlingClause : ExceptionHandlingClause public DelegatingExceptionHandlingClause(ExceptionHandlingClause clause) { - Debug.Assert(clause != null); + Debug.Assert(clause is not null); _clause = clause; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingFieldInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingFieldInfo.cs index 042e8058b57156..282771b619290d 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingFieldInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingFieldInfo.cs @@ -11,7 +11,7 @@ internal class DelegatingFieldInfo : FieldInfo { public DelegatingFieldInfo(FieldInfo field) { - Debug.Assert(null != field); + Debug.Assert(field is not null); UnderlyingField = field; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingLocalVariableInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingLocalVariableInfo.cs index 4a1b56f4078ee1..bf5a772000787e 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingLocalVariableInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingLocalVariableInfo.cs @@ -9,7 +9,7 @@ internal class DelegatingLocalVariableInfo : LocalVariableInfo { public DelegatingLocalVariableInfo(LocalVariableInfo variable) { - Debug.Assert(variable != null); + Debug.Assert(variable is not null); UnderlyingVariable = variable; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingManifestResourceInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingManifestResourceInfo.cs index fbe11a0ae40e75..3bac3e8ecec2b8 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingManifestResourceInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingManifestResourceInfo.cs @@ -10,7 +10,7 @@ internal class DelegatingManifestResourceInfo : ManifestResourceInfo public DelegatingManifestResourceInfo(ManifestResourceInfo resource) : base(resource.ReferencedAssembly, resource.FileName, resource.ResourceLocation) { - Debug.Assert(null != resource); + Debug.Assert(resource is not null); UnderlyingResource = resource; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodBody.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodBody.cs index d1810b1e6d6540..565c65fab6cd5b 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodBody.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodBody.cs @@ -12,7 +12,7 @@ internal class DelegatingMethodBody : MethodBody public DelegatingMethodBody(MethodBody body) { - Debug.Assert(null != body); + Debug.Assert(body is not null); _body = body; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodInfo.cs index 2b7fbee4f5e66f..c251e4cb51ddeb 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingMethodInfo.cs @@ -12,7 +12,7 @@ internal class DelegatingMethodInfo : MethodInfo { public DelegatingMethodInfo(MethodInfo method) { - Debug.Assert(null != method); + Debug.Assert(method is not null); UnderlyingMethod = method; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingModule.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingModule.cs index aa98340a318621..aa120fafa9fe5e 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingModule.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingModule.cs @@ -10,7 +10,7 @@ internal class DelegatingModule : Module { public DelegatingModule(Module module) { - Debug.Assert(null != module); + Debug.Assert(module is not null); UnderlyingModule = module; } @@ -84,7 +84,7 @@ public override FieldInfo[] GetFields(BindingFlags bindingFlags) protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { - if (types == null) + if (types is null) { return UnderlyingModule.GetMethod(name); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingParameterInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingParameterInfo.cs index 8f2bf3317f47b9..89cdaca06e3441 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingParameterInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingParameterInfo.cs @@ -10,7 +10,7 @@ internal class DelegatingParameterInfo : ParameterInfo { public DelegatingParameterInfo(ParameterInfo parameter) { - Debug.Assert(null != parameter); + Debug.Assert(parameter is not null); UnderlyingParameter = parameter; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingPropertyInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingPropertyInfo.cs index 3aaab34993ab6c..9a0cddb328b887 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingPropertyInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingPropertyInfo.cs @@ -11,7 +11,7 @@ internal class DelegatingPropertyInfo : PropertyInfo { public DelegatingPropertyInfo(PropertyInfo property) { - Debug.Assert(null != property); + Debug.Assert(property is not null); UnderlyingProperty = property; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingType.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingType.cs index e107493ff0af2b..ed8e979f501408 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingType.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Delegation/DelegatingType.cs @@ -14,10 +14,10 @@ internal abstract class DelegatingType : TypeInfo public DelegatingType(Type type) { - Debug.Assert(null != type); + Debug.Assert(type is not null); _typeInfo = type.GetTypeInfo(); - if (_typeInfo == null) + if (_typeInfo is null) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_NoTypeInfoForThisType, type.FullName)); } @@ -349,7 +349,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { // Unfortunately we cannot directly call the protected GetMethodImpl on _typeInfo. - return (types == null) ? + return (types is null) ? _typeInfo.GetMethod(name, bindingAttr) : _typeInfo.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } @@ -379,10 +379,10 @@ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindin // Unfortunately we cannot directly call the protected GetPropertyImpl on _typeInfo. PropertyInfo property; - if (types == null) + if (types is null) { // if types is null, we can ignore binder and modifiers - if (returnType == null) + if (returnType is null) { property = _typeInfo.GetProperty(name, bindingAttr); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingAssembly.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingAssembly.cs index ba18ce41cd4b64..eacd9db7a2226c 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingAssembly.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingAssembly.cs @@ -14,7 +14,7 @@ internal class ProjectingAssembly : DelegatingAssembly, IProjectable public ProjectingAssembly(Assembly assembly, Projector projector) : base(assembly) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } @@ -104,7 +104,7 @@ public override bool Equals(object o) { var other = o as ProjectingAssembly; - return other != null && + return other is not null && Projector == other.Projector && UnderlyingAssembly == other.UnderlyingAssembly; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingConstructorInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingConstructorInfo.cs index f420d4bfd76120..5caecc9c11cb34 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingConstructorInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingConstructorInfo.cs @@ -13,7 +13,7 @@ internal class ProjectingConstructorInfo : DelegatingConstructorInfo, IProjectab public ProjectingConstructorInfo(ConstructorInfo constructor, Projector projector) : base(constructor) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } @@ -73,7 +73,7 @@ public override bool Equals(object o) { ProjectingConstructorInfo other = o as ProjectingConstructorInfo; - return other != null && + return other is not null && Projector == other.Projector && UnderlyingConstructor.Equals(other.UnderlyingConstructor); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingCustomAttributeData.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingCustomAttributeData.cs index ac392a35b01a28..e54d8a83dc0b57 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingCustomAttributeData.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingCustomAttributeData.cs @@ -15,7 +15,7 @@ internal class ProjectingCustomAttributeData : DelegatingCustomAttributeData public ProjectingCustomAttributeData(CustomAttributeData attribute, Projector projector) : base(attribute) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); _projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingEventInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingEventInfo.cs index 628fc159c25702..3badf5a30a3906 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingEventInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingEventInfo.cs @@ -13,7 +13,7 @@ internal class ProjectingEventInfo : DelegatingEventInfo, IProjectable public ProjectingEventInfo(EventInfo @event, Projector projector) : base(@event) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } @@ -82,7 +82,7 @@ public override bool Equals(object o) { var other = o as ProjectingEventInfo; - return other != null && + return other is not null && Projector == other.Projector && UnderlyingEvent.Equals(other.UnderlyingEvent); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingExceptionHandlingClause.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingExceptionHandlingClause.cs index 255b082f6af442..552b0800fef208 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingExceptionHandlingClause.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingExceptionHandlingClause.cs @@ -14,7 +14,7 @@ internal class ProjectingExceptionHandlingClause : DelegatingExceptionHandlingCl public ProjectingExceptionHandlingClause(ExceptionHandlingClause clause, Projector projector) : base(clause) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); _projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingFieldInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingFieldInfo.cs index 1fa50872ca2bb1..79c50238050d8d 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingFieldInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingFieldInfo.cs @@ -13,7 +13,7 @@ internal class ProjectingFieldInfo : DelegatingFieldInfo, IProjectable public ProjectingFieldInfo(FieldInfo field, Projector projector) : base(field) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } @@ -73,7 +73,7 @@ public override bool Equals(object o) { var other = o as ProjectingFieldInfo; - return other != null && + return other is not null && Projector == other.Projector && UnderlyingField.Equals(other.UnderlyingField); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingLocalVariableInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingLocalVariableInfo.cs index e1003de06052d8..e673cc98359920 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingLocalVariableInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingLocalVariableInfo.cs @@ -14,7 +14,7 @@ internal class ProjectingLocalVariableInfo : DelegatingLocalVariableInfo public ProjectingLocalVariableInfo(LocalVariableInfo variable, Projector projector) : base(variable) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); _projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingManifestResourceInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingManifestResourceInfo.cs index 734efef1ff051d..e6d451f9cae0da 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingManifestResourceInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingManifestResourceInfo.cs @@ -14,7 +14,7 @@ internal class ProjectingManifestResourceInfo : DelegatingManifestResourceInfo public ProjectingManifestResourceInfo(ManifestResourceInfo resource, Projector projector) : base(resource) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); _projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodBody.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodBody.cs index 28e94fa661fb89..2e0a0dfa3ac375 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodBody.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodBody.cs @@ -15,7 +15,7 @@ internal class ProjectingMethodBody : DelegatingMethodBody public ProjectingMethodBody(MethodBody body, Projector projector) : base(body) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); _projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodInfo.cs index ad6aa9b5096917..0eca9fb8e8de95 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingMethodInfo.cs @@ -13,7 +13,7 @@ internal class ProjectingMethodInfo : DelegatingMethodInfo, IProjectable public ProjectingMethodInfo(MethodInfo method, Projector projector) : base(method) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } @@ -122,7 +122,7 @@ public override bool Equals(object o) { var other = o as ProjectingMethodInfo; - return other != null && + return other is not null && Projector == other.Projector && UnderlyingMethod.Equals(other.UnderlyingMethod); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingModule.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingModule.cs index 9867a1338b3860..2f7e2a01658d7c 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingModule.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingModule.cs @@ -13,7 +13,7 @@ internal class ProjectingModule : DelegatingModule, IProjectable public ProjectingModule(Module module, Projector projector) : base(module) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } @@ -111,7 +111,7 @@ public override bool Equals(object o) { var other = o as ProjectingModule; - return other != null && + return other is not null && Projector == other.Projector && UnderlyingModule.Equals(other.UnderlyingModule); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingParameterInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingParameterInfo.cs index 72b25b775f899f..8eff44846905ae 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingParameterInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingParameterInfo.cs @@ -13,7 +13,7 @@ internal class ProjectingParameterInfo : DelegatingParameterInfo, IProjectable public ProjectingParameterInfo(ParameterInfo parameter, Projector projector) : base(parameter) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingPropertyInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingPropertyInfo.cs index 3b68e6e0eff8be..f5553e29f57d75 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingPropertyInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingPropertyInfo.cs @@ -13,7 +13,7 @@ internal class ProjectingPropertyInfo : DelegatingPropertyInfo, IProjectable public ProjectingPropertyInfo(PropertyInfo property, Projector projector) : base(property) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); Projector = projector; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs index b80a12f3393fc4..189dde7bc42d55 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs @@ -15,7 +15,7 @@ internal class ProjectingType : DelegatingType, IProjectable public ProjectingType(Type type, Projector projector) : base(type) { - Debug.Assert(null != projector); + Debug.Assert(projector is not null); _projector = projector; } @@ -137,7 +137,7 @@ public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFla public override bool IsAssignableFrom(Type c) { ProjectingType otherType = c as ProjectingType; - if (otherType == null || Projector != otherType.Projector) + if (otherType is null || Projector != otherType.Projector) return false; return UnderlyingType.IsAssignableFrom(otherType.UnderlyingType); @@ -153,7 +153,7 @@ public override bool IsDefined(Type attributeType, bool inherit) public override bool IsEquivalentTo(Type other) { ProjectingType otherType = other as ProjectingType; - if (otherType == null || Projector != otherType.Projector) + if (otherType is null || Projector != otherType.Projector) return false; return UnderlyingType.IsEquivalentTo(otherType.UnderlyingType); @@ -172,7 +172,7 @@ public override bool IsInstanceOfType(object o) public override bool IsSubclassOf(Type c) { ProjectingType otherType = c as ProjectingType; - if (otherType == null || Projector != otherType.Projector) + if (otherType is null || Projector != otherType.Projector) return false; return UnderlyingType.IsSubclassOf(otherType.UnderlyingType); diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs index 19b9a82d28f07a..947c28d9710212 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs @@ -10,7 +10,7 @@ internal abstract class Projector { public IList Project(IList values, Func project) { - if (values == null || values.Count == 0) + if (values is null || values.Count == 0) return values; T[] projected = ProjectAll(values, project); @@ -20,7 +20,7 @@ public IList Project(IList values, Func project) public T[] Project(T[] values, Func project) { - if (values == null || values.Length == 0) + if (values is null || values.Length == 0) return values; return ProjectAll(values, project); @@ -61,7 +61,7 @@ public T Project(T value, Func project) public Type[] Unproject(Type[] values) { - if (values == null) + if (values is null) return null; Type[] newTypes = new Type[values.Length]; @@ -83,9 +83,9 @@ public Type Unproject(Type value) public bool NeedsProjection(object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); - if (value == null) + if (value is null) return false; if (value is IProjectable projector && projector == this) @@ -101,8 +101,8 @@ public bool NeedsProjection(object value) private T[] ProjectAll(IList values, Func project) { - Debug.Assert(null != project); - Debug.Assert(values != null && values.Count > 0); + Debug.Assert(project is not null); + Debug.Assert(values is not null && values.Count > 0); var projected = new T[values.Count]; diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedMethodInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedMethodInfo.cs index 734fbe4f8f1d19..6f3490b5dc5890 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedMethodInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedMethodInfo.cs @@ -14,7 +14,7 @@ internal partial class InheritedMethodInfo : DelegatingMethodInfo public InheritedMethodInfo(MethodInfo baseMethod, Type reflectedType) : base(baseMethod) { - Debug.Assert(reflectedType != null); + Debug.Assert(reflectedType is not null); Debug.Assert(reflectedType.IsSubclassOf(baseMethod.DeclaringType)); Debug.Assert(baseMethod is VirtualMethodBase); @@ -36,7 +36,7 @@ public override bool Equals(object o) { var other = o as InheritedMethodInfo; - return other != null && + return other is not null && UnderlyingMethod.Equals(other.UnderlyingMethod) && ReflectedType.Equals(other.ReflectedType); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedPropertyInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedPropertyInfo.cs index bc2cc4c67aa893..a5fa76f21b19b9 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedPropertyInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/InheritedPropertyInfo.cs @@ -14,7 +14,7 @@ internal partial class InheritedPropertyInfo : DelegatingPropertyInfo public InheritedPropertyInfo(PropertyInfo baseProperty, Type reflectedType) : base(baseProperty) { - Debug.Assert(reflectedType != null); + Debug.Assert(reflectedType is not null); Debug.Assert(reflectedType.IsSubclassOf(baseProperty.DeclaringType)); Debug.Assert(baseProperty is VirtualPropertyBase); @@ -35,7 +35,7 @@ public override Type ReflectedType public override MethodInfo GetGetMethod(bool nonPublic) { MethodInfo underlyingGetter = UnderlyingProperty.GetGetMethod(nonPublic); - if (underlyingGetter == null) + if (underlyingGetter is null) return null; else return new InheritedMethodInfo(underlyingGetter, _reflectedType); @@ -44,7 +44,7 @@ public override MethodInfo GetGetMethod(bool nonPublic) public override MethodInfo GetSetMethod(bool nonPublic) { MethodInfo underlyingSetter = UnderlyingProperty.GetSetMethod(nonPublic); - if (underlyingSetter == null) + if (underlyingSetter is null) return null; else return new InheritedMethodInfo(underlyingSetter, _reflectedType); diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.FuncPropertyAccessorBase.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.FuncPropertyAccessorBase.cs index dd0f2b5410d2e3..68b7da8522146f 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.FuncPropertyAccessorBase.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.FuncPropertyAccessorBase.cs @@ -11,7 +11,7 @@ protected abstract class FuncPropertyAccessorBase : VirtualMethodBase { protected FuncPropertyAccessorBase(VirtualPropertyBase declaringProperty) { - Debug.Assert(null != declaringProperty); + Debug.Assert(declaringProperty is not null); DeclaringProperty = declaringProperty; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.PropertySetterBase.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.PropertySetterBase.cs index 8385dbb231890c..3aeac2d117802a 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.PropertySetterBase.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.PropertySetterBase.cs @@ -26,7 +26,7 @@ public override sealed Type ReturnType protected override Type[] GetParameterTypes() { - return (_parameterTypes != null) ? + return (_parameterTypes is not null) ? _parameterTypes : _parameterTypes = new Type[1] { DeclaringProperty.PropertyType }; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs index fcd5e161a0cf9a..38d86fbcb6002a 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs @@ -17,16 +17,16 @@ internal abstract partial class VirtualPropertyBase : PropertyInfo protected VirtualPropertyBase(Type propertyType, string name, CustomReflectionContext context) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("", nameof(name)); - if (propertyType == null) + if (propertyType is null) throw new ArgumentNullException(nameof(propertyType)); - Debug.Assert(context != null); + Debug.Assert(context is not null); _propertyType = propertyType; _name = name; @@ -57,12 +57,12 @@ public override sealed Type PropertyType public override sealed bool CanRead { - get { return GetGetMethod(true) != null; } + get { return GetGetMethod(true) is not null; } } public override sealed bool CanWrite { - get { return GetSetMethod(true) != null; } + get { return GetSetMethod(true) is not null; } } public override sealed int MetadataToken @@ -85,9 +85,9 @@ public override sealed MethodInfo[] GetAccessors(bool nonPublic) MethodInfo getMethod = GetGetMethod(nonPublic); MethodInfo setMethod = GetSetMethod(nonPublic); - Debug.Assert(getMethod != null || setMethod != null); + Debug.Assert(getMethod is not null || setMethod is not null); - if (getMethod == null || setMethod == null) + if (getMethod is null || setMethod is null) { return new MethodInfo[] { getMethod ?? setMethod }; } @@ -103,7 +103,7 @@ public override sealed ParameterInfo[] GetIndexParameters() public override sealed object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { MethodInfo getMethod = GetGetMethod(true); - if (getMethod == null) + if (getMethod is null) throw new ArgumentException(SR.Argument_GetMethNotFnd); return getMethod.Invoke(obj, invokeAttr, binder, index, culture); @@ -112,12 +112,12 @@ public override sealed object GetValue(object obj, BindingFlags invokeAttr, Bind public override sealed void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { MethodInfo setMethod = GetSetMethod(true); - if (setMethod == null) + if (setMethod is null) throw new ArgumentException(SR.Argument_GetMethNotFnd); object[] args = null; - if (index != null) + if (index is not null) { args = new object[index.Length + 1]; @@ -205,10 +205,10 @@ internal void SetDeclaringType(Type declaringType) private ParameterInfo[] GetIndexParametersNoCopy() { - if (_indexedParameters == null) + if (_indexedParameters is null) { MethodInfo method = GetGetMethod(true); - if (method != null) + if (method is not null) { _indexedParameters = VirtualParameter.CloneParameters(this, method.GetParameters(), skipLastParameter: false); } @@ -216,7 +216,7 @@ private ParameterInfo[] GetIndexParametersNoCopy() { method = GetSetMethod(true); - Debug.Assert(null != method); + Debug.Assert(method is not null); _indexedParameters = VirtualParameter.CloneParameters(this, method.GetParameters(), skipLastParameter: true); } } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertyGetter.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertyGetter.cs index 4c3c1ee0643218..e6a9e7c5ec39ae 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertyGetter.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertyGetter.cs @@ -18,7 +18,7 @@ private class PropertyGetter : PropertyGetterBase public PropertyGetter(VirtualPropertyBase property, Func getter, IEnumerable getterAttributes) : base(property) { - Debug.Assert(null != getter); + Debug.Assert(getter is not null); _getter = getter; _attributes = getterAttributes ?? CollectionServices.Empty(); @@ -28,7 +28,7 @@ public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder { // invokeAttr, binder, and culture are ignored, similar to what runtime reflection does with the default binder. - if (parameters != null && parameters.Length > 0) + if (parameters is not null && parameters.Length > 0) throw new TargetParameterCountException(); if (!ReflectedType.IsInstanceOfType(obj)) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertySetter.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertySetter.cs index 49b7251b8631b8..4fac5ac014e7d8 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertySetter.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertySetter.cs @@ -19,7 +19,7 @@ private class PropertySetter : PropertySetterBase public PropertySetter(VirtualPropertyBase property, Action setter, IEnumerable setterAttributes) : base(property) { - Debug.Assert(null != setter); + Debug.Assert(setter is not null); _setter = setter; _valueParameter = new VirtualParameter(this, property.PropertyType, "value", 0); @@ -35,12 +35,12 @@ public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder { // invokeAttr, binder, and culture are ignored, similar to what runtime reflection does with the default binder. - if (parameters == null || parameters.Length != 1) + if (parameters is null || parameters.Length != 1) throw new TargetParameterCountException(); object value = parameters[0]; - if (obj == null) + if (obj is null) throw new TargetException(SR.Target_InstanceMethodRequiresTarget); if (!ReflectedType.IsInstanceOfType(obj)) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.cs index ea21ece64221b9..cb3025dede950b 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.cs @@ -25,17 +25,17 @@ public VirtualPropertyInfo( CustomReflectionContext context) : base(propertyType, name, context) { - if (getter == null && setter == null) + if (getter is null && setter is null) throw new ArgumentException(SR.ArgumentNull_GetterOrSetterMustBeSpecified); CustomType rcType = propertyType as CustomType; - if (rcType == null || rcType.ReflectionContext != context) + if (rcType is null || rcType.ReflectionContext != context) throw new ArgumentException(SR.Argument_PropertyTypeFromDifferentContext); - if (getter != null) + if (getter is not null) _getter = new PropertyGetter(this, getter, getterAttributes); - if (setter != null) + if (setter is not null) _setter = new PropertySetter(this, setter, setterAttributes); _attributes = propertyAttributes ?? CollectionServices.Empty(); @@ -44,14 +44,14 @@ public VirtualPropertyInfo( public override MethodInfo GetGetMethod(bool nonPublic) { // Current we don't support adding nonpulbic getters - Debug.Assert(_getter == null || _getter.IsPublic); + Debug.Assert(_getter is null || _getter.IsPublic); return _getter; } public override MethodInfo GetSetMethod(bool nonPublic) { // Current we don't support adding nonpulbic setters - Debug.Assert(_setter == null || _setter.IsPublic); + Debug.Assert(_setter is null || _setter.IsPublic); return _setter; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/ByteArrayMemoryProvider.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/ByteArrayMemoryProvider.cs index fae4a7196850cd..5d80d9aefd2cfc 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/ByteArrayMemoryProvider.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/ByteArrayMemoryProvider.cs @@ -43,11 +43,11 @@ internal unsafe byte* Pointer { get { - if (_pinned == null) + if (_pinned is null) { var newPinned = new PinnedObject(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(_array)!); - if (Interlocked.CompareExchange(ref _pinned, newPinned, null) != null) + if (Interlocked.CompareExchange(ref _pinned, newPinned, null) is not null) { // another thread has already allocated the handle: newPinned.Dispose(); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/StreamMemoryBlockProvider.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/StreamMemoryBlockProvider.cs index 7581e90f0cb4f1..ba2fe3541b702a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/StreamMemoryBlockProvider.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/StreamMemoryBlockProvider.cs @@ -124,7 +124,7 @@ public override Stream GetStream(out StreamConstraints constraints) /// IO error while mapping memory or not enough memory to create the mapping. private unsafe bool TryCreateMemoryMappedFileBlock(long start, int size, [NotNullWhen(true)]out MemoryMappedFileBlock? block) { - if (_lazyMemoryMap == null) + if (_lazyMemoryMap is null) { // leave the underlying stream open. It will be closed by the Dispose method. IDisposable newMemoryMap; @@ -135,20 +135,20 @@ private unsafe bool TryCreateMemoryMappedFileBlock(long start, int size, [NotNul newMemoryMap = MemoryMapLightUp.CreateMemoryMap(_stream); } - if (newMemoryMap == null) + if (newMemoryMap is null) { block = null; return false; } - if (Interlocked.CompareExchange(ref _lazyMemoryMap, newMemoryMap, null) != null) + if (Interlocked.CompareExchange(ref _lazyMemoryMap, newMemoryMap, null) is not null) { newMemoryMap.Dispose(); } } IDisposable accessor = MemoryMapLightUp.CreateViewAccessor(_lazyMemoryMap, start, size); - if (accessor == null) + if (accessor is null) { block = null; return false; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ByteSequenceComparer.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ByteSequenceComparer.cs index 89e4ce9c51c41c..73e66d5f88af9e 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ByteSequenceComparer.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ByteSequenceComparer.cs @@ -41,7 +41,7 @@ internal static bool Equals(ImmutableArray x, ImmutableArray y) internal static bool Equals(byte[] left, int leftStart, byte[] right, int rightStart, int length) { - if (left == null || right == null) + if (left is null || right is null) { return ReferenceEquals(left, right); } @@ -69,7 +69,7 @@ internal static bool Equals(byte[]? left, byte[]? right) return true; } - if (left == null || right == null || left.Length != right.Length) + if (left is null || right is null || left.Length != right.Length) { return false; } @@ -89,7 +89,7 @@ internal static bool Equals(byte[]? left, byte[]? right) internal static int GetHashCode(byte[] x) { - Debug.Assert(x != null); + Debug.Assert(x is not null); return Hash.GetFNVHashCode(x); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.cs index fc619c33a1a817..42d84bfd1ad5bf 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.cs @@ -42,7 +42,7 @@ namespace System.Reflection.Internal /// /// For both (2) and (3), the pooled buffers have a fixed size deemed large enough for the /// vast majority of metadata strings. In the rare worst case (byteCount > threshold and - /// (lightUpAttemptFailed || prefix != null), we give up and allocate a temporary array, + /// (lightUpAttemptFailed || prefix is not null), we give up and allocate a temporary array, /// copy to it, decode, and throw it away. /// internal static unsafe class EncodingHelper @@ -59,9 +59,9 @@ internal static unsafe class EncodingHelper public static string DecodeUtf8(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) { - Debug.Assert(utf8Decoder != null); + Debug.Assert(utf8Decoder is not null); - if (prefix != null) + if (prefix is not null) { return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder); } @@ -76,7 +76,7 @@ public static string DecodeUtf8(byte* bytes, int byteCount, byte[] prefix, Metad private static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) { - Debug.Assert(utf8Decoder != null); + Debug.Assert(utf8Decoder is not null); int prefixedByteCount = byteCount + prefix.Length; @@ -129,9 +129,9 @@ private static void ReleaseBuffer(byte[] buffer) public static string GetString(this Encoding encoding, byte* bytes, int byteCount) { - Debug.Assert(encoding != null); + Debug.Assert(encoding is not null); - if (s_getStringPlatform == null) + if (s_getStringPlatform is null) { return GetStringPortable(encoding, bytes, byteCount); } @@ -144,9 +144,9 @@ private static unsafe string GetStringPortable(Encoding encoding, byte* bytes, i // This implementation can leak publicly (by design) to MetadataStringDecoder.GetString. // Therefore we implement the same validation. - Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor. + Debug.Assert(encoding is not null); // validated by MetadataStringDecoder constructor. - if (bytes == null) + if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } @@ -171,7 +171,7 @@ private static Encoding_GetString LoadGetStringPlatform() MethodInfo getStringInfo = LightUpHelper.GetMethod(typeof(Encoding), "GetString", typeof(byte*), typeof(int)); - if (getStringInfo != null && getStringInfo.ReturnType == typeof(string)) + if (getStringInfo is not null && getStringInfo.ReturnType == typeof(string)) { try { @@ -248,9 +248,9 @@ private static unsafe string GetStringUsingCreateStringFromEncoding( // MetadataStringDecoder.GetString. Therefore, we implement the same validation // that Encoding.GetString would do if it were available directly. - Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor. + Debug.Assert(encoding is not null); // validated by MetadataStringDecoder constructor. - if (bytes == null) + if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } @@ -266,7 +266,7 @@ private static unsafe string GetStringUsingCreateStringFromEncoding( // Test hook to force portable implementation and ensure light is functioning. internal static bool TestOnly_LightUpEnabled { - get { return s_getStringPlatform != null; } + get { return s_getStringPlatform is not null; } set { s_getStringPlatform = value ? LoadGetStringPlatform() : null; } } #endregion diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.netcoreapp.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.netcoreapp.cs index 4b35952636ba81..fe08969e6ca7ab 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.netcoreapp.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/EncodingHelper.netcoreapp.cs @@ -18,9 +18,9 @@ internal static unsafe class EncodingHelper { public static string DecodeUtf8(byte* bytes, int byteCount, byte[]? prefix, MetadataStringDecoder utf8Decoder) { - Debug.Assert(utf8Decoder != null); + Debug.Assert(utf8Decoder is not null); - if (prefix != null) + if (prefix is not null) { return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder); } @@ -35,7 +35,7 @@ public static string DecodeUtf8(byte* bytes, int byteCount, byte[]? prefix, Meta private static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) { - Debug.Assert(utf8Decoder != null); + Debug.Assert(utf8Decoder is not null); int prefixedByteCount = byteCount + prefix.Length; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ExceptionUtilities.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ExceptionUtilities.cs index 3d6b4605cf492e..44a6023b3ed866 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ExceptionUtilities.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ExceptionUtilities.cs @@ -7,7 +7,7 @@ internal static class ExceptionUtilities { internal static Exception UnexpectedValue(object value) { - if (value?.GetType().FullName != null) + if (value?.GetType().FullName is not null) { return new InvalidOperationException(SR.Format(SR.UnexpectedValue, value, value.GetType().FullName)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.cs index 99539fc8f955e4..6e9024ae09ec8f 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.cs @@ -29,7 +29,7 @@ internal static class FileStreamReadLightUp return null; } - if (handle != null && handle.IsInvalid) + if (handle is not null && handle.IsInvalid) { // Also allow for FileStream implementations that do return a non-null, but invalid underlying OS handle. // This is how brokered files on WinRT will work. Fall back to slow path. @@ -47,7 +47,7 @@ internal static unsafe bool TryReadFile(Stream stream, byte* buffer, long start, } SafeHandle? handle = GetSafeFileHandle(stream); - if (handle == null) + if (handle is null) { return false; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.netstandard1.1.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.netstandard1.1.cs index 1bcc69e7a54c4f..4afe786ad23933 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.netstandard1.1.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/FileStreamReadLightUp.netstandard1.1.cs @@ -28,7 +28,7 @@ internal static class FileStreamReadLightUp internal static bool IsFileStream(Stream stream) { - if (FileStreamType.Value == null) + if (FileStreamType.Value is null) { return false; } @@ -39,7 +39,7 @@ internal static bool IsFileStream(Stream stream) internal static SafeHandle GetSafeFileHandle(Stream stream) { - Debug.Assert(FileStreamType.IsValueCreated && FileStreamType.Value != null && IsFileStream(stream)); + Debug.Assert(FileStreamType.IsValueCreated && FileStreamType.Value is not null && IsFileStream(stream)); if (safeFileHandleNotAvailable) { @@ -47,7 +47,7 @@ internal static SafeHandle GetSafeFileHandle(Stream stream) } PropertyInfo safeFileHandleProperty = SafeFileHandle.Value; - if (safeFileHandleProperty == null) + if (safeFileHandleProperty is null) { safeFileHandleNotAvailable = true; return null; @@ -76,7 +76,7 @@ internal static SafeHandle GetSafeFileHandle(Stream stream) return null; } - if (handle != null && handle.IsInvalid) + if (handle is not null && handle.IsInvalid) { // Also allow for FileStream implementations that do return a non-null, but invalid underlying OS handle. // This is how brokered files on WinRT will work. Fall back to slow path. @@ -94,7 +94,7 @@ internal static unsafe bool TryReadFile(Stream stream, byte* buffer, long start, } SafeHandle handle = GetSafeFileHandle(stream); - if (handle == null) + if (handle is null) { return false; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/LightUpHelper.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/LightUpHelper.cs index 9abce8f7492c96..677260296d141d 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/LightUpHelper.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/LightUpHelper.cs @@ -24,7 +24,7 @@ internal static Type GetType(string typeName, params string[] assemblyNames) // profile. It can still be thrown even when throwOnError is false. } - if (type != null) + if (type is not null) { return type; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs index a938d8766bec3f..a1350c40f4d75a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs @@ -18,7 +18,7 @@ internal readonly unsafe struct MemoryBlock internal MemoryBlock(byte* buffer, int length) { - Debug.Assert(length >= 0 && (buffer != null || length == 0)); + Debug.Assert(length >= 0 && (buffer is not null || length == 0)); this.Pointer = buffer; this.Length = length; } @@ -30,7 +30,7 @@ internal static MemoryBlock CreateChecked(byte* buffer, int length) throw new ArgumentOutOfRangeException(nameof(length)); } - if (buffer == null && length != 0) + if (buffer is null && length != 0) { throw new ArgumentNullException(nameof(buffer)); } @@ -49,12 +49,12 @@ private void CheckBounds(int offset, int byteCount) internal byte[]? ToArray() { - return Pointer == null ? null : PeekBytes(0, Length); + return Pointer is null ? null : PeekBytes(0, Length); } private string GetDebuggerDisplay() { - if (Pointer == null) + if (Pointer is null) { return ""; } @@ -77,7 +77,7 @@ internal string GetDebuggerDisplay(out int displayedBytes) internal string GetDebuggerDisplay(int offset) { - if (Pointer == null) + if (Pointer is null) { return ""; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryMapLightUp.netstandard1.1.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryMapLightUp.netstandard1.1.cs index 156650da78da59..f63face73c1562 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryMapLightUp.netstandard1.1.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryMapLightUp.netstandard1.1.cs @@ -46,7 +46,7 @@ internal static bool IsAvailable private static bool TryLoadType(string typeName, string modernAssembly, string classicAssembly, out Type type) { type = LightUpHelper.GetType(typeName, modernAssembly, classicAssembly); - return type != null; + return type is not null; } private static bool TryLoadTypes() @@ -57,7 +57,7 @@ private static bool TryLoadTypes() TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFileSecurity", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedFileSecurityType); - return FileStreamReadLightUp.FileStreamType.Value != null + return FileStreamReadLightUp.FileStreamType.Value is not null && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFile", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedFileType) && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedViewAccessor", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedViewAccessorType) && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFileAccess", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedFileAccessType) @@ -80,9 +80,9 @@ private static bool TryLoadMembers() ); // .NET < 4.6 - if (s_lazyCreateFromFile == null) + if (s_lazyCreateFromFile is null) { - if (s_lazyMemoryMappedFileSecurityType != null) + if (s_lazyMemoryMappedFileSecurityType is not null) { s_lazyCreateFromFileClassic = LightUpHelper.GetMethod( s_lazyMemoryMappedFileType, @@ -96,7 +96,7 @@ private static bool TryLoadMembers() typeof(bool)); } - if (s_lazyCreateFromFileClassic == null) + if (s_lazyCreateFromFileClassic is null) { return false; } @@ -109,13 +109,13 @@ private static bool TryLoadMembers() typeof(long), s_lazyMemoryMappedFileAccessType); - if (s_lazyCreateViewAccessor == null) + if (s_lazyCreateViewAccessor is null) { return false; } s_lazySafeMemoryMappedViewHandle = s_lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredProperty("SafeMemoryMappedViewHandle"); - if (s_lazySafeMemoryMappedViewHandle == null) + if (s_lazySafeMemoryMappedViewHandle is null) { return false; } @@ -124,16 +124,16 @@ private static bool TryLoadMembers() s_lazyPointerOffset = s_lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredProperty("PointerOffset"); // .NET < 4.5.1 - if (s_lazyPointerOffset == null) + if (s_lazyPointerOffset is null) { s_lazyInternalViewField = s_lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredField("m_view"); - if (s_lazyInternalViewField == null) + if (s_lazyInternalViewField is null) { return false; } s_lazyInternalPointerOffset = s_lazyInternalViewField.FieldType.GetTypeInfo().GetDeclaredProperty("PointerOffset"); - if (s_lazyInternalPointerOffset == null) + if (s_lazyInternalPointerOffset is null) { return false; } @@ -148,7 +148,7 @@ internal static IDisposable CreateMemoryMap(Stream stream) try { - if (s_lazyCreateFromFile != null) + if (s_lazyCreateFromFile is not null) { return (IDisposable)s_lazyCreateFromFile.Invoke(null, new object[6] { @@ -162,7 +162,7 @@ internal static IDisposable CreateMemoryMap(Stream stream) } else { - Debug.Assert(s_lazyCreateFromFileClassic != null); + Debug.Assert(s_lazyCreateFromFileClassic is not null); return (IDisposable)s_lazyCreateFromFileClassic.Invoke(null, new object[7] { stream, // fileStream @@ -235,7 +235,7 @@ internal static bool TryGetSafeBufferAndPointerOffset(object accessor, out SafeB try { - if (s_lazyPointerOffset != null) + if (s_lazyPointerOffset is not null) { offset = (long)s_lazyPointerOffset.GetValue(accessor); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ObjectPool`1.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ObjectPool`1.cs index 2130527181aa54..b6f196038b36ed 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ObjectPool`1.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ObjectPool`1.cs @@ -73,7 +73,7 @@ internal T Allocate() // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. inst = items[i].Value; - if (inst != null) + if (inst is not null) { if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) { @@ -101,7 +101,7 @@ internal void Free(T obj) var items = _items; for (int i = 0; i < items.Length; i++) { - if (items[i].Value == null) + if (items[i].Value is null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs index 03c69af04a2a15..da741d12bbc866 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs @@ -18,7 +18,7 @@ private static string PlatformSpecificDirectorySeparator { get { - if (s_platformSpecificDirectorySeparator == null) + if (s_platformSpecificDirectorySeparator is null) { // '*' is a valid char on Unix-based FS s_platformSpecificDirectorySeparator = @@ -35,7 +35,7 @@ private static string PlatformSpecificDirectorySeparator /// -1 if path is null. internal static int IndexOfFileName(string path) { - if (path == null) + if (path is null) { return -1; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PooledStringBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PooledStringBuilder.cs index 05ab60bb2baf83..fd6862dc6f0451 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PooledStringBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PooledStringBuilder.cs @@ -21,7 +21,7 @@ internal class PooledStringBuilder private PooledStringBuilder(ObjectPool pool) { - Debug.Assert(pool != null); + Debug.Assert(pool is not null); _pool = pool; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Blob.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Blob.cs index e6d479d8755676..2d4e4a68bdf66c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Blob.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Blob.cs @@ -16,7 +16,7 @@ internal Blob(byte[] buffer, int start, int length) Length = length; } - public bool IsDefault => Buffer == null; + public bool IsDefault => Buffer is null; public ArraySegment GetBytes() => new ArraySegment(Buffer, Start, Length); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.Enumerators.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.Enumerators.cs index c74d2ed5f4a7a7..8c7df20e9a04fd 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.Enumerators.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.Enumerators.cs @@ -77,7 +77,7 @@ public Blob Current get { var current = _chunks.Current; - if (current != null) + if (current is not null) { return new Blob(current._buffer, 0, current.Length); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs index a5bb62623e0a0c..1e43a0fc6d411c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs @@ -122,9 +122,9 @@ internal void ClearChunk() private void CheckInvariants() { #if DEBUG - Debug.Assert(_buffer != null); + Debug.Assert(_buffer is not null); Debug.Assert(Length >= 0 && Length <= _buffer.Length); - Debug.Assert(_nextOrPrevious != null); + Debug.Assert(_nextOrPrevious is not null); if (IsHead) { @@ -205,7 +205,7 @@ public bool ContentEquals(BlobBuilder other) return true; } - if (other == null) + if (other is null) { return false; } @@ -324,7 +324,7 @@ public ImmutableArray ToImmutableArray(int start, int byteCount) /// Content is not available, the builder has been linked with another one. public void WriteContentTo(Stream destination) { - if (destination == null) + if (destination is null) { Throw.ArgumentNull(nameof(destination)); } @@ -354,7 +354,7 @@ public void WriteContentTo(ref BlobWriter destination) /// Content is not available, the builder has been linked with another one. public void WriteContentTo(BlobBuilder destination) { - if (destination == null) + if (destination is null) { Throw.ArgumentNull(nameof(destination)); } @@ -369,7 +369,7 @@ public void WriteContentTo(BlobBuilder destination) /// Builder is not writable, it has been linked with another one. public void LinkPrefix(BlobBuilder prefix) { - if (prefix == null) + if (prefix is null) { Throw.ArgumentNull(nameof(prefix)); } @@ -429,7 +429,7 @@ public void LinkPrefix(BlobBuilder prefix) /// Builder is not writable, it has been linked with another one. public void LinkSuffix(BlobBuilder suffix) { - if (suffix == null) + if (suffix is null) { throw new ArgumentNullException(nameof(suffix)); } @@ -638,7 +638,7 @@ public void WriteBytes(byte value, int byteCount) /// Builder is not writable, it has been linked with another one. public unsafe void WriteBytes(byte* buffer, int byteCount) { - if (buffer == null) + if (buffer is null) { Throw.ArgumentNull(nameof(buffer)); } @@ -680,7 +680,7 @@ private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) /// Bytes successfully written from the . public int TryWriteBytes(Stream source, int byteCount) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -749,7 +749,7 @@ public void WriteBytes(byte[] buffer) /// Builder is not writable, it has been linked with another one. public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) { - if (buffer == null) + if (buffer is null) { Throw.ArgumentNull(nameof(buffer)); } @@ -932,7 +932,7 @@ public void WriteReference(int reference, bool isSmall) /// Builder is not writable, it has been linked with another one. public unsafe void WriteUTF16(char[] value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -971,7 +971,7 @@ public unsafe void WriteUTF16(char[] value) /// Builder is not writable, it has been linked with another one. public unsafe void WriteUTF16(string value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -1008,7 +1008,7 @@ public unsafe void WriteUTF16(string value) /// Builder is not writable, it has been linked with another one. public void WriteSerializedString(string? value) { - if (value == null) + if (value is null) { WriteByte(0xff); return; @@ -1030,7 +1030,7 @@ public void WriteSerializedString(string? value) /// Builder is not writable, it has been linked with another one. public void WriteUserString(string value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -1051,7 +1051,7 @@ public void WriteUserString(string value) /// Builder is not writable, it has been linked with another one. public void WriteUTF8(string value, bool allowUnpairedSurrogates = true) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs index 270c9112134690..f7b5d394671aae 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs @@ -27,7 +27,7 @@ public BlobContentId(ImmutableArray id) public unsafe BlobContentId(byte[] id) { - if (id == null) + if (id is null) { throw new ArgumentNullException(nameof(id)); } @@ -56,7 +56,7 @@ public static unsafe BlobContentId FromHash(byte[] hashCode) { const int minHashSize = 20; - if (hashCode == null) + if (hashCode is null) { throw new ArgumentNullException(nameof(hashCode)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobReader.cs index e7f05ceb42e956..5701307d78f678 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobReader.cs @@ -40,7 +40,7 @@ public BlobReader(byte* buffer, int length) internal BlobReader(MemoryBlock block) { - Debug.Assert(block.Length >= 0 && (block.Pointer != null || block.Length == 0)); + Debug.Assert(block.Length >= 0 && (block.Pointer is not null || block.Length == 0)); _block = block; _currentPointer = block.Pointer; _endPointer = block.Pointer + block.Length; @@ -48,7 +48,7 @@ internal BlobReader(MemoryBlock block) internal string GetDebuggerDisplay() { - if (_block.Pointer == null) + if (_block.Pointer is null) { return ""; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs index f8f1df5ae31555..e45a8c6016fee1 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs @@ -37,7 +37,7 @@ public BlobWriter(Blob blob) public BlobWriter(byte[] buffer, int start, int count) { - Debug.Assert(buffer != null); + Debug.Assert(buffer is not null); Debug.Assert(count >= 0); Debug.Assert(count <= buffer.Length - start); @@ -47,7 +47,7 @@ public BlobWriter(byte[] buffer, int start, int count) _end = start + count; } - internal bool IsDefault => _buffer == null; + internal bool IsDefault => _buffer is null; /// /// Compares the current content of this writer with another one. @@ -142,7 +142,7 @@ public void WriteBytes(byte value, int byteCount) /// is negative. public unsafe void WriteBytes(byte* buffer, int byteCount) { - if (buffer == null) + if (buffer is null) { Throw.ArgumentNull(nameof(buffer)); } @@ -164,7 +164,7 @@ private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) /// is null. public void WriteBytes(BlobBuilder source) { - if (source == null) + if (source is null) { Throw.ArgumentNull(nameof(source)); } @@ -176,7 +176,7 @@ public void WriteBytes(BlobBuilder source) /// is negative. public int WriteBytes(Stream source, int byteCount) { - if (source == null) + if (source is null) { Throw.ArgumentNull(nameof(source)); } @@ -215,7 +215,7 @@ public unsafe void WriteBytes(byte[] buffer) /// Range specified by and falls outside of the bounds of the . public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) { - if (buffer == null) + if (buffer is null) { Throw.ArgumentNull(nameof(buffer)); } @@ -371,7 +371,7 @@ public void WriteReference(int reference, bool isSmall) /// is null. public void WriteUTF16(char[] value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -393,7 +393,7 @@ public void WriteUTF16(char[] value) /// is null. public void WriteUTF16(string value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -414,7 +414,7 @@ public void WriteUTF16(string value) /// Builder is not writable, it has been linked with another one. public void WriteSerializedString(string? str) { - if (str == null) + if (str is null) { WriteByte(0xff); return; @@ -436,7 +436,7 @@ public void WriteSerializedString(string? str) /// Builder is not writable, it has been linked with another one. public void WriteUserString(string value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -452,7 +452,7 @@ public void WriteUserString(string value) /// is null. public void WriteUTF8(string value, bool allowUnpairedSurrogates) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriterImpl.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriterImpl.cs index 972def9f6955cb..be7771ab3ab8f0 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriterImpl.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriterImpl.cs @@ -146,7 +146,7 @@ internal static void WriteCompressedSignedInteger(BlobBuilder writer, int value) internal static void WriteConstant(ref BlobWriter writer, object? value) { - if (value == null) + if (value is null) { // The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit. writer.WriteUInt32(0); @@ -219,7 +219,7 @@ internal static void WriteConstant(ref BlobWriter writer, object? value) internal static void WriteConstant(BlobBuilder writer, object? value) { - if (value == null) + if (value is null) { // The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit. writer.WriteUInt32(0); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs index e08505c3f662c9..b24d3bd35bc8da 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs @@ -14,7 +14,7 @@ public readonly struct BlobEncoder public BlobEncoder(BlobBuilder builder) { - if (builder == null) + if (builder is null) { Throw.BuilderArgumentNull(); } @@ -116,8 +116,8 @@ public void CustomAttributeSignature(out FixedArgumentsEncoder fixedArguments, o /// or is null. public void CustomAttributeSignature(Action fixedArguments, Action namedArguments) { - if (fixedArguments == null) Throw.ArgumentNull(nameof(fixedArguments)); - if (namedArguments == null) Throw.ArgumentNull(nameof(namedArguments)); + if (fixedArguments is null) Throw.ArgumentNull(nameof(fixedArguments)); + if (namedArguments is null) Throw.ArgumentNull(nameof(namedArguments)); FixedArgumentsEncoder fixedArgumentsEncoder; CustomAttributeNamedArgumentsEncoder namedArgumentsEncoder; @@ -230,8 +230,8 @@ public void Parameters(int parameterCount, out ReturnTypeEncoder returnType, out /// or is null. public void Parameters(int parameterCount, Action returnType, Action parameters) { - if (returnType == null) Throw.ArgumentNull(nameof(returnType)); - if (parameters == null) Throw.ArgumentNull(nameof(parameters)); + if (returnType is null) Throw.ArgumentNull(nameof(returnType)); + if (parameters is null) Throw.ArgumentNull(nameof(parameters)); ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; @@ -332,7 +332,7 @@ public PermissionSetEncoder(BlobBuilder builder) public PermissionSetEncoder AddPermission(string typeName, ImmutableArray encodedArguments) { - if (typeName == null) + if (typeName is null) { Throw.ArgumentNull(nameof(typeName)); } @@ -355,12 +355,12 @@ public PermissionSetEncoder AddPermission(string typeName, ImmutableArray public PermissionSetEncoder AddPermission(string typeName, BlobBuilder encodedArguments) { - if (typeName == null) + if (typeName is null) { Throw.ArgumentNull(nameof(typeName)); } - if (encodedArguments == null) + if (encodedArguments is null) { Throw.ArgumentNull(nameof(encodedArguments)); } @@ -441,8 +441,8 @@ public void TaggedVector(out CustomAttributeArrayTypeEncoder arrayType, out Vect /// or is null. public void TaggedVector(Action arrayType, Action vector) { - if (arrayType == null) Throw.ArgumentNull(nameof(arrayType)); - if (vector == null) Throw.ArgumentNull(nameof(vector)); + if (arrayType is null) Throw.ArgumentNull(nameof(arrayType)); + if (vector is null) Throw.ArgumentNull(nameof(vector)); CustomAttributeArrayTypeEncoder arrayTypeEncoder; VectorEncoder vectorEncoder; @@ -480,8 +480,8 @@ public void TaggedScalar(out CustomAttributeElementTypeEncoder type, out ScalarE /// or is null. public void TaggedScalar(Action type, Action scalar) { - if (type == null) Throw.ArgumentNull(nameof(type)); - if (scalar == null) Throw.ArgumentNull(nameof(scalar)); + if (type is null) Throw.ArgumentNull(nameof(type)); + if (scalar is null) Throw.ArgumentNull(nameof(scalar)); CustomAttributeElementTypeEncoder typeEncoder; ScalarEncoder scalarEncoder; @@ -532,7 +532,7 @@ public void NullArray() public void Constant(object? value) { string? str = value as string; - if (str != null || value == null) + if (str is not null || value is null) { String(str); } @@ -549,7 +549,7 @@ public void Constant(object? value) /// is empty. public void SystemType(string? serializedTypeName) { - if (serializedTypeName != null && serializedTypeName.Length == 0) + if (serializedTypeName is not null && serializedTypeName.Length == 0) { Throw.ArgumentEmptyString(nameof(serializedTypeName)); } @@ -610,7 +610,7 @@ public NameEncoder(BlobBuilder builder) public void Name(string name) { - if (name == null) Throw.ArgumentNull(nameof(name)); + if (name is null) Throw.ArgumentNull(nameof(name)); if (name.Length == 0) Throw.ArgumentEmptyString(nameof(name)); Builder.WriteSerializedString(name); @@ -673,9 +673,9 @@ public void AddArgument(bool isField, out NamedArgumentTypeEncoder type, out Nam /// , or is null. public void AddArgument(bool isField, Action type, Action name, Action literal) { - if (type == null) Throw.ArgumentNull(nameof(type)); - if (name == null) Throw.ArgumentNull(nameof(name)); - if (literal == null) Throw.ArgumentNull(nameof(literal)); + if (type is null) Throw.ArgumentNull(nameof(type)); + if (name is null) Throw.ArgumentNull(nameof(name)); + if (literal is null) Throw.ArgumentNull(nameof(literal)); NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; @@ -795,7 +795,7 @@ public void SystemType() public void Enum(string enumTypeName) { - if (enumTypeName == null) Throw.ArgumentNull(nameof(enumTypeName)); + if (enumTypeName is null) Throw.ArgumentNull(nameof(enumTypeName)); if (enumTypeName.Length == 0) Throw.ArgumentEmptyString(nameof(enumTypeName)); WriteTypeCode(SerializationTypeCode.Enum); @@ -896,8 +896,8 @@ public void Array(out SignatureTypeEncoder elementType, out ArrayShapeEncoder ar /// or is null. public void Array(Action elementType, Action arrayShape) { - if (elementType == null) Throw.ArgumentNull(nameof(elementType)); - if (arrayShape == null) Throw.ArgumentNull(nameof(arrayShape)); + if (elementType is null) Throw.ArgumentNull(nameof(elementType)); + if (arrayShape is null) Throw.ArgumentNull(nameof(arrayShape)); SignatureTypeEncoder elementTypeEncoder; ArrayShapeEncoder arrayShapeEncoder; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs index bbe2809461b800..c603b515ec60e6 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs @@ -212,7 +212,7 @@ private void AddExceptionRegion( ValidateLabel(handlerStart, nameof(handlerStart)); ValidateLabel(handlerEnd, nameof(handlerEnd)); - if (_lazyExceptionHandlers == null) + if (_lazyExceptionHandlers is null) { _lazyExceptionHandlers = ImmutableArray.CreateBuilder(); } @@ -319,7 +319,7 @@ internal void CopyCodeAndFixupBranches(BlobBuilder srcBuilder, BlobBuilder dstBu internal void SerializeExceptionTable(BlobBuilder builder) { - if (_lazyExceptionHandlers == null || _lazyExceptionHandlers.Count == 0) + if (_lazyExceptionHandlers is null || _lazyExceptionHandlers.Count == 0) { return; } @@ -365,7 +365,7 @@ internal void SerializeExceptionTable(BlobBuilder builder) private bool HasSmallExceptionRegions() { - Debug.Assert(_lazyExceptionHandlers != null); + Debug.Assert(_lazyExceptionHandlers is not null); if (!ExceptionRegionEncoder.IsSmallRegionCount(_lazyExceptionHandlers.Count)) { diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ExceptionRegionEncoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ExceptionRegionEncoder.cs index b870ba8fa3de56..94256bbdde8bc9 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ExceptionRegionEncoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ExceptionRegionEncoder.cs @@ -209,7 +209,7 @@ public ExceptionRegionEncoder Add( EntityHandle catchType = default(EntityHandle), int filterOffset = 0) { - if (Builder == null) + if (Builder is null) { Throw.InvalidOperation(SR.MethodHasNoExceptionRegions); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs index f6155a2f4d2c0d..f916c4da3a28a3 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs @@ -34,7 +34,7 @@ public readonly struct InstructionEncoder /// public InstructionEncoder(BlobBuilder codeBuilder, ControlFlowBuilder? controlFlowBuilder = null) { - if (codeBuilder == null) + if (codeBuilder is null) { Throw.BuilderArgumentNull(); } @@ -437,7 +437,7 @@ public void MarkLabel(LabelHandle label) private ControlFlowBuilder GetBranchBuilder() { - if (ControlFlowBuilder == null) + if (ControlFlowBuilder is null) { Throw.ControlFlowBuilderNotAvailable(); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs index 1d2249c180051d..2725c2da104cad 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs @@ -12,7 +12,7 @@ public readonly struct MethodBodyStreamEncoder public MethodBodyStreamEncoder(BlobBuilder builder) { - if (builder == null) + if (builder is null) { Throw.BuilderArgumentNull(); } @@ -178,7 +178,7 @@ public int AddMethodBody( var codeBuilder = instructionEncoder.CodeBuilder; var flowBuilder = instructionEncoder.ControlFlowBuilder; - if (codeBuilder == null) + if (codeBuilder is null) { Throw.ArgumentNull(nameof(instructionEncoder)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs index f0f044d609a26e..a252d8e5378364 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs @@ -51,9 +51,9 @@ private MetadataAggregator( IReadOnlyList? baseHeapSizes, IReadOnlyList? deltaReaders) { - if (baseTableRowCounts == null) + if (baseTableRowCounts is null) { - if (baseReader == null) + if (baseReader is null) { throw new ArgumentNullException(nameof(baseReader)); } @@ -64,7 +64,7 @@ private MetadataAggregator( } CalculateBaseCounts(baseReader, out baseTableRowCounts, out baseHeapSizes); - Debug.Assert(baseTableRowCounts != null); + Debug.Assert(baseTableRowCounts is not null); } else { @@ -73,7 +73,7 @@ private MetadataAggregator( throw new ArgumentException(SR.Format(SR.ExpectedListOfSize, MetadataTokens.TableCount), nameof(baseTableRowCounts)); } - if (baseHeapSizes == null) + if (baseHeapSizes is null) { throw new ArgumentNullException(nameof(baseHeapSizes)); } @@ -84,7 +84,7 @@ private MetadataAggregator( } } - if (deltaReaders == null || deltaReaders.Count == 0) + if (deltaReaders is null || deltaReaders.Count == 0) { throw new ArgumentException(SR.ExpectedNonEmptyList, nameof(deltaReaders)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs index 3277792f61cb4f..5fa9257cb1b37c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs @@ -188,7 +188,7 @@ public void SetCapacity(HeapIndex heap, int byteCount) /// is null. public BlobHandle GetOrAddBlob(BlobBuilder value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -205,7 +205,7 @@ public BlobHandle GetOrAddBlob(BlobBuilder value) /// is null. public BlobHandle GetOrAddBlob(byte[] value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -303,7 +303,7 @@ public BlobHandle GetOrAddBlobUTF8(string value, bool allowUnpairedSurrogates = /// is null. public BlobHandle GetOrAddDocumentName(string value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -426,7 +426,7 @@ private GuidHandle GetNewGuidHandle() /// is null. public StringHandle GetOrAddString(string value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } @@ -482,7 +482,7 @@ public ReservedBlob ReserveUserString(int length) /// is null. public UserStringHandle GetOrAddUserString(string value) { - if (value == null) + if (value is null) { Throw.ArgumentNull(nameof(value)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs index 8ad28470a5a99d..53083c5659bed1 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs @@ -392,7 +392,7 @@ public AssemblyDefinitionHandle AddAssembly( AssemblyFlags flags, AssemblyHashAlgorithm hashAlgorithm) { - if (version == null) + if (version is null) { Throw.ArgumentNull(nameof(version)); } @@ -423,7 +423,7 @@ public AssemblyReferenceHandle AddAssemblyReference( AssemblyFlags flags, BlobHandle hashValue) { - if (version == null) + if (version is null) { Throw.ArgumentNull(nameof(version)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs index f675d4361dd5ef..3c7706a5b113c5 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs @@ -19,7 +19,7 @@ public static class MetadataReaderExtensions /// is not a valid table index. public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -39,7 +39,7 @@ public static int GetTableRowCount(this MetadataReader reader, TableIndex tableI /// is not a valid table index. public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -113,7 +113,7 @@ public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIn /// is not a valid table index. public static unsafe int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -123,7 +123,7 @@ public static unsafe int GetTableMetadataOffset(this MetadataReader reader, Tabl private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, TableIndex tableIndex) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); return tableIndex switch { @@ -194,7 +194,7 @@ private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, Tab /// is not a valid heap index. public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -209,7 +209,7 @@ public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex) /// is not a valid heap index. public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -224,7 +224,7 @@ public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapI /// is not a valid heap index. private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapIndex heapIndex) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); return heapIndex switch { @@ -242,7 +242,7 @@ private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapInde /// is null. public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -256,7 +256,7 @@ public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStr /// is null. public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -270,7 +270,7 @@ public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle ha /// is null. public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle) { - if (reader == null) + if (reader is null) { Throw.ArgumentNull(nameof(reader)); } @@ -284,7 +284,7 @@ public static StringHandle GetNextHandle(this MetadataReader reader, StringHandl /// is null. public static IEnumerable GetEditAndContinueLogEntries(this MetadataReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -303,7 +303,7 @@ public static IEnumerable GetEditAndContinueLogEntries( /// is null. public static IEnumerable GetEditAndContinueMapEntries(this MetadataReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -323,7 +323,7 @@ public static IEnumerable GetEditAndContinueMapEntries(this Metada /// public static IEnumerable GetTypesWithProperties(this MetadataReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -343,7 +343,7 @@ public static IEnumerable GetTypesWithProperties(this Meta /// public static IEnumerable GetTypesWithEvents(this MetadataReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -359,7 +359,7 @@ public static IEnumerable GetTypesWithEvents(this Metadata /// public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader, EntityHandle typeHandle, byte rawTypeKind) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs index 46e142638c13e1..59cde9c9977f96 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs @@ -53,13 +53,13 @@ public sealed class MetadataRootBuilder /// is too long (the number of bytes when UTF8-encoded must be less than 255). public MetadataRootBuilder(MetadataBuilder tablesAndHeaps, string? metadataVersion = null, bool suppressValidation = false) { - if (tablesAndHeaps == null) + if (tablesAndHeaps is null) { Throw.ArgumentNull(nameof(tablesAndHeaps)); } Debug.Assert(BlobUtilities.GetUTF8ByteCount(DefaultMetadataVersionString) == DefaultMetadataVersionString.Length); - int metadataVersionByteCount = metadataVersion != null ? BlobUtilities.GetUTF8ByteCount(metadataVersion) : DefaultMetadataVersionString.Length; + int metadataVersionByteCount = metadataVersion is not null ? BlobUtilities.GetUTF8ByteCount(metadataVersion) : DefaultMetadataVersionString.Length; if (metadataVersionByteCount > MetadataSizes.MaxMetadataVersionByteCount) { @@ -96,7 +96,7 @@ public MetadataRootBuilder(MetadataBuilder tablesAndHeaps, string? metadataVersi /// public void Serialize(BlobBuilder builder, int methodBodyStreamRva, int mappedFieldDataStreamRva) { - if (builder == null) + if (builder is null) { Throw.ArgumentNull(nameof(builder)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs index de27b363b7ab83..dfd862daee2340 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs @@ -50,7 +50,7 @@ public PortablePdbBuilder( MethodDefinitionHandle entryPoint, Func, BlobContentId>? idProvider = null) { - if (tablesAndHeaps == null) + if (tablesAndHeaps is null) { Throw.ArgumentNull(nameof(tablesAndHeaps)); } @@ -124,7 +124,7 @@ private void SerializeStandalonePdbStream(BlobBuilder builder) /// is null. public BlobContentId Serialize(BlobBuilder builder) { - if (builder == null) + if (builder is null) { Throw.ArgumentNull(nameof(builder)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs index c7697e5dde2b8b..6f4bc019a2a9a6 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs @@ -31,7 +31,7 @@ public SignatureDecoder( MetadataReader metadataReader, TGenericContext genericContext) { - if (provider == null) + if (provider is null) { Throw.ArgumentNull(nameof(provider)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs index 302a6167c55630..b97f152f4fe123 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs @@ -18,7 +18,7 @@ internal BlobHeap(MemoryBlock block, MetadataKind metadataKind) _lazyVirtualHeap = null; Block = block; - if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) + if (s_virtualValues is null && metadataKind != MetadataKind.Ecma335) { var blobs = new byte[(int)BlobHandle.VirtualIndex.Count][]; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/MetadataWriterUtilities.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/MetadataWriterUtilities.cs index 150da41a906305..7b958037832c5e 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/MetadataWriterUtilities.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/MetadataWriterUtilities.cs @@ -10,7 +10,7 @@ internal static class MetadataWriterUtilities { public static SignatureTypeCode GetConstantTypeCode(object? value) { - if (value == null) + if (value is null) { // The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a zero. return (SignatureTypeCode)0x12; // TODO diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs index d01611cd81602e..79df23cfc927ee 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs @@ -18,7 +18,7 @@ internal class NamespaceCache internal NamespaceCache(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _metadataReader = reader; } @@ -28,7 +28,7 @@ internal NamespaceCache(MetadataReader reader) /// internal bool CacheIsRealized { - get { return _namespaceTable != null; } + get { return _namespaceTable is not null; } } internal string GetFullName(NamespaceDefinitionHandle handle) @@ -41,7 +41,7 @@ internal string GetFullName(NamespaceDefinitionHandle handle) internal NamespaceData GetRootNamespace() { EnsureNamespaceTableIsPopulated(); - Debug.Assert(_rootNamespace != null); + Debug.Assert(_rootNamespace is not null); return _rootNamespace; } @@ -106,7 +106,7 @@ private void PopulateNamespaceTable() { lock (_namespaceTableAndListLock) { - if (_namespaceTable != null) + if (_namespaceTable is not null) { return; } @@ -146,7 +146,7 @@ private void PopulateNamespaceTable() namespaceTable.Add(group.Key, group.Value.Freeze()); } - if (virtualNamespaces != null) + if (virtualNamespaces is not null) { foreach (var virtualNamespace in virtualNamespaces) { @@ -178,7 +178,7 @@ private void MergeDuplicateNamespaces(Dictionary>(); } @@ -191,7 +191,7 @@ private void MergeDuplicateNamespaces(Dictionary private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) { - Debug.Assert(child != null && parent != null); + Debug.Assert(child is not null && parent is not null); Debug.Assert(!child.Handle.IsNil); child.Parent = parent.Handle; parent.Namespaces!.Add(child.Handle); @@ -278,7 +278,7 @@ private void LinkChildToParentNamespace(Dictionary return; } - if (virtualNamespaces != null) + if (virtualNamespaces is not null) { foreach (var data in virtualNamespaces) { @@ -323,7 +323,7 @@ private void ResolveParentChildRelationships(Dictionary private void PopulateTableWithTypeDefinitions(Dictionary table) { - Debug.Assert(table != null); + Debug.Assert(table is not null); foreach (var typeHandle in _metadataReader.TypeDefinitions) { @@ -355,7 +355,7 @@ private void PopulateTableWithTypeDefinitions(Dictionary private void PopulateTableWithExportedTypes(Dictionary table) { - Debug.Assert(table != null); + Debug.Assert(table is not null); foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { @@ -389,11 +389,11 @@ private void PopulateTableWithExportedTypes(Dictionary @@ -437,7 +437,7 @@ public NamespaceData Freeze() { // It is not an error to call this function multiple times. We cache the result // because it's immutable. - if (_frozen == null) + if (_frozen is null) { var namespaces = Namespaces!.ToImmutable(); Namespaces = null; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs index ea0e38e3cde1f9..4dc029719e2a57 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs @@ -20,7 +20,7 @@ internal StringHeap(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeap = null; - if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) + if (s_virtualValues is null && metadataKind != MetadataKind.Ecma335) { // Note: // Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent @@ -113,7 +113,7 @@ private static void AssertFilled() { for (int i = 0; i < s_virtualValues!.Length; i++) { - Debug.Assert(s_virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i); + Debug.Assert(s_virtualValues[i] is not null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i); } } @@ -248,7 +248,7 @@ internal StringHandle GetNextHandle(StringHandle handle) internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { - Debug.Assert(value != null); + Debug.Assert(value is not null); if (handle.IsVirtual) { @@ -267,7 +267,7 @@ internal bool Equals(StringHandle handle, string value, MetadataStringDecoder ut internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { - Debug.Assert(value != null); + Debug.Assert(value is not null); if (handle.IsVirtual) { diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/Tables.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/Tables.cs index 9cef4ec444960d..2943779b22f2ac 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/Tables.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/Tables.cs @@ -814,7 +814,7 @@ internal void GetAttributeRange(EntityHandle parentHandle, out int firstImplRowI { int startRowNumber, endRowNumber; - if (this.PtrTable != null) + if (this.PtrTable is not null) { this.Block.BinarySearchReferenceRange( this.PtrTable, diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/VirtualHeap.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/VirtualHeap.cs index 551ee9112c964d..dc7f6018ec5e53 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/VirtualHeap.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/VirtualHeap.cs @@ -55,7 +55,7 @@ protected override void Release() { var blobs = Interlocked.Exchange(ref _blobs, null); - if (blobs != null) + if (blobs is not null) { foreach (var blobPair in blobs) { @@ -68,7 +68,7 @@ protected override void Release() private Dictionary GetBlobs() { var blobs = _blobs; - if (blobs == null) + if (blobs is null) { throw new ObjectDisposedException(nameof(VirtualHeap)); } @@ -110,7 +110,7 @@ internal MemoryBlock AddBlob(uint rawHandle, byte[] value) internal static VirtualHeap GetOrCreateVirtualHeap(ref VirtualHeap? lazyHeap) { - if (lazyHeap == null) + if (lazyHeap is null) { Interlocked.CompareExchange(ref lazyHeap, new VirtualHeap(), null); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs index 49a0debe174ce7..baf1134acd3d16 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs @@ -101,31 +101,31 @@ private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex) { - Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); + Debug.Assert(s_projectionInfos is not null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef); } internal static StringHandle GetProjectedName(int projectionIndex) { - Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); + Debug.Assert(s_projectionInfos is not null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName); } internal static StringHandle GetProjectedNamespace(int projectionIndex) { - Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); + Debug.Assert(s_projectionInfos is not null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace); } internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex) { - Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); + Debug.Assert(s_projectionInfos is not null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return s_projectionInfos[projectionIndex].SignatureTreatment; } private static void InitializeProjectedTypes() { - if (s_projectedTypeNames == null || s_projectionInfos == null) + if (s_projectedTypeNames is null || s_projectionInfos is null) { var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime; var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs index 925bd4fa6f4a73..8f155d2479c619 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs @@ -80,12 +80,12 @@ internal unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions Throw.ArgumentOutOfRange(nameof(length)); } - if (metadata == null) + if (metadata is null) { Throw.ArgumentNull(nameof(metadata)); } - if (utf8Decoder == null) + if (utf8Decoder is null) { utf8Decoder = MetadataStringDecoder.DefaultUTF8; } @@ -750,7 +750,7 @@ private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapS // Type-system metadata tables may be stored in a separate (external) metadata file. // We need to use the row counts of the external tables when referencing them. // Debug tables are local to the current metadata image and type system metadata tables are external and precede all debug tables. - var combinedRowCounts = (externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, firstLocalTableIndex: TableIndex.Document) : rowCounts; + var combinedRowCounts = (externalRowCountsOpt is not null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, firstLocalTableIndex: TableIndex.Document) : rowCounts; int methodRefSizeCombined = GetReferenceSize(combinedRowCounts, TableIndex.MethodDef); int hasCustomDebugInformationRefSizeCombined = ComputeCodedTokenSize(HasCustomDebugInformationTag.LargeRowSize, combinedRowCounts, HasCustomDebugInformationTag.TablesReferenced); @@ -1110,7 +1110,7 @@ public Guid GetGuid(GuidHandle handle) public ModuleDefinition GetModuleDefinition() { - if (_debugMetadataHeader != null) + if (_debugMetadataHeader is not null) { throw new InvalidOperationException(SR.StandaloneDebugMetadataImageDoesNotContainModuleTable); } @@ -1463,10 +1463,10 @@ private void InitializeNestedTypesMap() /// internal ImmutableArray GetNestedTypes(TypeDefinitionHandle typeDef) { - if (_lazyNestedTypesMap == null) + if (_lazyNestedTypesMap is null) { InitializeNestedTypesMap(); - Debug.Assert(_lazyNestedTypesMap != null); + Debug.Assert(_lazyNestedTypesMap is not null); } ImmutableArray nestedTypes; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs index 7179ae12a52066..99824f80d9630c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs @@ -32,13 +32,13 @@ public sealed class MetadataReaderProvider : IDisposable private MetadataReaderProvider(AbstractMemoryBlock metadataBlock) { - Debug.Assert(metadataBlock != null); + Debug.Assert(metadataBlock is not null); _lazyMetadataBlock = metadataBlock; } private MetadataReaderProvider(MemoryBlockProvider blockProvider) { - Debug.Assert(blockProvider != null); + Debug.Assert(blockProvider is not null); _blockProviderOpt = blockProvider; } @@ -70,7 +70,7 @@ private MetadataReaderProvider(MemoryBlockProvider blockProvider) /// public static unsafe MetadataReaderProvider FromMetadataImage(byte* start, int size) { - if (start == null) + if (start is null) { throw new ArgumentNullException(nameof(start)); } @@ -162,7 +162,7 @@ public static MetadataReaderProvider FromMetadataImage(ImmutableArray imag /// Error reading from the stream (only when is specified). public static MetadataReaderProvider FromMetadataStream(Stream stream, MetadataStreamOptions options = MetadataStreamOptions.Default, int size = 0) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -273,22 +273,22 @@ public unsafe MetadataReader GetMetadataReader(MetadataReaderOptions options = M private static bool CanReuseReader(MetadataReader? reader, MetadataReaderOptions options, MetadataStringDecoder? utf8DecoderOpt) { - return reader != null && reader.Options == options && ReferenceEquals(reader.UTF8Decoder, utf8DecoderOpt ?? MetadataStringDecoder.DefaultUTF8); + return reader is not null && reader.Options == options && ReferenceEquals(reader.UTF8Decoder, utf8DecoderOpt ?? MetadataStringDecoder.DefaultUTF8); } /// IO error while reading from the underlying stream. /// Provider has been disposed. internal AbstractMemoryBlock GetMetadataBlock() { - if (_lazyMetadataBlock == null) + if (_lazyMetadataBlock is null) { - if (_blockProviderOpt == null) + if (_blockProviderOpt is null) { throw new ObjectDisposedException(nameof(MetadataReaderProvider)); } var newBlock = _blockProviderOpt.GetMemoryBlock(0, _blockProviderOpt.Size); - if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) != null) + if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) is not null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs index 97c68fff88a7b2..17bfadb9c50eba 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs @@ -51,7 +51,7 @@ public readonly struct MetadataStringComparer internal MetadataStringComparer(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; } @@ -62,7 +62,7 @@ public bool Equals(StringHandle handle, string value) public bool Equals(StringHandle handle, string value, bool ignoreCase) { - if (value == null) + if (value is null) { Throw.ValueArgumentNull(); } @@ -77,7 +77,7 @@ public bool Equals(NamespaceDefinitionHandle handle, string value) public bool Equals(NamespaceDefinitionHandle handle, string value, bool ignoreCase) { - if (value == null) + if (value is null) { Throw.ValueArgumentNull(); } @@ -97,7 +97,7 @@ public bool Equals(DocumentNameBlobHandle handle, string value) public bool Equals(DocumentNameBlobHandle handle, string value, bool ignoreCase) { - if (value == null) + if (value is null) { Throw.ValueArgumentNull(); } @@ -112,7 +112,7 @@ public bool StartsWith(StringHandle handle, string value) public bool StartsWith(StringHandle handle, string value, bool ignoreCase) { - if (value == null) + if (value is null) { Throw.ValueArgumentNull(); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs index efcd48f1ca1e24..323a3470a58220 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs @@ -43,7 +43,7 @@ public class MetadataStringDecoder /// public MetadataStringDecoder(Encoding encoding) { - if (encoding == null) + if (encoding is null) { throw new ArgumentNullException(nameof(encoding)); } @@ -72,7 +72,7 @@ public MetadataStringDecoder(Encoding encoding) /// The decoded string. public unsafe virtual string GetString(byte* bytes, int byteCount) { - Debug.Assert(Encoding != null); + Debug.Assert(Encoding is not null); // Note that this call is currently wired to the light-up extension in EncodingHelper // for portability. diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs index 8f769a21319a15..77def6dcdc3d3c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs @@ -23,7 +23,7 @@ public static class PEReaderExtensions /// IO error while reading from the underlying stream. public static MethodBodyBlock GetMethodBody(this PEReader peReader, int relativeVirtualAddress) { - if (peReader == null) + if (peReader is null) { throw new ArgumentNullException(nameof(peReader)); } @@ -78,7 +78,7 @@ public static MetadataReader GetMetadataReader(this PEReader peReader, MetadataR /// IO error while reading from the underlying stream. public static unsafe MetadataReader GetMetadataReader(this PEReader peReader, MetadataReaderOptions options, MetadataStringDecoder? utf8Decoder) { - if (peReader == null) + if (peReader is null) { throw new ArgumentNullException(nameof(peReader)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/CustomDebugInformation.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/CustomDebugInformation.cs index c6837b65d0e9bb..9c5477b82c4481 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/CustomDebugInformation.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/CustomDebugInformation.cs @@ -14,7 +14,7 @@ public readonly struct CustomDebugInformation internal CustomDebugInformation(MetadataReader reader, CustomDebugInformationHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/Document.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/Document.cs index 0e228cca4d9ac1..5a447738918c22 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/Document.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/Document.cs @@ -20,7 +20,7 @@ public readonly struct Document internal Document(MetadataReader reader, DocumentHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/HandleCollections.Debug.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/HandleCollections.Debug.cs index 7fcefdc429f29c..15f9495ea00bdf 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/HandleCollections.Debug.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/HandleCollections.Debug.cs @@ -17,7 +17,7 @@ namespace System.Reflection.Metadata internal DocumentHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; @@ -116,7 +116,7 @@ void IDisposable.Dispose() internal MethodDebugInformationHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; @@ -215,7 +215,7 @@ void IDisposable.Dispose() internal LocalScopeHandleCollection(MetadataReader reader, int methodDefinitionRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; if (methodDefinitionRowId == 0) @@ -423,7 +423,7 @@ void IDisposable.Dispose() internal LocalVariableHandleCollection(MetadataReader reader, LocalScopeHandle scope) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; if (scope.IsNil) @@ -529,7 +529,7 @@ void IDisposable.Dispose() internal LocalConstantHandleCollection(MetadataReader reader, LocalScopeHandle scope) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; if (scope.IsNil) @@ -635,7 +635,7 @@ void IDisposable.Dispose() internal ImportScopeCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; @@ -734,7 +734,7 @@ void IDisposable.Dispose() internal CustomDebugInformationHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; @@ -743,7 +743,7 @@ internal CustomDebugInformationHandleCollection(MetadataReader reader) internal CustomDebugInformationHandleCollection(MetadataReader reader, EntityHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; reader.CustomDebugInformationTable.GetRange(handle, out _firstRowId, out _lastRowId); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/ImportScope.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/ImportScope.cs index ca34a56939f440..468267ffebc140 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/ImportScope.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/ImportScope.cs @@ -20,7 +20,7 @@ public readonly struct ImportScope internal ImportScope(MetadataReader reader, ImportScopeHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalConstant.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalConstant.cs index 048c053903f00c..3b626a1f124021 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalConstant.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalConstant.cs @@ -20,7 +20,7 @@ public readonly struct LocalConstant internal LocalConstant(MetadataReader reader, LocalConstantHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalScope.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalScope.cs index 8a5468b99b0d08..b8720f01ca03f6 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalScope.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalScope.cs @@ -20,7 +20,7 @@ public readonly struct LocalScope internal LocalScope(MetadataReader reader, LocalScopeHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalVariable.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalVariable.cs index 623b08f80d2cbd..1d61793408e9ca 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalVariable.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/LocalVariable.cs @@ -20,7 +20,7 @@ public readonly struct LocalVariable internal LocalVariable(MetadataReader reader, LocalVariableHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/MethodDebugInformation.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/MethodDebugInformation.cs index 50949a86681f14..ada178a2282710 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/MethodDebugInformation.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/MethodDebugInformation.cs @@ -20,7 +20,7 @@ public readonly struct MethodDebugInformation internal MethodDebugInformation(MetadataReader reader, MethodDebugInformationHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _rowId = handle.RowId; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs index 20005491dddd31..fb3ca8be44e925 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs @@ -11,7 +11,7 @@ public readonly partial struct AssemblyDefinition internal AssemblyDefinition(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyFile.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyFile.cs index cf2704e426a998..8bba395580d035 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyFile.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyFile.cs @@ -14,7 +14,7 @@ public readonly struct AssemblyFile internal AssemblyFile(MetadataReader reader, AssemblyFileHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs index f621279549a543..66da62841e9099 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs @@ -17,7 +17,7 @@ public readonly partial struct AssemblyReference internal AssemblyReference(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); // only virtual bit can be set in highest byte: diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Constant.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Constant.cs index 36e95fb0c6d660..2c4e981a933988 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Constant.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Constant.cs @@ -14,7 +14,7 @@ public readonly struct Constant internal Constant(MetadataReader reader, int rowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(rowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/CustomAttribute.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/CustomAttribute.cs index dfd9428d067d38..30a277be8fde5c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/CustomAttribute.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/CustomAttribute.cs @@ -15,7 +15,7 @@ public readonly struct CustomAttribute internal CustomAttribute(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/DeclarativeSecurityAttribute.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/DeclarativeSecurityAttribute.cs index e00aa060484229..f99a95dfd6b36c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/DeclarativeSecurityAttribute.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/DeclarativeSecurityAttribute.cs @@ -15,7 +15,7 @@ public readonly struct DeclarativeSecurityAttribute internal DeclarativeSecurityAttribute(MetadataReader reader, int rowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(rowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs index 5cacd03d7329a3..b9b11e4b3c154b 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs @@ -16,7 +16,7 @@ public readonly struct EventDefinition internal EventDefinition(MetadataReader reader, EventDefinitionHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; @@ -84,7 +84,7 @@ public EventAccessors GetAccessors() break; case MethodSemanticsAttributes.Other: - if (other == null) + if (other is null) other = ImmutableArray.CreateBuilder(); other.Add(_reader.MethodSemanticsTable.GetMethod(rowId)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ExportedType.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ExportedType.cs index 569347a16c1531..d7cc909f2523a9 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ExportedType.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ExportedType.cs @@ -14,7 +14,7 @@ public readonly struct ExportedType internal ExportedType(MetadataReader reader, int rowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(rowId != 0); this.reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/FieldDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/FieldDefinition.cs index 62b0137cb28794..b86342ea6f5a8d 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/FieldDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/FieldDefinition.cs @@ -15,7 +15,7 @@ public readonly struct FieldDefinition internal FieldDefinition(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameter.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameter.cs index 2cdc675b3f10f3..99d2923d3863ad 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameter.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameter.cs @@ -14,7 +14,7 @@ public readonly struct GenericParameter internal GenericParameter(MetadataReader reader, GenericParameterHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameterConstraint.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameterConstraint.cs index 3d381b935d98a2..c0f00c3a37e64f 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameterConstraint.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/GenericParameterConstraint.cs @@ -14,7 +14,7 @@ public readonly struct GenericParameterConstraint internal GenericParameterConstraint(MetadataReader reader, GenericParameterConstraintHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/HandleCollections.TypeSystem.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/HandleCollections.TypeSystem.cs index e1538cccaac881..8359957cf6201e 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/HandleCollections.TypeSystem.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/HandleCollections.TypeSystem.cs @@ -234,7 +234,7 @@ void IDisposable.Dispose() internal CustomAttributeHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; _lastRowId = reader.CustomAttributeTable.NumberOfRows; @@ -242,7 +242,7 @@ internal CustomAttributeHandleCollection(MetadataReader reader) internal CustomAttributeHandleCollection(MetadataReader reader, EntityHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; reader.CustomAttributeTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId); @@ -296,7 +296,7 @@ public CustomAttributeHandle Current { // PERF: keep this code small to enable inlining. - if (_reader.CustomAttributeTable.PtrTable != null) + if (_reader.CustomAttributeTable.PtrTable is not null) { return GetCurrentCustomAttributeIndirect(); } @@ -354,7 +354,7 @@ void IDisposable.Dispose() internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; _lastRowId = reader.DeclSecurityTable.NumberOfRows; @@ -362,7 +362,7 @@ internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader) internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader, EntityHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; @@ -461,7 +461,7 @@ void IDisposable.Dispose() internal MethodDefinitionHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; _lastRowId = reader.MethodDefTable.NumberOfRows; @@ -469,7 +469,7 @@ internal MethodDefinitionHandleCollection(MetadataReader reader) internal MethodDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!containingType.IsNil); _reader = reader; @@ -581,7 +581,7 @@ void IDisposable.Dispose() internal FieldDefinitionHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; _lastRowId = reader.FieldTable.NumberOfRows; @@ -589,7 +589,7 @@ internal FieldDefinitionHandleCollection(MetadataReader reader) internal FieldDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!containingType.IsNil); _reader = reader; @@ -701,7 +701,7 @@ void IDisposable.Dispose() internal PropertyDefinitionHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; _lastRowId = reader.PropertyTable.NumberOfRows; @@ -709,7 +709,7 @@ internal PropertyDefinitionHandleCollection(MetadataReader reader) internal PropertyDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!containingType.IsNil); _reader = reader; @@ -821,7 +821,7 @@ void IDisposable.Dispose() internal EventDefinitionHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; _firstRowId = 1; _lastRowId = reader.EventTable.NumberOfRows; @@ -829,7 +829,7 @@ internal EventDefinitionHandleCollection(MetadataReader reader) internal EventDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!containingType.IsNil); _reader = reader; @@ -939,7 +939,7 @@ void IDisposable.Dispose() internal MethodImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); if (containingType.IsNil) { @@ -1044,7 +1044,7 @@ void IDisposable.Dispose() internal ParameterHandleCollection(MetadataReader reader, MethodDefinitionHandle containingMethod) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!containingMethod.IsNil); _reader = reader; @@ -1156,7 +1156,7 @@ void IDisposable.Dispose() internal InterfaceImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle implementingType) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!implementingType.IsNil); _reader = reader; @@ -1657,7 +1657,7 @@ internal EventAccessors(int adderRowId, int removerRowId, int raiserRowId, Immut internal AssemblyReferenceHandleCollection(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/InterfaceImplementation.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/InterfaceImplementation.cs index 311c7e8a5a2aca..ebe5c9121f7c4a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/InterfaceImplementation.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/InterfaceImplementation.cs @@ -14,7 +14,7 @@ public readonly struct InterfaceImplementation internal InterfaceImplementation(MetadataReader reader, InterfaceImplementationHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ManifestResource.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ManifestResource.cs index 561f6e63b91fc4..326951c1d2ed71 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ManifestResource.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ManifestResource.cs @@ -14,7 +14,7 @@ public readonly struct ManifestResource internal ManifestResource(MetadataReader reader, ManifestResourceHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MemberReference.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MemberReference.cs index da34876df946a6..e6dffdfb07b6f7 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MemberReference.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MemberReference.cs @@ -15,7 +15,7 @@ public readonly struct MemberReference internal MemberReference(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs index b9017ecd214946..208928e04f401c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs @@ -15,7 +15,7 @@ public readonly struct MethodDefinition internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodImplementation.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodImplementation.cs index 4f0971cdb913e8..8a56cc3e1027e8 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodImplementation.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodImplementation.cs @@ -14,7 +14,7 @@ public readonly struct MethodImplementation internal MethodImplementation(MetadataReader reader, MethodImplementationHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodSpecification.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodSpecification.cs index dd6b8ff8e13262..c6fa8d892c4c00 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodSpecification.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodSpecification.cs @@ -15,7 +15,7 @@ public readonly struct MethodSpecification internal MethodSpecification(MetadataReader reader, MethodSpecificationHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs index 20c5c44ac04f7c..a38a13a791c1d1 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs @@ -11,7 +11,7 @@ public readonly struct ModuleDefinition internal ModuleDefinition(MetadataReader reader) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); _reader = reader; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleReference.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleReference.cs index b9ffa670e22165..19a6b0c7e2896a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleReference.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleReference.cs @@ -14,7 +14,7 @@ public readonly struct ModuleReference internal ModuleReference(MetadataReader reader, ModuleReferenceHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/NamespaceDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/NamespaceDefinition.cs index 34f7b98983e794..949667b4c82772 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/NamespaceDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/NamespaceDefinition.cs @@ -13,7 +13,7 @@ public struct NamespaceDefinition internal NamespaceDefinition(NamespaceData data) { - Debug.Assert(data != null); + Debug.Assert(data is not null); _data = data; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Parameter.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Parameter.cs index 72f40fbc3311ee..355f4d74ce6ea5 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Parameter.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/Parameter.cs @@ -14,7 +14,7 @@ public readonly struct Parameter internal Parameter(MetadataReader reader, ParameterHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs index c527ef4518456f..2fcba1582dcd61 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs @@ -16,7 +16,7 @@ public readonly struct PropertyDefinition internal PropertyDefinition(MetadataReader reader, PropertyDefinitionHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; @@ -91,7 +91,7 @@ public PropertyAccessors GetAccessors() break; case MethodSemanticsAttributes.Other: - if (other == null) + if (other is null) other = ImmutableArray.CreateBuilder(); other.Add(_reader.MethodSemanticsTable.GetMethod(rowId)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/StandaloneSignature.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/StandaloneSignature.cs index f19e51c2c61415..7dee4ba19262c3 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/StandaloneSignature.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/StandaloneSignature.cs @@ -16,7 +16,7 @@ public readonly struct StandaloneSignature internal StandaloneSignature(MetadataReader reader, StandaloneSignatureHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeDefinition.cs index 455499b2c88028..010d0797a2e65a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeDefinition.cs @@ -16,7 +16,7 @@ public readonly struct TypeDefinition internal TypeDefinition(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeReference.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeReference.cs index 7c19d7d73e19f3..e47931790cf5d4 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeReference.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeReference.cs @@ -15,7 +15,7 @@ public readonly struct TypeReference internal TypeReference(MetadataReader reader, uint treatmentAndRowId) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeSpecification.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeSpecification.cs index a9946f764940e7..add1d1603d97f7 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeSpecification.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/TypeSpecification.cs @@ -15,7 +15,7 @@ public readonly struct TypeSpecification internal TypeSpecification(MetadataReader reader, TypeSpecificationHandle handle) { - Debug.Assert(reader != null); + Debug.Assert(reader is not null); Debug.Assert(!handle.IsNil); _reader = reader; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/CodeViewDebugDirectoryData.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/CodeViewDebugDirectoryData.cs index 185435d41beba8..399f5f5f6f72b7 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/CodeViewDebugDirectoryData.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/CodeViewDebugDirectoryData.cs @@ -24,7 +24,7 @@ public readonly struct CodeViewDebugDirectoryData internal CodeViewDebugDirectoryData(Guid guid, int age, string path) { - Debug.Assert(path != null); + Debug.Assert(path is not null); Path = path; Guid = guid; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs index d05b5a6c922e58..66d8d523d50d1b 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs @@ -20,7 +20,7 @@ public sealed partial class DebugDirectoryBuilder /// is smaller than 0x0100. public void AddEmbeddedPortablePdbEntry(BlobBuilder debugMetadata, ushort portablePdbVersion) { - if (debugMetadata == null) + if (debugMetadata is null) { Throw.ArgumentNull(nameof(debugMetadata)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs index 9546a078534cf2..debd0c69c6c5bb 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs @@ -57,7 +57,7 @@ public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp) /// Serializes data to a . public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp, TData data, Action dataSerializer) { - if (dataSerializer == null) + if (dataSerializer is null) { Throw.ArgumentNull(nameof(dataSerializer)); } @@ -103,7 +103,7 @@ internal void AddCodeViewEntry( ushort portablePdbVersion, int age) { - if (pdbPath == null) + if (pdbPath is null) { Throw.ArgumentNull(nameof(pdbPath)); } @@ -170,7 +170,7 @@ private static int WriteCodeViewData(BlobBuilder builder, string pdbPath, Guid p /// or is empty. public void AddPdbChecksumEntry(string algorithmName, ImmutableArray checksum) { - if (algorithmName == null) + if (algorithmName is null) { Throw.ArgumentNull(nameof(algorithmName)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs index b83a3555d13fb3..ac2cccfe5e6432 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs @@ -48,17 +48,17 @@ public ManagedPEBuilder( Func, BlobContentId>? deterministicIdProvider = null) : base(header, deterministicIdProvider) { - if (header == null) + if (header is null) { Throw.ArgumentNull(nameof(header)); } - if (metadataRootBuilder == null) + if (metadataRootBuilder is null) { Throw.ArgumentNull(nameof(metadataRootBuilder)); } - if (ilStream == null) + if (ilStream is null) { Throw.ArgumentNull(nameof(ilStream)); } @@ -98,7 +98,7 @@ protected override ImmutableArray
CreateSections() var builder = ImmutableArray.CreateBuilder
(3); builder.Add(new Section(TextSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode)); - if (_nativeResourcesOpt != null) + if (_nativeResourcesOpt is not null) { builder.Add(new Section(ResourceSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData)); } @@ -143,7 +143,7 @@ private BlobBuilder SerializeTextSection(SectionLocation location) DirectoryEntry debugDirectoryEntry; BlobBuilder? debugTableBuilderOpt; - if (_debugDirectoryBuilderOpt != null) + if (_debugDirectoryBuilderOpt is not null) { int debugDirectoryOffset = textSection.ComputeOffsetToDebugDirectory(); debugTableBuilderOpt = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize); @@ -186,7 +186,7 @@ private BlobBuilder SerializeTextSection(SectionLocation location) private BlobBuilder SerializeResourceSection(SectionLocation location) { - Debug.Assert(_nativeResourcesOpt != null); + Debug.Assert(_nativeResourcesOpt is not null); var sectionBuilder = new BlobBuilder(); _nativeResourcesOpt.Serialize(sectionBuilder, location); @@ -229,12 +229,12 @@ protected internal override PEDirectoriesBuilder GetDirectories() public void Sign(BlobBuilder peImage, Func, byte[]> signatureProvider) { - if (peImage == null) + if (peImage is null) { Throw.ArgumentNull(nameof(peImage)); } - if (signatureProvider == null) + if (signatureProvider is null) { Throw.ArgumentNull(nameof(signatureProvider)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedTextSection.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedTextSection.cs index 33bd80dec21f75..746f016fa79817 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedTextSection.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedTextSection.cs @@ -265,7 +265,7 @@ public void Serialize( builder.LinkSuffix(metadataBuilder); // managed resources: - if (resourceBuilderOpt != null) + if (resourceBuilderOpt is not null) { builder.LinkSuffix(resourceBuilderOpt); } @@ -278,7 +278,7 @@ public void Serialize( new BlobWriter(strongNameSignature).WriteBytes(0, StrongNameSignatureSize); // debug directory and data: - if (debugDataBuilderOpt != null) + if (debugDataBuilderOpt is not null) { builder.LinkSuffix(debugDataBuilderOpt); } @@ -291,7 +291,7 @@ public void Serialize( } // mapped field data: - if (mappedFieldDataBuilderOpt != null) + if (mappedFieldDataBuilderOpt is not null) { builder.LinkSuffix(mappedFieldDataBuilderOpt); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs index 112359f45462e8..d421c4611f7390 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs @@ -25,7 +25,7 @@ protected readonly struct Section public Section(string name, SectionCharacteristics characteristics) { - if (name == null) + if (name is null) { Throw.ArgumentNull(nameof(name)); } @@ -60,13 +60,13 @@ public SerializedSection(BlobBuilder builder, string name, SectionCharacteristic protected PEBuilder(PEHeaderBuilder header, Func, BlobContentId>? deterministicIdProvider) { - if (header == null) + if (header is null) { Throw.ArgumentNull(nameof(header)); } IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider(); - IsDeterministic = deterministicIdProvider != null; + IsDeterministic = deterministicIdProvider is not null; Header = header; _lazySections = new Lazy>(CreateSections); } @@ -489,14 +489,14 @@ internal static IEnumerable GetContentToChecksum(BlobBuilder peImage, Blob internal void Sign(BlobBuilder peImage, Blob strongNameSignatureFixup, Func, byte[]> signatureProvider) { - Debug.Assert(peImage != null); - Debug.Assert(signatureProvider != null); + Debug.Assert(peImage is not null); + Debug.Assert(signatureProvider is not null); int peHeadersSize = Header.ComputeSizeOfPEHeaders(GetSections().Length); byte[] signature = signatureProvider(GetContentToSign(peImage, peHeadersSize, Header.FileAlignment, strongNameSignatureFixup)); // signature may be shorter (the rest of the reserved space is padding): - if (signature == null || signature.Length > strongNameSignatureFixup.Length) + if (signature is null || signature.Length > strongNameSignatureFixup.Length) { throw new InvalidOperationException(SR.SignatureProviderReturnedInvalidSignature); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs index af4e9eb4dc7a31..74bfb999e7aece 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs @@ -72,7 +72,7 @@ public PEHeaders(Stream peStream, int size) /// Size is negative or extends past the end of the stream. public PEHeaders(Stream peStream, int size, bool isLoadedImage) { - if (peStream == null) + if (peStream is null) { throw new ArgumentNullException(nameof(peStream)); } @@ -153,7 +153,7 @@ public int CoffHeaderStartOffset /// public bool IsCoffOnly { - get { return _peHeader == null; } + get { return _peHeader is null; } } /// @@ -203,7 +203,7 @@ public bool IsConsoleApplication { get { - return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui; + return _peHeader is not null && _peHeader.Subsystem == Subsystem.WindowsCui; } } @@ -396,7 +396,7 @@ private void CalculateMetadataLocation(long peImageSize, out int start, out int size = SectionHeaders[cormeta].SizeOfRawData; } } - else if (_corHeader == null) + else if (_corHeader is null) { start = 0; size = 0; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEMemoryBlock.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEMemoryBlock.cs index e450f7015f489f..b34eaafe20f7aa 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEMemoryBlock.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEMemoryBlock.cs @@ -16,7 +16,7 @@ public readonly struct PEMemoryBlock internal PEMemoryBlock(AbstractMemoryBlock block, int offset = 0) { - Debug.Assert(block != null); + Debug.Assert(block is not null); Debug.Assert(offset >= 0 && offset <= block.Size); _block = block; @@ -26,7 +26,7 @@ internal PEMemoryBlock(AbstractMemoryBlock block, int offset = 0) /// /// Pointer to the first byte of the block. /// - public unsafe byte* Pointer => (_block != null) ? _block.Pointer + _offset : null; + public unsafe byte* Pointer => (_block is not null) ? _block.Pointer + _offset : null; /// /// Length of the block. diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.EmbeddedPortablePdb.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.EmbeddedPortablePdb.cs index f5566f79e69d99..8a02622c1eb471 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.EmbeddedPortablePdb.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.EmbeddedPortablePdb.cs @@ -147,7 +147,7 @@ partial void TryOpenEmbeddedPortablePdb(DebugDirectoryEntry embeddedPdbEntry, re } finally { - if (candidate == null) + if (candidate is null) { candidate?.Dispose(); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs index 73cce730ad0b9c..5b62b88c9254da 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs @@ -32,7 +32,7 @@ public sealed partial class PEReader : IDisposable // _lazyPEHeaders are not null in that case. private MemoryBlockProvider? _peImage; - // If we read the data from the image lazily (peImage != null) we defer reading the PE headers. + // If we read the data from the image lazily (peImage is not null) we defer reading the PE headers. private PEHeaders? _lazyPEHeaders; private AbstractMemoryBlock? _lazyMetadataBlock; @@ -71,7 +71,7 @@ public unsafe PEReader(byte* peImage, int size) /// public unsafe PEReader(byte* peImage, int size, bool isLoadedImage) { - if (peImage == null) + if (peImage is null) { throw new ArgumentNullException(nameof(peImage)); } @@ -152,7 +152,7 @@ public PEReader(Stream peStream, PEStreamOptions options) /// is specified and the PE headers of the image are invalid. public unsafe PEReader(Stream peStream, PEStreamOptions options, int size) { - if (peStream == null) + if (peStream is null) { throw new ArgumentNullException(nameof(peStream)); } @@ -255,7 +255,7 @@ public void Dispose() _lazyMetadataBlock = null; var peSectionBlocks = _lazyPESectionBlocks; - if (peSectionBlocks != null) + if (peSectionBlocks is not null) { foreach (var block in peSectionBlocks) { @@ -269,9 +269,9 @@ public void Dispose() private MemoryBlockProvider GetPEImage() { var peImage = _peImage; - if (peImage == null) + if (peImage is null) { - if (_lazyPEHeaders == null) + if (_lazyPEHeaders is null) { Throw.PEReaderDisposed(); } @@ -291,10 +291,10 @@ public PEHeaders PEHeaders { get { - if (_lazyPEHeaders == null) + if (_lazyPEHeaders is null) { InitializePEHeaders(); - Debug.Assert(_lazyPEHeaders != null); + Debug.Assert(_lazyPEHeaders is not null); } return _lazyPEHeaders; @@ -308,7 +308,7 @@ private void InitializePEHeaders() Stream stream = GetPEImage().GetStream(out constraints); PEHeaders headers; - if (constraints.GuardOpt != null) + if (constraints.GuardOpt is not null) { lock (constraints.GuardOpt) { @@ -337,10 +337,10 @@ private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosit /// PE image not available. private AbstractMemoryBlock GetEntireImageBlock() { - if (_lazyImageBlock == null) + if (_lazyImageBlock is null) { var newBlock = GetPEImage().GetMemoryBlock(); - if (Interlocked.CompareExchange(ref _lazyImageBlock, newBlock, null) != null) + if (Interlocked.CompareExchange(ref _lazyImageBlock, newBlock, null) is not null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); @@ -359,10 +359,10 @@ private AbstractMemoryBlock GetMetadataBlock() throw new InvalidOperationException(SR.PEImageDoesNotHaveMetadata); } - if (_lazyMetadataBlock == null) + if (_lazyMetadataBlock is null) { var newBlock = GetPEImage().GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize); - if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) != null) + if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) is not null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); @@ -380,7 +380,7 @@ private AbstractMemoryBlock GetPESectionBlock(int index) var peImage = GetPEImage(); - if (_lazyPESectionBlocks == null) + if (_lazyPESectionBlocks is null) { Interlocked.CompareExchange(ref _lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null); } @@ -410,7 +410,7 @@ private AbstractMemoryBlock GetPESectionBlock(int index) newBlock = peImage.GetMemoryBlock(PEHeaders.SectionHeaders[index].PointerToRawData, size); } - if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], newBlock, null) != null) + if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], newBlock, null) is not null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); @@ -425,7 +425,7 @@ private AbstractMemoryBlock GetPESectionBlock(int index) /// /// Returns false if the is constructed from a stream and only part of it is prefetched into memory. /// - public bool IsEntireImageAvailable => _lazyImageBlock != null || _peImage != null; + public bool IsEntireImageAvailable => _lazyImageBlock is not null || _peImage is not null; /// /// Gets a pointer to and size of the PE image if available (). @@ -504,7 +504,7 @@ public PEMemoryBlock GetSectionData(int relativeVirtualAddress) /// PE image not available. public PEMemoryBlock GetSectionData(string sectionName) { - if (sectionName == null) + if (sectionName is null) { Throw.ArgumentNull(nameof(sectionName)); } @@ -526,7 +526,7 @@ public PEMemoryBlock GetSectionData(string sectionName) /// PE image not available. public ImmutableArray ReadDebugDirectory() { - Debug.Assert(PEHeaders.PEHeader != null); + Debug.Assert(PEHeaders.PEHeader is not null); var debugDirectory = PEHeaders.PEHeader.DebugTableDirectory; if (debugDirectory.Size == 0) @@ -701,12 +701,12 @@ internal static PdbChecksumDebugDirectoryData DecodePdbChecksumDebugDirectoryDat /// No matching PDB file is found due to an error: An IO error occurred while reading the PE image or the PDB. public bool TryOpenAssociatedPortablePdb(string peImagePath, Func pdbFileStreamProvider, out MetadataReaderProvider? pdbReaderProvider, out string? pdbPath) { - if (peImagePath == null) + if (peImagePath is null) { Throw.ArgumentNull(nameof(peImagePath)); } - if (pdbFileStreamProvider == null) + if (pdbFileStreamProvider is null) { Throw.ArgumentNull(nameof(pdbFileStreamProvider)); } @@ -749,7 +749,7 @@ public bool TryOpenAssociatedPortablePdb(string peImagePath, FuncAssembly qualified type name of the resource public void AddResource(string name, string value, string typeName) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); // determine if the type is a primitive type @@ -94,7 +94,7 @@ public void AddResource(string name, string value, string typeName) // and instead will only ever convert to one of the known types. TypeConverter converter = TypeDescriptor.GetConverter(primitiveType); - if (converter == null) + if (converter is null) { throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, primitiveType)); } @@ -122,11 +122,11 @@ public void AddResource(string name, string value, string typeName) /// Assembly qualified type name of the resource public void AddTypeConverterResource(string name, byte[] value, string typeName) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); AddResourceData(name, typeName, new ResourceDataRecord(SerializationFormat.TypeConverterByteArray, value)); @@ -143,11 +143,11 @@ public void AddTypeConverterResource(string name, byte[] value, string typeName) /// Assembly qualified type name of the resource public void AddBinaryFormattedResource(string name, byte[] value, string? typeName = null) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (typeName == null) + if (typeName is null) { // Some resx-files are missing type information for binary-formatted resources. // These would have previously been handled by deserializing once, capturing the type @@ -174,11 +174,11 @@ public void AddBinaryFormattedResource(string name, byte[] value, string? typeNa /// Indicates that the stream should be closed after resources have been written public void AddActivatorResource(string name, Stream value, string typeName, bool closeAfterWrite = false) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); if (!value.CanSeek) @@ -207,7 +207,7 @@ private void WriteData(BinaryWriter writer, object dataContext) { ResourceDataRecord? record = dataContext as ResourceDataRecord; - Debug.Assert(record != null); + Debug.Assert(record is not null); // Only write the format if we resources are in DeserializingResourceReader format if (_requiresDeserializingResourceReader) diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs index 860931e66cd668..75c90045fcb62e 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs @@ -56,9 +56,9 @@ private static bool IsMscorlib(ReadOnlySpan assemblyName) public bool Equals(string assemblyQualifiedTypeName1, string assemblyQualifiedTypeName2) #pragma warning restore CS8767 { - if (assemblyQualifiedTypeName1 == null) + if (assemblyQualifiedTypeName1 is null) throw new ArgumentNullException(nameof(assemblyQualifiedTypeName1)); - if (assemblyQualifiedTypeName2 == null) + if (assemblyQualifiedTypeName2 is null) throw new ArgumentNullException(nameof(assemblyQualifiedTypeName2)); if (ReferenceEquals(assemblyQualifiedTypeName1, assemblyQualifiedTypeName2)) diff --git a/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs b/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs index 6d87f6a0964231..a62b8feca58594 100644 --- a/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs +++ b/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs @@ -24,10 +24,10 @@ public partial class ResourceWriter // Doesn't close the Stream when done. public void AddResource(string name, Stream? value) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (_resourceList == null) + if (_resourceList is null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); AddResourceInternal(name, value, false); @@ -35,11 +35,11 @@ public void AddResource(string name, Stream? value) public void AddResourceData(string name, string typeName, byte[] serializedData) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); - if (serializedData == null) + if (serializedData is null) throw new ArgumentNullException(nameof(serializedData)); AddResourceData(name, typeName, (object)serializedData); @@ -52,7 +52,7 @@ private void WriteData(BinaryWriter writer, object dataContext) { byte[]? data = dataContext as byte[]; - Debug.Assert(data != null); + Debug.Assert(data is not null); writer.Write(data); } diff --git a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/OSPlatform.cs b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/OSPlatform.cs index 91dcbad86e1748..2a960543202b3c 100644 --- a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/OSPlatform.cs +++ b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/OSPlatform.cs @@ -17,7 +17,7 @@ namespace System.Runtime.InteropServices private OSPlatform(string osPlatform) { - if (osPlatform == null) throw new ArgumentNullException(nameof(osPlatform)); + if (osPlatform is null) throw new ArgumentNullException(nameof(osPlatform)); if (osPlatform.Length == 0) throw new ArgumentException(SR.Argument_EmptyValue, nameof(osPlatform)); Name = osPlatform; @@ -49,7 +49,7 @@ public override bool Equals(object? obj) public override int GetHashCode() { - return Name == null ? 0 : Name.GetHashCode(StringComparison.OrdinalIgnoreCase); + return Name is null ? 0 : Name.GetHashCode(StringComparison.OrdinalIgnoreCase); } public override string ToString() diff --git a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs index df0fb53273d423..380fc97e418cd6 100644 --- a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs +++ b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs @@ -15,12 +15,12 @@ public static string FrameworkDescription { get { - if (s_frameworkDescription == null) + if (s_frameworkDescription is null) { string? versionString = typeof(object).Assembly.GetCustomAttribute()?.InformationalVersion; // Strip the git hash if there is one - if (versionString != null) + if (versionString is not null) { int plusIndex = versionString.IndexOf('+'); if (plusIndex != -1) diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs index f0274c92c78883..b8774c829cde2e 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs @@ -477,7 +477,7 @@ internal BigInteger(int n, uint[]? rgu) /// The bool indicating the sign of the value. internal BigInteger(uint[] value, bool negative) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); int len; @@ -514,7 +514,7 @@ internal BigInteger(uint[] value, bool negative) /// private BigInteger(uint[] value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); int dwordCount = value.Length; @@ -625,7 +625,7 @@ public bool IsPowerOfTwo { AssertValid(); - if (_bits == null) + if (_bits is null) return (_sign & (_sign - 1)) == 0 && _sign != 0; if (_sign != 1) @@ -644,9 +644,9 @@ public bool IsPowerOfTwo public bool IsZero { get { AssertValid(); return _sign == 0; } } - public bool IsOne { get { AssertValid(); return _sign == 1 && _bits == null; } } + public bool IsOne { get { AssertValid(); return _sign == 1 && _bits is null; } } - public bool IsEven { get { AssertValid(); return _bits == null ? (_sign & 1) == 0 : (_bits[0] & 1) == 0; } } + public bool IsEven { get { AssertValid(); return _bits is null ? (_sign & 1) == 0 : (_bits[0] & 1) == 0; } } public int Sign { @@ -738,8 +738,8 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big dividend.AssertValid(); divisor.AssertValid(); - bool trivialDividend = dividend._bits == null; - bool trivialDivisor = divisor._bits == null; + bool trivialDividend = dividend._bits is null; + bool trivialDivisor = divisor._bits is null; if (trivialDividend && trivialDivisor) { @@ -755,7 +755,7 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big return s_bnZeroInt; } - Debug.Assert(dividend._bits != null); + Debug.Assert(dividend._bits is not null); if (trivialDivisor) { @@ -766,7 +766,7 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big return new BigInteger(bits, (dividend._sign < 0) ^ (divisor._sign < 0)); } - Debug.Assert(divisor._bits != null); + Debug.Assert(divisor._bits is not null); if (dividend._bits.Length < divisor._bits.Length) { @@ -801,7 +801,7 @@ public static double Log(BigInteger value, double baseValue) return value.IsOne ? 0.0D : double.NaN; if (baseValue == 0.0D && !value.IsOne) return double.NaN; - if (value._bits == null) + if (value._bits is null) return Math.Log(value._sign, baseValue); ulong h = value._bits[value._bits.Length - 1]; @@ -830,8 +830,8 @@ public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right left.AssertValid(); right.AssertValid(); - bool trivialLeft = left._bits == null; - bool trivialRight = right._bits == null; + bool trivialLeft = left._bits is null; + bool trivialRight = right._bits is null; if (trivialLeft && trivialRight) { @@ -840,7 +840,7 @@ public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right if (trivialLeft) { - Debug.Assert(right._bits != null); + Debug.Assert(right._bits is not null); return left._sign != 0 ? BigIntegerCalculator.Gcd(right._bits, NumericsHelpers.Abs(left._sign)) : new BigInteger(right._bits, false); @@ -848,13 +848,13 @@ public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right if (trivialRight) { - Debug.Assert(left._bits != null); + Debug.Assert(left._bits is not null); return right._sign != 0 ? BigIntegerCalculator.Gcd(left._bits, NumericsHelpers.Abs(right._sign)) : new BigInteger(left._bits, false); } - Debug.Assert(left._bits != null && right._bits != null); + Debug.Assert(left._bits is not null && right._bits is not null); if (BigIntegerCalculator.Compare(left._bits, right._bits) < 0) { @@ -914,9 +914,9 @@ public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigIntege exponent.AssertValid(); modulus.AssertValid(); - bool trivialValue = value._bits == null; - bool trivialExponent = exponent._bits == null; - bool trivialModulus = modulus._bits == null; + bool trivialValue = value._bits is null; + bool trivialExponent = exponent._bits is null; + bool trivialModulus = modulus._bits is null; if (trivialModulus) { @@ -950,7 +950,7 @@ public static BigInteger Pow(BigInteger value, int exponent) if (exponent == 1) return value; - bool trivialValue = value._bits == null; + bool trivialValue = value._bits is null; if (trivialValue) { @@ -973,7 +973,7 @@ public override int GetHashCode() { AssertValid(); - if (_bits == null) + if (_bits is null) return _sign; int hash = _sign; for (int iv = _bits.Length; --iv >= 0;) @@ -994,7 +994,7 @@ public bool Equals(long other) { AssertValid(); - if (_bits == null) + if (_bits is null) return _sign == other; int cu; @@ -1015,7 +1015,7 @@ public bool Equals(ulong other) if (_sign < 0) return false; - if (_bits == null) + if (_bits is null) return (ulong)_sign == other; int cu = _bits.Length; @@ -1034,10 +1034,10 @@ public bool Equals(BigInteger other) if (_sign != other._sign) return false; if (_bits == other._bits) - // _sign == other._sign && _bits == null && other._bits == null + // _sign == other._sign && _bits is null && other._bits is null return true; - if (_bits == null || other._bits == null) + if (_bits is null || other._bits is null) return false; int cu = _bits.Length; if (cu != other._bits.Length) @@ -1050,7 +1050,7 @@ public int CompareTo(long other) { AssertValid(); - if (_bits == null) + if (_bits is null) return ((long)_sign).CompareTo(other); int cu; if ((_sign ^ other) < 0 || (cu = _bits.Length) > 2) @@ -1067,7 +1067,7 @@ public int CompareTo(ulong other) if (_sign < 0) return -1; - if (_bits == null) + if (_bits is null) return ((ulong)_sign).CompareTo(other); int cu = _bits.Length; if (cu > 2) @@ -1088,14 +1088,14 @@ public int CompareTo(BigInteger other) } // Same signs - if (_bits == null) + if (_bits is null) { - if (other._bits == null) + if (other._bits is null) return _sign < other._sign ? -1 : _sign > other._sign ? +1 : 0; return -other._sign; } int cuThis, cuOther; - if (other._bits == null || (cuThis = _bits.Length) > (cuOther = other._bits.Length)) + if (other._bits is null || (cuThis = _bits.Length) > (cuOther = other._bits.Length)) return _sign; if (cuThis < cuOther) return -_sign; @@ -1108,7 +1108,7 @@ public int CompareTo(BigInteger other) public int CompareTo(object? obj) { - if (obj == null) + if (obj is null) return 1; if (!(obj is BigInteger)) throw new ArgumentException(SR.Argument_MustBeBigInt, nameof(obj)); @@ -1179,7 +1179,7 @@ public byte[] ToByteArray(bool isUnsigned = false, bool isBigEndian = false) public bool TryWriteBytes(Span destination, out int bytesWritten, bool isUnsigned = false, bool isBigEndian = false) { bytesWritten = 0; - if (TryGetBytes(GetBytesMode.Span, destination, isUnsigned, isBigEndian, ref bytesWritten) == null) + if (TryGetBytes(GetBytesMode.Span, destination, isUnsigned, isBigEndian, ref bytesWritten) is null) { bytesWritten = 0; return false; @@ -1190,7 +1190,7 @@ public bool TryWriteBytes(Span destination, out int bytesWritten, bool isU internal bool TryWriteOrCountBytes(Span destination, out int bytesWritten, bool isUnsigned = false, bool isBigEndian = false) { bytesWritten = 0; - return TryGetBytes(GetBytesMode.Span, destination, isUnsigned, isBigEndian, ref bytesWritten) != null; + return TryGetBytes(GetBytesMode.Span, destination, isUnsigned, isBigEndian, ref bytesWritten) is not null; } /// Gets the number of bytes that will be output by and . @@ -1261,7 +1261,7 @@ private enum GetBytesMode { AllocateArray, Count, Span } int nonZeroDwordIndex = 0; uint highDword; uint[]? bits = _bits; - if (bits == null) + if (bits is null) { highByte = (byte)((sign < 0) ? 0xff : 0x00); highDword = unchecked((uint)sign); @@ -1324,7 +1324,7 @@ private enum GetBytesMode { AllocateArray, Count, Span } // Ensure high bit is 0 if positive, 1 if negative bool needExtraByte = (msb & 0x80) != (highByte & 0x80) && !isUnsigned; int length = msbIndex + 1 + (needExtraByte ? 1 : 0); - if (bits != null) + if (bits is not null) { length = checked(4 * (bits.Length - 1) + length); } @@ -1351,7 +1351,7 @@ private enum GetBytesMode { AllocateArray, Count, Span } int curByte = isBigEndian ? length - 1 : 0; int increment = isBigEndian ? -1 : 1; - if (bits != null) + if (bits is not null) { for (int i = 0; i < bits.Length - 1; i++) { @@ -1417,13 +1417,13 @@ private enum GetBytesMode { AllocateArray, Count, Span } /// private uint[] ToUInt32Array() { - if (_bits == null && _sign == 0) + if (_bits is null && _sign == 0) return new uint[] { 0 }; uint[] dwords; uint highDWord; - if (_bits == null) + if (_bits is null) { dwords = new uint[] { unchecked((uint)_sign) }; highDWord = (_sign < 0) ? uint.MaxValue : 0; @@ -1483,8 +1483,8 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan private static BigInteger Add(uint[]? leftBits, int leftSign, uint[]? rightBits, int rightSign) { - bool trivialLeft = leftBits == null; - bool trivialRight = rightBits == null; + bool trivialLeft = leftBits is null; + bool trivialRight = rightBits is null; if (trivialLeft && trivialRight) { @@ -1493,19 +1493,19 @@ private static BigInteger Add(uint[]? leftBits, int leftSign, uint[]? rightBits, if (trivialLeft) { - Debug.Assert(rightBits != null); + Debug.Assert(rightBits is not null); uint[] bits = BigIntegerCalculator.Add(rightBits, NumericsHelpers.Abs(leftSign)); return new BigInteger(bits, leftSign < 0); } if (trivialRight) { - Debug.Assert(leftBits != null); + Debug.Assert(leftBits is not null); uint[] bits = BigIntegerCalculator.Add(leftBits, NumericsHelpers.Abs(rightSign)); return new BigInteger(bits, leftSign < 0); } - Debug.Assert(leftBits != null && rightBits != null); + Debug.Assert(leftBits is not null && rightBits is not null); if (leftBits.Length < rightBits.Length) { @@ -1531,8 +1531,8 @@ private static BigInteger Add(uint[]? leftBits, int leftSign, uint[]? rightBits, private static BigInteger Subtract(uint[]? leftBits, int leftSign, uint[]? rightBits, int rightSign) { - bool trivialLeft = leftBits == null; - bool trivialRight = rightBits == null; + bool trivialLeft = leftBits is null; + bool trivialRight = rightBits is null; if (trivialLeft && trivialRight) { @@ -1541,19 +1541,19 @@ private static BigInteger Subtract(uint[]? leftBits, int leftSign, uint[]? right if (trivialLeft) { - Debug.Assert(rightBits != null); + Debug.Assert(rightBits is not null); uint[] bits = BigIntegerCalculator.Subtract(rightBits, NumericsHelpers.Abs(leftSign)); return new BigInteger(bits, leftSign >= 0); } if (trivialRight) { - Debug.Assert(leftBits != null); + Debug.Assert(leftBits is not null); uint[] bits = BigIntegerCalculator.Subtract(leftBits, NumericsHelpers.Abs(rightSign)); return new BigInteger(bits, leftSign < 0); } - Debug.Assert(leftBits != null && rightBits != null); + Debug.Assert(leftBits is not null && rightBits is not null); if (BigIntegerCalculator.Compare(leftBits, rightBits) < 0) { @@ -1651,7 +1651,7 @@ public static explicit operator ushort(BigInteger value) public static explicit operator int(BigInteger value) { value.AssertValid(); - if (value._bits == null) + if (value._bits is null) { return value._sign; // Value packed into int32 sign } @@ -1676,7 +1676,7 @@ public static explicit operator int(BigInteger value) public static explicit operator uint(BigInteger value) { value.AssertValid(); - if (value._bits == null) + if (value._bits is null) { return checked((uint)value._sign); } @@ -1693,7 +1693,7 @@ public static explicit operator uint(BigInteger value) public static explicit operator long(BigInteger value) { value.AssertValid(); - if (value._bits == null) + if (value._bits is null) { return value._sign; } @@ -1727,7 +1727,7 @@ public static explicit operator long(BigInteger value) public static explicit operator ulong(BigInteger value) { value.AssertValid(); - if (value._bits == null) + if (value._bits is null) { return checked((ulong)value._sign); } @@ -1757,7 +1757,7 @@ public static explicit operator double(BigInteger value) int sign = value._sign; uint[]? bits = value._bits; - if (bits == null) + if (bits is null) return sign; int length = bits.Length; @@ -1790,7 +1790,7 @@ public static explicit operator double(BigInteger value) public static explicit operator decimal(BigInteger value) { value.AssertValid(); - if (value._bits == null) + if (value._bits is null) return value._sign; int length = value._bits.Length; @@ -1815,7 +1815,7 @@ public static explicit operator decimal(BigInteger value) return Zero; } - if (left._bits == null && right._bits == null) + if (left._bits is null && right._bits is null) { return left._sign & right._sign; } @@ -1842,7 +1842,7 @@ public static explicit operator decimal(BigInteger value) if (right.IsZero) return left; - if (left._bits == null && right._bits == null) + if (left._bits is null && right._bits is null) { return left._sign | right._sign; } @@ -1864,7 +1864,7 @@ public static explicit operator decimal(BigInteger value) public static BigInteger operator ^(BigInteger left, BigInteger right) { - if (left._bits == null && right._bits == null) + if (left._bits is null && right._bits is null) { return left._sign ^ right._sign; } @@ -2022,8 +2022,8 @@ public static explicit operator decimal(BigInteger value) left.AssertValid(); right.AssertValid(); - bool trivialLeft = left._bits == null; - bool trivialRight = right._bits == null; + bool trivialLeft = left._bits is null; + bool trivialRight = right._bits is null; if (trivialLeft && trivialRight) { @@ -2032,19 +2032,19 @@ public static explicit operator decimal(BigInteger value) if (trivialLeft) { - Debug.Assert(right._bits != null); + Debug.Assert(right._bits is not null); uint[] bits = BigIntegerCalculator.Multiply(right._bits, NumericsHelpers.Abs(left._sign)); return new BigInteger(bits, (left._sign < 0) ^ (right._sign < 0)); } if (trivialRight) { - Debug.Assert(left._bits != null); + Debug.Assert(left._bits is not null); uint[] bits = BigIntegerCalculator.Multiply(left._bits, NumericsHelpers.Abs(right._sign)); return new BigInteger(bits, (left._sign < 0) ^ (right._sign < 0)); } - Debug.Assert(left._bits != null && right._bits != null); + Debug.Assert(left._bits is not null && right._bits is not null); if (left._bits == right._bits) { @@ -2069,8 +2069,8 @@ public static explicit operator decimal(BigInteger value) dividend.AssertValid(); divisor.AssertValid(); - bool trivialDividend = dividend._bits == null; - bool trivialDivisor = divisor._bits == null; + bool trivialDividend = dividend._bits is null; + bool trivialDivisor = divisor._bits is null; if (trivialDividend && trivialDivisor) { @@ -2086,12 +2086,12 @@ public static explicit operator decimal(BigInteger value) if (trivialDivisor) { - Debug.Assert(dividend._bits != null); + Debug.Assert(dividend._bits is not null); uint[] bits = BigIntegerCalculator.Divide(dividend._bits, NumericsHelpers.Abs(divisor._sign)); return new BigInteger(bits, (dividend._sign < 0) ^ (divisor._sign < 0)); } - Debug.Assert(dividend._bits != null && divisor._bits != null); + Debug.Assert(dividend._bits is not null && divisor._bits is not null); if (dividend._bits.Length < divisor._bits.Length) { @@ -2109,8 +2109,8 @@ public static explicit operator decimal(BigInteger value) dividend.AssertValid(); divisor.AssertValid(); - bool trivialDividend = dividend._bits == null; - bool trivialDivisor = divisor._bits == null; + bool trivialDividend = dividend._bits is null; + bool trivialDivisor = divisor._bits is null; if (trivialDividend && trivialDivisor) { @@ -2126,12 +2126,12 @@ public static explicit operator decimal(BigInteger value) if (trivialDivisor) { - Debug.Assert(dividend._bits != null); + Debug.Assert(dividend._bits is not null); uint remainder = BigIntegerCalculator.Remainder(dividend._bits, NumericsHelpers.Abs(divisor._sign)); return dividend._sign < 0 ? -1 * remainder : remainder; } - Debug.Assert(dividend._bits != null && divisor._bits != null); + Debug.Assert(dividend._bits is not null && divisor._bits is not null); if (dividend._bits.Length < divisor._bits.Length) { @@ -2316,7 +2316,7 @@ public long GetBitLength() int sign = _sign; uint[]? bits = _bits; - if (bits == null) + if (bits is null) { bitsArrayLength = 1; highValue = (uint)(sign < 0 ? -sign : sign); @@ -2366,7 +2366,7 @@ public long GetBitLength() /// True for negative numbers. private static bool GetPartsForBitManipulation(ref BigInteger x, out uint[] xd, out int xl) { - if (x._bits == null) + if (x._bits is null) { if (x._sign < 0) { @@ -2401,7 +2401,7 @@ internal static int GetDiffLength(uint[] rgu1, uint[] rgu2, int cu) [Conditional("DEBUG")] private void AssertValid() { - if (_bits != null) + if (_bits is not null) { // _sign must be +1 or -1 when _bits is non-null Debug.Assert(_sign == 1 || _sign == -1); diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.AddSub.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.AddSub.cs index 4439d67346de63..a5e4f108d7445d 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.AddSub.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.AddSub.cs @@ -10,7 +10,7 @@ internal static partial class BigIntegerCalculator { public static uint[] Add(uint[] left, uint right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 1); // Executes the addition for one big and one 32-bit integer. @@ -36,8 +36,8 @@ public static uint[] Add(uint[] left, uint right) public static unsafe uint[] Add(uint[] left, uint[] right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); Debug.Assert(left.Length >= right.Length); // Switching to unsafe pointers helps sparing @@ -119,7 +119,7 @@ private static unsafe void AddSelf(uint* left, int leftLength, public static uint[] Subtract(uint[] left, uint right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 1); Debug.Assert(left[0] >= right || left.Length >= 2); @@ -145,8 +145,8 @@ public static uint[] Subtract(uint[] left, uint right) public static unsafe uint[] Subtract(uint[] left, uint[] right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); Debug.Assert(left.Length >= right.Length); Debug.Assert(Compare(left, right) >= 0); @@ -232,8 +232,8 @@ private static unsafe void SubtractSelf(uint* left, int leftLength, public static int Compare(uint[] left, uint[] right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); if (left.Length < right.Length) return -1; diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.BitsBuffer.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.BitsBuffer.cs index ec05118f03007e..5fa5081ac88ee7 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.BitsBuffer.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.BitsBuffer.cs @@ -34,7 +34,7 @@ public BitsBuffer(int size, uint value) public BitsBuffer(int size, uint[] value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(size >= ActualLength(value)); _bits = new uint[size]; @@ -98,7 +98,7 @@ public void Reduce(ref FastReducer reducer) public unsafe void Reduce(uint[] modulus) { - Debug.Assert(modulus != null); + Debug.Assert(modulus is not null); // Executes a modulo operation using the divide operation. // Thus, no need of any switching here, happens in-line. diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.DivRem.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.DivRem.cs index 7607f5c5671183..b2eb950b4ec6df 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.DivRem.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.DivRem.cs @@ -11,7 +11,7 @@ internal static partial class BigIntegerCalculator public static uint[] Divide(uint[] left, uint right, out uint remainder) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 1); // Executes the division for one big and one 32-bit integer. @@ -35,7 +35,7 @@ public static uint[] Divide(uint[] left, uint right, public static uint[] Divide(uint[] left, uint right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 1); // Same as above, but only computing the quotient. @@ -56,7 +56,7 @@ public static uint[] Divide(uint[] left, uint right) public static uint Remainder(uint[] left, uint right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 1); // Same as above, but only computing the remainder. @@ -74,8 +74,8 @@ public static uint Remainder(uint[] left, uint right) public static unsafe uint[] Divide(uint[] left, uint[] right, out uint[] remainder) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); Debug.Assert(left.Length >= 1); Debug.Assert(right.Length >= 1); Debug.Assert(left.Length >= right.Length); @@ -102,8 +102,8 @@ public static unsafe uint[] Divide(uint[] left, uint[] right, public static unsafe uint[] Divide(uint[] left, uint[] right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); Debug.Assert(left.Length >= 1); Debug.Assert(right.Length >= 1); Debug.Assert(left.Length >= right.Length); @@ -127,8 +127,8 @@ public static unsafe uint[] Divide(uint[] left, uint[] right) public static unsafe uint[] Remainder(uint[] left, uint[] right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); Debug.Assert(left.Length >= 1); Debug.Assert(right.Length >= 1); Debug.Assert(left.Length >= right.Length); @@ -314,7 +314,7 @@ private static bool DivideGuessTooBig(ulong q, ulong valHi, uint valLo, private static uint[] CreateCopy(uint[] value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(value.Length != 0); uint[] bits = new uint[value.Length]; diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.FastReducer.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.FastReducer.cs index d19b87b2f943fa..55d594dab2004b 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.FastReducer.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.FastReducer.cs @@ -25,7 +25,7 @@ internal readonly struct FastReducer public FastReducer(uint[] modulus) { - Debug.Assert(modulus != null); + Debug.Assert(modulus is not null); // Let r = 4^k, with 2^k > m uint[] r = new uint[modulus.Length * 2 + 1]; @@ -44,7 +44,7 @@ public FastReducer(uint[] modulus) public int Reduce(uint[] value, int length) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(length <= value.Length); Debug.Assert(value.Length <= _modulus.Length * 2); @@ -69,11 +69,11 @@ private static unsafe int DivMul(uint[] left, int leftLength, uint[] right, int rightLength, uint[] bits, int k) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= leftLength); - Debug.Assert(right != null); + Debug.Assert(right is not null); Debug.Assert(right.Length >= rightLength); - Debug.Assert(bits != null); + Debug.Assert(bits is not null); Debug.Assert(bits.Length + k >= leftLength + rightLength); // Executes the multiplication algorithm for left and right, @@ -113,9 +113,9 @@ private static unsafe int SubMod(uint[] left, int leftLength, uint[] right, int rightLength, uint[] modulus, int k) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= leftLength); - Debug.Assert(right != null); + Debug.Assert(right is not null); Debug.Assert(right.Length >= rightLength); // Executes the subtraction algorithm for left and right, diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.GcdInv.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.GcdInv.cs index d984912ec62467..501179099698ea 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.GcdInv.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.GcdInv.cs @@ -42,7 +42,7 @@ public static ulong Gcd(ulong left, ulong right) public static uint Gcd(uint[] left, uint right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 1); Debug.Assert(right != 0); @@ -56,9 +56,9 @@ public static uint Gcd(uint[] left, uint right) public static uint[] Gcd(uint[] left, uint[] right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); Debug.Assert(left.Length >= 2); - Debug.Assert(right != null); + Debug.Assert(right is not null); Debug.Assert(right.Length >= 2); Debug.Assert(Compare(left, right) >= 0); diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.PowMod.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.PowMod.cs index c6461734302750..a7835907303aca 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.PowMod.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.PowMod.cs @@ -25,7 +25,7 @@ public static uint[] Pow(uint value, uint power) public static uint[] Pow(uint[] value, uint power) { - Debug.Assert(value != null); + Debug.Assert(value is not null); // The basic pow method for a big integer. // To spare memory allocations we first roughly @@ -96,7 +96,7 @@ public static uint Pow(uint value, uint power, uint modulus) public static uint Pow(uint[] value, uint power, uint modulus) { - Debug.Assert(value != null); + Debug.Assert(value is not null); // The 32-bit modulus pow method for a big integer // raised by a 32-bit integer... @@ -107,7 +107,7 @@ public static uint Pow(uint[] value, uint power, uint modulus) public static uint Pow(uint value, uint[] power, uint modulus) { - Debug.Assert(power != null); + Debug.Assert(power is not null); // The 32-bit modulus pow method for a 32-bit integer // raised by a big integer... @@ -117,8 +117,8 @@ public static uint Pow(uint value, uint[] power, uint modulus) public static uint Pow(uint[] value, uint[] power, uint modulus) { - Debug.Assert(value != null); - Debug.Assert(power != null); + Debug.Assert(value is not null); + Debug.Assert(power is not null); // The 32-bit modulus pow method for a big integer // raised by a big integer... @@ -168,7 +168,7 @@ private static uint PowCore(uint power, uint modulus, public static uint[] Pow(uint value, uint power, uint[] modulus) { - Debug.Assert(modulus != null); + Debug.Assert(modulus is not null); // The big modulus pow method for a 32-bit integer // raised by a 32-bit integer... @@ -180,8 +180,8 @@ public static uint[] Pow(uint value, uint power, uint[] modulus) public static uint[] Pow(uint[] value, uint power, uint[] modulus) { - Debug.Assert(value != null); - Debug.Assert(modulus != null); + Debug.Assert(value is not null); + Debug.Assert(modulus is not null); // The big modulus pow method for a big integer // raised by a 32-bit integer... @@ -196,8 +196,8 @@ public static uint[] Pow(uint[] value, uint power, uint[] modulus) public static uint[] Pow(uint value, uint[] power, uint[] modulus) { - Debug.Assert(power != null); - Debug.Assert(modulus != null); + Debug.Assert(power is not null); + Debug.Assert(modulus is not null); // The big modulus pow method for a 32-bit integer // raised by a big integer... @@ -209,9 +209,9 @@ public static uint[] Pow(uint value, uint[] power, uint[] modulus) public static uint[] Pow(uint[] value, uint[] power, uint[] modulus) { - Debug.Assert(value != null); - Debug.Assert(power != null); - Debug.Assert(modulus != null); + Debug.Assert(value is not null); + Debug.Assert(power is not null); + Debug.Assert(modulus is not null); // The big modulus pow method for a big integer // raised by a big integer... @@ -395,7 +395,7 @@ private static int ActualLength(uint[] value) private static int ActualLength(uint[] value, int length) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(length <= value.Length); while (length > 0 && value[length - 1] == 0) diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.SquMul.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.SquMul.cs index f77d02f37ccb32..00309659bb7dc0 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.SquMul.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.SquMul.cs @@ -10,7 +10,7 @@ internal static partial class BigIntegerCalculator { public static unsafe uint[] Square(uint[] value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); // Switching to unsafe pointers helps sparing // some nasty index calculations... @@ -162,7 +162,7 @@ private static unsafe void Square(uint* value, int valueLength, public static uint[] Multiply(uint[] left, uint right) { - Debug.Assert(left != null); + Debug.Assert(left is not null); // Executes the multiplication for one big and one 32-bit integer. // Since every step holds the already slightly familiar equation @@ -186,8 +186,8 @@ public static uint[] Multiply(uint[] left, uint right) public static unsafe uint[] Multiply(uint[] left, uint[] right) { - Debug.Assert(left != null); - Debug.Assert(right != null); + Debug.Assert(left is not null); + Debug.Assert(right is not null); Debug.Assert(left.Length >= right.Length); // Switching to unsafe pointers helps sparing diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs index f8697ddebbeb20..7063c4dfc70b6b 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs @@ -324,7 +324,7 @@ internal static bool TryValidateParseStyleInteger(NumberStyles style, [NotNullWh internal static bool TryParseBigInteger(string? value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { - if (value == null) + if (value is null) { result = default(BigInteger); return false; @@ -366,7 +366,7 @@ internal static bool TryParseBigInteger(ReadOnlySpan value, NumberStyles s internal static BigInteger ParseBigInteger(string value, NumberStyles style, NumberFormatInfo info) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -390,7 +390,7 @@ internal static BigInteger ParseBigInteger(ReadOnlySpan value, NumberStyle private static unsafe bool HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { - if (number.digits == null || number.digits.Length == 0) + if (number.digits is null || number.digits.Length == 0) return false; int len = number.digits.Length - 1; // Ignore trailing '\0' @@ -555,7 +555,7 @@ internal static char ParseFormatSpecifier(ReadOnlySpan format, out int dig digits - sb.Length); } - if (arrayToReturnToPool != null) + if (arrayToReturnToPool is not null) { ArrayPool.Shared.Return(arrayToReturnToPool); } @@ -589,7 +589,7 @@ internal static bool TryFormatBigInteger(BigInteger value, ReadOnlySpan fo string? formatString, ReadOnlySpan formatSpan, NumberFormatInfo info, Span destination, out int charsWritten, out bool spanSuccess) { - Debug.Assert(formatString == null || formatString.Length == formatSpan.Length); + Debug.Assert(formatString is null || formatString.Length == formatSpan.Length); int digits = 0; char fmt = ParseFormatSpecifier(formatSpan, out digits); @@ -599,7 +599,7 @@ internal static bool TryFormatBigInteger(BigInteger value, ReadOnlySpan fo } - if (value._bits == null) + if (value._bits is null) { if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R') { diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/NumericsHelpers.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/NumericsHelpers.cs index 82866c353b5bb6..a9e19cf0439eae 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/NumericsHelpers.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/NumericsHelpers.cs @@ -108,7 +108,7 @@ public static double GetDoubleFromParts(int sign, int exp, ulong man) // a mutation and needs to be used with care for immutable types. public static void DangerousMakeTwosComplement(uint[] d) { - if (d != null && d.Length > 0) + if (d is not null && d.Length > 0) { d[0] = unchecked(~d[0] + 1); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs index 5d97328d8569db..e6cf43980278ed 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs @@ -45,7 +45,7 @@ protected Formatter() protected virtual long Schedule(object? obj) { - if (obj == null) + if (obj is null) { return 0; } @@ -87,7 +87,7 @@ protected virtual long Schedule(object? obj) protected virtual void WriteMember(string memberName, object? data) { - if (data == null) + if (data is null) { WriteObjectRef(data, memberName, typeof(object)); return; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs index ed0fbd11fe65da..7763cc088b047b 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs @@ -11,107 +11,107 @@ public class FormatterConverter : IFormatterConverter { public object Convert(object value, Type type) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } public object Convert(object value, TypeCode typeCode) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); } public bool ToBoolean(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture); } public char ToChar(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToChar(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public sbyte ToSByte(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToSByte(value, CultureInfo.InvariantCulture); } public byte ToByte(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToByte(value, CultureInfo.InvariantCulture); } public short ToInt16(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToInt16(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public ushort ToUInt16(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture); } public int ToInt32(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToInt32(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public uint ToUInt32(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture); } public long ToInt64(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToInt64(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public ulong ToUInt64(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture); } public float ToSingle(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToSingle(value, CultureInfo.InvariantCulture); } public double ToDouble(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToDouble(value, CultureInfo.InvariantCulture); } public decimal ToDecimal(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture); } public DateTime ToDateTime(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture); } public string? ToString(object value) { - if (value == null) ThrowValueNullException(); + if (value is null) ThrowValueNullException(); return System.Convert.ToString(value, CultureInfo.InvariantCulture); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs index 3403898e2e2b37..dea2e844b0ff21 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs @@ -18,7 +18,7 @@ public static class FormatterServices private static FieldInfo[] InternalGetSerializableMembers(Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); if (type.IsInterface) { @@ -37,7 +37,7 @@ private static FieldInfo[] InternalGetSerializableMembers(Type type) // get all of the private and assembly-access fields (e.g. all fields that aren't // virtual) and include them in the list of things to be serialized. Type? parentType = type.BaseType; - if (parentType != null && parentType != typeof(object)) + if (parentType is not null && parentType != typeof(object)) { bool classNamesUnique = GetParentTypes(parentType, out Type[]? parentTypes, out int parentTypeCount); @@ -66,7 +66,7 @@ private static FieldInfo[] InternalGetSerializableMembers(Type type) // If we actually found any new MemberInfo's, we need to create a new MemberInfo array and // copy all of the members which we've found so far into that. - if (allMembers != null && allMembers.Count > 0) + if (allMembers is not null && allMembers.Count > 0) { var membersTemp = new FieldInfo[allMembers.Count + typeMembers.Length]; Array.Copy(typeMembers, membersTemp, typeMembers.Length); @@ -145,7 +145,7 @@ private static bool GetParentTypes(Type parentType, out Type[]? parentTypes, out } // expand array if needed - if (parentTypes == null || parentTypeCount == parentTypes.Length) + if (parentTypes is null || parentTypeCount == parentTypes.Length) { Array.Resize(ref parentTypes, Math.Max(parentTypeCount * 2, 12)); } @@ -163,7 +163,7 @@ public static MemberInfo[] GetSerializableMembers(Type type) public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -193,7 +193,7 @@ public static object GetUninitializedObject( internal static void SerializationSetValue(MemberInfo fi, object? target, object? value) { - Debug.Assert(fi != null); + Debug.Assert(fi is not null); if (fi is FieldInfo serField) { @@ -206,15 +206,15 @@ internal static void SerializationSetValue(MemberInfo fi, object? target, object public static object PopulateObjectMembers(object obj, MemberInfo[] members, object?[] data) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } - if (members == null) + if (members is null) { throw new ArgumentNullException(nameof(members)); } - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } @@ -226,7 +226,7 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj for (int i = 0; i < members.Length; i++) { MemberInfo member = members[i]; - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(members), SR.Format(SR.ArgumentNull_NullMember, i)); } @@ -235,7 +235,7 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj // This is either a forward reference or a null. In either case, this may break some of the // invariants mantained by the setter, so we'll do nothing with it for right now. object? value = data[i]; - if (value == null) + if (value is null) { continue; } @@ -256,11 +256,11 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj public static object?[] GetObjectData(object obj, MemberInfo[] members) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } - if (members == null) + if (members is null) { throw new ArgumentNullException(nameof(members)); } @@ -269,13 +269,13 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj for (int i = 0; i < members.Length; i++) { MemberInfo member = members[i]; - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(members), SR.Format(SR.ArgumentNull_NullMember, i)); } FieldInfo? field = member as FieldInfo; - if (field == null) + if (field is null) { throw new SerializationException(SR.Serialization_UnknownMemberInfo); } @@ -287,7 +287,7 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { - if (innerSurrogate == null) + if (innerSurrogate is null) { throw new ArgumentNullException(nameof(innerSurrogate)); } @@ -296,7 +296,7 @@ public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializ public static Type? GetTypeFromAssembly(Assembly assem, string name) { - if (assem == null) + if (assem is null) { throw new ArgumentNullException(nameof(assem)); } @@ -320,7 +320,7 @@ internal static Assembly LoadAssemblyFromString(string assemblyName) internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -386,7 +386,7 @@ internal sealed class SurrogateForCyclicalReference : ISerializationSurrogate internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { - Debug.Assert(innerSurrogate != null); + Debug.Assert(innerSurrogate is not null); _innerSurrogate = innerSurrogate; } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryArray.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryArray.cs index 4a3cb8fe95f468..5440f1a386dd04 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryArray.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryArray.cs @@ -55,7 +55,7 @@ internal void Set(int objectId, int rank, int[] lengthA, int[]? lowerBoundA, Bin public void Write(BinaryFormatterWriter output) { - Debug.Assert(_lengthA != null); + Debug.Assert(_lengthA is not null); switch (_binaryHeaderEnum) { case BinaryHeaderEnum.ArraySinglePrimitive: @@ -87,7 +87,7 @@ public void Write(BinaryFormatterWriter output) (_binaryArrayTypeEnum == BinaryArrayTypeEnum.JaggedOffset) || (_binaryArrayTypeEnum == BinaryArrayTypeEnum.RectangularOffset)) { - Debug.Assert(_lowerBoundA != null); + Debug.Assert(_lowerBoundA is not null); for (int i = 0; i < _rank; i++) { output.WriteInt32(_lowerBoundA[i]); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssembly.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssembly.cs index 54e9817aeb9cbd..90b81b7ae326ef 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssembly.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssembly.cs @@ -22,7 +22,7 @@ public void Write(BinaryFormatterWriter output) { output.WriteByte((byte)BinaryHeaderEnum.Assembly); output.WriteInt32(_assemId); - Debug.Assert(_assemblyString != null); + Debug.Assert(_assemblyString is not null); output.WriteString(_assemblyString); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssemblyInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssemblyInfo.cs index 78048519d06bad..04fff7a23f5f0f 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssemblyInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssemblyInfo.cs @@ -22,10 +22,10 @@ internal BinaryAssemblyInfo(string assemblyString, Assembly? assembly) : this(as internal Assembly GetAssembly() { - if (_assembly == null) + if (_assembly is null) { _assembly = FormatterServices.LoadAssemblyFromStringNoThrow(_assemblyString); - if (_assembly == null) + if (_assembly is null) { throw new SerializationException(SR.Format(SR.Serialization_AssemblyNotFound, _assemblyString)); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs index 939b78ad9535dc..8ff4aff9535816 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs @@ -16,7 +16,7 @@ public object Deserialize(Stream serializationStream) throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } - if (serializationStream == null) + if (serializationStream is null) { throw new ArgumentNullException(nameof(serializationStream)); } @@ -66,7 +66,7 @@ public void Serialize(Stream serializationStream, object graph) throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } - if (serializationStream == null) + if (serializationStream is null) { throw new ArgumentNullException(nameof(serializationStream)); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterEventSource.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterEventSource.cs index ca8efd4c0978a9..0462629f1fbfeb 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterEventSource.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterEventSource.cs @@ -44,7 +44,7 @@ public void SerializationStop() [NonEvent] public void SerializingObject(Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); if (IsEnabled(EventLevel.Informational, Keywords.Serialization)) { @@ -79,7 +79,7 @@ public void DeserializationStop() [NonEvent] public void DeserializingObject(Type type) { - Debug.Assert(type != null); + Debug.Assert(type is not null); if (IsEnabled(EventLevel.Informational, Keywords.Deserialization)) { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs index e8a130510e6f5d..4aefa587ddf82f 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs @@ -117,22 +117,22 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb int assemId; int objectId = (int)nameInfo._objectId; - Debug.Assert(typeNameInfo != null); // Explicitly called with null, asserting for now https://github.com/dotnet/runtime/issues/31402 + Debug.Assert(typeNameInfo is not null); // Explicitly called with null, asserting for now https://github.com/dotnet/runtime/issues/31402 string? objectName = objectId < 0 ? typeNameInfo.NIname : // Nested Object nameInfo.NIname; // Non-Nested - if (_objectMapTable == null) + if (_objectMapTable is null) { _objectMapTable = new Dictionary(); } - Debug.Assert(objectName != null); + Debug.Assert(objectName is not null); if (_objectMapTable.TryGetValue(objectName, out ObjectMapInfo? objectMapInfo) && objectMapInfo.IsCompatible(numMembers, memberNames, memberTypes)) { // Object - if (_binaryObject == null) + if (_binaryObject is null) { _binaryObject = new BinaryObject(); } @@ -143,7 +143,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb else if (!typeNameInfo._transmitTypeOnObject) { // ObjectWithMap - if (_binaryObjectWithMap == null) + if (_binaryObjectWithMap is null) { _binaryObjectWithMap = new BinaryObjectWithMap(); } @@ -153,7 +153,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb _binaryObjectWithMap.Set(objectId, objectName, numMembers, memberNames, assemId); _binaryObjectWithMap.Write(this); - if (objectMapInfo == null) + if (objectMapInfo is null) { _objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } @@ -172,7 +172,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb assemIdA[i] = assemId; } - if (_binaryObjectWithMapTyped == null) + if (_binaryObjectWithMapTyped is null) { _binaryObjectWithMapTyped = new BinaryObjectWithMapTyped(); } @@ -181,7 +181,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb assemId = (int)typeNameInfo._assemId; _binaryObjectWithMapTyped.Set(objectId, objectName, numMembers, memberNames, binaryTypeEnumA, typeInformationA, assemIdA, assemId); _binaryObjectWithMapTyped.Write(this); - if (objectMapInfo == null) + if (objectMapInfo is null) { _objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } @@ -192,7 +192,7 @@ internal void WriteObjectString(int objectId, string? value) { InternalWriteItemNull(); - if (_binaryObjectString == null) + if (_binaryObjectString is null) { _binaryObjectString = new BinaryObjectString(); } @@ -225,7 +225,7 @@ internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo( arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); - if (_binaryArray == null) + if (_binaryArray is null) { _binaryArray = new BinaryArray(); } @@ -255,7 +255,7 @@ private void WriteArrayAsBytes(Array array, int typeLength) { InternalWriteItemNull(); int arrayOffset = 0; - if (_byteBuffer == null) + if (_byteBuffer is null) { _byteBuffer = new byte[ChunkSize]; } @@ -307,7 +307,7 @@ internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); - if (_binaryArray == null) + if (_binaryArray is null) { _binaryArray = new BinaryArray(); } @@ -325,7 +325,7 @@ internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInf int assemId = 0; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); - if (_binaryArray == null) + if (_binaryArray is null) { _binaryArray = new BinaryArray(); } @@ -357,7 +357,7 @@ internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object // Writes Members with primitive values if (memberNameInfo._transmitTypeOnMember) { - if (_memberPrimitiveTyped == null) + if (_memberPrimitiveTyped is null) { _memberPrimitiveTyped = new MemberPrimitiveTyped(); } @@ -366,7 +366,7 @@ internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object } else { - if (_memberPrimitiveUnTyped == null) + if (_memberPrimitiveUnTyped is null) { _memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); } @@ -378,7 +378,7 @@ internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) { InternalWriteItemNull(); - if (_objectNull == null) + if (_objectNull is null) { _objectNull = new ObjectNull(); } @@ -394,7 +394,7 @@ internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) internal void WriteMemberObjectRef(NameInfo memberNameInfo, int idRef) { InternalWriteItemNull(); - if (_memberReference == null) + if (_memberReference is null) { _memberReference = new MemberReference(); } @@ -436,7 +436,7 @@ private void InternalWriteItemNull() { if (_consecutiveNullArrayEntryCount > 0) { - if (_objectNull == null) + if (_objectNull is null) { _objectNull = new ObjectNull(); } @@ -457,14 +457,14 @@ internal void WriteAssembly(Type? type, string assemblyString, int assemId, bool //If the file being tested wasn't built as an assembly, then we're going to get null back //for the assembly name. This is very unfortunate. InternalWriteItemNull(); - if (assemblyString == null) + if (assemblyString is null) { assemblyString = string.Empty; } if (isNew) { - if (_binaryAssembly == null) + if (_binaryAssembly is null) { _binaryAssembly = new BinaryAssembly(); } @@ -526,7 +526,7 @@ internal bool IsCompatible(int numMembers, string[] memberNames, Type[]? memberT return false; } - if ((memberTypes != null) && (_memberTypes[i] != memberTypes[i])) + if ((memberTypes is not null) && (_memberTypes[i] != memberTypes[i])) { return false; } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs index 64f4e6ddcd830d..4290ba99efe762 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs @@ -41,7 +41,7 @@ internal WriteObjectInfo() { } internal void ObjectEnd() { - Debug.Assert(_serObjectInfoInit != null); + Debug.Assert(_serObjectInfoInit is not null); PutObjectInfo(_serObjectInfoInit, this); } @@ -91,7 +91,7 @@ internal void InitSerialize(object obj, ISurrogateSelector? surrogateSelector, S objectWriter.ObjectManager.RegisterObject(obj); ISurrogateSelector surrogateSelectorTemp; - if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) != null) + if (surrogateSelector is not null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) is not null) { _si = new SerializationInfo(_objectType, converter); if (!_objectType.IsPrimitive) @@ -140,12 +140,12 @@ internal void InitSerialize(Type objectType, ISurrogateSelector? surrogateSelect InvokeSerializationBinder(binder); - if (surrogateSelector != null) + if (surrogateSelector is not null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out ISurrogateSelector surrogateSelectorTemp); } - if (_serializationSurrogate != null) + if (_serializationSurrogate is not null) { // surrogate does not have this problem since user has pass in through the BF's ctor _si = new SerializationInfo(objectType, converter); @@ -171,7 +171,7 @@ private void InitSiWrite() { SerializationInfoEnumerator? siEnum = null; _isSi = true; - Debug.Assert(_si != null); + Debug.Assert(_si is not null); siEnum = _si.GetEnumerator(); int infoLength = 0; @@ -195,7 +195,7 @@ private void InitSiWrite() if (!_si.IsAssemblyNameSetExplicit) { - if (typeInformation == null) + if (typeInformation is null) { typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType); } @@ -227,7 +227,7 @@ private static void CheckTypeForwardedFrom(SerObjectInfoCache? cache, Type objec private void InitNoMembers() { - Debug.Assert(_serObjectInfoInit != null && _objectType != null); + Debug.Assert(_serObjectInfoInit is not null && _objectType is not null); if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache!)) { _cache = new SerObjectInfoCache(_objectType); @@ -237,7 +237,7 @@ private void InitNoMembers() private void InitMemberInfo() { - Debug.Assert(_serObjectInfoInit != null && _objectType != null); + Debug.Assert(_serObjectInfoInit is not null && _objectType is not null); if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache!)) { _cache = new SerObjectInfoCache(_objectType); @@ -256,7 +256,7 @@ private void InitMemberInfo() _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache); } - if (_obj != null) + if (_obj is not null) { _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos!); } @@ -383,11 +383,11 @@ internal void Init(Type? objectType, string[] memberNames, Type[]? memberTypes, _serObjectInfoInit = serObjectInfoInit; _formatterConverter = converter; _isSimpleAssembly = bSimpleAssembly; - if (memberTypes != null) + if (memberTypes is not null) { _isTyped = true; } - if (objectType != null) + if (objectType is not null) { InitReadConstructor(objectType, surrogateSelector, context); } @@ -404,12 +404,12 @@ private void InitReadConstructor(Type objectType, ISurrogateSelector? surrogateS } ISurrogateSelector? surrogateSelectorTemp = null; - if (surrogateSelector != null) + if (surrogateSelector is not null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } - if (_serializationSurrogate != null) + if (_serializationSurrogate is not null) { _isSi = true; } @@ -430,7 +430,7 @@ private void InitReadConstructor(Type objectType, ISurrogateSelector? surrogateS private void InitSiRead() { - if (_memberTypesList != null) + if (_memberTypesList is not null) { _memberTypesList = new List(20); } @@ -462,7 +462,7 @@ private void InitMemberInfo() // Get the memberInfo for a memberName internal MemberInfo? GetMemberInfo(string? name) { - if (_cache == null) + if (_cache is null) { return null; } @@ -472,7 +472,7 @@ private void InitMemberInfo() throw new SerializationException(SR.Format(SR.Serialization_MemberInfo, _objectType + " " + name)); } - if (_cache._memberInfos == null) + if (_cache._memberInfos is null) { throw new SerializationException(SR.Format(SR.Serialization_NoMemberInfo, _objectType + " " + name)); } @@ -491,7 +491,7 @@ private void InitMemberInfo() } Type type = _isTyped ? _cache!._memberTypes![position] : _memberTypesList![position]; - if (type == null) + if (type is null) { throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, _objectType + " " + name)); } @@ -504,7 +504,7 @@ internal void AddValue(string name, object? value, ref SerializationInfo? si, re { if (_isSi) { - Debug.Assert(si != null); + Debug.Assert(si is not null); si.AddValue(name, value); } else @@ -513,7 +513,7 @@ internal void AddValue(string name, object? value, ref SerializationInfo? si, re int position = Position(name); if (position != -1) { - Debug.Assert(memberData != null); + Debug.Assert(memberData is not null); memberData[position] = value; } } @@ -523,17 +523,17 @@ internal void InitDataStore(ref SerializationInfo? si, ref object?[]? memberData { if (_isSi) { - if (si == null) + if (si is null) { - Debug.Assert(_objectType != null); + Debug.Assert(_objectType is not null); si = new SerializationInfo(_objectType, _formatterConverter!); } } else { - if (memberData == null && _cache != null) + if (memberData is null && _cache is not null) { - Debug.Assert(_cache._memberNames != null); + Debug.Assert(_cache._memberNames is not null); memberData = new object[_cache._memberNames.Length]; } } @@ -544,7 +544,7 @@ internal void RecordFixup(long objectId, string name, long idRef) { if (_isSi) { - if (_objectManager == null) + if (_objectManager is null) { throw new SerializationException(SR.Serialization_CorruptedStream); } @@ -556,12 +556,12 @@ internal void RecordFixup(long objectId, string name, long idRef) int position = Position(name); if (position != -1) { - if (_objectManager == null) + if (_objectManager is null) { throw new SerializationException(SR.Serialization_CorruptedStream); } - Debug.Assert(_cache != null && _cache._memberInfos != null); + Debug.Assert(_cache is not null && _cache._memberInfos is not null); _objectManager.RecordFixup(objectId, _cache._memberInfos[position], idRef); } } @@ -570,9 +570,9 @@ internal void RecordFixup(long objectId, string name, long idRef) // Fills in the values for an object internal void PopulateObjectMembers(object obj, object?[]? memberData) { - if (!_isSi && memberData != null) + if (!_isSi && memberData is not null) { - Debug.Assert(_cache != null && _cache._memberInfos != null); + Debug.Assert(_cache is not null && _cache._memberInfos is not null); FormatterServices.PopulateObjectMembers(obj, _cache._memberInfos, memberData); } } @@ -580,12 +580,12 @@ internal void PopulateObjectMembers(object obj, object?[]? memberData) // Specifies the position in the memberNames array of this name private int Position(string? name) { - if (_cache == null) + if (_cache is null) { return -1; } - Debug.Assert(_cache._memberNames != null); + Debug.Assert(_cache._memberNames is not null); if (_cache._memberNames.Length > 0 && _cache._memberNames[_lastPosition].Equals(name)) { return _lastPosition; @@ -619,13 +619,13 @@ private int Position(string? name) throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, objectType)); } - if (_cache == null) + if (_cache is null) { return null; } - Debug.Assert(_cache._memberInfos != null); - if (_cache._memberTypes == null) + Debug.Assert(_cache._memberInfos is not null); + if (_cache._memberTypes is null) { _cache._memberTypes = new Type[_count]; for (int i = 0; i < _count; i++) @@ -666,9 +666,9 @@ private int Position(string? name) // A field on the type isn't found. See if the field has OptionalFieldAttribute. We only throw // when the assembly format is set appropriately. if (!_isSimpleAssembly && - _cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null) + _cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) is null) { - Debug.Assert(_cache._memberNames != null); + Debug.Assert(_cache._memberNames is not null); throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName)); } } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs index cb1d8f45cd6b4c..4b53553c969dd3 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs @@ -54,7 +54,7 @@ internal object? TopObject set { _topObject = value; - if (_objectManager != null) + if (_objectManager is not null) { _objectManager.TopObject = value; } @@ -63,7 +63,7 @@ internal object? TopObject internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } @@ -76,7 +76,7 @@ internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingCont } internal object Deserialize(BinaryParser serParser) { - if (serParser == null) + if (serParser is null) { throw new ArgumentNullException(nameof(serParser)); } @@ -104,7 +104,7 @@ internal object Deserialize(BinaryParser serParser) _objectManager!.DoFixups(); } - if (TopObject == null) + if (TopObject is null) { throw new SerializationException(SR.Serialization_TopObject); } @@ -113,7 +113,7 @@ internal object Deserialize(BinaryParser serParser) //So refresh it using topID. if (HasSurrogate(TopObject.GetType()) && _topId != 0)//Not yet resolved { - Debug.Assert(_objectManager != null); + Debug.Assert(_objectManager is not null); TopObject = _objectManager.GetObject(_topId); } @@ -133,7 +133,7 @@ internal object Deserialize(BinaryParser serParser) private bool HasSurrogate(Type t) { ISurrogateSelector ignored; - return _surrogates != null && _surrogates.GetSurrogate(t, _context, out ignored) != null; + return _surrogates is not null && _surrogates.GetSurrogate(t, _context, out ignored) is not null; } private void CheckSerializable(Type t) @@ -149,7 +149,7 @@ private void InitFullDeserialization() _fullDeserialization = true; _stack = new SerStack("ObjectReader Object Stack"); _objectManager = new ObjectManager(_surrogates, _context); - if (_formatterConverter == null) + if (_formatterConverter is null) { _formatterConverter = new FormatterConverter(); } @@ -157,7 +157,7 @@ private void InitFullDeserialization() internal object CrossAppDomainArray(int index) { - Debug.Assert(_crossAppDomainArray != null); + Debug.Assert(_crossAppDomainArray is not null); Debug.Assert(index < _crossAppDomainArray.Length, "[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]"); return _crossAppDomainArray[index]; } @@ -243,7 +243,7 @@ private void ParseObject(ParseRecord pr) // If the Type is null, this means we have a typeload issue // mark the object with TypeLoadExceptionHolder - if (pr._dtType == null) + if (pr._dtType is null) { pr._newObj = new TypeLoadExceptionHolder(pr._keyDt); return; @@ -252,7 +252,7 @@ private void ParseObject(ParseRecord pr) if (ReferenceEquals(pr._dtType, Converter.s_typeofString)) { // String as a top level object - if (pr._value != null) + if (pr._value is not null) { pr._newObj = pr._value; if (pr._objectPositionEnum == InternalObjectPositionE.Top) @@ -278,12 +278,12 @@ private void ParseObject(ParseRecord pr) CheckSerializable(pr._dtType); pr._newObj = FormatterServices.GetUninitializedObject(pr._dtType); - Debug.Assert(_objectManager != null); + Debug.Assert(_objectManager is not null); // Run the OnDeserializing methods _objectManager.RaiseOnDeserializingEvent(pr._newObj); } - if (pr._newObj == null) + if (pr._newObj is null) { throw new SerializationException(SR.Format(SR.Serialization_TopObjectInstantiate, pr._dtType)); } @@ -293,7 +293,7 @@ private void ParseObject(ParseRecord pr) TopObject = pr._newObj; } - if (pr._objectInfo == null) + if (pr._objectInfo is null) { pr._objectInfo = ReadObjectInfo.Create(pr._dtType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); } @@ -302,7 +302,7 @@ private void ParseObject(ParseRecord pr) // End of object encountered in stream private void ParseObjectEnd(ParseRecord pr) { - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); ParseRecord objectPr = (ParseRecord?)_stack.Peek() ?? pr; if (objectPr._objectPositionEnum == InternalObjectPositionE.Top) @@ -318,7 +318,7 @@ private void ParseObjectEnd(ParseRecord pr) _stack.Pop(); ParseRecord? parentPr = (ParseRecord?)_stack.Peek(); - if (objectPr._newObj == null) + if (objectPr._newObj is null) { return; } @@ -334,7 +334,7 @@ private void ParseObjectEnd(ParseRecord pr) return; } - Debug.Assert(objectPr._objectInfo != null); + Debug.Assert(objectPr._objectInfo is not null); objectPr._objectInfo.PopulateObjectMembers(objectPr._newObj, objectPr._memberData); // Registration is after object is populated @@ -346,7 +346,7 @@ private void ParseObjectEnd(ParseRecord pr) if (objectPr._isValueTypeFixup) { ValueFixup? fixup = (ValueFixup?)ValueFixupStack.Pop(); //Value fixup - Debug.Assert(fixup != null && parentPr != null); + Debug.Assert(fixup is not null && parentPr is not null); fixup.Fixup(objectPr, parentPr); // Value fixup } @@ -361,10 +361,10 @@ private void ParseObjectEnd(ParseRecord pr) // Array object encountered in stream private void ParseArray(ParseRecord pr) { - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); if (pr._arrayTypeEnum == InternalArrayTypeE.Base64) { - Debug.Assert(pr._value != null); + Debug.Assert(pr._value is not null); // ByteArray pr._newObj = pr._value.Length > 0 ? Convert.FromBase64String(pr._value) : @@ -384,7 +384,7 @@ private void ParseArray(ParseRecord pr) // Base64 can be registered at this point because it is populated RegisterObject(pr._newObj, pr, parentPr); } - else if ((pr._newObj != null) && Converter.IsWriteAsByteArray(pr._arrayElementTypeCode)) + else if ((pr._newObj is not null) && Converter.IsWriteAsByteArray(pr._arrayElementTypeCode)) { // Primtive typed Array has already been read if (pr._objectPositionEnum == InternalObjectPositionE.Top) @@ -399,10 +399,10 @@ private void ParseArray(ParseRecord pr) } else if ((pr._arrayTypeEnum == InternalArrayTypeE.Jagged) || (pr._arrayTypeEnum == InternalArrayTypeE.Single)) { - Debug.Assert(pr._lengthA != null); + Debug.Assert(pr._lengthA is not null); // Multidimensional jagged array or single array bool couldBeValueType = true; - if ((pr._lowerBoundA == null) || (pr._lowerBoundA[0] == 0)) + if ((pr._lowerBoundA is null) || (pr._lowerBoundA[0] == 0)) { if (ReferenceEquals(pr._arrayElementType, Converter.s_typeofString)) { @@ -416,7 +416,7 @@ private void ParseArray(ParseRecord pr) pr._newObj = pr._objectA; couldBeValueType = false; } - else if (pr._arrayElementType != null) + else if (pr._arrayElementType is not null) { pr._newObj = Array.CreateInstance(pr._arrayElementType, pr._lengthA[0]); } @@ -424,7 +424,7 @@ private void ParseArray(ParseRecord pr) } else { - if (pr._arrayElementType != null) + if (pr._arrayElementType is not null) { pr._newObj = Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA); } @@ -435,10 +435,10 @@ private void ParseArray(ParseRecord pr) { if (!pr._isLowerBound && (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode))) { - Debug.Assert(pr._newObj != null); + Debug.Assert(pr._newObj is not null); pr._primitiveArray = new PrimitiveArray(pr._arrayElementTypeCode, (Array)pr._newObj); } - else if (couldBeValueType && pr._arrayElementType != null) + else if (couldBeValueType && pr._arrayElementType is not null) { if (!pr._arrayElementType.IsValueType && !pr._isLowerBound) { @@ -454,7 +454,7 @@ private void ParseArray(ParseRecord pr) // Rectangle array pr._isLowerBound = false; - if (pr._lowerBoundA != null) + if (pr._lowerBoundA is not null) { for (int i = 0; i < pr._rank; i++) { @@ -465,10 +465,10 @@ private void ParseArray(ParseRecord pr) } } - Debug.Assert(pr._lengthA != null); - if (pr._arrayElementType != null) + Debug.Assert(pr._lengthA is not null); + if (pr._arrayElementType is not null) { - Debug.Assert(pr._lowerBoundA != null); + Debug.Assert(pr._lowerBoundA is not null); pr._newObj = !pr._isLowerBound ? Array.CreateInstance(pr._arrayElementType, pr._lengthA) : Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA); @@ -493,7 +493,7 @@ private void ParseArray(ParseRecord pr) // Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object private void NextRectangleMap(ParseRecord pr) { - Debug.Assert(pr._rectangularMap != null && pr._lengthA != null && pr._indexMap != null); + Debug.Assert(pr._rectangularMap is not null && pr._lengthA is not null && pr._indexMap is not null); // For each invocation, calculate the next rectangular array position // example // indexMap 0 [0,0,0] @@ -526,10 +526,10 @@ private void NextRectangleMap(ParseRecord pr) // Array object item encountered in stream private void ParseArrayMember(ParseRecord pr) { - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); ParseRecord? objectPr = (ParseRecord?)_stack.Peek(); - Debug.Assert(objectPr != null && objectPr._indexMap != null && objectPr._lowerBoundA != null); + Debug.Assert(objectPr is not null && objectPr._indexMap is not null && objectPr._lowerBoundA is not null); // Set up for inserting value into correct array position if (objectPr._arrayTypeEnum == InternalArrayTypeE.Rectangular) { @@ -539,7 +539,7 @@ private void ParseArrayMember(ParseRecord pr) } if (objectPr._isLowerBound) { - Debug.Assert(objectPr._rectangularMap != null); + Debug.Assert(objectPr._rectangularMap is not null); for (int i = 0; i < objectPr._rank; i++) { objectPr._indexMap[i] = objectPr._rectangularMap[i] + objectPr._lowerBoundA[i]; @@ -559,10 +559,10 @@ private void ParseArrayMember(ParseRecord pr) { // Object Reference - Debug.Assert(_objectManager != null); + Debug.Assert(_objectManager is not null); // See if object has already been instantiated object? refObj = _objectManager.GetObject(pr._idRef); - if (refObj == null) + if (refObj is null) { // Object not instantiated // Array fixup manager @@ -573,13 +573,13 @@ private void ParseArrayMember(ParseRecord pr) } else { - if (objectPr._objectA != null) + if (objectPr._objectA is not null) { objectPr._objectA[objectPr._indexMap[0]] = refObj; } else { - Debug.Assert(objectPr._newObj != null); + Debug.Assert(objectPr._newObj is not null); ((Array)objectPr._newObj).SetValue(refObj, objectPr._indexMap); // Object has been instantiated } } @@ -587,7 +587,7 @@ private void ParseArrayMember(ParseRecord pr) else if (pr._memberValueEnum == InternalMemberValueE.Nested) { //Set up dtType for ParseObject - if (pr._dtType == null) + if (pr._dtType is null) { pr._dtType = objectPr._arrayElementType; } @@ -595,9 +595,9 @@ private void ParseArrayMember(ParseRecord pr) ParseObject(pr); _stack.Push(pr); - if (objectPr._arrayElementType != null) + if (objectPr._arrayElementType is not null) { - Debug.Assert(objectPr._newObj != null); + Debug.Assert(objectPr._newObj is not null); if ((objectPr._arrayElementType.IsValueType) && (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Invalid)) { pr._isValueTypeFixup = true; //Valuefixup @@ -605,7 +605,7 @@ private void ParseArrayMember(ParseRecord pr) } else { - if (objectPr._objectA != null) + if (objectPr._objectA is not null) { objectPr._objectA[objectPr._indexMap[0]] = pr._newObj; } @@ -622,20 +622,20 @@ private void ParseArrayMember(ParseRecord pr) { // String in either a string array, or a string element of an object array ParseString(pr, objectPr); - if (objectPr._objectA != null) + if (objectPr._objectA is not null) { objectPr._objectA[objectPr._indexMap[0]] = pr._value; } else { - Debug.Assert(objectPr._newObj != null); + Debug.Assert(objectPr._newObj is not null); ((Array)objectPr._newObj).SetValue(pr._value, objectPr._indexMap); } } else if (objectPr._isArrayVariant) { // Array of type object - if (pr._keyDt == null) + if (pr._keyDt is null) { throw new SerializationException(SR.Serialization_ArrayTypeObject); } @@ -649,41 +649,41 @@ private void ParseArrayMember(ParseRecord pr) } else { - var = pr._varValue != null ? + var = pr._varValue is not null ? pr._varValue : Converter.FromString(pr._value, pr._dtTypeCode); } - if (objectPr._objectA != null) + if (objectPr._objectA is not null) { objectPr._objectA[objectPr._indexMap[0]] = var; } else { - Debug.Assert(objectPr._newObj != null); + Debug.Assert(objectPr._newObj is not null); ((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type } } else { // Primitive type - if (objectPr._primitiveArray != null) + if (objectPr._primitiveArray is not null) { - Debug.Assert(pr._value != null); + Debug.Assert(pr._value is not null); // Fast path for Soap primitive arrays. Binary was handled in the BinaryParser objectPr._primitiveArray.SetValue(pr._value, objectPr._indexMap[0]); } else { - object? var = pr._varValue != null ? + object? var = pr._varValue is not null ? pr._varValue : Converter.FromString(pr._value, objectPr._arrayElementTypeCode); - if (objectPr._objectA != null) + if (objectPr._objectA is not null) { objectPr._objectA[objectPr._indexMap[0]] = var; } else { - Debug.Assert(objectPr._newObj != null); + Debug.Assert(objectPr._newObj is not null); ((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type } } @@ -713,7 +713,7 @@ private void ParseArrayMemberEnd(ParseRecord pr) // Object member encountered in stream private void ParseMember(ParseRecord pr) { - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); ParseRecord? objectPr = (ParseRecord?)_stack.Peek(); switch (pr._memberTypeEnum) @@ -725,13 +725,13 @@ private void ParseMember(ParseRecord pr) break; } - Debug.Assert(objectPr!= null && objectPr._objectInfo != null && pr._name != null); - //if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi) - if (pr._dtType == null && objectPr._objectInfo._isTyped) + Debug.Assert(objectPr is not null && objectPr._objectInfo is not null && pr._name is not null); + //if ((pr.PRdtType is null) && !objectPr.PRobjectInfo.isSi) + if (pr._dtType is null && objectPr._objectInfo._isTyped) { pr._dtType = objectPr._objectInfo.GetType(pr._name); - if (pr._dtType != null) + if (pr._dtType is not null) { pr._dtTypeCode = Converter.ToCode(pr._dtType); } @@ -747,7 +747,7 @@ private void ParseMember(ParseRecord pr) ParseObject(pr); _stack.Push(pr); - if ((pr._objectInfo != null) && pr._objectInfo._objectType != null && (pr._objectInfo._objectType.IsValueType)) + if ((pr._objectInfo is not null) && pr._objectInfo._objectType is not null && (pr._objectInfo._objectType.IsValueType)) { pr._isValueTypeFixup = true; //Valuefixup ValueFixupStack.Push(new ValueFixup(objectPr._newObj, pr._name, objectPr._objectInfo)); //valuefixup @@ -759,10 +759,10 @@ private void ParseMember(ParseRecord pr) } else if (pr._memberValueEnum == InternalMemberValueE.Reference) { - Debug.Assert(_objectManager != null); + Debug.Assert(_objectManager is not null); // See if object has already been instantiated object? refObj = _objectManager.GetObject(pr._idRef); - if (refObj == null) + if (refObj is null) { objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData); objectPr._objectInfo.RecordFixup(objectPr._objectId, pr._name, pr._idRef); // Object not instantiated @@ -786,7 +786,7 @@ private void ParseMember(ParseRecord pr) // The member field was an object put the value is Inline either bin.Base64 or invalid if (pr._arrayTypeEnum == InternalArrayTypeE.Base64) { - Debug.Assert(pr._value != null); + Debug.Assert(pr._value is not null); objectPr._objectInfo.AddValue(pr._name, Convert.FromBase64String(pr._value), ref objectPr._si, ref objectPr._memberData); } else if (ReferenceEquals(pr._dtType, Converter.s_typeofObject)) @@ -812,7 +812,7 @@ private void ParseMember(ParseRecord pr) } else { - object? var = pr._varValue != null ? + object? var = pr._varValue is not null ? pr._varValue : Converter.FromString(pr._value, pr._dtTypeCode); objectPr._objectInfo.AddValue(pr._name, var, ref objectPr._si, ref objectPr._memberData); @@ -839,7 +839,7 @@ private void ParseMemberEnd(ParseRecord pr) } break; default: - Debug.Assert(_stack != null); + Debug.Assert(_stack is not null); ParseError(pr, (ParseRecord)_stack.Peek()!); break; } @@ -873,12 +873,12 @@ private void RegisterObject(object? obj, ParseRecord pr, ParseRecord? objectPr, MemberInfo? memberInfo = null; int[]? indexMap = null; - if (objectPr != null) + if (objectPr is not null) { indexMap = objectPr._indexMap; parentId = objectPr._objectId; - if (objectPr._objectInfo != null) + if (objectPr._objectInfo is not null) { if (!objectPr._objectInfo._isSi) { @@ -890,14 +890,14 @@ private void RegisterObject(object? obj, ParseRecord pr, ParseRecord? objectPr, // SerializationInfo is always needed for ISerialization si = pr._si; - Debug.Assert(_objectManager != null); + Debug.Assert(_objectManager is not null); if (bIsString) { _objectManager.RegisterString((string?)obj, pr._objectId, si, parentId, memberInfo); } else { - Debug.Assert(obj != null); + Debug.Assert(obj is not null); _objectManager.RegisterObject(obj, pr._objectId, si, parentId, memberInfo, indexMap); } } @@ -920,7 +920,7 @@ internal long GetId(long objectId) { // Alarm bells. This is an old format. Deal with it. _oldFormatDetected = true; - if (_valTypeObjectIdTable == null) + if (_valTypeObjectIdTable is null) { _valTypeObjectIdTable = new IntSizedArray(); } @@ -940,11 +940,11 @@ internal long GetId(long objectId) internal Type? Bind(string assemblyString, string typeString) { Type? type = null; - if (_binder != null) + if (_binder is not null) { type = _binder.BindToType(assemblyString, typeString); } - if (type == null) + if (type is null) { type = FastBindToType(assemblyString, typeString); } @@ -963,10 +963,10 @@ internal sealed class TypeNAssembly TypeNAssembly? entry = (TypeNAssembly?)_typeCache.GetCachedValue(typeName); - if (entry == null || entry.AssemblyName != assemblyName) + if (entry is null || entry.AssemblyName != assemblyName) { // Check early to avoid throwing unnecessary exceptions - if (assemblyName == null) + if (assemblyName is null) { return null; } @@ -996,7 +996,7 @@ internal sealed class TypeNAssembly catch { } } - if (assm == null) + if (assm is null) { return null; } @@ -1010,7 +1010,7 @@ internal sealed class TypeNAssembly type = FormatterServices.GetTypeFromAssembly(assm, typeName); } - if (type == null) + if (type is null) { return null; } @@ -1034,7 +1034,7 @@ internal sealed class TypeNAssembly } catch { } - if (assemblyName != null) + if (assemblyName is not null) { try { @@ -1059,7 +1059,7 @@ private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeNam catch (FileLoadException) { } catch (BadImageFormatException) { } - if (type == null) + if (type is null) { type = Type.GetType(typeName, ResolveSimpleAssemblyName, new TopLevelAssemblyTypeResolver(assm).ResolveType, throwOnError: false); } @@ -1073,15 +1073,15 @@ private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeNam { Type? objectType; - if (((_previousName != null) && (_previousName.Length == name.Length) && (_previousName.Equals(name))) && - ((_previousAssemblyString != null) && (_previousAssemblyString.Length == assemblyInfo._assemblyString.Length) && (_previousAssemblyString.Equals(assemblyInfo._assemblyString)))) + if (((_previousName is not null) && (_previousName.Length == name.Length) && (_previousName.Equals(name))) && + ((_previousAssemblyString is not null) && (_previousAssemblyString.Length == assemblyInfo._assemblyString.Length) && (_previousAssemblyString.Equals(assemblyInfo._assemblyString)))) { objectType = _previousType; } else { objectType = Bind(assemblyInfo._assemblyString, name); - if (objectType == null) + if (objectType is null) { Assembly sourceAssembly = assemblyInfo.GetAssembly(); @@ -1095,7 +1095,7 @@ private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeNam } // here let us do the security check - if (objectType != null) + if (objectType is not null) { CheckTypeForwardedTo(sourceAssembly, objectType.Assembly, objectType); } @@ -1124,7 +1124,7 @@ public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly) public Type? ResolveType(Assembly? assembly, string simpleTypeName, bool ignoreCase) { - if (assembly == null) + if (assembly is null) { assembly = _topLevelAssembly; } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMap.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMap.cs index e50143abd73aff..04cc70cea0e930 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMap.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMap.cs @@ -36,7 +36,7 @@ internal void Set(int objectId, string name, int numMembers, string[] memberName public void Write(BinaryFormatterWriter output) { - Debug.Assert(_name != null && _memberNames != null); + Debug.Assert(_name is not null && _memberNames is not null); output.WriteByte((byte)_binaryHeaderEnum); output.WriteInt32(_objectId); output.WriteString(_name); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMapTyped.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMapTyped.cs index 881d25ddc57e4e..853a692479b7fa 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMapTyped.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMapTyped.cs @@ -43,7 +43,7 @@ internal void Set(int objectId, string name, int numMembers, string[] memberName public void Write(BinaryFormatterWriter output) { - Debug.Assert(_name != null && _memberNames != null && _binaryTypeEnumA != null && _typeInformationA != null && _memberAssemIds != null); + Debug.Assert(_name is not null && _memberNames is not null && _binaryTypeEnumA is not null && _typeInformationA is not null && _memberAssemIds is not null); output.WriteByte((byte)_binaryHeaderEnum); output.WriteInt32(_objectId); output.WriteString(_name); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs index d4207fbfa68e8a..80639c0e35904d 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs @@ -49,11 +49,11 @@ internal ObjectWriter(ISurrogateSelector? selector, StreamingContext context, In internal void Serialize(object graph, BinaryFormatterWriter serWriter) { - if (graph == null) + if (graph is null) { throw new ArgumentNullException(nameof(graph)); } - if (serWriter == null) + if (serWriter is null) { throw new ArgumentNullException(nameof(serWriter)); } @@ -76,7 +76,7 @@ internal void Serialize(object graph, BinaryFormatterWriter serWriter) WriteSerializedStreamHeader(_topId, headerId); _objectQueue.Enqueue(graph); - while ((obj = GetNext(out long objectId)) != null) + while ((obj = GetNext(out long objectId)) is not null) { WriteObjectInfo? objectInfo = null; @@ -112,7 +112,7 @@ internal void Serialize(object graph, BinaryFormatterWriter serWriter) private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) { object? obj = objectInfo._obj; - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(objectInfo) + "." + nameof(objectInfo._obj)); } @@ -121,7 +121,7 @@ private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo if (ReferenceEquals(objType, Converter.s_typeofString)) { - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); // Top level String memberNameInfo._objectId = objectId; _serWriter.WriteObjectString((int)objectId, obj.ToString()); @@ -146,7 +146,7 @@ private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo._isParentTypeOnObject = true; } - Debug.Assert(memberNames != null && memberTypes != null && memberData != null); + Debug.Assert(memberNames is not null && memberTypes is not null && memberData is not null); var memberObjectInfos = new WriteObjectInfo[memberNames.Length]; // Get assembly information @@ -158,16 +158,16 @@ private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo for (int i = 0; i < memberTypes.Length; i++) { Type type = - memberTypes[i] != null ? memberTypes[i] : - memberData[i] != null ? GetType(memberData[i]!) : // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) + memberTypes[i] is not null ? memberTypes[i] : + memberData[i] is not null ? GetType(memberData[i]!) : // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) Converter.s_typeofObject; InternalPrimitiveTypeE code = ToCode(type); if ((code == InternalPrimitiveTypeE.Invalid) && (!ReferenceEquals(type, Converter.s_typeofString))) { - Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null); - if (memberData[i] != null) + Debug.Assert(_serObjectInfoInit is not null && _formatterConverter is not null); + if (memberData[i] is not null) { memberObjectInfos[i] = WriteObjectInfo.Serialize( memberData[i]!, // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) @@ -208,8 +208,8 @@ private void Write(WriteObjectInfo objectInfo, { int numItems = memberNames.Length; - Debug.Assert(_serWriter != null); - if (memberNameInfo != null) + Debug.Assert(_serWriter is not null); + if (memberNameInfo is not null) { memberNameInfo._objectId = objectInfo._objectId; _serWriter.WriteObject(memberNameInfo, typeNameInfo, numItems, memberNames, memberTypes, memberObjectInfos); @@ -220,7 +220,7 @@ private void Write(WriteObjectInfo objectInfo, _serWriter.WriteObject(typeNameInfo, null, numItems, memberNames, memberTypes, memberObjectInfos); } - Debug.Assert(memberNameInfo != null); + Debug.Assert(memberNameInfo is not null); if (memberNameInfo._isParentTypeOnObject) { memberNameInfo._transmitTypeOnObject = true; @@ -237,7 +237,7 @@ private void Write(WriteObjectInfo objectInfo, WriteMemberSetup(objectInfo, memberNameInfo, typeNameInfo, memberNames[i], memberTypes[i], memberData[i], memberObjectInfos[i]); } - if (memberNameInfo != null) + if (memberNameInfo is not null) { memberNameInfo._objectId = objectInfo._objectId; _serWriter.WriteObjectEnd(memberNameInfo, typeNameInfo); @@ -258,7 +258,7 @@ private void WriteMemberSetup(WriteObjectInfo objectInfo, { NameInfo newMemberNameInfo = MemberToNameInfo(memberName); // newMemberNameInfo contains the member type - if (memberObjectInfo != null) + if (memberObjectInfo is not null) { newMemberNameInfo._assemId = memberObjectInfo._assemId; } @@ -266,7 +266,7 @@ private void WriteMemberSetup(WriteObjectInfo objectInfo, // newTypeNameInfo contains the data type NameInfo newTypeNameInfo; - if (memberObjectInfo == null) + if (memberObjectInfo is null) { newTypeNameInfo = TypeToNameInfo(memberType); } @@ -298,7 +298,7 @@ private void WriteMembers(NameInfo memberNameInfo, // The member object of type is ISerializable and // Binary - Types always transmitted. - if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType!) != null) + if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType!) is not null) { memberTypeNameInfo._transmitTypeOnMember = true; memberNameInfo._transmitTypeOnMember = true; @@ -334,7 +334,7 @@ private void WriteMembers(NameInfo memberNameInfo, { assignUniqueIdToValueType = true; memberType = GetType(memberData!); - if (memberObjectInfo == null) + if (memberObjectInfo is null) { TypeToNameInfo(memberType, memberTypeNameInfo); } @@ -344,7 +344,7 @@ private void WriteMembers(NameInfo memberNameInfo, } } - if (memberObjectInfo != null && memberObjectInfo._isArray) + if (memberObjectInfo is not null && memberObjectInfo._isArray) { // outObj is an array. It can never be a value type. long arrayId = Schedule(outObj, false, null, memberObjectInfo); @@ -356,7 +356,7 @@ private void WriteMembers(NameInfo memberNameInfo, } else { - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); // Nested Array _serWriter.WriteMemberNested(memberNameInfo); @@ -370,7 +370,7 @@ private void WriteMembers(NameInfo memberNameInfo, if (!WriteKnownValueClass(memberNameInfo, memberTypeNameInfo, memberData!)) { - if (outType == null) + if (outType is null) { outType = GetType(outObj); } @@ -378,7 +378,7 @@ private void WriteMembers(NameInfo memberNameInfo, long memberObjectId = Schedule(outObj, assignUniqueIdToValueType, outType, memberObjectInfo); if (memberObjectId < 0) { - Debug.Assert(memberObjectInfo != null); + Debug.Assert(memberObjectInfo is not null); // Nested object memberObjectInfo._objectId = memberObjectId; NameInfo newTypeNameInfo = TypeToNameInfo(memberObjectInfo); @@ -400,7 +400,7 @@ private void WriteMembers(NameInfo memberNameInfo, private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, WriteObjectInfo? memberObjectInfo) { bool isAllocatedMemberNameInfo = false; - if (memberNameInfo == null) + if (memberNameInfo is null) { memberNameInfo = TypeToNameInfo(objectInfo); isAllocatedMemberNameInfo = true; @@ -421,12 +421,12 @@ private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, Wr WriteObjectInfo? arrayElemObjectInfo = null; if (!arrayElemType.IsPrimitive) { - Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null); + Debug.Assert(_serObjectInfoInit is not null && _formatterConverter is not null); arrayElemObjectInfo = WriteObjectInfo.Serialize(arrayElemType, _surrogates, _context, _serObjectInfoInit, _formatterConverter, _binder); arrayElemObjectInfo._assemId = GetAssemblyId(arrayElemObjectInfo); } - NameInfo arrayElemTypeNameInfo = arrayElemObjectInfo == null ? + NameInfo arrayElemTypeNameInfo = arrayElemObjectInfo is null ? TypeToNameInfo(arrayElemType) : TypeToNameInfo(arrayElemObjectInfo); arrayElemTypeNameInfo._isArray = arrayElemTypeNameInfo._type!.IsArray; @@ -466,7 +466,7 @@ private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, Wr } arrayElemTypeNameInfo._arrayEnum = arrayEnum; - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); // Byte array if ((ReferenceEquals(arrayElemType, Converter.s_typeofByte)) && (rank == 1) && (lowerBoundA[0] == 0)) { @@ -474,7 +474,7 @@ private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, Wr return; } - if (ReferenceEquals(arrayElemType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(arrayElemType) != null) + if (ReferenceEquals(arrayElemType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(arrayElemType) is not null) { memberNameInfo._transmitTypeOnMember = true; arrayElemTypeNameInfo._transmitTypeOnMember = true; @@ -506,7 +506,7 @@ private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, Wr int upperBound = upperBoundA[0] + 1; for (int i = lowerBoundA[0]; i < upperBound; i++) { - if (objectA == null) + if (objectA is null) { WriteArrayMember(objectInfo, arrayElemTypeNameInfo, array.GetValue(i)); } @@ -599,7 +599,7 @@ private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemType if (isObjectOnMember) { // Object array, need type of member - if (dataType == null) + if (dataType is null) { dataType = GetType(data!); } @@ -629,10 +629,10 @@ private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemType actualTypeInfo._objectId = arrayId; if (arrayId < 1) { - Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null); + Debug.Assert(_serObjectInfoInit is not null && _formatterConverter is not null); WriteObjectInfo newObjectInfo = WriteObjectInfo.Serialize(obj, _surrogates, _context, _serObjectInfoInit, _formatterConverter, this, _binder); newObjectInfo._objectId = arrayId; - newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type!) == null ? + newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type!) is null ? actualTypeInfo._assemId : GetAssemblyId(newObjectInfo); NameInfo typeNameInfo = TypeToNameInfo(newObjectInfo); @@ -643,7 +643,7 @@ private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemType } else { - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); _serWriter.WriteItemObjectRef(arrayElemTypeNameInfo, (int)arrayId); } } @@ -659,7 +659,7 @@ private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Ar int[] currentA = new int[rank]; int[]? indexMap = null; bool isLowerBound = false; - if (lowerBoundA != null) + if (lowerBoundA is not null) { for (int i = 0; i < rank; i++) { @@ -733,7 +733,7 @@ private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Ar // A WriteObjectInfo is queued if this object was a member of another object object? realObj = obj is WriteObjectInfo ? ((WriteObjectInfo)obj)._obj : obj; - Debug.Assert(realObj != null); + Debug.Assert(realObj is not null); objID = _idGenerator!.HasId(realObj, out isNew); if (isNew) { @@ -754,9 +754,9 @@ private long InternalGetId(object obj, bool assignUniqueIdToValueType, Type? typ isNew = false; return _previousId; } - Debug.Assert(_idGenerator != null); + Debug.Assert(_idGenerator is not null); _idGenerator._currentCount = _currentId; - if (type != null && type.IsValueType) + if (type is not null && type.IsValueType) { if (!assignUniqueIdToValueType) { @@ -783,13 +783,13 @@ private long Schedule(object obj, bool assignUniqueIdToValueType, Type? type) => private long Schedule(object obj, bool assignUniqueIdToValueType, Type? type, WriteObjectInfo? objectInfo) { long id = 0; - if (obj != null) + if (obj is not null) { bool isNew; id = InternalGetId(obj, assignUniqueIdToValueType, type, out isNew); if (isNew && id > 0) { - Debug.Assert(_objectQueue != null); + Debug.Assert(_objectQueue is not null); _objectQueue.Enqueue(objectInfo ?? obj); } } @@ -811,7 +811,7 @@ private bool WriteKnownValueClass(NameInfo memberNameInfo, NameInfo typeNameInfo } else { - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); if (typeNameInfo._isArray) // null if an array { _serWriter.WriteItem(memberNameInfo, typeNameInfo, data); @@ -846,7 +846,7 @@ private void WriteString(NameInfo memberNameInfo, NameInfo typeNameInfo, object if ((isFirstTime) || (stringId < 0)) { - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); _serWriter.WriteMemberString(memberNameInfo, typeNameInfo, (string)stringObject); } else @@ -858,7 +858,7 @@ private void WriteString(NameInfo memberNameInfo, NameInfo typeNameInfo, object // Writes a null member into the stream private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo, object? data) { - bool isNull = data == null; + bool isNull = data is null; // Optimization, Null members are only written for Binary if ((isNull) && (((_formatterEnums._serializerTypeEnum == InternalSerializerTypeE.Binary)) || @@ -868,7 +868,7 @@ private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, N objectInfo._isSi || (CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways)))) { - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); if (typeNameInfo._isArrayItem) { if (typeNameInfo._arrayEnum == InternalArrayTypeE.Single) @@ -897,7 +897,7 @@ private void WriteSerializedStreamHeader(long topId, long headerId) => // Transforms a type to the serialized string form. URT Primitive types are converted to XMLData Types private NameInfo TypeToNameInfo(Type? type, WriteObjectInfo? objectInfo, InternalPrimitiveTypeE code, NameInfo? nameInfo) { - if (nameInfo == null) + if (nameInfo is null) { nameInfo = GetNameInfo(); } @@ -908,7 +908,7 @@ private NameInfo TypeToNameInfo(Type? type, WriteObjectInfo? objectInfo, Interna if (code == InternalPrimitiveTypeE.Invalid) { - if (objectInfo != null) + if (objectInfo is not null) { nameInfo.NIname = objectInfo.GetTypeFullName(); nameInfo._assemId = objectInfo._assemId; @@ -961,7 +961,7 @@ internal InternalPrimitiveTypeE ToCode(Type? type) private long GetAssemblyId(WriteObjectInfo objectInfo) { //use objectInfo to get assembly string with new criteria - if (_assemblyToIdTable == null) + if (_assemblyToIdTable is null) { _assemblyToIdTable = new Dictionary(); } @@ -997,7 +997,7 @@ private long GetAssemblyId(WriteObjectInfo objectInfo) _assemblyToIdTable[assemblyString] = assemId; } - Debug.Assert(_serWriter != null); + Debug.Assert(_serWriter is not null); _serWriter.WriteAssembly(objectInfo._objectType, serializedAssemblyString, (int)assemId, isNew); } return assemId; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs index 07ded6d66157ef..c65d68db5fdc87 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs @@ -156,7 +156,7 @@ internal void Run() while (!isData) { ObjectProgress? op = (ObjectProgress?)_stack.Peek(); - if (op == null) + if (op is null) { // No more object on stack, then the next record is a top level object _expectedType = BinaryTypeEnum.ObjectUrt; @@ -290,7 +290,7 @@ internal void ReadAssembly(BinaryHeaderEnum binaryHeaderEnum) crossAppDomainAssembly.Read(this); record._assemId = crossAppDomainAssembly._assemId; record._assemblyString = _objectReader.CrossAppDomainArray(crossAppDomainAssembly._assemblyIndex) as string; - if (record._assemblyString == null) + if (record._assemblyString is null) { throw new SerializationException(SR.Format(SR.Serialization_CrossAppDomainError, "String", crossAppDomainAssembly._assemblyIndex)); } @@ -305,14 +305,14 @@ internal void ReadAssembly(BinaryHeaderEnum binaryHeaderEnum) private void ReadObject() { - if (_binaryObject == null) + if (_binaryObject is null) { _binaryObject = new BinaryObject(); } _binaryObject.Read(this); ObjectMap? objectMap = (ObjectMap?)ObjectMapIdTable[_binaryObject._mapId]; - if (objectMap == null) + if (objectMap is null) { throw new SerializationException(SR.Format(SR.Serialization_Map, _binaryObject._mapId)); } @@ -328,7 +328,7 @@ private void ReadObject() op._typeInformationA = objectMap._typeInformationA; op._memberLength = op._binaryTypeEnumA.Length; ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek(); - if ((objectOp == null) || (objectOp._isInitial)) + if ((objectOp is null) || (objectOp._isInitial)) { // Non-Nested Object op._name = objectMap._objectName; @@ -397,7 +397,7 @@ internal void ReadCrossAppDomainMap() internal void ReadObjectWithMap(BinaryHeaderEnum binaryHeaderEnum) { - if (_bowm == null) + if (_bowm is null) { _bowm = new BinaryObjectWithMap(binaryHeaderEnum); } @@ -425,7 +425,7 @@ private void ReadObjectWithMap(BinaryObjectWithMap record) assemblyInfo = ((BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId]); - if (assemblyInfo == null) + if (assemblyInfo is null) { throw new SerializationException(SR.Format(SR.Serialization_Assembly, record._assemId + " " + record._name)); } @@ -435,10 +435,10 @@ private void ReadObjectWithMap(BinaryObjectWithMap record) assemblyInfo = SystemAssemblyInfo; //Urt assembly } - Debug.Assert(record._name != null && record._memberNames != null); + Debug.Assert(record._name is not null && record._memberNames is not null); Type? objectType = _objectReader.GetType(assemblyInfo!, record._name); - Debug.Assert(objectType != null); + Debug.Assert(objectType is not null); ObjectMap objectMap = ObjectMap.Create(record._name, objectType, record._memberNames, _objectReader, record._objectId, assemblyInfo!); ObjectMapIdTable[record._objectId] = objectMap; @@ -451,7 +451,7 @@ private void ReadObjectWithMap(BinaryObjectWithMap record) ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek(); - if ((objectOp == null) || (objectOp._isInitial)) + if ((objectOp is null) || (objectOp._isInitial)) { // Non-Nested Object op._name = record._name; @@ -497,7 +497,7 @@ private void ReadObjectWithMap(BinaryObjectWithMap record) internal void ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum) { - if (_bowmt == null) + if (_bowmt is null) { _bowmt = new BinaryObjectWithMapTyped(binaryHeaderEnum); } @@ -524,7 +524,7 @@ private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) } assemblyInfo = (BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId]; - if (assemblyInfo == null) + if (assemblyInfo is null) { throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._assemId + " " + record._name)); } @@ -534,7 +534,7 @@ private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) assemblyInfo = SystemAssemblyInfo; // Urt assembly } - Debug.Assert(record._name != null && record._memberNames != null && record._binaryTypeEnumA != null && record._typeInformationA != null && record._memberAssemIds != null); + Debug.Assert(record._name is not null && record._memberNames is not null && record._binaryTypeEnumA is not null && record._typeInformationA is not null && record._memberAssemIds is not null); ObjectMap objectMap = ObjectMap.Create(record._name, record._memberNames, record._binaryTypeEnumA, record._typeInformationA, record._memberAssemIds, _objectReader, record._objectId, assemblyInfo!, AssemIdToAssemblyTable); ObjectMapIdTable[record._objectId] = objectMap; op._objectTypeEnum = InternalObjectTypeE.Object; @@ -546,7 +546,7 @@ private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek(); - if ((objectOp == null) || (objectOp._isInitial)) + if ((objectOp is null) || (objectOp._isInitial)) { // Non-Nested Object op._name = record._name; @@ -591,7 +591,7 @@ private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) { - if (_objectString == null) + if (_objectString is null) { _objectString = new BinaryObjectString(); } @@ -602,13 +602,13 @@ private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) } else { - if (_crossAppDomainString == null) + if (_crossAppDomainString is null) { _crossAppDomainString = new BinaryCrossAppDomainString(); } _crossAppDomainString.Read(this); _objectString._value = _objectReader.CrossAppDomainArray(_crossAppDomainString._value) as string; - if (_objectString._value == null) + if (_objectString._value is null) { throw new SerializationException(SR.Format(SR.Serialization_CrossAppDomainError, "String", _crossAppDomainString._value)); } @@ -635,7 +635,7 @@ private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) PRs._dtTypeCode = InternalPrimitiveTypeE.Invalid; PRs._varValue = _objectString._value; //Need to set it because ObjectReader is picking up value from variant, not pr.PRvalue - if (objectOp == null) + if (objectOp is null) { // Top level String PRs._parseTypeEnum = InternalParseTypeE.Object; @@ -667,7 +667,7 @@ private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) private void ReadMemberPrimitiveTyped() { - if (_memberPrimitiveTyped == null) + if (_memberPrimitiveTyped is null) { _memberPrimitiveTyped = new MemberPrimitiveTyped(); } @@ -682,7 +682,7 @@ private void ReadMemberPrimitiveTyped() PRs._dtType = Converter.ToType(_memberPrimitiveTyped._primitiveTypeEnum); PRs._dtTypeCode = _memberPrimitiveTyped._primitiveTypeEnum; - if (objectOp == null) + if (objectOp is null) { // Top level boxed primitive PRs._parseTypeEnum = InternalParseTypeE.Object; @@ -739,7 +739,7 @@ private void ReadArray(BinaryHeaderEnum binaryHeaderEnum) op._typeInformation = record._typeInformation; ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek(); - if ((objectOp == null) || (record._objectId > 0)) + if ((objectOp is null) || (record._objectId > 0)) { // Non-Nested Object op._name = "System.Array"; @@ -798,14 +798,14 @@ private void ReadArray(BinaryHeaderEnum binaryHeaderEnum) pr._lowerBoundA = record._lowerBoundA; bool isPrimitiveArray = false; - Debug.Assert(record._lengthA != null); + Debug.Assert(record._lengthA is not null); switch (record._binaryArrayTypeEnum) { case BinaryArrayTypeEnum.Single: case BinaryArrayTypeEnum.SingleOffset: op._numItems = record._lengthA[0]; pr._arrayTypeEnum = InternalArrayTypeE.Single; - Debug.Assert(record._lowerBoundA != null); + Debug.Assert(record._lowerBoundA is not null); if (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode) && (record._lowerBoundA[0] == 0)) { @@ -850,7 +850,7 @@ private void ReadArray(BinaryHeaderEnum binaryHeaderEnum) private void ReadArrayAsBytes(ParseRecord pr) { - Debug.Assert(pr._lengthA != null); + Debug.Assert(pr._lengthA is not null); if (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Byte) { pr._newObj = ReadBytes(pr._lengthA[0]); @@ -864,11 +864,11 @@ private void ReadArrayAsBytes(ParseRecord pr) int typeLength = Converter.TypeLength(pr._arrayElementTypeCode); pr._newObj = Converter.CreatePrimitiveArray(pr._arrayElementTypeCode, pr._lengthA[0]); - Debug.Assert((pr._newObj != null), "[BinaryParser expected a Primitive Array]"); + Debug.Assert((pr._newObj is not null), "[BinaryParser expected a Primitive Array]"); Array array = (Array)pr._newObj; int arrayOffset = 0; - if (_byteBuffer == null) + if (_byteBuffer is null) { _byteBuffer = new byte[ChunkSize]; } @@ -901,7 +901,7 @@ private void ReadArrayAsBytes(ParseRecord pr) private void ReadMemberPrimitiveUnTyped() { ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek(); - if (memberPrimitiveUnTyped == null) + if (memberPrimitiveUnTyped is null) { memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); } @@ -916,7 +916,7 @@ private void ReadMemberPrimitiveUnTyped() PRs._parseTypeEnum = InternalParseTypeE.Member; PRs._memberValueEnum = InternalMemberValueE.InlineValue; - Debug.Assert(objectOp != null); + Debug.Assert(objectOp is not null); if (objectOp._objectTypeEnum == InternalObjectTypeE.Object) { PRs._memberTypeEnum = InternalMemberTypeE.Field; @@ -932,7 +932,7 @@ private void ReadMemberPrimitiveUnTyped() private void ReadMemberReference() { - if (_memberReference == null) + if (_memberReference is null) { _memberReference = new MemberReference(); } @@ -945,7 +945,7 @@ private void ReadMemberReference() PRs._parseTypeEnum = InternalParseTypeE.Member; PRs._memberValueEnum = InternalMemberValueE.Reference; - Debug.Assert(objectOp != null); + Debug.Assert(objectOp is not null); if (objectOp._objectTypeEnum == InternalObjectTypeE.Object) { PRs._memberTypeEnum = InternalMemberTypeE.Field; @@ -962,7 +962,7 @@ private void ReadMemberReference() private void ReadObjectNull(BinaryHeaderEnum binaryHeaderEnum) { - if (_objectNull == null) + if (_objectNull is null) { _objectNull = new ObjectNull(); } @@ -974,7 +974,7 @@ private void ReadObjectNull(BinaryHeaderEnum binaryHeaderEnum) PRs._parseTypeEnum = InternalParseTypeE.Member; PRs._memberValueEnum = InternalMemberValueE.Null; - Debug.Assert(objectOp != null); + Debug.Assert(objectOp is not null); if (objectOp._objectTypeEnum == InternalObjectTypeE.Object) { PRs._memberTypeEnum = InternalMemberTypeE.Field; @@ -994,7 +994,7 @@ private void ReadObjectNull(BinaryHeaderEnum binaryHeaderEnum) private void ReadMessageEnd() { - if (_messageEnd == null) + if (_messageEnd is null) { _messageEnd = new MessageEnd(); } @@ -1032,7 +1032,7 @@ private ObjectProgress GetOp() { ObjectProgress op; - if (_opPool != null && !_opPool.IsEmpty()) + if (_opPool is not null && !_opPool.IsEmpty()) { op = (ObjectProgress)_opPool.Pop()!; op.Init(); @@ -1047,7 +1047,7 @@ private ObjectProgress GetOp() private void PutOp(ObjectProgress op) { - if (_opPool == null) + if (_opPool is null) { _opPool = new SerStack("opPool"); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs index 9dbe26f1fdd7e7..dd00c129ba5589 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs @@ -21,7 +21,7 @@ internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? obj { binaryTypeEnum = BinaryTypeEnum.String; } - else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject))) + else if (((objectInfo is null) || ((objectInfo is not null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject))) { // If objectInfo.Si then can be a surrogate which will change the type binaryTypeEnum = BinaryTypeEnum.Object; @@ -45,7 +45,7 @@ internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? obj { case InternalPrimitiveTypeE.Invalid: string? assembly = null; - if (objectInfo == null) + if (objectInfo is null) { assembly = type.Assembly.FullName; typeInformation = type.FullName; @@ -56,7 +56,7 @@ internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? obj typeInformation = objectInfo.GetTypeFullName(); } - Debug.Assert(assembly != null); + Debug.Assert(assembly is not null); if (assembly.Equals(Converter.s_urtAssemblyString) || assembly.Equals(Converter.s_urtAlternativeAssemblyString)) { binaryTypeEnum = BinaryTypeEnum.ObjectUrt; @@ -65,7 +65,7 @@ internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? obj else { binaryTypeEnum = BinaryTypeEnum.ObjectUser; - Debug.Assert(objectInfo != null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object"); + Debug.Assert(objectInfo is not null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object"); assemId = (int)objectInfo._assemId; if (assemId == 0) { @@ -137,7 +137,7 @@ internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object? typeIn { case BinaryTypeEnum.Primitive: case BinaryTypeEnum.PrimitiveArray: - Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); + Debug.Assert(typeInformation is not null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); output.WriteByte((byte)((InternalPrimitiveTypeE)typeInformation)); break; case BinaryTypeEnum.String: @@ -146,11 +146,11 @@ internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object? typeIn case BinaryTypeEnum.ObjectArray: break; case BinaryTypeEnum.ObjectUrt: - Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); + Debug.Assert(typeInformation is not null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); output.WriteString(typeInformation.ToString()!); break; case BinaryTypeEnum.ObjectUser: - Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); + Debug.Assert(typeInformation is not null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); output.WriteString(typeInformation.ToString()!); output.WriteInt32(assemId); break; @@ -231,7 +231,7 @@ internal static void TypeFromInfo(BinaryTypeEnum binaryTypeEnum, break; case BinaryTypeEnum.ObjectUser: case BinaryTypeEnum.ObjectUrt: - if (typeInformation != null) + if (typeInformation is not null) { typeString = typeInformation.ToString(); type = objectReader.GetType(assemblyInfo!, typeString!); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryUtilClasses.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryUtilClasses.cs index ef67ed5d6dc8e4..dcff57ebe684f4 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryUtilClasses.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryUtilClasses.cs @@ -407,7 +407,7 @@ internal void Fixup(ParseRecord record, ParseRecord parent) case ValueFixupEnum.Header: throw new PlatformNotSupportedException(); case ValueFixupEnum.Member: - Debug.Assert(_objectInfo!._objectManager != null); + Debug.Assert(_objectInfo!._objectManager is not null); if (_objectInfo._isSi) { _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName!, record._objectId); @@ -415,7 +415,7 @@ internal void Fixup(ParseRecord record, ParseRecord parent) else { MemberInfo? memberInfo = _objectInfo.GetMemberInfo(_memberName); - if (memberInfo != null) + if (memberInfo is not null) { _objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId); } @@ -475,7 +475,7 @@ public bool IsSealed { if (!_sealedStatusChecked) { - Debug.Assert(_type != null); + Debug.Assert(_type is not null); _isSealed = _type.IsSealed; _sealedStatusChecked = true; } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/Converter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/Converter.cs index 6afada7f23ce36..6e8affddfac855 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/Converter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/Converter.cs @@ -71,7 +71,7 @@ internal static class Converter private static volatile InternalPrimitiveTypeE[]? s_codeA; internal static InternalPrimitiveTypeE ToCode(Type? type) => - type == null ? ToPrimitiveTypeEnum(TypeCode.Empty) : + type is null ? ToPrimitiveTypeEnum(TypeCode.Empty) : type.IsPrimitive ? ToPrimitiveTypeEnum(Type.GetTypeCode(type)) : ReferenceEquals(type, s_typeofDateTime) ? InternalPrimitiveTypeE.DateTime : ReferenceEquals(type, s_typeofTimeSpan) ? InternalPrimitiveTypeE.TimeSpan : @@ -120,7 +120,7 @@ internal static int TypeLength(InternalPrimitiveTypeE code) => internal static Type? ToArrayType(InternalPrimitiveTypeE code) { - if (s_arrayTypeA == null) + if (s_arrayTypeA is null) { InitArrayTypeA(); } @@ -173,7 +173,7 @@ private static void InitArrayTypeA() internal static Type? ToType(InternalPrimitiveTypeE code) { - if (s_typeA == null) + if (s_typeA is null) { InitTypeA(); } @@ -248,7 +248,7 @@ private static void InitValueA() internal static string? ToComType(InternalPrimitiveTypeE code) { - if (s_valueA == null) + if (s_valueA is null) { InitValueA(); } @@ -280,7 +280,7 @@ private static void InitTypeCodeA() // Returns a System.TypeCode from a InternalPrimitiveTypeE internal static TypeCode ToTypeCode(InternalPrimitiveTypeE code) { - if (s_typeCodeA == null) + if (s_typeCodeA is null) { InitTypeCodeA(); } @@ -315,7 +315,7 @@ private static void InitCodeA() // Returns a InternalPrimitiveTypeE from a System.TypeCode internal static InternalPrimitiveTypeE ToPrimitiveTypeEnum(TypeCode typeCode) { - if (s_codeA == null) + if (s_codeA is null) { InitCodeA(); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs index 1a3d907c92bf96..42b71f0f0c31b4 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs @@ -55,7 +55,7 @@ internal ObjectMap(string objectName, string[] memberNames, BinaryTypeEnum[] bin _objectId = objectId; _assemblyInfo = assemblyInfo; - if (assemblyInfo == null) + if (assemblyInfo is null) { throw new SerializationException(SR.Format(SR.Serialization_Assembly, objectName)); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.cs index dfeb372b8a9fda..e6cb6ba54852ea 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.cs @@ -107,7 +107,7 @@ internal bool GetNext(out BinaryTypeEnum outBinaryTypeEnum, out object? outTypeI } else { - Debug.Assert(_binaryTypeEnumA != null && _typeInformationA != null && _memberNames != null && _memberTypes != null); + Debug.Assert(_binaryTypeEnumA is not null && _typeInformationA is not null && _memberNames is not null && _memberTypes is not null); outBinaryTypeEnum = _binaryTypeEnumA[_count]; outTypeInformation = _typeInformationA[_count]; if (_count == 0) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs index 704cbe4aafcc85..9f5383cf7644ae 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs @@ -39,7 +39,7 @@ private int FindElement(object obj, out bool found) int pos = ((hashcode & 0x7FFFFFFF) % _currentSize) * NumBins; for (int i = pos; i < pos + NumBins; i++) { - if (_objs[i] == null) + if (_objs[i] is null) { found = false; return i; @@ -63,7 +63,7 @@ private int FindElement(object obj, out bool found) // is set to true if this is the first time that we have seen this object. public virtual long GetId(object obj, out bool firstTime) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } @@ -98,7 +98,7 @@ public virtual long GetId(object obj, out bool firstTime) // we return that id, otherwise we return 0. public virtual long HasId(object obj, out bool firstTime) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } @@ -140,7 +140,7 @@ private void Rehash() for (int j = 0; j < oldObjs.Length; j++) { - if (oldObjs[j] != null) + if (oldObjs[j] is not null) { int pos = FindElement(oldObjs[j], out _); _objs[pos] = oldObjs[j]; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs index c42125527494e8..b144bb85eaddd8 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs @@ -57,7 +57,7 @@ internal object? TopObject // Walk the chain in that bin. Return the ObjectHolder if we find it, otherwise // return null. - while (temp != null) + while (temp is not null) { if (temp._id == objectID) { @@ -72,7 +72,7 @@ internal object? TopObject internal ObjectHolder FindOrCreateObjectHolder(long objectID) { ObjectHolder? holder = FindObjectHolder(objectID); - if (holder == null) + if (holder is null) { holder = new ObjectHolder(objectID); AddObjectHolder(holder); @@ -82,7 +82,7 @@ internal ObjectHolder FindOrCreateObjectHolder(long objectID) private void AddObjectHolder(ObjectHolder holder) { - Debug.Assert(holder != null, "holder!=null"); + Debug.Assert(holder is not null, "holder!=null"); Debug.Assert(holder._id >= 0, "holder.m_id>=0"); //If the id that we need to place is greater than our current length, and less @@ -132,11 +132,11 @@ private bool GetCompletionInfo(FixupHolder fixup, [NotNullWhen(true)] out Object //Find the object required for the fixup. Throw if we can't find it. holder = FindObjectHolder(fixup._id); - if (holder == null || holder.CanObjectValueChange || holder.ObjectValue == null) + if (holder is null || holder.CanObjectValueChange || holder.ObjectValue is null) { if (bThrowIfMissing) { - if (holder == null) + if (holder is null) { throw new SerializationException(SR.Format(SR.Serialization_NeverSeen, fixup._id)); } @@ -154,7 +154,7 @@ private bool GetCompletionInfo(FixupHolder fixup, [NotNullWhen(true)] out Object // ISerializable. In that case, we can't do any fixups on them later, so we need to delay the fixups further. if (!holder.CompletelyFixed) { - if (holder.ObjectValue != null && holder.ObjectValue is ValueType) + if (holder.ObjectValue is not null && holder.ObjectValue is ValueType) { SpecialFixupObjects.Add(holder); return false; @@ -172,10 +172,10 @@ private void FixupSpecialObject(ObjectHolder holder) if (holder.HasSurrogate) { ISerializationSurrogate? surrogate = holder.Surrogate; - Debug.Assert(surrogate != null, "surrogate!=null"); - Debug.Assert(holder.SerializationInfo != null); + Debug.Assert(surrogate is not null, "surrogate!=null"); + Debug.Assert(holder.SerializationInfo is not null); object? returnValue = surrogate.SetObjectData(holder.ObjectValue!, holder.SerializationInfo, _context, uselessSelector); - if (returnValue != null) + if (returnValue is not null) { if (!holder.CanSurrogatedObjectValueChange && returnValue != holder.ObjectValue) { @@ -235,12 +235,12 @@ private bool ResolveObjectReference(ObjectHolder holder) do { tempObject = holder.ObjectValue; - Debug.Assert(holder.ObjectValue != null); + Debug.Assert(holder.ObjectValue is not null); holder.SetObjectValue(((IObjectReference)(holder.ObjectValue)).GetRealObject(_context), this); //The object didn't yet have enough information to resolve the reference, so we'll //return false and the graph walker should call us back again after more objects have //been resolved. - if (holder.ObjectValue == null) + if (holder.ObjectValue is null) { holder.SetObjectValue(tempObject, this); return false; @@ -276,7 +276,7 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec ValueTypeFixupInfo currFixup; object? fixupObj = holder.ObjectValue; - Debug.Assert(holder != null, "[TypedReferenceBuilder.ctor]holder!=null"); + Debug.Assert(holder is not null, "[TypedReferenceBuilder.ctor]holder!=null"); Debug.Assert(holder.RequiresValueTypeFixup, "[TypedReferenceBuilder.ctor]holder.RequiresValueTypeFixup"); //In order to get a TypedReference, we need to get a list of all of the FieldInfos to @@ -300,17 +300,17 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec //down the chain, so we have to do a lot of caching. currFixup = holder.ValueFixup!; fixupObj = holder.ObjectValue; //Save the most derived - if (currFixup.ParentField != null) + if (currFixup.ParentField is not null) { FieldInfo parentField = currFixup.ParentField; ObjectHolder? tempHolder = FindObjectHolder(currFixup.ContainerID); - Debug.Assert(tempHolder != null); - if (tempHolder.ObjectValue == null) + Debug.Assert(tempHolder is not null); + if (tempHolder.ObjectValue is null) { break; } - if (Nullable.GetUnderlyingType(parentField.FieldType) != null) + if (Nullable.GetUnderlyingType(parentField.FieldType) is not null) { fieldsTemp[currentFieldIndex] = parentField.FieldType.GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance)!; currentFieldIndex++; @@ -323,7 +323,7 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec else { //If we find an index into an array, save that information. - Debug.Assert(currFixup.ParentIndex != null, "[ObjectManager.DoValueTypeFixup]currFixup.ParentIndex!=null"); + Debug.Assert(currFixup.ParentIndex is not null, "[ObjectManager.DoValueTypeFixup]currFixup.ParentIndex!=null"); holder = FindObjectHolder(currFixup.ContainerID)!; //find the array to fix. arrayIndex = currFixup.ParentIndex; break; @@ -333,10 +333,10 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec //If the outermost container isn't an array, we need to grab it. Otherwise, we just need to hang onto //the boxed object that we already grabbed. We'll assign the boxed object back into the array as the //last step. - if (!(holder.ObjectValue is Array) && holder.ObjectValue != null) + if (!(holder.ObjectValue is Array) && holder.ObjectValue is not null) { fixupObj = holder.ObjectValue; - Debug.Assert(fixupObj != null, "[ObjectManager.DoValueTypeFixup]FixupObj!=null"); + Debug.Assert(fixupObj is not null, "[ObjectManager.DoValueTypeFixup]FixupObj!=null"); } if (currentFieldIndex != 0) @@ -349,13 +349,13 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec { FieldInfo? fieldInfo = fieldsTemp[(currentFieldIndex - 1 - i)]; SerializationFieldInfo? serInfo = fieldInfo as SerializationFieldInfo; - fields[i] = serInfo == null ? fieldInfo : serInfo.FieldInfo; + fields[i] = serInfo is null ? fieldInfo : serInfo.FieldInfo; } - Debug.Assert(fixupObj != null, "[ObjectManager.DoValueTypeFixup]fixupObj!=null"); + Debug.Assert(fixupObj is not null, "[ObjectManager.DoValueTypeFixup]fixupObj!=null"); //Make the TypedReference and use it to set the value. TypedReference typedRef = TypedReference.MakeTypedReference(fixupObj, fields); - if (memberToFix != null) + if (memberToFix is not null) { memberToFix.SetValueDirect(typedRef, value!); } @@ -364,14 +364,14 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec TypedReference.SetTypedReference(typedRef, value); } } - else if (memberToFix != null) + else if (memberToFix is not null) { FormatterServices.SerializationSetValue(memberToFix, fixupObj, value); } //If we have an array index, it means that our outermost container was an array. We don't have //any way to build a TypedReference into an array, so we'll use the array functions to set the value. - if (arrayIndex != null && holder.ObjectValue != null) + if (arrayIndex is not null && holder.ObjectValue is not null) { ((Array)(holder.ObjectValue)).SetValue(fixupObj, arrayIndex); } @@ -388,13 +388,13 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) ObjectHolder? tempObjectHolder = null; int fixupsPerformed = 0; - Debug.Assert(holder != null, "[ObjectManager.CompleteObject]holder.m_object!=null"); - if (holder.ObjectValue == null) + Debug.Assert(holder is not null, "[ObjectManager.CompleteObject]holder.m_object!=null"); + if (holder.ObjectValue is null) { throw new SerializationException(SR.Format(SR.Serialization_MissingObject, holder._id)); } - if (fixups == null) + if (fixups is null) { return; } @@ -403,17 +403,17 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) if (holder.HasSurrogate || holder.HasISerializable) { si = holder._serInfo; - if (si == null) + if (si is null) { throw new SerializationException(SR.Serialization_InvalidFixupDiscovered); } //Walk each of the fixups and complete the name-value pair in the SerializationInfo. - if (fixups != null) + if (fixups is not null) { for (int i = 0; i < fixups._count; i++) { - if (fixups._values[i] == null) + if (fixups._values[i] is null) { continue; } @@ -423,7 +423,7 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) //Walk the SerializationInfo and find the member needing completion. All we have to do //at this point is set the member into the Object object? holderValue = tempObjectHolder.ObjectValue; - Debug.Assert(holderValue != null); + Debug.Assert(holderValue is not null); if (CanCallGetType(holderValue)) { si.UpdateValue((string)fixupInfo, holderValue, holderValue.GetType()); @@ -449,7 +449,7 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) for (int i = 0; i < fixups._count; i++) { currentFixup = fixups._values[i]; - if (currentFixup == null) + if (currentFixup is null) { continue; } @@ -564,7 +564,7 @@ private void DoNewlyRegisteredObjectFixups(ObjectHolder holder) //If we don't have any dependencies, we're done. LongList? dependencies = holder.DependentObjects; - if (dependencies == null) + if (dependencies is null) { return; } @@ -576,14 +576,14 @@ private void DoNewlyRegisteredObjectFixups(ObjectHolder holder) while (dependencies.MoveNext()) { ObjectHolder? temp = FindObjectHolder(dependencies.Current); - Debug.Assert(temp != null); + Debug.Assert(temp is not null); Debug.Assert(temp.DirectlyDependentObjects > 0, "temp.m_missingElementsRemaining>0"); temp.DecrementFixupsRemaining(this); if (((temp.DirectlyDependentObjects)) == 0) { // If this is null, we have the case where a fixup was registered for a child, the object // required by the fixup was provided, and the object to be fixed hasn't yet been seen. - if (temp.ObjectValue != null) + if (temp.ObjectValue is not null) { CompleteObject(temp, true); } @@ -605,7 +605,7 @@ private void DoNewlyRegisteredObjectFixups(ObjectHolder holder) //Find the bin in which we're interested. IObjectReference's shouldn't be returned -- the graph //needs to link to the objects to which they refer, not to the references themselves. ObjectHolder? holder = FindObjectHolder(objectID); - if (holder == null || holder.CanObjectValueChange) + if (holder is null || holder.CanObjectValueChange) { return null; } @@ -631,7 +631,7 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l internal void RegisterString(string? obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member) { ObjectHolder temp; - Debug.Assert(member == null || member is FieldInfo, "RegisterString - member is FieldInfo"); + Debug.Assert(member is null || member is FieldInfo, "RegisterString - member is FieldInfo"); temp = new ObjectHolder(obj, objectID, info, null, idOfContainingObj, (FieldInfo?)member, null); AddObjectHolder(temp); @@ -640,7 +640,7 @@ internal void RegisterString(string? obj, long objectID, SerializationInfo? info public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member, int[]? arrayIndex) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } @@ -648,7 +648,7 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l { throw new ArgumentOutOfRangeException(nameof(objectID), SR.ArgumentOutOfRange_ObjectID); } - if (member != null && !(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib + if (member is not null && !(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib { throw new SerializationException(SR.Serialization_UnknownMemberInfo); } @@ -657,7 +657,7 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l ISerializationSurrogate? surrogate = null; ISurrogateSelector useless; - if (_selector != null) + if (_selector is not null) { Type selectorType = CanCallGetType(obj) ? obj.GetType() : @@ -676,14 +676,14 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l //Formatter developers may cache and reuse arrayIndex in their code. //So that we don't get bitten by this, take a copy up front. - if (arrayIndex != null) + if (arrayIndex is not null) { arrayIndex = (int[])arrayIndex.Clone(); } //This is the first time which we've seen the object, we need to create a new holder. temp = FindObjectHolder(objectID); - if (temp == null) + if (temp is null) { temp = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex); AddObjectHolder(temp); @@ -698,7 +698,7 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l } //If the object isn't null, we've registered this before. Not good. - if (temp.ObjectValue != null) + if (temp.ObjectValue is not null) { throw new SerializationException(SR.Serialization_RegisterTwice); } @@ -752,7 +752,7 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l /// The streaming context in which the serialization is taking place. internal void CompleteISerializableObject(object obj, SerializationInfo? info, StreamingContext context) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } @@ -812,7 +812,7 @@ public virtual void DoFixups() while (fixupObjectsEnum.MoveNext()) { temp = fixupObjectsEnum.Current; - if (temp.ObjectValue == null) + if (temp.ObjectValue is null) { throw new SerializationException(SR.Format(SR.Serialization_ObjectNotSupplied, temp._id)); } @@ -853,7 +853,7 @@ public virtual void DoFixups() for (int i = 0; i < _objects.Length; i++) { temp = _objects[i]; - while (temp != null) + while (temp is not null) { if (temp.TotalDependentObjects > 0 /*|| temp.m_missingElements!=null*/) { @@ -908,7 +908,7 @@ public virtual void RecordFixup(long objectToBeFixed, MemberInfo member, long ob { throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } - if (member == null) + if (member is null) { throw new ArgumentNullException(nameof(member)); } @@ -929,7 +929,7 @@ public virtual void RecordDelayedFixup(long objectToBeFixed, string memberName, { throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } - if (memberName == null) + if (memberName is null) { throw new ArgumentNullException(nameof(memberName)); } @@ -953,7 +953,7 @@ public virtual void RecordArrayElementFixup(long arrayToBeFixed, int[] indices, { throw new ArgumentOutOfRangeException(arrayToBeFixed <= 0 ? nameof(arrayToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } - if (indices == null) + if (indices is null) { throw new ArgumentNullException(nameof(indices)); } @@ -1047,7 +1047,7 @@ internal ObjectHolder( _typeLoad = (TypeLoadExceptionHolder)obj; } - if (idOfContainingObj != 0 && ((field != null && field.FieldType.IsValueType) || arrayIndex != null)) + if (idOfContainingObj != 0 && ((field is not null && field.FieldType.IsValueType) || arrayIndex is not null)) { if (idOfContainingObj == objID) { @@ -1079,12 +1079,12 @@ internal ObjectHolder( _surrogate = surrogate; _markForFixupWhenAvailable = false; - if (idOfContainingObj != 0 && arrayIndex != null) + if (idOfContainingObj != 0 && arrayIndex is not null) { _valueFixup = new ValueTypeFixupInfo(idOfContainingObj, field, arrayIndex); } - if (_valueFixup != null) + if (_valueFixup is not null) { _flags |= REQUIRES_VALUETYPE_FIXUP; } @@ -1110,7 +1110,7 @@ internal void DecrementFixupsRemaining(ObjectManager manager) /// The id of the object for which to remove the dependency. internal void RemoveDependency(long id) { - Debug.Assert(_dependentObjects != null, "[ObjectHolder.RemoveDependency]m_dependentObjects!=null"); + Debug.Assert(_dependentObjects is not null, "[ObjectHolder.RemoveDependency]m_dependentObjects!=null"); Debug.Assert(id >= 0, "[ObjectHolder.RemoveDependency]id>=0"); _dependentObjects.RemoveElement(id); } @@ -1125,7 +1125,7 @@ internal void RemoveDependency(long id) /// The associated object manager. internal void AddFixup(FixupHolder fixup, ObjectManager manager) { - if (_missingElements == null) + if (_missingElements is null) { _missingElements = new FixupHolderList(); } @@ -1154,7 +1154,7 @@ private void UpdateDescendentDependencyChain(int amount, ObjectManager manager) do { holder = manager.FindOrCreateObjectHolder(holder.ContainerID); - Debug.Assert(holder != null, "[ObjectHolder.UpdateTotalDependencyChain]holder!=null"); + Debug.Assert(holder is not null, "[ObjectHolder.UpdateTotalDependencyChain]holder!=null"); holder.IncrementDescendentFixups(amount); } while (holder.RequiresValueTypeFixup); } @@ -1167,7 +1167,7 @@ private void UpdateDescendentDependencyChain(int amount, ObjectManager manager) /// the id of the object which is dependent on this object being provided. internal void AddDependency(long dependentObject) { - if (_dependentObjects == null) + if (_dependentObjects is null) { _dependentObjects = new LongList(); } @@ -1192,7 +1192,7 @@ internal void UpdateData( object obj, SerializationInfo? info, ISerializationSurrogate? surrogate, long idOfContainer, FieldInfo? field, int[]? arrayIndex, ObjectManager manager) { - Debug.Assert(obj != null, "obj!=null"); + Debug.Assert(obj is not null, "obj!=null"); Debug.Assert(_id > 0, "m_id>0"); //Record the fields that we can. @@ -1200,7 +1200,7 @@ internal void UpdateData( _serInfo = info; _surrogate = surrogate; - if (idOfContainer != 0 && ((field != null && field.FieldType.IsValueType) || arrayIndex != null)) + if (idOfContainer != 0 && ((field is not null && field.FieldType.IsValueType) || arrayIndex is not null)) { if (idOfContainer == _id) { @@ -1231,7 +1231,7 @@ internal void SetFlags() } _flags &= ~(HAS_ISERIALIZABLE | HAS_SURROGATE); - if (_surrogate != null) + if (_surrogate is not null) { _flags |= HAS_SURROGATE; } @@ -1240,7 +1240,7 @@ internal void SetFlags() _flags |= HAS_ISERIALIZABLE; } - if (_valueFixup != null) + if (_valueFixup is not null) { _flags |= REQUIRES_VALUETYPE_FIXUP; } @@ -1277,7 +1277,7 @@ internal bool ValueTypeFixupPerformed get { return (((_flags & VALUETYPE_FIXUP_PERFORMED) != 0) || - (_object != null && ((_dependentObjects == null) || _dependentObjects.Count == 0))); + (_object is not null && ((_dependentObjects is null) || _dependentObjects.Count == 0))); } set { @@ -1293,7 +1293,7 @@ internal bool ValueTypeFixupPerformed internal bool HasSurrogate => (_flags & HAS_SURROGATE) != 0; internal bool CanSurrogatedObjectValueChange => - (_surrogate == null || _surrogate.GetType() != typeof(SurrogateForCyclicalReference)); + (_surrogate is null || _surrogate.GetType() != typeof(SurrogateForCyclicalReference)); internal bool CanObjectValueChange => IsIncompleteObjectReference ? true : @@ -1306,7 +1306,7 @@ internal bool ValueTypeFixupPerformed internal bool Reachable { get { return _reachable; } set { _reachable = value; } } - internal bool TypeLoadExceptionReachable => _typeLoad != null; + internal bool TypeLoadExceptionReachable => _typeLoad is not null; internal TypeLoadExceptionHolder? TypeLoadException { get { return _typeLoad; } set { _typeLoad = value; } } @@ -1364,7 +1364,7 @@ internal bool RequiresSerInfoFixup internal bool CompletelyFixed => !RequiresSerInfoFixup && !IsIncompleteObjectReference; - internal long ContainerID => _valueFixup != null ? _valueFixup.ContainerID : 0; + internal long ContainerID => _valueFixup is not null ? _valueFixup.ContainerID : 0; } internal sealed class FixupHolder @@ -1380,7 +1380,7 @@ internal sealed class FixupHolder internal FixupHolder(long id, object fixupInfo, int fixupType) { Debug.Assert(id > 0, "id>0"); - Debug.Assert(fixupInfo != null, "fixupInfo!=null"); + Debug.Assert(fixupInfo is not null, "fixupInfo!=null"); Debug.Assert(fixupType == ArrayFixup || fixupType == MemberFixup || fixupType == DelayedFixup, "fixupType==ArrayFixup || fixupType == MemberFixup || fixupType==DelayedFixup"); _id = id; @@ -1569,7 +1569,7 @@ internal sealed class ObjectHolderListEnumerator internal ObjectHolderListEnumerator(ObjectHolderList list, bool isFixupEnumerator) { - Debug.Assert(list != null, "[ObjectHolderListEnumerator.ctor]list!=null"); + Debug.Assert(list is not null, "[ObjectHolderListEnumerator.ctor]list!=null"); _list = list; _startingVersion = _list.Version; _currPos = -1; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs index 1bebb7b5192081..3a4162f9540940 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs @@ -29,7 +29,7 @@ internal SerializationEvents(Type? t) // Traverse the hierarchy to find all methods with the particular attribute Type? baseType = t; - while (baseType != null && baseType != typeof(object)) + while (baseType is not null && baseType != typeof(object)) { // Get all methods which are declared on this type, instance and public or nonpublic MethodInfo[] mis = baseType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); @@ -38,7 +38,7 @@ internal SerializationEvents(Type? t) // For each method find if attribute is present, the return type is void and the method is not virtual if (m.IsDefined(attribute, false)) { - if (mi == null) mi = new List(); + if (mi is null) mi = new List(); mi.Add(m); } } @@ -50,7 +50,7 @@ internal SerializationEvents(Type? t) } internal bool HasOnSerializingEvents => - _onSerializingMethods != null || _onSerializedMethods != null; + _onSerializingMethods is not null || _onSerializedMethods is not null; internal void InvokeOnSerializing(object obj, StreamingContext context) => InvokeOnDelegate(obj, context, _onSerializingMethods); @@ -70,14 +70,14 @@ internal void InvokeOnDeserialized(object obj, StreamingContext context) => /// Invoke all methods. private static void InvokeOnDelegate(object obj, StreamingContext context, List? methods) { - Debug.Assert(obj != null, "object should have been initialized"); + Debug.Assert(obj is not null, "object should have been initialized"); AddOnDelegate(obj, null, methods)?.Invoke(context); } /// Add all methods to a delegate. private static SerializationEventHandler? AddOnDelegate(object obj, SerializationEventHandler? handler, List? methods) { - if (methods != null) + if (methods is not null) { foreach (MethodInfo m in methods) { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationFieldInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationFieldInfo.cs index 8df8c2836f17c6..0918e3c20d1b17 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationFieldInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationFieldInfo.cs @@ -14,8 +14,8 @@ internal sealed class SerializationFieldInfo : FieldInfo internal SerializationFieldInfo(FieldInfo field, string namePrefix) { - Debug.Assert(field != null); - Debug.Assert(namePrefix != null); + Debug.Assert(field is not null); + Debug.Assert(namePrefix is not null); m_field = field; m_serializationName = namePrefix + "+" + m_field.Name; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs index 39bb23890fdee1..24330936b33689 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs @@ -13,11 +13,11 @@ public class SurrogateSelector : ISurrogateSelector public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (surrogate == null) + if (surrogate is null) { throw new ArgumentNullException(nameof(surrogate)); } @@ -28,13 +28,13 @@ public virtual void AddSurrogate(Type type, StreamingContext context, ISerializa private static bool HasCycle(ISurrogateSelector selector) { - Debug.Assert(selector != null, "[HasCycle]selector!=null"); + Debug.Assert(selector is not null, "[HasCycle]selector!=null"); ISurrogateSelector? head = selector, tail = selector; - while (head != null) + while (head is not null) { head = head.GetNextSelector(); - if (head == null) + if (head is null) { return true; } @@ -58,7 +58,7 @@ private static bool HasCycle(ISurrogateSelector selector) // The logic is:"Add this onto the list as the first thing that you check after yourself." public virtual void ChainSelector(ISurrogateSelector selector) { - if (selector == null) + if (selector is null) { throw new ArgumentNullException(nameof(selector)); } @@ -79,7 +79,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) // insert for use later. ISurrogateSelector? tempCurr = selector.GetNextSelector(); ISurrogateSelector tempEnd = selector; - while (tempCurr != null && tempCurr != this) + while (tempCurr is not null && tempCurr != this) { tempEnd = tempCurr; tempCurr = tempCurr.GetNextSelector(); @@ -92,7 +92,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) // Check for a cycle later in the list which would be introduced by this insertion. tempCurr = selector; ISurrogateSelector? tempPrev = selector; - while (tempCurr != null) + while (tempCurr is not null) { if (tempCurr == tempEnd) { @@ -102,7 +102,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) { tempCurr = tempCurr.GetNextSelector(); } - if (tempCurr == null) + if (tempCurr is null) { break; } @@ -127,7 +127,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) } else { - Debug.Assert(tempPrev != null); + Debug.Assert(tempPrev is not null); tempPrev = tempPrev.GetNextSelector(); } if (tempCurr == tempPrev) @@ -139,7 +139,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) // Add the new selector and it's entire chain of selectors as the next thing that we check. ISurrogateSelector? temp = _nextSelector; _nextSelector = selector; - if (temp != null) + if (temp is not null) { tempEnd.ChainSelector(temp); } @@ -152,7 +152,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) // provide a surrogate, it checks with all of it's children before returning null. public virtual ISerializationSurrogate? GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -161,11 +161,11 @@ public virtual void ChainSelector(ISurrogateSelector selector) SurrogateKey key = new SurrogateKey(type, context); ISerializationSurrogate? temp = (ISerializationSurrogate?)_surrogates[key]; - if (temp != null) + if (temp is not null) { return temp; } - if (_nextSelector != null) + if (_nextSelector is not null) { return _nextSelector.GetSurrogate(type, context, out selector); } @@ -176,7 +176,7 @@ public virtual void ChainSelector(ISurrogateSelector selector) // check chained surrogates. public virtual void RemoveSurrogate(Type type, StreamingContext context) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -193,7 +193,7 @@ internal sealed class SurrogateKey internal SurrogateKey(Type type, StreamingContext context) { - Debug.Assert(type != null); + Debug.Assert(type is not null); _type = type; _context = context; } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ValueTypeFixupInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ValueTypeFixupInfo.cs index 7972bf41b258ce..a24c3eeb2d355d 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ValueTypeFixupInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ValueTypeFixupInfo.cs @@ -32,12 +32,12 @@ public ValueTypeFixupInfo(long containerID, FieldInfo? member, int[]? parentInde { // If both member and arrayIndex are null, we don't have enough information to create // a tunnel to do the fixup. - if (member == null && parentIndex == null) + if (member is null && parentIndex is null) { throw new ArgumentException(SR.Argument_MustSupplyParent); } - if (containerID == 0 && member == null) + if (containerID == 0 && member is null) { _containerID = containerID; _parentField = member; @@ -46,9 +46,9 @@ public ValueTypeFixupInfo(long containerID, FieldInfo? member, int[]? parentInde // If the member isn't null, we know that they supplied a MemberInfo as the parent. This means // that the arrayIndex must be null because we can't have a FieldInfo into an array. - if (member != null) + if (member is not null) { - if (parentIndex != null) + if (parentIndex is not null) { throw new ArgumentException(SR.Argument_MemberAndArray); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs index 6f632645f0ea50..4b0388f68c58f0 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs @@ -112,7 +112,7 @@ internal void MarshalHeader(byte[] binaryForm, int offset) { int Length = BinaryLength; // Invokes the most derived property - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -243,7 +243,7 @@ internal static AceFlags AceFlagsFromInheritanceFlags(InheritanceFlags inheritan internal static void VerifyHeader(byte[] binaryForm, int offset) { - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -541,7 +541,7 @@ public sealed override bool Equals(object? o) { GenericAce? ace = (o as GenericAce); - if (ace == null) + if (ace is null) { return false; } @@ -609,11 +609,11 @@ public sealed override int GetHashCode() object? l = left; object? r = right; - if (l == null && r == null) + if (l is null && r is null) { return true; } - else if (l == null || r == null) + else if (l is null || r is null) { return false; } @@ -663,7 +663,7 @@ public abstract class KnownAce : GenericAce internal KnownAce(AceType type, AceFlags flags, int accessMask, SecurityIdentifier securityIdentifier) : base(type, flags) { - if (securityIdentifier == null) + if (securityIdentifier is null) { throw new ArgumentNullException(nameof(securityIdentifier)); } @@ -713,7 +713,7 @@ public SecurityIdentifier SecurityIdentifier [MemberNotNull(nameof(_sid))] set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -781,7 +781,7 @@ public int OpaqueLength { get { - if (_opaque == null) + if (_opaque is null) { return 0; } @@ -821,7 +821,7 @@ public int OpaqueLength public void SetOpaque(byte[]? opaque) { - if (opaque != null) + if (opaque is not null) { if (opaque.Length > MaxOpaqueLength) { @@ -1247,7 +1247,7 @@ public int OpaqueLength { get { - if (_opaque != null) + if (_opaque is not null) { return _opaque.Length; } @@ -1274,7 +1274,7 @@ public int OpaqueLength public void SetOpaque(byte[]? opaque) { - if (opaque != null) + if (opaque is not null) { if (opaque.Length > MaxOpaqueLengthInternal) { @@ -1604,7 +1604,7 @@ internal override int MaxOpaqueLengthInternal // Finally, if opaque is supported, store it // - if (GetOpaque() != null) + if (GetOpaque() is not null) { if (OpaqueLength > MaxOpaqueLengthInternal) { @@ -2156,7 +2156,7 @@ internal override int MaxOpaqueLengthInternal // Finally, if opaque is supported, store it // - if (GetOpaque() != null) + if (GetOpaque() is not null) { if (OpaqueLength > MaxOpaqueLengthInternal) { diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs index 16dd918e4b959c..70cf8e040e944b 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs @@ -39,7 +39,7 @@ public sealed class AceEnumerator : IEnumerator internal AceEnumerator(GenericAcl collection) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -169,7 +169,7 @@ protected GenericAcl() void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } @@ -242,7 +242,7 @@ public sealed class RawAcl : GenericAcl private static void VerifyHeader(byte[] binaryForm, int offset, out byte revision, out int count, out int length) { - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -288,7 +288,7 @@ private static void VerifyHeader(byte[] binaryForm, int offset, out byte revisio private void MarshalHeader(byte[] binaryForm, int offset) { - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -531,7 +531,7 @@ public override GenericAce this[int index] set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -568,7 +568,7 @@ public override GenericAce this[int index] public void InsertAce(int index, GenericAce ace) { - if (ace == null) + if (ace is null) { throw new ArgumentNullException(nameof(ace)); } @@ -1088,7 +1088,7 @@ private bool InspectAce(ref GenericAce ace, bool isDacl) KnownAce? knownAce = ace as KnownAce; - if (knownAce != null) + if (knownAce is not null) { if (knownAce.AccessMask == 0) { @@ -1153,7 +1153,7 @@ private bool InspectAce(ref GenericAce ace, bool isDacl) unchecked { ace.AceFlags &= ~AuditFlags; } - if (qualifiedAce != null) + if (qualifiedAce is not null) { // // Qualified ACEs in a DACL must be allow or deny ACEs @@ -1182,7 +1182,7 @@ private bool InspectAce(ref GenericAce ace, bool isDacl) // Qualified ACEs in a SACL must be audit ACEs // - if (qualifiedAce != null) + if (qualifiedAce is not null) { if (qualifiedAce.AceQualifier != AceQualifier.SystemAudit) { @@ -1241,14 +1241,14 @@ private void Canonicalize(bool compact, bool isDacl) { QualifiedAce? thisAce = _acl[i] as QualifiedAce; - if (thisAce == null) + if (thisAce is null) { continue; } QualifiedAce? nextAce = _acl[i + 1] as QualifiedAce; - if (nextAce == null) + if (nextAce is null) { continue; } @@ -1482,7 +1482,7 @@ private static bool AceOpaquesMatch(QualifiedAce ace, QualifiedAce newAce) byte[]? aceOpaque = ace.GetOpaque(); byte[]? newAceOpaque = newAce.GetOpaque(); - if (aceOpaque == null || newAceOpaque == null) + if (aceOpaque is null || newAceOpaque is null) { return aceOpaque == newAceOpaque; } @@ -1710,7 +1710,7 @@ private bool CanonicalCheck(bool isDacl) { QualifiedAce? qualifiedAce = ace as QualifiedAce; - if (qualifiedAce == null) + if (qualifiedAce is null) { // // Explicit ACE is not recognized - this is not a canonical ACL @@ -1772,14 +1772,14 @@ private bool CanonicalCheck(bool isDacl) GenericAce ace = _acl[i]; - if (ace == null) + if (ace is null) { // // Afraid to yank this statement now // for fear of destabilization, so adding an assert instead // - Debug.Assert(ace != null, "How did a null ACE end up in a SACL?"); + Debug.Assert(ace is not null, "How did a null ACE end up in a SACL?"); continue; } @@ -1791,7 +1791,7 @@ private bool CanonicalCheck(bool isDacl) { QualifiedAce? qualifiedAce = ace as QualifiedAce; - if (qualifiedAce == null) + if (qualifiedAce is null) { // // Explicit ACE is not recognized - this is not a canonical ACL @@ -1866,7 +1866,7 @@ internal CommonAcl(bool isContainer, bool isDS, byte revision, int capacity) internal CommonAcl(bool isContainer, bool isDS, RawAcl rawAcl, bool trusted, bool isDacl) : base() { - if (rawAcl == null) + if (rawAcl is null) { throw new ArgumentNullException(nameof(rawAcl)); } @@ -1993,7 +1993,7 @@ internal void CheckFlags(InheritanceFlags inheritanceFlags, PropagationFlags pro internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } @@ -2045,7 +2045,7 @@ internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, in { QualifiedAce? ace = _acl[i] as QualifiedAce; - if (ace == null) + if (ace is null) { continue; } @@ -2076,7 +2076,7 @@ internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, in internal void SetQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } @@ -2126,7 +2126,7 @@ internal void SetQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, in // Not a qualified ACE - keep going // - if (ace == null) + if (ace is null) { continue; } @@ -2202,7 +2202,7 @@ internal bool RemoveQualifiedAces(SecurityIdentifier sid, AceQualifier qualifier nameof(flags)); } - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } @@ -2249,7 +2249,7 @@ internal bool RemoveQualifiedAces(SecurityIdentifier sid, AceQualifier qualifier // Not a qualified ACE - keep going // - if (ace == null) + if (ace is null) { continue; } @@ -2645,7 +2645,7 @@ internal void RemoveQualifiedAcesSpecific(SecurityIdentifier sid, AceQualifier q nameof(flags)); } - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } @@ -2660,7 +2660,7 @@ internal void RemoveQualifiedAcesSpecific(SecurityIdentifier sid, AceQualifier q // Not a qualified ACE - keep going // - if (ace == null) + if (ace is null) { continue; } @@ -2864,7 +2864,7 @@ public void RemoveInheritedAces() public void Purge(SecurityIdentifier sid) { - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } @@ -2879,7 +2879,7 @@ public void Purge(SecurityIdentifier sid) // Skip over unknown ACEs // - if (ace == null) + if (ace is null) { continue; } @@ -3094,7 +3094,7 @@ public DiscretionaryAcl(bool isContainer, bool isDS, RawAcl? rawAcl) // internal DiscretionaryAcl(bool isContainer, bool isDS, RawAcl? rawAcl, bool trusted) - : base(isContainer, isDS, rawAcl == null ? new RawAcl(isDS ? AclRevisionDS : AclRevision, 0) : rawAcl, trusted, true) + : base(isContainer, isDS, rawAcl is null ? new RawAcl(isDS ? AclRevisionDS : AclRevision, 0) : rawAcl, trusted, true) { } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs index e03dd2ca45f62c..8a39c20b58c382 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs @@ -84,7 +84,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, } } - if (acl == null) + if (acl is null) { // // The required ACL was not present; return an empty collection. @@ -183,7 +183,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, private bool AceNeedsTranslation([NotNullWhen(true)] CommonAce? ace, bool isAccessAce, bool includeExplicit, bool includeInherited) { - if (ace == null) + if (ace is null) { // // Only consider common ACEs @@ -224,7 +224,7 @@ private bool AceNeedsTranslation([NotNullWhen(true)] CommonAce? ace, bool isAcce // protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -234,7 +234,7 @@ protected override bool ModifyAccess(AccessControlModification modification, Acc { bool result = true; - if (_securityDescriptor.DiscretionaryAcl == null) + if (_securityDescriptor.DiscretionaryAcl is null) { if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || @@ -354,7 +354,7 @@ protected override bool ModifyAccess(AccessControlModification modification, Acc protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -364,7 +364,7 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi { bool result = true; - if (_securityDescriptor.SystemAcl == null) + if (_securityDescriptor.SystemAcl is null) { if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || @@ -437,7 +437,7 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi protected void AddAccessRule(AccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -457,7 +457,7 @@ protected void AddAccessRule(AccessRule rule) protected void SetAccessRule(AccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -477,7 +477,7 @@ protected void SetAccessRule(AccessRule rule) protected void ResetAccessRule(AccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -499,7 +499,7 @@ protected void ResetAccessRule(AccessRule rule) protected bool RemoveAccessRule(AccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -508,7 +508,7 @@ protected bool RemoveAccessRule(AccessRule rule) try { - if (_securityDescriptor == null) + if (_securityDescriptor is null) { return true; } @@ -524,7 +524,7 @@ protected bool RemoveAccessRule(AccessRule rule) protected void RemoveAccessRuleAll(AccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -533,7 +533,7 @@ protected void RemoveAccessRuleAll(AccessRule rule) try { - if (_securityDescriptor == null) + if (_securityDescriptor is null) { return; } @@ -551,7 +551,7 @@ protected void RemoveAccessRuleAll(AccessRule rule) protected void RemoveAccessRuleSpecific(AccessRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -560,7 +560,7 @@ protected void RemoveAccessRuleSpecific(AccessRule rule) try { - if (_securityDescriptor == null) + if (_securityDescriptor is null) { return; } @@ -576,7 +576,7 @@ protected void RemoveAccessRuleSpecific(AccessRule rule) protected void AddAuditRule(AuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -596,7 +596,7 @@ protected void AddAuditRule(AuditRule rule) protected void SetAuditRule(AuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -616,7 +616,7 @@ protected void SetAuditRule(AuditRule rule) protected bool RemoveAuditRule(AuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -636,7 +636,7 @@ protected bool RemoveAuditRule(AuditRule rule) protected void RemoveAuditRuleAll(AuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -656,7 +656,7 @@ protected void RemoveAuditRuleAll(AuditRule rule) protected void RemoveAuditRuleSpecific(AuditRule rule) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs index 6a50a775a1ea41..297772e17db634 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs @@ -99,11 +99,11 @@ private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType int error; RawSecurityDescriptor? rawSD; - if (createByName && name == null) + if (createByName && name is null) { throw new ArgumentNullException(nameof(name)); } - else if (!createByName && handle == null) + else if (!createByName && handle is null) { throw new ArgumentNullException(nameof(handle)); } @@ -114,12 +114,12 @@ private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType { System.Exception? exception = null; - if (exceptionFromErrorCode != null) + if (exceptionFromErrorCode is not null) { exception = exceptionFromErrorCode(error, name, handle, exceptionContext); } - if (exception == null) + if (exception is null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { @@ -191,13 +191,13 @@ private void Persist(string? name, SafeHandle? handle, AccessControlSections inc SystemAcl? sacl = null; DiscretionaryAcl? dacl = null; - if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) + if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner is not null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } - if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) + if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group is not null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; @@ -207,7 +207,7 @@ private void Persist(string? name, SafeHandle? handle, AccessControlSections inc { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && - _securityDescriptor.SystemAcl != null && + _securityDescriptor.SystemAcl is not null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; @@ -266,12 +266,12 @@ private void Persist(string? name, SafeHandle? handle, AccessControlSections inc { System.Exception? exception = null; - if (_exceptionFromErrorCode != null) + if (_exceptionFromErrorCode is not null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } - if (exception == null) + if (exception is null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { @@ -345,7 +345,7 @@ protected sealed override void Persist(string name, AccessControlSections includ protected void Persist(string name, AccessControlSections includeSections, object? exceptionContext) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -366,7 +366,7 @@ protected sealed override void Persist(SafeHandle handle, AccessControlSections protected void Persist(SafeHandle handle, AccessControlSections includeSections, object? exceptionContext) { - if (handle == null) + if (handle is null) { throw new ArgumentNullException(nameof(handle)); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs index e49e9d061ae75f..ae1440c6743bc8 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs @@ -74,7 +74,7 @@ protected ObjectSecurity(bool isContainer, bool isDS) protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor) : this() { - if (securityDescriptor == null) + if (securityDescriptor is null) { throw new ArgumentNullException(nameof(securityDescriptor)); } @@ -88,7 +88,7 @@ protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor) private void UpdateWithNewSecurityDescriptor(RawSecurityDescriptor newOne, AccessControlSections includeSections) { - Debug.Assert(newOne != null, "Must not supply a null parameter here"); + Debug.Assert(newOne is not null, "Must not supply a null parameter here"); if ((includeSections & AccessControlSections.Owner) != 0) { @@ -105,7 +105,7 @@ private void UpdateWithNewSecurityDescriptor(RawSecurityDescriptor newOne, Acces if ((includeSections & AccessControlSections.Audit) != 0) { _saclModified = true; - if (newOne!.SystemAcl != null) + if (newOne!.SystemAcl is not null) { _securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, newOne.SystemAcl, true); } @@ -120,7 +120,7 @@ private void UpdateWithNewSecurityDescriptor(RawSecurityDescriptor newOne, Acces if ((includeSections & AccessControlSections.Access) != 0) { _daclModified = true; - if (newOne!.DiscretionaryAcl != null) + if (newOne!.DiscretionaryAcl is not null) { _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(IsContainer, IsDS, newOne.DiscretionaryAcl, true); } @@ -308,7 +308,7 @@ protected virtual void Persist(bool enableOwnershipPrivilege, string name, Acces catch { // protection against exception filter-based luring attacks - if (ownerPrivilege != null) + if (ownerPrivilege is not null) { ownerPrivilege.Revert(); } @@ -316,7 +316,7 @@ protected virtual void Persist(bool enableOwnershipPrivilege, string name, Acces } finally { - if (ownerPrivilege != null) + if (ownerPrivilege is not null) { ownerPrivilege.Revert(); } @@ -348,7 +348,7 @@ protected virtual void Persist(SafeHandle handle, AccessControlSections includeS try { - if (_securityDescriptor.Owner == null) + if (_securityDescriptor.Owner is null) { return null; } @@ -363,7 +363,7 @@ protected virtual void Persist(SafeHandle handle, AccessControlSections includeS public void SetOwner(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -391,7 +391,7 @@ public void SetOwner(IdentityReference identity) try { - if (_securityDescriptor.Group == null) + if (_securityDescriptor.Group is null) { return null; } @@ -406,7 +406,7 @@ public void SetOwner(IdentityReference identity) public void SetGroup(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -426,7 +426,7 @@ public void SetGroup(IdentityReference identity) public virtual void PurgeAccessRules(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -446,7 +446,7 @@ public virtual void PurgeAccessRules(IdentityReference identity) public virtual void PurgeAuditRules(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -588,7 +588,7 @@ public void SetSecurityDescriptorSddlForm(string sddlForm) public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections) { - if (sddlForm == null) + if (sddlForm is null) { throw new ArgumentNullException(nameof(sddlForm)); } @@ -637,7 +637,7 @@ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm) public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections) { - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -670,7 +670,7 @@ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSect public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } @@ -696,7 +696,7 @@ public virtual bool ModifyAccessRule(AccessControlModification modification, Acc public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified) { - if (rule == null) + if (rule is null) { throw new ArgumentNullException(nameof(rule)); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs index de42e45d8b6b3c..c89b2fd409d4ff 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs @@ -319,7 +319,7 @@ private void Dispose(bool disposing) if (disposing) { - if (this.threadHandle != null) + if (this.threadHandle is not null) { this.threadHandle.Dispose(); this.threadHandle = null!; @@ -381,7 +381,7 @@ public bool IsImpersonating public Privilege(string privilegeName) { - if (privilegeName == null) + if (privilegeName is null) { throw new ArgumentNullException(nameof(privilegeName)); } @@ -462,7 +462,7 @@ private unsafe void ToggleState(bool enable) this.tlsContents = t_tlsSlotData; - if (this.tlsContents == null) + if (this.tlsContents is null) { this.tlsContents = new TlsContents(); t_tlsSlotData = this.tlsContents; @@ -633,7 +633,7 @@ public unsafe void Revert() #if false public static void RunWithPrivilege( string privilege, bool enabled, PrivilegedHelper helper ) { - if ( helper == null ) + if ( helper is null ) { throw new ArgumentNullException( "helper" ); } @@ -666,7 +666,7 @@ private void Reset() this.initialState = false; this.needToRevert = false; - if (this.tlsContents != null) + if (this.tlsContents is not null) { if (0 == this.tlsContents.DecrementReferenceCount()) { diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs index 201acabc7a52ca..b5ac7f4737add2 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs @@ -37,7 +37,7 @@ protected internal AuthorizationRule( InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs index 80e6780f977a8f..f0e862f9a7256b 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs @@ -168,24 +168,24 @@ public int BinaryLength { int result = HeaderLength; - if (Owner != null) + if (Owner is not null) { result += Owner.BinaryLength; } - if (Group != null) + if (Group is not null) { result += Group.BinaryLength; } if ((ControlFlags & ControlFlags.SystemAclPresent) != 0 && - GenericSacl != null) + GenericSacl is not null) { result += GenericSacl.BinaryLength; } if ((ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && - GenericDacl != null && !IsCraftedAefaDacl) + GenericDacl is not null && !IsCraftedAefaDacl) { result += GenericDacl.BinaryLength; } @@ -259,7 +259,7 @@ public string GetSddlForm(AccessControlSections includeSections) public void GetBinaryForm(byte[] binaryForm, int offset) { - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -322,7 +322,7 @@ public void GetBinaryForm(byte[] binaryForm, int offset) // Marhsal the Owner SID into place // - if (Owner != null) + if (Owner is not null) { MarshalInt(binaryForm, ownerOffset, offset - originalOffset); Owner.GetBinaryForm(binaryForm, offset); @@ -341,7 +341,7 @@ public void GetBinaryForm(byte[] binaryForm, int offset) // Marshal the Group SID into place // - if (Group != null) + if (Group is not null) { MarshalInt(binaryForm, groupOffset, offset - originalOffset); Group.GetBinaryForm(binaryForm, offset); @@ -361,7 +361,7 @@ public void GetBinaryForm(byte[] binaryForm, int offset) // if ((ControlFlags & ControlFlags.SystemAclPresent) != 0 && - GenericSacl != null) + GenericSacl is not null) { MarshalInt(binaryForm, saclOffset, offset - originalOffset); GenericSacl.GetBinaryForm(binaryForm, offset); @@ -381,7 +381,7 @@ public void GetBinaryForm(byte[] binaryForm, int offset) // if ((ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && - GenericDacl != null && !IsCraftedAefaDacl) + GenericDacl is not null && !IsCraftedAefaDacl) { MarshalInt(binaryForm, daclOffset, offset - originalOffset); GenericDacl.GetBinaryForm(binaryForm, offset); @@ -474,7 +474,7 @@ public RawSecurityDescriptor(byte[] binaryForm, int offset) // The array passed in must be valid // - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -624,7 +624,7 @@ public RawSecurityDescriptor(byte[] binaryForm, int offset) private static byte[] BinaryFormFromSddlForm(string sddlForm) { - if (sddlForm == null) + if (sddlForm is null) { throw new ArgumentNullException(nameof(sddlForm)); } @@ -834,7 +834,7 @@ public sealed class CommonSecurityDescriptor : GenericSecurityDescriptor [MemberNotNull(nameof(_rawSd))] private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier? owner, SecurityIdentifier? group, SystemAcl? systemAcl, DiscretionaryAcl? discretionaryAcl) { - if (systemAcl != null && + if (systemAcl is not null && systemAcl.IsContainer != isContainer) { throw new ArgumentException( @@ -844,7 +844,7 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se nameof(systemAcl)); } - if (discretionaryAcl != null && + if (discretionaryAcl is not null && discretionaryAcl.IsContainer != isContainer) { throw new ArgumentException( @@ -856,7 +856,7 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se _isContainer = isContainer; - if (systemAcl != null && + if (systemAcl is not null && systemAcl.IsDS != isDS) { throw new ArgumentException( @@ -866,7 +866,7 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se nameof(systemAcl)); } - if (discretionaryAcl != null && + if (discretionaryAcl is not null && discretionaryAcl.IsDS != isDS) { throw new ArgumentException( @@ -884,7 +884,7 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se // Replace null DACL with an allow-all for everyone DACL // - if (discretionaryAcl == null) + if (discretionaryAcl is null) { // // to conform to native behavior, we will add allow everyone ace for DACL @@ -905,7 +905,7 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se // Keep SACL and the flag bit in sync. // - if (systemAcl == null) + if (systemAcl is null) { unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); } } @@ -914,7 +914,7 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se actualFlags |= (ControlFlags.SystemAclPresent); } - _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl); + _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl is null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl); } #endregion @@ -931,7 +931,7 @@ public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, } private CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier? owner, SecurityIdentifier? group, RawAcl? systemAcl, RawAcl? discretionaryAcl) - : this(isContainer, isDS, flags, owner, group, systemAcl == null ? null : new SystemAcl(isContainer, isDS, systemAcl), discretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, discretionaryAcl)) + : this(isContainer, isDS, flags, owner, group, systemAcl is null ? null : new SystemAcl(isContainer, isDS, systemAcl), discretionaryAcl is null ? null : new DiscretionaryAcl(isContainer, isDS, discretionaryAcl)) { } @@ -942,7 +942,7 @@ public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescript internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted) { - if (rawSecurityDescriptor == null) + if (rawSecurityDescriptor is null) { throw new ArgumentNullException(nameof(rawSecurityDescriptor)); } @@ -953,8 +953,8 @@ internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescri rawSecurityDescriptor.ControlFlags, rawSecurityDescriptor.Owner, rawSecurityDescriptor.Group, - rawSecurityDescriptor.SystemAcl == null ? null : new SystemAcl(isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted), - rawSecurityDescriptor.DiscretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted)); + rawSecurityDescriptor.SystemAcl is null ? null : new SystemAcl(isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted), + rawSecurityDescriptor.DiscretionaryAcl is null ? null : new DiscretionaryAcl(isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted)); } // @@ -1060,7 +1060,7 @@ public SystemAcl? SystemAcl set { - if (value != null) + if (value is not null) { if (value.IsContainer != this.IsContainer) { @@ -1083,7 +1083,7 @@ public SystemAcl? SystemAcl _sacl = value; - if (_sacl != null) + if (_sacl is not null) { _rawSd.SystemAcl = _sacl.RawAcl; AddControlFlags(ControlFlags.SystemAclPresent); @@ -1109,7 +1109,7 @@ public DiscretionaryAcl? DiscretionaryAcl set { - if (value != null) + if (value is not null) { if (value.IsContainer != this.IsContainer) { @@ -1134,7 +1134,7 @@ public DiscretionaryAcl? DiscretionaryAcl // NULL DACLs are replaced with allow everyone full access DACLs. // - if (value == null) + if (value is null) { _dacl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(IsDS, IsContainer); } @@ -1150,12 +1150,12 @@ public DiscretionaryAcl? DiscretionaryAcl public bool IsSystemAclCanonical { - get { return (SystemAcl == null || SystemAcl.IsCanonical); } + get { return (SystemAcl is null || SystemAcl.IsCanonical); } } public bool IsDiscretionaryAclCanonical { - get { return (DiscretionaryAcl == null || DiscretionaryAcl.IsCanonical); } + get { return (DiscretionaryAcl is null || DiscretionaryAcl.IsCanonical); } } #endregion @@ -1170,7 +1170,7 @@ public void SetSystemAclProtection(bool isProtected, bool preserveInheritance) } else { - if (!preserveInheritance && SystemAcl != null) + if (!preserveInheritance && SystemAcl is not null) { SystemAcl.RemoveInheritedAces(); } @@ -1187,14 +1187,14 @@ public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInherit } else { - if (!preserveInheritance && DiscretionaryAcl != null) + if (!preserveInheritance && DiscretionaryAcl is not null) { DiscretionaryAcl.RemoveInheritedAces(); } AddControlFlags(ControlFlags.DiscretionaryAclProtected); } - if (DiscretionaryAcl != null && DiscretionaryAcl.EveryOneFullAccessForNullDacl) + if (DiscretionaryAcl is not null && DiscretionaryAcl.EveryOneFullAccessForNullDacl) { DiscretionaryAcl.EveryOneFullAccessForNullDacl = false; } @@ -1202,12 +1202,12 @@ public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInherit public void PurgeAccessControl(SecurityIdentifier sid) { - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } - if (DiscretionaryAcl != null) + if (DiscretionaryAcl is not null) { DiscretionaryAcl.Purge(sid); } @@ -1215,12 +1215,12 @@ public void PurgeAccessControl(SecurityIdentifier sid) public void PurgeAudit(SecurityIdentifier sid) { - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } - if (SystemAcl != null) + if (SystemAcl is not null) { SystemAcl.Purge(sid); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs index 15f3301eb7daad..adc808af35b2bc 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs @@ -104,7 +104,7 @@ out RawSecurityDescriptor? resultSd try { - if (privilege != null) + if (privilege is not null) { try { @@ -116,11 +116,11 @@ out RawSecurityDescriptor? resultSd } } - if (name != null) + if (name is not null) { errorCode = (int)Interop.Advapi32.GetSecurityInfoByName(name, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray); } - else if (handle != null) + else if (handle is not null) { if (handle.IsInvalid) { @@ -168,7 +168,7 @@ out RawSecurityDescriptor? resultSd catch { // protection against exception filter-based luring attacks - if (privilege != null) + if (privilege is not null) { privilege.Revert(); } @@ -176,7 +176,7 @@ out RawSecurityDescriptor? resultSd } finally { - if (privilege != null) + if (privilege is not null) { privilege.Revert(); } @@ -227,28 +227,28 @@ internal static int SetSecurityInfo( byte[]? OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null; Privilege? securityPrivilege = null; - if (owner != null) + if (owner is not null) { Length = owner.BinaryLength; OwnerBinary = new byte[Length]; owner.GetBinaryForm(OwnerBinary, 0); } - if (group != null) + if (group is not null) { Length = group.BinaryLength; GroupBinary = new byte[Length]; group.GetBinaryForm(GroupBinary, 0); } - if (dacl != null) + if (dacl is not null) { Length = dacl.BinaryLength; DaclBinary = new byte[Length]; dacl.GetBinaryForm(DaclBinary, 0); } - if (sacl != null) + if (sacl is not null) { Length = sacl.BinaryLength; SaclBinary = new byte[Length]; @@ -267,7 +267,7 @@ internal static int SetSecurityInfo( try { - if (securityPrivilege != null) + if (securityPrivilege is not null) { try { @@ -279,11 +279,11 @@ internal static int SetSecurityInfo( } } - if (name != null) + if (name is not null) { errorCode = (int)Interop.Advapi32.SetSecurityInfoByName(name, (uint)type, unchecked((uint)securityInformation), OwnerBinary, GroupBinary, DaclBinary, SaclBinary); } - else if (handle != null) + else if (handle is not null) { if (handle.IsInvalid) { @@ -321,7 +321,7 @@ internal static int SetSecurityInfo( catch { // protection against exception filter-based luring attacks - if (securityPrivilege != null) + if (securityPrivilege is not null) { securityPrivilege.Revert(); } @@ -329,7 +329,7 @@ internal static int SetSecurityInfo( } finally { - if (securityPrivilege != null) + if (securityPrivilege is not null) { securityPrivilege.Revert(); } diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs index fbb764fb0d00f0..a71926806caa1d 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs @@ -58,7 +58,7 @@ public Claim(BinaryReader reader) /// if 'reader' is null. public Claim(BinaryReader reader, ClaimsIdentity? subject) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -253,12 +253,12 @@ public Claim(string type, string value, string? valueType, string? issuer, strin /// The value associated with the property. internal Claim(string type, string value, string? valueType, string? issuer, string? originalIssuer, ClaimsIdentity? subject, string? propertyKey, string? propertyValue) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -270,7 +270,7 @@ internal Claim(string type, string value, string? valueType, string? issuer, str _originalIssuer = string.IsNullOrEmpty(originalIssuer) ? _issuer : originalIssuer; _subject = subject; - if (propertyKey != null) + if (propertyKey is not null) { _properties = new Dictionary(); _properties[propertyKey] = propertyValue!; @@ -284,7 +284,7 @@ internal Claim(string type, string value, string? valueType, string? issuer, str /// will be set to 'null'. /// if 'other' is null. protected Claim(Claim other) - : this(other, (other == null ? (ClaimsIdentity?)null : other._subject)) + : this(other, (other is null ? (ClaimsIdentity?)null : other._subject)) { } @@ -297,7 +297,7 @@ protected Claim(Claim other) /// if 'other' is null. protected Claim(Claim other, ClaimsIdentity? subject) { - if (other == null) + if (other is null) throw new ArgumentNullException(nameof(other)); _issuer = other._issuer; @@ -306,12 +306,12 @@ protected Claim(Claim other, ClaimsIdentity? subject) _type = other._type; _value = other._value; _valueType = other._valueType; - if (other._properties != null) + if (other._properties is not null) { _properties = new Dictionary(other._properties); } - if (other._userSerializationData != null) + if (other._userSerializationData is not null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } @@ -356,7 +356,7 @@ public IDictionary Properties { get { - if (_properties == null) + if (_properties is null) { _properties = new Dictionary(); } @@ -434,7 +434,7 @@ public virtual void WriteTo(BinaryWriter writer) /// if 'writer' is null. protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -476,13 +476,13 @@ protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) mask |= SerializationMask.OriginalIssuer; } - if (_properties != null && _properties.Count > 0) + if (_properties is not null && _properties.Count > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.HasProperties; } - if (userData != null && userData.Length > 0) + if (userData is not null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs index 2126308dc518d7..9c4ad063434415 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs @@ -149,16 +149,16 @@ public ClaimsIdentity(IIdentity? identity, IEnumerable? claims, string? a { ClaimsIdentity? claimsIdentity = identity as ClaimsIdentity; - _authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType; - _nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType); - _roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType); + _authenticationType = (identity is not null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType; + _nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity is not null ? claimsIdentity._nameClaimType : DefaultNameClaimType); + _roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity is not null ? claimsIdentity._roleClaimType : DefaultRoleClaimType); - if (claimsIdentity != null) + if (claimsIdentity is not null) { _label = claimsIdentity._label; _bootstrapContext = claimsIdentity._bootstrapContext; - if (claimsIdentity.Actor != null) + if (claimsIdentity.Actor is not null) { // // Check if the Actor is circular before copying. That check is done while setting @@ -177,13 +177,13 @@ public ClaimsIdentity(IIdentity? identity, IEnumerable? claims, string? a } else { - if (identity != null && !string.IsNullOrEmpty(identity.Name)) + if (identity is not null && !string.IsNullOrEmpty(identity.Name)) { SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this)); } } - if (claims != null) + if (claims is not null) { SafeAddClaims(claims); } @@ -197,7 +197,7 @@ public ClaimsIdentity(IIdentity? identity, IEnumerable? claims, string? a /// if 'reader' is null. public ClaimsIdentity(BinaryReader reader) { - if (reader == null) + if (reader is null) throw new ArgumentNullException(nameof(reader)); Initialize(reader); @@ -210,12 +210,12 @@ public ClaimsIdentity(BinaryReader reader) /// if 'other' is null. protected ClaimsIdentity(ClaimsIdentity other) { - if (other == null) + if (other is null) { throw new ArgumentNullException(nameof(other)); } - if (other._actor != null) + if (other._actor is not null) { _actor = other._actor.Clone(); } @@ -225,7 +225,7 @@ protected ClaimsIdentity(ClaimsIdentity other) _label = other._label; _nameClaimType = other._nameClaimType; _roleClaimType = other._roleClaimType; - if (other._userSerializationData != null) + if (other._userSerializationData is not null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } @@ -276,7 +276,7 @@ public ClaimsIdentity? Actor get { return _actor; } set { - if (value != null) + if (value is not null) { if (IsCircular(value)) { @@ -304,7 +304,7 @@ public virtual IEnumerable Claims { get { - if (_externalClaims == null) + if (_externalClaims is null) { return _instanceClaims; } @@ -322,7 +322,7 @@ private IEnumerable CombinedClaimsIterator() for (int j = 0; j < _externalClaims!.Count; j++) { - if (_externalClaims[j] != null) + if (_externalClaims[j] is not null) { foreach (Claim claim in _externalClaims[j]) { @@ -351,7 +351,7 @@ internal List> ExternalClaims { get { - if (_externalClaims == null) + if (_externalClaims is null) { _externalClaims = new List>(); } @@ -378,7 +378,7 @@ public virtual string? Name get { Claim? claim = FindFirst(_nameClaimType); - if (claim != null) + if (claim is not null) { return claim.Value; } @@ -419,7 +419,7 @@ public virtual ClaimsIdentity Clone() /// if 'claim' is null. public virtual void AddClaim(Claim claim) { - if (claim == null) + if (claim is null) { throw new ArgumentNullException(nameof(claim)); } @@ -442,14 +442,14 @@ public virtual void AddClaim(Claim claim) /// if 'claims' is null. public virtual void AddClaims(IEnumerable claims) { - if (claims == null) + if (claims is null) { throw new ArgumentNullException(nameof(claims)); } foreach (Claim? claim in claims) { - if (claim == null) + if (claim is null) { continue; } @@ -474,7 +474,7 @@ public virtual void AddClaims(IEnumerable claims) /// public virtual bool TryRemoveClaim(Claim? claim) { - if (claim == null) + if (claim is null) { return false; } @@ -518,7 +518,7 @@ private void SafeAddClaims(IEnumerable claims) { foreach (Claim? claim in claims) { - if (claim == null) + if (claim is null) continue; if (object.ReferenceEquals(claim.Subject, this)) @@ -538,7 +538,7 @@ private void SafeAddClaims(IEnumerable claims) /// private only call from constructor, adds to internal list. private void SafeAddClaim(Claim? claim) { - if (claim == null) + if (claim is null) return; if (object.ReferenceEquals(claim.Subject, this)) @@ -559,7 +559,7 @@ private void SafeAddClaim(Claim? claim) /// if 'match' is null. public virtual IEnumerable FindAll(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } @@ -582,14 +582,14 @@ public virtual IEnumerable FindAll(Predicate match) /// if 'type' is null. public virtual IEnumerable FindAll(string type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } foreach (Claim claim in Claims) { - if (claim != null) + if (claim is not null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { @@ -607,7 +607,7 @@ public virtual IEnumerable FindAll(string type) /// if 'match' is null. public virtual Claim? FindFirst(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } @@ -632,14 +632,14 @@ public virtual IEnumerable FindAll(string type) /// if 'type' is null. public virtual Claim? FindFirst(string type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } foreach (Claim claim in Claims) { - if (claim != null) + if (claim is not null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { @@ -659,7 +659,7 @@ public virtual IEnumerable FindAll(string type) /// if 'match' is null. public virtual bool HasClaim(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } @@ -686,19 +686,19 @@ public virtual bool HasClaim(Predicate match) /// if 'value' is null. public virtual bool HasClaim(string type, string value) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } foreach (Claim claim in Claims) { - if (claim != null + if (claim is not null && string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase) && string.Equals(claim.Value, value, StringComparison.Ordinal)) { @@ -717,7 +717,7 @@ public virtual bool HasClaim(string type, string value) /// if 'reader' is null. private void Initialize(BinaryReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -800,7 +800,7 @@ private void Initialize(BinaryReader reader) /// a new . protected virtual Claim CreateClaim(BinaryReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -826,20 +826,20 @@ public virtual void WriteTo(BinaryWriter writer) /// if 'writer' is null. protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; - if (_authenticationType != null) + if (_authenticationType is not null) { mask |= SerializationMask.AuthenticationType; numberOfPropertiesWritten++; } - if (_bootstrapContext != null) + if (_bootstrapContext is not null) { if (_bootstrapContext is string rawData) { @@ -872,13 +872,13 @@ protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) numberOfPropertiesWritten++; } - if (_actor != null) + if (_actor is not null) { mask |= SerializationMask.Actor; numberOfPropertiesWritten++; } - if (userData != null && userData.Length > 0) + if (userData is not null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; @@ -948,7 +948,7 @@ private bool IsCircular(ClaimsIdentity subject) ClaimsIdentity currSubject = subject; - while (currSubject.Actor != null) + while (currSubject.Actor is not null) { if (ReferenceEquals(this, currSubject.Actor)) { diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs index 4e99666d326175..284f047c7a42c0 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs @@ -54,14 +54,14 @@ protected ClaimsPrincipal(SerializationInfo info, StreamingContext context) /// private static ClaimsIdentity? SelectPrimaryIdentity(IEnumerable identities) { - if (identities == null) + if (identities is null) { throw new ArgumentNullException(nameof(identities)); } foreach (ClaimsIdentity identity in identities) { - if (identity != null) + if (identity is not null) { return identity; } @@ -108,7 +108,7 @@ public ClaimsPrincipal() /// if 'identities' is null. public ClaimsPrincipal(IEnumerable identities) { - if (identities == null) + if (identities is null) { throw new ArgumentNullException(nameof(identities)); } @@ -123,7 +123,7 @@ public ClaimsPrincipal(IEnumerable identities) /// if 'identity' is null. public ClaimsPrincipal(IIdentity identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -145,7 +145,7 @@ public ClaimsPrincipal(IIdentity identity) /// if 'principal' is null. public ClaimsPrincipal(IPrincipal principal) { - if (null == principal) + if (principal is null) { throw new ArgumentNullException(nameof(principal)); } @@ -155,13 +155,13 @@ public ClaimsPrincipal(IPrincipal principal) // If IPrincipal is not a ClaimsPrincipal, create a new identity from IPrincipal.Identity // ClaimsPrincipal? cp = principal as ClaimsPrincipal; - if (null == cp) + if (cp is null) { _identities.Add(new ClaimsIdentity(principal.Identity)); } else { - if (null != cp.Identities) + if (cp.Identities is not null) { _identities.AddRange(cp.Identities); } @@ -176,7 +176,7 @@ public ClaimsPrincipal(IPrincipal principal) /// if 'reader' is null. public ClaimsPrincipal(BinaryReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -215,7 +215,7 @@ public ClaimsPrincipal(BinaryReader reader) /// if 'identity' is null. public virtual void AddIdentity(ClaimsIdentity identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -230,7 +230,7 @@ public virtual void AddIdentity(ClaimsIdentity identity) /// if 'identities' is null. public virtual void AddIdentities(IEnumerable identities) { - if (identities == null) + if (identities is null) { throw new ArgumentNullException(nameof(identities)); } @@ -282,7 +282,7 @@ public virtual ClaimsPrincipal Clone() /// a new . protected virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -311,14 +311,14 @@ public static ClaimsPrincipal? Current /// if 'match' is null. public virtual IEnumerable FindAll(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } foreach (ClaimsIdentity identity in Identities) { - if (identity != null) + if (identity is not null) { foreach (Claim claim in identity.FindAll(match)) { @@ -337,14 +337,14 @@ public virtual IEnumerable FindAll(Predicate match) /// if 'type' is null. public virtual IEnumerable FindAll(string type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } foreach (ClaimsIdentity identity in Identities) { - if (identity != null) + if (identity is not null) { foreach (Claim claim in identity.FindAll(type)) { @@ -363,7 +363,7 @@ public virtual IEnumerable FindAll(string type) /// if 'match' is null. public virtual Claim? FindFirst(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } @@ -372,10 +372,10 @@ public virtual IEnumerable FindAll(string type) foreach (ClaimsIdentity identity in Identities) { - if (identity != null) + if (identity is not null) { claim = identity.FindFirst(match); - if (claim != null) + if (claim is not null) { return claim; } @@ -394,7 +394,7 @@ public virtual IEnumerable FindAll(string type) /// if 'type' is null. public virtual Claim? FindFirst(string type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -403,10 +403,10 @@ public virtual IEnumerable FindAll(string type) for (int i = 0; i < _identities.Count; i++) { - if (_identities[i] != null) + if (_identities[i] is not null) { claim = _identities[i].FindFirst(type); - if (claim != null) + if (claim is not null) { return claim; } @@ -425,14 +425,14 @@ public virtual IEnumerable FindAll(string type) /// if 'match' is null. public virtual bool HasClaim(Predicate match) { - if (match == null) + if (match is null) { throw new ArgumentNullException(nameof(match)); } for (int i = 0; i < _identities.Count; i++) { - if (_identities[i] != null) + if (_identities[i] is not null) { if (_identities[i].HasClaim(match)) { @@ -455,19 +455,19 @@ public virtual bool HasClaim(Predicate match) /// if 'value' is null. public virtual bool HasClaim(string type, string value) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } for (int i = 0; i < _identities.Count; i++) { - if (_identities[i] != null) + if (_identities[i] is not null) { if (_identities[i].HasClaim(type, value)) { @@ -497,7 +497,7 @@ public virtual System.Security.Principal.IIdentity? Identity { get { - if (s_identitySelector != null) + if (s_identitySelector is not null) { return s_identitySelector(_identities); } @@ -519,7 +519,7 @@ public virtual bool IsInRole(string role) { for (int i = 0; i < _identities.Count; i++) { - if (_identities[i] != null) + if (_identities[i] is not null) { if (_identities[i].HasClaim(_identities[i].RoleClaimType, role)) { @@ -548,7 +548,7 @@ public virtual void WriteTo(BinaryWriter writer) /// if 'writer' is null. protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -561,7 +561,7 @@ protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) numberOfPropertiesWritten++; } - if (userData != null && userData.Length > 0) + if (userData is not null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs index bb222ee9c77af3..dab2f7c8116e50 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs @@ -13,7 +13,7 @@ public class GenericIdentity : ClaimsIdentity public GenericIdentity(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); m_name = name; @@ -24,9 +24,9 @@ public GenericIdentity(string name) public GenericIdentity(string name, string type) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); m_name = name; @@ -84,7 +84,7 @@ public override bool IsAuthenticated private void AddNameClaim() { - if (m_name != null) + if (m_name is not null) { base.AddClaim(new Claim(base.NameClaimType, m_name, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, ClaimsIdentity.DefaultIssuer, this)); } diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs index 51e79cdf0db51a..206e3558ad6c9b 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs @@ -13,11 +13,11 @@ public class GenericPrincipal : ClaimsPrincipal public GenericPrincipal(IIdentity identity, string[]? roles) { - if (identity == null) + if (identity is null) throw new ArgumentNullException(nameof(identity)); m_identity = identity; - if (roles != null) + if (roles is not null) { m_roles = (string[])roles.Clone(); } @@ -44,7 +44,7 @@ private void AddIdentityWithRoles(IIdentity identity, string[]? roles) } // Add 'roles' as external claims so they are not serialized - if (roles != null && roles.Length > 0) + if (roles is not null && roles.Length > 0) { List roleClaims = new List(roles.Length); @@ -69,7 +69,7 @@ public override IIdentity Identity public override bool IsInRole(string? role) { - if (role == null || m_roles == null) + if (role is null || m_roles is null) return false; for (int i = 0; i < m_roles.Length; ++i) diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/AesImplementation.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/AesImplementation.cs index 9041682804d6d1..4bc815575237d3 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/AesImplementation.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/AesImplementation.cs @@ -47,14 +47,14 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr { // note: rbgIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) + if (rgbKey is null) throw new ArgumentNullException(nameof(rgbKey)); long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(this.LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); - if (rgbIV != null) + if (rgbIV is not null) { long ivSize = rgbIV.Length * (long)BitsPerByte; if (ivSize != BlockSize) diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/DesImplementation.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/DesImplementation.cs index 9c1bf00bbf4698..db727702eb0e2c 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/DesImplementation.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/DesImplementation.cs @@ -52,7 +52,7 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) + if (rgbKey is null) throw new ArgumentNullException(nameof(rgbKey)); long keySize = rgbKey.Length * (long)BitsPerByte; @@ -64,7 +64,7 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr if (IsSemiWeakKey(rgbKey)) throw new CryptographicException(SR.Cryptography_InvalidKey_SemiWeak, "DES"); - if (rgbIV != null) + if (rgbIV is not null) { long ivSize = rgbIV.Length * (long)BitsPerByte; if (ivSize != BlockSize) diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HMACCommon.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HMACCommon.cs index 8d844023b37b43..05da2a539c6468 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HMACCommon.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HMACCommon.cs @@ -57,7 +57,7 @@ public void ChangeKey(byte[] key) if (key.Length > _blockSize && _blockSize > 0) { // Perform RFC 2104, section 2 key adjustment. - if (_lazyHashProvider == null) + if (_lazyHashProvider is null) { _lazyHashProvider = HashProviderDispenser.CreateHashProvider(_hashAlgorithmId); } @@ -99,7 +99,7 @@ public int GetCurrentHash(Span destination) => public void Dispose(bool disposing) { - if (disposing && _hMacProvider != null) + if (disposing && _hMacProvider is not null) { _hMacProvider.Dispose(true); _hMacProvider = null!; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HashProviderDispenser.Unix.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HashProviderDispenser.Unix.cs index a67223334986f6..c6a739a6e5e89c 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HashProviderDispenser.Unix.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HashProviderDispenser.Unix.cs @@ -172,7 +172,7 @@ public override int GetCurrentHash(Span destination) public override void Dispose(bool disposing) { - if (disposing && _hmacCtx != null) + if (disposing && _hmacCtx is not null) { _hmacCtx.Dispose(); _hmacCtx = null!; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/Helpers.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/Helpers.cs index 76c7608cf0a885..8d60ae95bcbc94 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/Helpers.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/Helpers.cs @@ -20,7 +20,7 @@ public static bool UsesIv(this CipherMode cipherMode) { if (cipherMode.UsesIv()) { - if (iv == null) + if (iv is null) { throw new CryptographicException(SR.Cryptography_MissingIV); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/OpenSslCipher.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/OpenSslCipher.cs index 6adbec36bb8f93..bd1e3d79dafc57 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/OpenSslCipher.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/OpenSslCipher.cs @@ -30,7 +30,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_ctx != null) + if (_ctx is not null) { _ctx.Dispose(); _ctx = null!; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RC2Implementation.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RC2Implementation.cs index f4f1ed12315199..cf2effa91fd4e6 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RC2Implementation.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RC2Implementation.cs @@ -58,14 +58,14 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) + if (rgbKey is null) throw new ArgumentNullException(nameof(rgbKey)); long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); - if (rgbIV != null) + if (rgbIV is not null) { long ivSize = rgbIV.Length * (long)BitsPerByte; if (ivSize != BlockSize) diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RandomNumberGeneratorImplementation.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RandomNumberGeneratorImplementation.cs index e403b0a7c220cb..eb4a5d94b8baaf 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RandomNumberGeneratorImplementation.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RandomNumberGeneratorImplementation.cs @@ -19,7 +19,7 @@ internal static unsafe void FillSpan(Span data) public override void GetBytes(byte[] data) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data is null) throw new ArgumentNullException(nameof(data)); GetBytes(new Span(data)); } @@ -39,7 +39,7 @@ public override unsafe void GetBytes(Span data) public override void GetNonZeroBytes(byte[] data) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data is null) throw new ArgumentNullException(nameof(data)); GetNonZeroBytes(new Span(data)); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/SHAHashProvider.Browser.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/SHAHashProvider.Browser.cs index 9fd4ab1a47661c..1a4dde4b24c0e7 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/SHAHashProvider.Browser.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/SHAHashProvider.Browser.cs @@ -41,7 +41,7 @@ public SHAHashProvider(string hashAlgorithmId) public override void AppendHashData(ReadOnlySpan data) { - if (buffer == null) + if (buffer is null) { buffer = new MemoryStream(1000); } @@ -62,7 +62,7 @@ public override int GetCurrentHash(Span destination) Debug.Assert(destination.Length >= hashSizeInBytes); impl.Initialize(); - if (buffer != null) + if (buffer is not null) { impl.HashCore(buffer.GetBuffer(), 0, (int)buffer.Length); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/TripleDesImplementation.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/TripleDesImplementation.cs index 691c5736ea05d1..9adc1c72250b4a 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/TripleDesImplementation.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/TripleDesImplementation.cs @@ -52,14 +52,14 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) + if (rgbKey is null) throw new ArgumentNullException(nameof(rgbKey)); long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); - if (rgbIV != null) + if (rgbIV is not null) { long ivSize = rgbIV.Length * (long)BitsPerByte; if (ivSize != BlockSize) diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesAEAD.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesAEAD.cs index 7a327e60a5c71e..22b511756a04ad 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesAEAD.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesAEAD.cs @@ -21,16 +21,16 @@ public static void CheckArgumentsForNull( byte[] ciphertext, byte[] tag) { - if (nonce == null) + if (nonce is null) throw new ArgumentNullException(nameof(nonce)); - if (plaintext == null) + if (plaintext is null) throw new ArgumentNullException(nameof(plaintext)); - if (ciphertext == null) + if (ciphertext is null) throw new ArgumentNullException(nameof(ciphertext)); - if (tag == null) + if (tag is null) throw new ArgumentNullException(nameof(tag)); } } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesCcm.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesCcm.cs index 1e1f32adc87462..bc86983533167e 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesCcm.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesCcm.cs @@ -20,7 +20,7 @@ public AesCcm(ReadOnlySpan key) public AesCcm(byte[] key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); AesAEAD.CheckKeySize(key.Length * 8); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesGcm.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesGcm.cs index 07bbb6daa0eb33..43074700600cb8 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesGcm.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AesGcm.cs @@ -21,7 +21,7 @@ public AesGcm(ReadOnlySpan key) public AesGcm(byte[] key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); AesAEAD.CheckKeySize(key.Length * 8); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs index 1783303ea8d522..9bf23b1c2c2a4f 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs @@ -17,11 +17,11 @@ protected AsymmetricSignatureDeformatter() { } public virtual bool VerifySignature(HashAlgorithm hash, byte[] rgbSignature) { - if (hash == null) + if (hash is null) throw new ArgumentNullException(nameof(hash)); SetHashAlgorithm(hash.ToAlgorithmName()!); - Debug.Assert(hash.Hash != null); + Debug.Assert(hash.Hash is not null); return VerifySignature(hash.Hash, rgbSignature); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs index 95d0a92c763e3e..0ea9829f6114c0 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs @@ -17,11 +17,11 @@ protected AsymmetricSignatureFormatter() { } public virtual byte[] CreateSignature(HashAlgorithm hash) { - if (hash == null) + if (hash is null) throw new ArgumentNullException(nameof(hash)); SetHashAlgorithm(hash.ToAlgorithmName()!); - Debug.Assert(hash.Hash != null); + Debug.Assert(hash.Hash is not null); return CreateSignature(hash.Hash); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CngKeyLite.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CngKeyLite.cs index b4497cc57de8cf..aa816d41204d17 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CngKeyLite.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CngKeyLite.cs @@ -92,7 +92,7 @@ ref MemoryMarshal.GetReference(keyBlob), throw errorCode.ToCryptographicException(); } - Debug.Assert(keyHandle != null); + Debug.Assert(keyHandle is not null); SetExportable(keyHandle); return keyHandle; @@ -104,7 +104,7 @@ internal static SafeNCryptKeyHandle ImportKeyBlob(string blobType, byte[] keyBlo keyHandle = ECCng.ImportKeyBlob(blobType, keyBlob, curveName, s_microsoftSoftwareProviderHandle); - Debug.Assert(keyHandle != null); + Debug.Assert(keyHandle is not null); SetExportable(keyHandle); return keyHandle; @@ -602,7 +602,7 @@ private static SafeNCryptProviderHandle OpenNCryptProvider(string providerName) { Debug.Assert(!ncryptHandle.IsInvalid); byte[]? value = GetProperty(ncryptHandle, propertyName, options); - if (value == null) + if (value is null) return null; // .NET Framework compat: return null if key not present. if (value.Length == 0) return string.Empty; // .NET Framework compat: return empty if property value is 0-length. diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CryptoConfig.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CryptoConfig.cs index 10ada271582680..2385f689574c9a 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CryptoConfig.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/CryptoConfig.cs @@ -47,7 +47,7 @@ private static Dictionary DefaultOidHT { get { - if (s_defaultOidHT != null) + if (s_defaultOidHT is not null) { return s_defaultOidHT; } @@ -110,7 +110,7 @@ private static Dictionary DefaultNameHT { get { - if (s_defaultNameHT != null) + if (s_defaultNameHT is not null) { return s_defaultNameHT; } @@ -299,11 +299,11 @@ private static Dictionary DefaultNameHT public static void AddAlgorithm(Type algorithm, params string[] names) { - if (algorithm == null) + if (algorithm is null) throw new ArgumentNullException(nameof(algorithm)); if (!algorithm.IsVisible) throw new ArgumentException(SR.Cryptography_AlgorithmTypesMustBeVisible, nameof(algorithm)); - if (names == null) + if (names is null) throw new ArgumentNullException(nameof(names)); string[] algorithmNames = new string[names.Length]; @@ -329,7 +329,7 @@ public static void AddAlgorithm(Type algorithm, params string[] names) [RequiresUnreferencedCode("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] public static object? CreateFromName(string name, params object?[]? args) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); // Check to see if we have an application defined mapping @@ -338,21 +338,21 @@ public static void AddAlgorithm(Type algorithm, params string[] names) // We allow the default table to Types and Strings // Types get used for types in .Algorithms assembly. // strings get used for delay-loaded stuff in other assemblies such as .Csp. - if (retvalType == null && DefaultNameHT.TryGetValue(name, out object? retvalObj)) + if (retvalType is null && DefaultNameHT.TryGetValue(name, out object? retvalObj)) { retvalType = retvalObj as Type; - if (retvalType == null) + if (retvalType is null) { if (retvalObj is string retvalString) { retvalType = Type.GetType(retvalString, false, false); - if (retvalType != null && !retvalType.IsVisible) + if (retvalType is not null && !retvalType.IsVisible) { retvalType = null; } - if (retvalType != null) + if (retvalType is not null) { // Add entry to the appNameHT, which makes subsequent calls much faster. appNameHT[name] = retvalType; @@ -367,37 +367,37 @@ public static void AddAlgorithm(Type algorithm, params string[] names) // Special case asking for "ECDsa" since the default map from .NET Framework uses // a Windows-only type. - if (retvalType == null && - (args == null || args.Length == 1) && + if (retvalType is null && + (args is null || args.Length == 1) && name == ECDsaIdentifier) { return ECDsa.Create(); } // Maybe they gave us a classname. - if (retvalType == null) + if (retvalType is null) { retvalType = Type.GetType(name, false, false); - if (retvalType != null && !retvalType.IsVisible) + if (retvalType is not null && !retvalType.IsVisible) { retvalType = null; } } // Still null? Then we didn't find it. - if (retvalType == null) + if (retvalType is null) { return null; } // Locate all constructors. MethodBase[] cons = retvalType.GetConstructors(ConstructorDefault); - if (cons == null) + if (cons is null) { return null; } - if (args == null) + if (args is null) { args = Array.Empty(); } @@ -430,7 +430,7 @@ public static void AddAlgorithm(Type algorithm, params string[] names) out object? state) as ConstructorInfo; // Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand). - if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType)) + if (rci is null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType)) { return null; } @@ -439,7 +439,7 @@ public static void AddAlgorithm(Type algorithm, params string[] names) object retval = rci.Invoke(ConstructorDefault, Type.DefaultBinder, args, null); // Reset any parameter re-ordering performed by the binder. - if (state != null) + if (state is not null) { Type.DefaultBinder.ReorderArgumentArray(ref args, state); } @@ -455,9 +455,9 @@ public static void AddAlgorithm(Type algorithm, params string[] names) public static void AddOID(string oid, params string[] names) { - if (oid == null) + if (oid is null) throw new ArgumentNullException(nameof(oid)); - if (names == null) + if (names is null) throw new ArgumentNullException(nameof(names)); string[] oidNames = new string[names.Length]; @@ -482,7 +482,7 @@ public static void AddOID(string oid, params string[] names) public static string? MapNameToOID(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); appOidHT.TryGetValue(name, out string? oidName); @@ -502,7 +502,7 @@ public static void AddOID(string oid, params string[] names) public static byte[] EncodeOID(string str) { - if (str == null) + if (str is null) throw new ArgumentNullException(nameof(str)); string[] oidString = str.Split('.'); // valid ASN.1 separator @@ -555,7 +555,7 @@ private static void EncodeSingleOidNum(uint value, byte[]? destination, ref int // If destination is null, just return updated index. if (unchecked((int)value) < 0x80) { - if (destination != null) + if (destination is not null) { destination[index++] = unchecked((byte)value); } @@ -566,7 +566,7 @@ private static void EncodeSingleOidNum(uint value, byte[]? destination, ref int } else if (value < 0x4000) { - if (destination != null) + if (destination is not null) { destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); @@ -578,7 +578,7 @@ private static void EncodeSingleOidNum(uint value, byte[]? destination, ref int } else if (value < 0x200000) { - if (destination != null) + if (destination is not null) { unchecked { @@ -594,7 +594,7 @@ private static void EncodeSingleOidNum(uint value, byte[]? destination, ref int } else if (value < 0x10000000) { - if (destination != null) + if (destination is not null) { unchecked { @@ -611,7 +611,7 @@ private static void EncodeSingleOidNum(uint value, byte[]? destination, ref int } else { - if (destination != null) + if (destination is not null) { unchecked { diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DES.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DES.cs index e9383f6ba4f5d7..9974946dca78e8 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DES.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DES.cs @@ -45,7 +45,7 @@ public override byte[] Key } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value.Length * 8).IsLegalSize(s_legalKeySizes)) @@ -107,7 +107,7 @@ public static bool IsSemiWeakKey(byte[] rgbKey) private static bool IsLegalKeySize(byte[]? rgbKey) { - if (rgbKey != null && rgbKey.Length == 8) + if (rgbKey is not null && rgbKey.Length == 8) return true; return false; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs index a0c8cf6afa7a7e..6a3404c297ad4e 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs @@ -17,7 +17,7 @@ private static byte[] ReadRequiredElement( { byte[]? ret = XmlKeyHelper.ReadCryptoBinary(ref state, name, sizeHint); - if (ret == null) + if (ret is null) { throw new CryptographicException( SR.Format(SR.Cryptography_InvalidFromXmlString, nameof(DSA), name)); @@ -40,7 +40,7 @@ public override void FromXmlString(string xmlString) int counter = 0; byte[]? x = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.X), q.Length); - if (seed != null) + if (seed is not null) { byte[] counterBytes = ReadRequiredElement(ref state, CounterElementName); counter = XmlKeyHelper.ReadCryptoBinaryInt32(counterBytes); @@ -60,7 +60,7 @@ public override void FromXmlString(string xmlString) // Check for Counter without Seed after getting X, since that prevents an extra cycle in the // canonical element order. - if (dsaParameters.Seed == null) + if (dsaParameters.Seed is null) { if (XmlKeyHelper.HasElement(ref state, CounterElementName)) { @@ -103,7 +103,7 @@ public override string ToXmlString(bool includePrivateParameters) // StringBuilder to need to grow. DSAParameters keyParameters = ExportParameters(includePrivateParameters); - Debug.Assert(keyParameters.P != null); + Debug.Assert(keyParameters.P is not null); StringBuilder builder = new StringBuilder((keyParameters.P.Length << 1) / 3); builder.Append(""); XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.P), keyParameters.P, builder); @@ -111,12 +111,12 @@ public override string ToXmlString(bool includePrivateParameters) XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.G), keyParameters.G, builder); XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.Y), keyParameters.Y, builder); - if (keyParameters.J != null) + if (keyParameters.J is not null) { XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.J), keyParameters.J, builder); } - if (keyParameters.Seed != null) + if (keyParameters.Seed is not null) { XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.Seed), keyParameters.Seed, builder); XmlKeyHelper.WriteCryptoBinary(CounterElementName, keyParameters.Counter, builder); @@ -124,7 +124,7 @@ public override string ToXmlString(bool includePrivateParameters) if (includePrivateParameters) { - if (keyParameters.X == null) + if (keyParameters.X is null) { #pragma warning disable CA2208 // Instantiate argument exceptions correctly // .NET Framework compat when a 3rd party type lets X be null when diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.cs index e4fccad9ec08d5..dc66f775ecb0fa 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.cs @@ -83,7 +83,7 @@ protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); // hashAlgorithm is verified in the overload @@ -113,7 +113,7 @@ public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) /// public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -125,7 +125,7 @@ public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatur public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -181,7 +181,7 @@ public byte[] SignData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -228,7 +228,7 @@ protected virtual byte[] SignDataCore( public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -260,7 +260,7 @@ public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) /// public byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -290,7 +290,7 @@ protected virtual byte[] SignDataCore(Stream data, HashAlgorithmName hashAlgorit public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } @@ -300,13 +300,13 @@ public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgo public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -360,13 +360,13 @@ public bool VerifyData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -378,9 +378,9 @@ public bool VerifyData( public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -408,7 +408,7 @@ public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName /// public byte[] CreateSignature(byte[] rgbHash, DSASignatureFormat signatureFormat) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -654,9 +654,9 @@ public bool VerifyData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -694,9 +694,9 @@ public bool VerifyData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); @@ -804,9 +804,9 @@ protected virtual bool VerifyDataCore( /// public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature, DSASignatureFormat signatureFormat) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) + if (rgbSignature is null) throw new ArgumentNullException(nameof(rgbSignature)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -866,7 +866,7 @@ protected virtual bool VerifySignatureCore( // If the signature failed normalization to IEEE P1363 then it // obviously doesn't verify. - if (sig == null) + if (sig is null) { return false; } @@ -928,7 +928,7 @@ public override bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -952,7 +952,7 @@ public override bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSACng.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSACng.cs index 9cdf2b83cab31b..371d37592850fa 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSACng.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSACng.cs @@ -38,7 +38,7 @@ private SafeNCryptKeyHandle GetDuplicatedKeyHandle() if (_lastKeySize != keySize) { - if (_keyHandle != null) + if (_keyHandle is not null) { _keyHandle.Dispose(); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureDeformatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureDeformatter.cs index b2fb1ee1da41b9..69296cba640694 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureDeformatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureDeformatter.cs @@ -15,7 +15,7 @@ public DSASignatureDeformatter() { } public DSASignatureDeformatter(AsymmetricAlgorithm key) : this() { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _dsaKey = (DSA)key; @@ -23,7 +23,7 @@ public DSASignatureDeformatter(AsymmetricAlgorithm key) : this() public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _dsaKey = (DSA)key; @@ -40,11 +40,11 @@ public override void SetHashAlgorithm(string strName) public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) + if (rgbSignature is null) throw new ArgumentNullException(nameof(rgbSignature)); - if (_dsaKey == null) + if (_dsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _dsaKey.VerifySignature(rgbHash, rgbSignature); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureFormatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureFormatter.cs index f6f5bf3f4283a5..2c9b4a4eb37526 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSASignatureFormatter.cs @@ -15,7 +15,7 @@ public DSASignatureFormatter() { } public DSASignatureFormatter(AsymmetricAlgorithm key) : this() { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _dsaKey = (DSA)key; @@ -23,7 +23,7 @@ public DSASignatureFormatter(AsymmetricAlgorithm key) : this() public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _dsaKey = (DSA)key; @@ -40,9 +40,9 @@ public override void SetHashAlgorithm(string strName) public override byte[] CreateSignature(byte[] rgbHash) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (_dsaKey == null) + if (_dsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _dsaKey.CreateSignature(rgbHash); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCngKey.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCngKey.cs index 19a678d5c15874..8656278ae3987b 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCngKey.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCngKey.cs @@ -86,7 +86,7 @@ internal SafeNCryptKeyHandle GetDuplicatedKeyHandle(int callerKeySizeProperty) throw new ArgumentException(SR.Cryptography_InvalidKeySize); } - if (_keyHandle != null) + if (_keyHandle is not null) { DisposeKey(); } @@ -106,7 +106,7 @@ internal void GenerateKey(ECCurve curve) curve.Validate(); ThrowIfDisposed(); - if (_keyHandle != null) + if (_keyHandle is not null) { DisposeKey(); } @@ -205,7 +205,7 @@ internal void FullDispose() internal void DisposeKey() { - if (_keyHandle != null) + if (_keyHandle is not null) { _keyHandle.Dispose(); _keyHandle = null; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCurve.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCurve.cs index 11de2e1cfd62a4..bb71e5aa8d871c 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCurve.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECCurve.cs @@ -76,7 +76,7 @@ public Oid Oid get => _oid; private set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(Oid)); if (string.IsNullOrEmpty(value.Value) && string.IsNullOrEmpty(value.FriendlyName)) @@ -106,7 +106,7 @@ public static ECCurve CreateFromOid(Oid curveOid) /// An ECCurve representing a named curve. public static ECCurve CreateFromFriendlyName(string oidFriendlyName) { - if (oidFriendlyName == null) + if (oidFriendlyName is null) { throw new ArgumentNullException(nameof(oidFriendlyName)); } @@ -120,7 +120,7 @@ public static ECCurve CreateFromFriendlyName(string oidFriendlyName) /// An ECCurve representing a named curve. public static ECCurve CreateFromValue(string oidValue) { - if (oidValue == null) + if (oidValue is null) { throw new ArgumentNullException(nameof(oidValue)); } @@ -131,7 +131,7 @@ private static ECCurve CreateFromValueAndName(string? oidValue, string? oidFrien { Oid? oid = null; - if (oidValue == null && oidFriendlyName != null) + if (oidValue is null && oidFriendlyName is not null) { try { @@ -195,7 +195,7 @@ public void Validate() throw new CryptographicException(SR.Cryptography_InvalidECNamedCurve); } - if (Oid == null || + if (Oid is null || (string.IsNullOrEmpty(Oid.FriendlyName) && string.IsNullOrEmpty(Oid.Value))) { throw new CryptographicException(SR.Cryptography_InvalidCurveOid); @@ -205,12 +205,12 @@ public void Validate() { bool hasErrors = false; - if (A == null || - B == null || B.Length != A.Length || - G.X == null || G.X.Length != A.Length || - G.Y == null || G.Y.Length != A.Length || - Order == null || Order.Length == 0 || - Cofactor == null || Cofactor.Length == 0) + if (A is null || + B is null || B.Length != A.Length || + G.X is null || G.X.Length != A.Length || + G.Y is null || G.Y.Length != A.Length || + Order is null || Order.Length == 0 || + Cofactor is null || Cofactor.Length == 0) { hasErrors = true; } @@ -219,7 +219,7 @@ public void Validate() { if (!hasErrors) { - if (Prime == null || Prime.Length != A!.Length) + if (Prime is null || Prime.Length != A!.Length) { hasErrors = true; } @@ -232,7 +232,7 @@ public void Validate() { if (!hasErrors) { - if (Polynomial == null || Polynomial.Length == 0) + if (Polynomial is null || Polynomial.Length == 0) { hasErrors = true; } @@ -246,7 +246,7 @@ public void Validate() { // Implicit; if there are any values, throw Debug.Assert(CurveType == ECCurveType.Implicit); - if (HasAnyExplicitParameters() || Oid != null) + if (HasAnyExplicitParameters() || Oid is not null) { throw new CryptographicException(SR.Format(SR.Cryptography_CurveNotSupported, CurveType.ToString())); } @@ -255,16 +255,16 @@ public void Validate() private bool HasAnyExplicitParameters() { - return (A != null || - B != null || - G.X != null || - G.Y != null || - Order != null || - Cofactor != null || - Prime != null || - Polynomial != null || - Seed != null || - Hash != null); + return (A is not null || + B is not null || + G.X is not null || + G.Y is not null || + Order is not null || + Cofactor is not null || + Prime is not null || + Polynomial is not null || + Seed is not null || + Hash is not null); } } } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellman.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellman.cs index de14abd8089bf1..be29e88022a2cf 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellman.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellman.cs @@ -33,7 +33,7 @@ public override string? SignatureAlgorithm public static new ECDiffieHellman? Create(string algorithm) { - if (algorithm == null) + if (algorithm is null) { throw new ArgumentNullException(nameof(algorithm)); } @@ -185,7 +185,7 @@ public override unsafe bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -221,7 +221,7 @@ public override unsafe bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs index d3e2c527169c39..07c53f3f2263ec 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs @@ -15,7 +15,7 @@ public sealed partial class ECDiffieHellmanCng : ECDiffieHellman // for DeriveKeyMaterial. public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) { - if (otherPartyPublicKey == null) + if (otherPartyPublicKey is null) { throw new ArgumentNullException(nameof(otherPartyPublicKey)); } @@ -34,7 +34,7 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl private SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicKey otherPartyPublicKey) { - if (otherPartyPublicKey == null) + if (otherPartyPublicKey is null) { throw new ArgumentNullException(nameof(otherPartyPublicKey)); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs index 5ccb8f4468213b..2d68e2e655aa8b 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs @@ -34,7 +34,7 @@ public override ECDiffieHellmanPublicKey PublicKey string? curveName = GetCurveName(out _); return new ECDiffieHellmanCngPublicKey( - curveName == null + curveName is null ? ExportFullKeyBlob(includePrivateParameters: false) : ExportKeyBlob(includePrivateParameters: false), curveName); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs index 99bdc7604bc069..be32bab091688d 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs @@ -30,7 +30,7 @@ public static ECDiffieHellmanCngPublicKey FromXmlString(string xml) internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string? curveName) : base(keyBlob) { - Debug.Assert(keyBlob != null); + Debug.Assert(keyBlob is not null); _keyBlob = keyBlob; _curveName = curveName; @@ -48,7 +48,7 @@ internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string? curveName) : base(k /// The key and explicit curve parameters used by the ECC object. public override ECParameters ExportExplicitParameters() { - if (_keyBlob == null) + if (_keyBlob is null) { throw new ObjectDisposedException(nameof(ECDiffieHellmanPublicKey)); } @@ -69,7 +69,7 @@ public override ECParameters ExportExplicitParameters() /// The key and named curve parameters used by the ECC object. public override ECParameters ExportParameters() { - if (_keyBlob == null) + if (_keyBlob is null) { throw new ObjectDisposedException(nameof(ECDiffieHellmanPublicKey)); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs index eb72cb592deae3..4912fd36605fcb 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs @@ -17,7 +17,7 @@ protected ECDiffieHellmanPublicKey() protected ECDiffieHellmanPublicKey(byte[] keyBlob) { - if (keyBlob == null) + if (keyBlob is null) { throw new ArgumentNullException(nameof(keyBlob)); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDsa.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDsa.cs index 2ca1f5c288e2fd..2a03ad2ca4cd8f 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDsa.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDsa.cs @@ -30,7 +30,7 @@ protected ECDsa() { } public static new ECDsa? Create(string algorithm) { - if (algorithm == null) + if (algorithm is null) { throw new ArgumentNullException(nameof(algorithm)); } @@ -79,7 +79,7 @@ public virtual void GenerateKey(ECCurve curve) public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); // hashAlgorithm is verified in the overload @@ -88,7 +88,7 @@ public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -144,7 +144,7 @@ public byte[] SignData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -202,7 +202,7 @@ protected virtual byte[] SignDataCore( } finally { - if (rented != null) + if (rented is not null) { CryptographicOperations.ZeroMemory(rented.AsSpan(0, bytesWritten)); @@ -237,7 +237,7 @@ protected virtual byte[] SignDataCore( /// public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -270,7 +270,7 @@ public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatur /// public byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -320,7 +320,7 @@ protected virtual byte[] SignDataCore( /// public byte[] SignHash(byte[] hash, DSASignatureFormat signatureFormat) { - if (hash == null) + if (hash is null) throw new ArgumentNullException(nameof(hash)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -368,7 +368,7 @@ protected virtual byte[] SignHashCore(ReadOnlySpan hash, DSASignatureForma } finally { - if (rented != null) + if (rented is not null) { CryptographicOperations.ZeroMemory(rented.AsSpan(0, bytesWritten)); @@ -468,7 +468,7 @@ protected virtual bool TrySignDataCore( public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -479,7 +479,7 @@ public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); return VerifyData(data, 0, data.Length, signature, hashAlgorithm); @@ -487,13 +487,13 @@ public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgo public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -547,13 +547,13 @@ public bool VerifyData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -591,9 +591,9 @@ public bool VerifyData( /// public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -681,9 +681,9 @@ protected virtual bool VerifyDataCore( public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -720,9 +720,9 @@ public bool VerifyData( HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); @@ -897,9 +897,9 @@ public virtual bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signa /// public bool VerifyHash(byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { - if (hash == null) + if (hash is null) throw new ArgumentNullException(nameof(hash)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -955,7 +955,7 @@ protected virtual bool VerifyHashCore( byte[]? sig = this.ConvertSignatureToIeeeP1363(signatureFormat, signature); // If the signature failed normalization to P1363, it obviously doesn't verify. - if (sig == null) + if (sig is null) { return false; } @@ -1010,7 +1010,7 @@ public override unsafe bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -1046,7 +1046,7 @@ public override unsafe bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECParameters.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECParameters.cs index 5aec01dd373ec5..7ae2ad31a2fb5f 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECParameters.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECParameters.cs @@ -39,9 +39,9 @@ public void Validate() { bool hasErrors = true; - if (D != null && Q.Y is null && Q.X is null) + if (D is not null && Q.Y is null && Q.X is null) hasErrors = false; - if (Q.Y != null && Q.X != null && Q.Y.Length == Q.X.Length) + if (Q.Y is not null && Q.X is not null && Q.Y.Length == Q.X.Length) hasErrors = false; if (!hasErrors) @@ -49,13 +49,13 @@ public void Validate() if (Curve.IsExplicit) { // Explicit curves require D length to match Curve.Order - hasErrors = (D != null && (D.Length != Curve.Order!.Length)); + hasErrors = (D is not null && (D.Length != Curve.Order!.Length)); } - else if (Curve.IsNamed && Q.X != null) + else if (Curve.IsNamed && Q.X is not null) { // Named curves require D length to match Q.X and Q.Y if Q // is present. - hasErrors = (D != null && (D.Length != Q.X.Length)); + hasErrors = (D is not null && (D.Length != Q.X.Length)); } } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HKDF.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HKDF.cs index 0a6335c2ce623a..324cd05c57b75b 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HKDF.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HKDF.cs @@ -27,7 +27,7 @@ public static class HKDF /// The pseudo random key (prk). public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[]? salt = null) { - if (ikm == null) + if (ikm is null) throw new ArgumentNullException(nameof(ikm)); int hashLength = HashLength(hashAlgorithmName); @@ -86,7 +86,7 @@ private static void Extract(HashAlgorithmName hashAlgorithmName, int hashLength, /// The output keying material. public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[]? info = null) { - if (prk == null) + if (prk is null) throw new ArgumentNullException(nameof(prk)); int hashLength = HashLength(hashAlgorithmName); @@ -176,7 +176,7 @@ private static void Expand(HashAlgorithmName hashAlgorithmName, int hashLength, /// The output keying material. public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[]? salt = null, byte[]? info = null) { - if (ikm == null) + if (ikm is null) throw new ArgumentNullException(nameof(ikm)); int hashLength = HashLength(hashAlgorithmName); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACMD5.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACMD5.cs index b408c4ae422385..b12d7dc2323d7b 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACMD5.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACMD5.cs @@ -76,7 +76,7 @@ protected override void Dispose(bool disposing) if (disposing) { HMACCommon hMacCommon = _hMacCommon; - if (hMacCommon != null) + if (hMacCommon is not null) { _hMacCommon = null!; hMacCommon.Dispose(disposing); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA1.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA1.cs index 5f7b12ea64ebae..e9d999b7c400b7 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA1.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA1.cs @@ -83,7 +83,7 @@ protected override void Dispose(bool disposing) if (disposing) { HMACCommon hMacCommon = _hMacCommon; - if (hMacCommon != null) + if (hMacCommon is not null) { _hMacCommon = null!; hMacCommon.Dispose(disposing); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA256.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA256.cs index 01212cabc15b08..42e3e710dac1d5 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA256.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA256.cs @@ -79,7 +79,7 @@ protected override void Dispose(bool disposing) if (disposing) { HMACCommon hMacCommon = _hMacCommon; - if (hMacCommon != null) + if (hMacCommon is not null) { _hMacCommon = null!; hMacCommon.Dispose(disposing); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA384.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA384.cs index 4a3c79ccd5e7fe..784d6b5f9ee820 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA384.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA384.cs @@ -95,7 +95,7 @@ protected override void Dispose(bool disposing) if (disposing) { HMACCommon hMacCommon = _hMacCommon; - if (hMacCommon != null) + if (hMacCommon is not null) { _hMacCommon = null!; hMacCommon.Dispose(disposing); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA512.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA512.cs index 0e685cd3a23abd..07ac430ce309d7 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA512.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/HMACSHA512.cs @@ -93,7 +93,7 @@ protected override void Dispose(bool disposing) if (disposing) { HMACCommon hMacCommon = _hMacCommon; - if (hMacCommon != null) + if (hMacCommon is not null) { _hMacCommon = null!; hMacCommon.Dispose(disposing); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.cs index 55d4ee2f8294d9..5dee2a893e182c 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.cs @@ -28,7 +28,7 @@ public sealed class IncrementalHash : IDisposable private IncrementalHash(HashAlgorithmName name, HashProvider hash) { Debug.Assert(!string.IsNullOrEmpty(name.Name)); - Debug.Assert(hash != null); + Debug.Assert(hash is not null); _algorithmName = name; _hash = hash; @@ -38,7 +38,7 @@ private IncrementalHash(HashAlgorithmName name, HashProvider hash) private IncrementalHash(HashAlgorithmName name, HMACCommon hmac) { Debug.Assert(!string.IsNullOrEmpty(name.Name)); - Debug.Assert(hmac != null); + Debug.Assert(hmac is not null); _algorithmName = new HashAlgorithmName("HMAC" + name.Name); _hmac = hmac; @@ -58,7 +58,7 @@ private IncrementalHash(HashAlgorithmName name, HMACCommon hmac) /// The object has already been disposed. public void AppendData(byte[] data) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); AppendData(new ReadOnlySpan(data)); @@ -86,7 +86,7 @@ public void AppendData(byte[] data) /// The object has already been disposed. public void AppendData(byte[] data, int offset, int count) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -107,8 +107,8 @@ public void AppendData(ReadOnlySpan data) throw new ObjectDisposedException(nameof(IncrementalHash)); } - Debug.Assert((_hash != null) ^ (_hmac != null)); - if (_hash != null) + Debug.Assert((_hash is not null) ^ (_hmac is not null)); + if (_hash is not null) { _hash.AppendHashData(data); } @@ -184,8 +184,8 @@ private int GetHashAndResetCore(Span destination) { Debug.Assert(destination.Length >= HashLengthInBytes); - Debug.Assert((_hash != null) ^ (_hmac != null)); - return _hash != null ? + Debug.Assert((_hash is not null) ^ (_hmac is not null)); + return _hash is not null ? _hash.FinalizeHashAndReset(destination) : _hmac!.FinalizeHashAndReset(destination); } @@ -277,8 +277,8 @@ private int GetCurrentHashCore(Span destination) { Debug.Assert(destination.Length >= HashLengthInBytes); - Debug.Assert((_hash != null) ^ (_hmac != null)); - return _hash != null ? + Debug.Assert((_hash is not null) ^ (_hmac is not null)); + return _hash is not null ? _hash.GetCurrentHash(destination) : _hmac!.GetCurrentHash(destination); } @@ -291,13 +291,13 @@ public void Dispose() { _disposed = true; - if (_hash != null) + if (_hash is not null) { _hash.Dispose(); _hash = null; } - if (_hmac != null) + if (_hmac is not null) { _hmac.Dispose(true); _hmac = null; @@ -350,7 +350,7 @@ public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm) [UnsupportedOSPlatform("browser")] public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); return CreateHMAC(hashAlgorithm, (ReadOnlySpan)key); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/PKCS1MaskGenerationMethod.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/PKCS1MaskGenerationMethod.cs index 376a039d7901ea..3388118e33fcf6 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/PKCS1MaskGenerationMethod.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/PKCS1MaskGenerationMethod.cs @@ -44,7 +44,7 @@ public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) BinaryPrimitives.WriteUInt32BigEndian(rgbCounter, counter++); hasher.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0); hasher.TransformFinalBlock(rgbCounter, 0, 4); - Debug.Assert(hasher.Hash != null); + Debug.Assert(hasher.Hash is not null); byte[] hash = hasher.Hash; hasher.Initialize(); Buffer.BlockCopy(hash, 0, rgbT, ib, Math.Min(rgbT.Length - ib, hash.Length)); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.Xml.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.Xml.cs index 1869e76adbac74..63de0a7f3485d7 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.Xml.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.Xml.cs @@ -14,7 +14,7 @@ private static byte[] ReadRequiredElement( { byte[]? ret = XmlKeyHelper.ReadCryptoBinary(ref state, name, sizeHint); - if (ret == null) + if (ret is null) { throw new CryptographicException( SR.Format(SR.Cryptography_InvalidFromXmlString, nameof(RSA), name)); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.cs index d488b016003212..13728ad66411d7 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSA.cs @@ -147,7 +147,7 @@ public virtual byte[] EncryptValue(byte[] rgb) => public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } @@ -162,7 +162,7 @@ public virtual byte[] SignData( HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -170,7 +170,7 @@ public virtual byte[] SignData( throw new ArgumentOutOfRangeException(nameof(count)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); @@ -179,11 +179,11 @@ public virtual byte[] SignData( public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); @@ -196,7 +196,7 @@ public virtual bool TrySignData(ReadOnlySpan data, Span destination, { throw HashAlgorithmNameNullOrEmpty(); } - if (padding == null) + if (padding is null) { throw new ArgumentNullException(nameof(padding)); } @@ -213,7 +213,7 @@ public virtual bool TrySignData(ReadOnlySpan data, Span destination, public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); @@ -227,17 +227,17 @@ public virtual bool VerifyData( HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); @@ -246,13 +246,13 @@ public virtual bool VerifyData( public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); @@ -265,7 +265,7 @@ public virtual bool VerifyData(ReadOnlySpan data, ReadOnlySpan signa { throw HashAlgorithmNameNullOrEmpty(); } - if (padding == null) + if (padding is null) { throw new ArgumentNullException(nameof(padding)); } @@ -396,7 +396,7 @@ public override bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -420,7 +420,7 @@ public override bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSACng.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSACng.cs index fecac4b75dd319..cc39522f9444ae 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSACng.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSACng.cs @@ -39,7 +39,7 @@ private SafeNCryptKeyHandle GetDuplicatedKeyHandle() if (_lastKeySize != keySize) { - if (_keyHandle != null) + if (_keyHandle is not null) { _keyHandle.Dispose(); } diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs index 0c2b3ba17ddaeb..0c11313a04ca51 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs @@ -13,7 +13,7 @@ public class RSAOAEPKeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter public RSAOAEPKeyExchangeDeformatter() { } public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -27,7 +27,7 @@ public override string? Parameters public override byte[] DecryptKeyExchange(byte[] rgbData) { - if (_rsaKey == null) + if (_rsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _rsaKey.Decrypt(rgbData, RSAEncryptionPadding.OaepSHA1); @@ -35,7 +35,7 @@ public override byte[] DecryptKeyExchange(byte[] rgbData) public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs index e6eceeaca70860..aad00c989e23b9 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs @@ -15,7 +15,7 @@ public class RSAOAEPKeyExchangeFormatter : AsymmetricKeyExchangeFormatter public RSAOAEPKeyExchangeFormatter() { } public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -25,7 +25,7 @@ public byte[]? Parameter { get { - if (ParameterValue != null) + if (ParameterValue is not null) { return (byte[])ParameterValue.Clone(); } @@ -34,7 +34,7 @@ public byte[]? Parameter } set { - if (value != null) + if (value is not null) { ParameterValue = (byte[])value.Clone(); } @@ -58,7 +58,7 @@ public RandomNumberGenerator? Rng public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -71,7 +71,7 @@ public override byte[] CreateKeyExchange(byte[] rgbData, Type? symAlgType) public override byte[] CreateKeyExchange(byte[] rgbData) { - if (_rsaKey == null) + if (_rsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _rsaKey.Encrypt(rgbData, RSAEncryptionPadding.OaepSHA1); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs index 8270bcb7427dd8..905b0e110d1ce8 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs @@ -15,7 +15,7 @@ public RSAPKCS1KeyExchangeDeformatter() { } public RSAPKCS1KeyExchangeDeformatter(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -35,7 +35,7 @@ public override string? Parameters public override byte[] DecryptKeyExchange(byte[] rgbIn) { - if (_rsaKey == null) + if (_rsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _rsaKey.Decrypt(rgbIn, RSAEncryptionPadding.Pkcs1); @@ -43,7 +43,7 @@ public override byte[] DecryptKeyExchange(byte[] rgbIn) public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs index 9251511ae15359..0a7cb5a4a7d1ba 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs @@ -15,7 +15,7 @@ public RSAPKCS1KeyExchangeFormatter() { } public RSAPKCS1KeyExchangeFormatter(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -37,7 +37,7 @@ public RandomNumberGenerator? Rng public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -50,7 +50,7 @@ public override byte[] CreateKeyExchange(byte[] rgbData, Type? symAlgType) public override byte[] CreateKeyExchange(byte[] rgbData) { - if (_rsaKey == null) + if (_rsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _rsaKey.Encrypt(rgbData, RSAEncryptionPadding.Pkcs1); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs index 81feeca7e89775..81308afe28d4b5 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs @@ -15,7 +15,7 @@ public class RSAPKCS1SignatureDeformatter : AsymmetricSignatureDeformatter public RSAPKCS1SignatureDeformatter() { } public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -23,7 +23,7 @@ public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key) public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -32,7 +32,7 @@ public override void SetKey(AsymmetricAlgorithm key) public override void SetHashAlgorithm(string strName) { // Verify the name - if (CryptoConfig.MapNameToOID(strName) != null) + if (CryptoConfig.MapNameToOID(strName) is not null) { // Uppercase known names as required for BCrypt _algName = HashAlgorithmNames.ToUpper(strName); @@ -46,13 +46,13 @@ public override void SetHashAlgorithm(string strName) public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) + if (rgbSignature is null) throw new ArgumentNullException(nameof(rgbSignature)); - if (_algName == null) + if (_algName is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingOID); - if (_rsaKey == null) + if (_rsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _rsaKey.VerifyHash(rgbHash, rgbSignature, new HashAlgorithmName(_algName), RSASignaturePadding.Pkcs1); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs index dcd7139c2a5a82..0c07ade9c7da8d 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs @@ -16,7 +16,7 @@ public RSAPKCS1SignatureFormatter() { } public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -24,7 +24,7 @@ public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key) public override void SetKey(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; @@ -33,7 +33,7 @@ public override void SetKey(AsymmetricAlgorithm key) public override void SetHashAlgorithm(string strName) { // Verify the name - if (CryptoConfig.MapNameToOID(strName) != null) + if (CryptoConfig.MapNameToOID(strName) is not null) { // Uppercase known names as required for BCrypt _algName = HashAlgorithmNames.ToUpper(strName); @@ -47,11 +47,11 @@ public override void SetHashAlgorithm(string strName) public override byte[] CreateSignature(byte[] rgbHash) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (_algName == null) + if (_algName is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingOID); - if (_rsaKey == null) + if (_rsaKey is null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey); return _rsaKey.SignHash(rgbHash, new HashAlgorithmName(_algName), RSASignaturePadding.Pkcs1); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RandomNumberGenerator.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RandomNumberGenerator.cs index 8d87e49690aca8..f622243da54de9 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RandomNumberGenerator.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/RandomNumberGenerator.cs @@ -168,7 +168,7 @@ public static byte[] GetBytes(int count) internal void VerifyGetBytes(byte[] data, int offset, int count) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs index 395a42352f88c4..459bb6bf5986b6 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs @@ -36,13 +36,13 @@ public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) { - if (salt == null) + if (salt is null) throw new ArgumentNullException(nameof(salt)); if (salt.Length < MinimumSaltSize) throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt, nameof(salt)); if (iterations <= 0) throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); - if (password == null) + if (password is null) throw new NullReferenceException(); // This "should" be ArgumentNullException but for compat, we throw NullReferenceException. _salt = new byte[salt.Length + sizeof(uint)]; @@ -129,7 +129,7 @@ public byte[] Salt set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length < MinimumSaltSize) throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt); @@ -144,17 +144,17 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_hmac != null) + if (_hmac is not null) { _hmac.Dispose(); _hmac = null!; } - if (_buffer != null) + if (_buffer is not null) Array.Clear(_buffer, 0, _buffer.Length); - if (_password != null) + if (_password is not null) Array.Clear(_password, 0, _password.Length); - if (_salt != null) + if (_salt is not null) Array.Clear(_salt, 0, _salt.Length); } base.Dispose(disposing); @@ -227,7 +227,7 @@ public override void Reset() [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "HMACSHA1 is needed for compat. (https://github.com/dotnet/runtime/issues/17618)")] private HMAC OpenHmac() { - Debug.Assert(_password != null); + Debug.Assert(_password is not null); HashAlgorithmName hashAlgorithm = HashAlgorithm; @@ -249,7 +249,7 @@ private HMAC OpenHmac() [MemberNotNull(nameof(_buffer))] private void Initialize() { - if (_buffer != null) + if (_buffer is not null) Array.Clear(_buffer, 0, _buffer.Length); _buffer = new byte[_blockSize]; _block = 0; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/SignatureDescription.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/SignatureDescription.cs index 80ce5193909243..26e24b2ab55756 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/SignatureDescription.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/SignatureDescription.cs @@ -20,7 +20,7 @@ public SignatureDescription() public SignatureDescription(SecurityElement el) { - if (el == null) + if (el is null) throw new ArgumentNullException(nameof(el)); KeyAlgorithm = el.SearchForTextOfTag("Key"); DigestAlgorithm = el.SearchForTextOfTag("Digest"); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/TripleDES.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/TripleDES.cs index 82589b6636fe58..a232bff18bc8a4 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/TripleDES.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/TripleDES.cs @@ -45,7 +45,7 @@ public override byte[] Key set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value.Length * 8).IsLegalSize(s_legalKeySizes)) @@ -60,7 +60,7 @@ public override byte[] Key public static bool IsWeakKey(byte[] rgbKey) { - if (rgbKey == null) + if (rgbKey is null) throw new CryptographicException(SR.Cryptography_InvalidKeySize); // .NET Framework compat: Strange exception for a null value, but this is what we threw in classic CLR. if (!(rgbKey.Length * 8).IsLegalSize(s_legalKeySizes)) diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/XmlKeyHelper.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/XmlKeyHelper.cs index b810f22935f57a..bb7804d1bf61cd 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/XmlKeyHelper.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/XmlKeyHelper.cs @@ -13,7 +13,7 @@ internal static class XmlKeyHelper { internal static ParseState ParseDocument(string xmlString) { - if (xmlString == null) + if (xmlString is null) { throw new ArgumentNullException(nameof(xmlString)); } @@ -37,7 +37,7 @@ internal static bool HasElement(ref ParseState state, string name) { string? value = state.GetValue(name); - if (value == null) + if (value is null) { return null; } @@ -78,7 +78,7 @@ internal static bool HasElement(ref ParseState state, string name) internal static int ReadCryptoBinaryInt32(byte[] buf) { - Debug.Assert(buf != null); + Debug.Assert(buf is not null); int val = 0; int idx = Math.Max(0, buf.Length - sizeof(int)); @@ -126,7 +126,7 @@ internal static void WriteCryptoBinary(string name, ReadOnlySpan value, St { Debug.Assert(name.Length > 0); Debug.Assert(value.Length > 0); - Debug.Assert(builder != null); + Debug.Assert(builder is not null); builder.Append('<'); builder.Append(name); @@ -185,7 +185,7 @@ internal bool HasElement(string localName) { string? value = GetValue(localName); - bool ret = value != null; + bool ret = value is not null; if (ret) { @@ -199,12 +199,12 @@ internal bool HasElement(string localName) internal string? GetValue(string localName) { - if (_enumerable == null) + if (_enumerable is null) { return null; } - if (_enumerator == null) + if (_enumerator is null) { _enumerator = _enumerable.GetEnumerator(); } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/BasicSymmetricCipherNCrypt.cs b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/BasicSymmetricCipherNCrypt.cs index 2fee494418b43d..c366ebde569daa 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/BasicSymmetricCipherNCrypt.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/BasicSymmetricCipherNCrypt.cs @@ -90,7 +90,7 @@ protected sealed override void Dispose(bool disposing) { if (disposing) { - if (_cngKey != null) + if (_cngKey is not null) { _cngKey.Dispose(); _cngKey = null!; @@ -102,7 +102,7 @@ protected sealed override void Dispose(bool disposing) private void Reset() { - if (IV != null) + if (IV is not null) { CngProperty prop = new CngProperty(Interop.NCrypt.NCRYPT_INITIALIZATION_VECTOR, IV, CngPropertyOptions.None); _cngKey!.SetProperty(prop); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngAlgorithmCore.cs b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngAlgorithmCore.cs index ec907439516d97..134c415a3ffe30 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngAlgorithmCore.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngAlgorithmCore.cs @@ -35,12 +35,12 @@ public static CngKey Duplicate(CngKey key) public bool IsKeyGeneratedNamedCurve() { ThrowIfDisposed(); - return (_lazyKey != null && _lazyKey.IsECNamedCurve()); + return (_lazyKey is not null && _lazyKey.IsECNamedCurve()); } public void DisposeKey() { - if (_lazyKey != null) + if (_lazyKey is not null) { _lazyKey.Dispose(); _lazyKey = null; @@ -52,14 +52,14 @@ public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm) ThrowIfDisposed(); // If our key size was changed, we need to generate a new key. - if (_lazyKey != null) + if (_lazyKey is not null) { if (_lazyKey.KeySize != keySize) DisposeKey(); } // If we don't have a key yet, we need to generate one now. - if (_lazyKey == null) + if (_lazyKey is null) { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { @@ -79,7 +79,7 @@ public CngKey GetOrGenerateKey(ECCurve? curve) { ThrowIfDisposed(); - if (_lazyKey != null) + if (_lazyKey is not null) { return _lazyKey; } @@ -133,7 +133,7 @@ public CngKey GetOrGenerateKey(ECCurve? curve) public void SetKey(CngKey key) { - Debug.Assert(key != null); + Debug.Assert(key is not null); ThrowIfDisposed(); // If we already have a key, clear it out. diff --git a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngSymmetricAlgorithmCore.cs b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngSymmetricAlgorithmCore.cs index 6aa654e1eeabcc..4499a14af72dba 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngSymmetricAlgorithmCore.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/CngSymmetricAlgorithmCore.cs @@ -30,9 +30,9 @@ public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer) /// public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { - if (keyName == null) + if (keyName is null) throw new ArgumentNullException(nameof(keyName)); - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); _outer = outer; @@ -81,7 +81,7 @@ public void SetKeySize(int keySize, ICngSymmetricAlgorithm outer) { // Warning: This gets invoked once before "this" is initialized, due to Aes(), DES(), etc., setting the KeySize property in their // nullary constructor. That's why we require "outer" being passed as parameter. - Debug.Assert(_outer == null || _outer == outer); + Debug.Assert(_outer is null || _outer == outer); outer.BaseKeySize = keySize; _keyName = null; // Setting _keyName to null signifies that this object is now based on a plaintext key, not a stored CNG key. @@ -131,7 +131,7 @@ private ICryptoTransform CreateCryptoTransform(bool encrypting) private ICryptoTransform CreateCryptoTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { - if (rgbKey == null) + if (rgbKey is null) throw new ArgumentNullException(nameof(rgbKey)); byte[] key = rgbKey.CloneByteArray(); @@ -143,7 +143,7 @@ private ICryptoTransform CreateCryptoTransform(byte[] rgbKey, byte[]? rgbIV, boo if (_outer.IsWeakKey(key)) throw new CryptographicException(SR.Cryptography_WeakKey); - if (rgbIV != null && rgbIV.Length != _outer.BlockSize.BitSizeToByteSize()) + if (rgbIV is not null && rgbIV.Length != _outer.BlockSize.BitSizeToByteSize()) throw new ArgumentException(SR.Cryptography_InvalidIVSize, nameof(rgbIV)); // CloneByteArray is null-preserving. So even when GetCipherIv returns null the iv variable @@ -192,7 +192,7 @@ private CngKey ProduceCngKey() private bool KeyInPlainText { - get { return _keyName == null; } + get { return _keyName is null; } } private readonly ICngSymmetricAlgorithm _outer; diff --git a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs index 12494c06a96077..8d92b4772fb02b 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs @@ -24,7 +24,7 @@ public static bool UsesIv(this CipherMode cipherMode) { if (cipherMode.UsesIv()) { - if (iv == null) + if (iv is null) { throw new CryptographicException(SR.Cryptography_MissingIV); } @@ -51,7 +51,7 @@ public static bool UsesIv(this CipherMode cipherMode) // public static byte[]? MapZeroLengthArrayToNonNullPointer(this byte[]? src) { - if (src != null && src.Length == 0) + if (src is not null && src.Length == 0) return new byte[1]; return src; } @@ -106,7 +106,7 @@ public static SafeNCryptProviderHandle OpenStorageProvider(this CngProvider prov public static string? GetPropertyAsString(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { byte[]? value = ncryptHandle.GetProperty(propertyName, options); - if (value == null) + if (value is null) return null; // .NET Framework compat: return null if key not present. if (value.Length == 0) return string.Empty; // .NET Framework compat: return empty if property value is 0-length. @@ -127,7 +127,7 @@ public static SafeNCryptProviderHandle OpenStorageProvider(this CngProvider prov public static int GetPropertyAsDword(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { byte[]? value = ncryptHandle.GetProperty(propertyName, options); - if (value == null) + if (value is null) return 0; // .NET Framework compat: return 0 if key not present. return BitConverter.ToInt32(value, 0); } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs b/src/libraries/System.Security.Cryptography.Cng/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs index 28508857bc2b8c..3e6ef315c3cb18 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs @@ -73,7 +73,7 @@ protected SafeNCryptHandle() : base(true) protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle) : base(true) { - if (parentHandle == null) + if (parentHandle is null) throw new ArgumentNullException(nameof(parentHandle)); if (parentHandle.IsClosed || parentHandle.IsInvalid) throw new ArgumentException(SR.Argument_Invalid_SafeHandleInvalidOrClosed, nameof(parentHandle)); @@ -103,9 +103,9 @@ private SafeNCryptHandle? Holder { get { - Debug.Assert((_ownershipState == OwnershipState.Duplicate && _holder != null) || - (_ownershipState != OwnershipState.Duplicate && _holder == null)); - Debug.Assert(_holder == null || _holder._ownershipState == OwnershipState.Holder); + Debug.Assert((_ownershipState == OwnershipState.Duplicate && _holder is not null) || + (_ownershipState != OwnershipState.Duplicate && _holder is null)); + Debug.Assert(_holder is null || _holder._ownershipState == OwnershipState.Holder); return _holder; } @@ -136,7 +136,7 @@ private bool IsValidOpenState { // Owner handles do not have a holder case OwnershipState.Owner: - return Holder == null && !IsInvalid && !IsClosed; + return Holder is null && !IsInvalid && !IsClosed; // Duplicate handles have valid open holders with the same raw handle value, // and should not be tracking a distinct parent. @@ -147,19 +147,19 @@ private bool IsValidOpenState { IntPtr holderRawHandle = IntPtr.Zero; - if (Holder != null) + if (Holder is not null) { Holder.DangerousAddRef(ref acquiredHolder); holderRawHandle = Holder.DangerousGetHandle(); } - bool holderValid = Holder != null && + bool holderValid = Holder is not null && !Holder.IsInvalid && !Holder.IsClosed && holderRawHandle != IntPtr.Zero && holderRawHandle == handle && - _parentHandle == null; + _parentHandle is null; return holderValid && !IsInvalid && !IsClosed; } @@ -173,7 +173,7 @@ private bool IsValidOpenState // Holder handles do not have a holder case OwnershipState.Holder: - return Holder == null && !IsInvalid && !IsClosed; + return Holder is null && !IsInvalid && !IsClosed; // Unknown ownership state default: @@ -273,7 +273,7 @@ private bool IsValidOpenState // Move the parent handle to the Holder - if (_parentHandle != null) + if (_parentHandle is not null) { holder._parentHandle = _parentHandle; _parentHandle = null; @@ -313,7 +313,7 @@ protected override bool ReleaseHandle() Holder!.DangerousRelease(); return true; } - else if (_parentHandle != null) + else if (_parentHandle is not null) { _parentHandle.DangerousRelease(); return true; diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithm.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithm.cs index 4b09c9756d5a11..e4a8237209491c 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithm.cs @@ -16,7 +16,7 @@ public sealed class CngAlgorithm : IEquatable { public CngAlgorithm(string algorithm) { - if (algorithm == null) + if (algorithm is null) throw new ArgumentNullException(nameof(algorithm)); if (algorithm.Length == 0) throw new ArgumentException(SR.Format(SR.Cryptography_InvalidAlgorithmName, algorithm), nameof(algorithm)); @@ -57,7 +57,7 @@ public string Algorithm public override bool Equals(object? obj) { - Debug.Assert(_algorithm != null); + Debug.Assert(_algorithm is not null); return Equals(obj as CngAlgorithm); } @@ -74,13 +74,13 @@ public bool Equals(CngAlgorithm? other) public override int GetHashCode() { - Debug.Assert(_algorithm != null); + Debug.Assert(_algorithm is not null); return _algorithm.GetHashCode(); } public override string ToString() { - Debug.Assert(_algorithm != null); + Debug.Assert(_algorithm is not null); return _algorithm; } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithmGroup.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithmGroup.cs index b5c45227b90106..eb00ac47638f7f 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithmGroup.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngAlgorithmGroup.cs @@ -17,7 +17,7 @@ public sealed class CngAlgorithmGroup : IEquatable { public CngAlgorithmGroup(string algorithmGroup) { - if (algorithmGroup == null) + if (algorithmGroup is null) throw new ArgumentNullException(nameof(algorithmGroup)); if (algorithmGroup.Length == 0) throw new ArgumentException(SR.Format(SR.Cryptography_InvalidAlgorithmGroup, algorithmGroup), nameof(algorithmGroup)); @@ -58,7 +58,7 @@ public string AlgorithmGroup public override bool Equals(object? obj) { - Debug.Assert(_algorithmGroup != null); + Debug.Assert(_algorithmGroup is not null); return Equals(obj as CngAlgorithmGroup); } @@ -75,13 +75,13 @@ public bool Equals(CngAlgorithmGroup? other) public override int GetHashCode() { - Debug.Assert(_algorithmGroup != null); + Debug.Assert(_algorithmGroup is not null); return _algorithmGroup.GetHashCode(); } public override string ToString() { - Debug.Assert(_algorithmGroup != null); + Debug.Assert(_algorithmGroup is not null); return _algorithmGroup; } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Create.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Create.cs index d56aaacb33598f..ff0ac092503bdd 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Create.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Create.cs @@ -30,10 +30,10 @@ public static CngKey Create(CngAlgorithm algorithm, string? keyName) public static CngKey Create(CngAlgorithm algorithm, string? keyName, CngKeyCreationParameters? creationParameters) { - if (algorithm == null) + if (algorithm is null) throw new ArgumentNullException(nameof(algorithm)); - if (creationParameters == null) + if (creationParameters is null) creationParameters = new CngKeyCreationParameters(); SafeNCryptProviderHandle providerHandle = creationParameters.Provider!.OpenStorageProvider(); @@ -57,7 +57,7 @@ public static CngKey Create(CngAlgorithm algorithm, string? keyName, CngKeyCreat CngKey key = new CngKey(providerHandle, keyHandle); // No name translates to an ephemeral key - if (keyName == null) + if (keyName is null) { key.IsEphemeral = true; } @@ -95,7 +95,7 @@ private static void InitializeKeyProperties(SafeNCryptKeyHandle keyHandle, CngKe } CngUIPolicy? uiPolicy = creationParameters.UIPolicy; - if (uiPolicy != null) + if (uiPolicy is not null) { InitializeKeyUiPolicyProperties(keyHandle, uiPolicy); } @@ -104,7 +104,7 @@ private static void InitializeKeyProperties(SafeNCryptKeyHandle keyHandle, CngKe foreach (CngProperty property in creationParameters.Parameters) { byte[]? value = property.GetValueWithoutCopying(); - int valueLength = (value == null) ? 0 : value.Length; + int valueLength = (value is null) ? 0 : value.Length; fixed (byte* pValue = value.MapZeroLengthArrayToNonNullPointer()) { ErrorCode errorCode = Interop.NCrypt.NCryptSetProperty(keyHandle, property.Name, pValue, valueLength, property.Options); @@ -141,7 +141,7 @@ private static void InitializeKeyUiPolicyProperties(SafeNCryptKeyHandle keyHandl } string? useContext = uiPolicy.UseContext; - if (useContext != null) + if (useContext is not null) { int useContextByteLength = checked((useContext.Length + 1) * sizeof(char)); fixed (char* pinnedUseContext = useContext) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.EC.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.EC.cs index 32f7af604ea439..5414fbdce9fc97 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.EC.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.EC.cs @@ -132,7 +132,7 @@ internal static CngAlgorithm EcdhCurveNameToAlgorithm(string name) internal static CngKey Create(ECCurve curve, Func algorithmResolver) { - System.Diagnostics.Debug.Assert(algorithmResolver != null); + System.Diagnostics.Debug.Assert(algorithmResolver is not null); curve.Validate(); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Exists.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Exists.cs index d4124aafc272b4..81995ac09160bb 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Exists.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Exists.cs @@ -30,10 +30,10 @@ public static bool Exists(string keyName, CngProvider provider) public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options) { - if (keyName == null) + if (keyName is null) throw new ArgumentNullException(nameof(keyName)); - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); using (SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider()) @@ -50,7 +50,7 @@ public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOption } finally { - if (keyHandle != null) + if (keyHandle is not null) keyHandle.Dispose(); } } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Export.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Export.cs index 272b6708efeb9c..c51984fb4082a3 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Export.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Export.cs @@ -20,7 +20,7 @@ public sealed partial class CngKey : IDisposable /// public byte[] Export(CngKeyBlobFormat format) { - if (format == null) + if (format is null) throw new ArgumentNullException(nameof(format)); int numBytesNeeded; @@ -99,7 +99,7 @@ internal byte[] ExportPkcs8KeyBlob( out byte[]? allocated); Debug.Assert(ret); - Debug.Assert(allocated != null); // since `allocate: true` + Debug.Assert(allocated is not null); // since `allocate: true` return allocated; } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs index 94a16df59de9b8..6b4cc245973b5e 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs @@ -104,7 +104,7 @@ internal static CngKey Import( CngKeyBlobFormat format, CngProvider provider) { - if (keyBlob == null) + if (keyBlob is null) throw new ArgumentNullException(nameof(keyBlob)); return Import(new ReadOnlySpan(keyBlob), curveName, format, provider); @@ -116,16 +116,16 @@ internal static CngKey Import( CngKeyBlobFormat format, CngProvider provider) { - if (format == null) + if (format is null) throw new ArgumentNullException(nameof(format)); - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider(); SafeNCryptKeyHandle? keyHandle = null; ErrorCode errorCode; - if (curveName == null) + if (curveName is null) { errorCode = Interop.NCrypt.NCryptImportKey( providerHandle, diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Open.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Open.cs index 838a934a2b10b1..09f538cd768184 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Open.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Open.cs @@ -30,9 +30,9 @@ public static CngKey Open(string keyName, CngProvider provider) public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { - if (keyName == null) + if (keyName is null) throw new ArgumentNullException(nameof(keyName)); - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider(); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.OpenHandle.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.OpenHandle.cs index a5b61dc82fd907..884e2fceef579c 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.OpenHandle.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.OpenHandle.cs @@ -17,7 +17,7 @@ public sealed partial class CngKey : IDisposable /// public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions) { - if (keyHandle == null) + if (keyHandle is null) throw new ArgumentNullException(nameof(keyHandle)); if (keyHandle.IsClosed || keyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(keyHandle)); @@ -65,7 +65,7 @@ public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions catch { // Make sure that we don't leak the handle the CngKey duplicated - if (key != null) + if (key is not null) key.Dispose(); throw; diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs index 5da2553d01f089..14392dcaf8faf9 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs @@ -17,11 +17,11 @@ public sealed partial class CngKey : IDisposable /// public CngProperty GetProperty(string name, CngPropertyOptions options) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); byte[]? value = _keyHandle.GetProperty(name, options); - if (value == null) + if (value is null) throw ErrorCode.NTE_NOT_FOUND.ToCryptographicException(); if (value.Length == 0) @@ -35,7 +35,7 @@ public CngProperty GetProperty(string name, CngPropertyOptions options) /// public bool HasProperty(string name, CngPropertyOptions options) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); unsafe @@ -60,7 +60,7 @@ public void SetProperty(CngProperty property) byte[]? propertyValue = property.GetValueWithoutCopying(); // .NET Framework compat. It would have nicer to throw an ArgumentNull exception or something... - if (propertyValue == null) + if (propertyValue is null) throw ErrorCode.NTE_INVALID_PARAMETER.ToCryptographicException(); fixed (byte* pinnedPropertyValue = propertyValue.MapZeroLengthArrayToNonNullPointer()) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.StandardProperties.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.StandardProperties.cs index a54bfe4e8f7b08..166af8a95ea51a 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.StandardProperties.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.StandardProperties.cs @@ -44,7 +44,7 @@ public CngAlgorithmGroup? AlgorithmGroup get { string? algorithmGroup = _keyHandle.GetPropertyAsString(KeyPropertyName.AlgorithmGroup, CngPropertyOptions.None); - if (algorithmGroup == null) + if (algorithmGroup is null) return null; return new CngAlgorithmGroup(algorithmGroup); } @@ -230,7 +230,7 @@ public CngProvider? Provider get { string? provider = _providerHandle.GetPropertyAsString(ProviderPropertyName.Name, CngPropertyOptions.None); - if (provider == null) + if (provider is null) return null; return new CngProvider(provider); } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.cs index 1b42de8ccb702d..668952d417840d 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.cs @@ -19,8 +19,8 @@ public sealed partial class CngKey : IDisposable { private CngKey(SafeNCryptProviderHandle providerHandle, SafeNCryptKeyHandle keyHandle) { - Debug.Assert(keyHandle != null && !keyHandle.IsInvalid && !keyHandle.IsClosed); - Debug.Assert(providerHandle != null && !providerHandle.IsInvalid && !providerHandle.IsClosed); + Debug.Assert(keyHandle is not null && !keyHandle.IsInvalid && !keyHandle.IsClosed); + Debug.Assert(providerHandle is not null && !providerHandle.IsInvalid && !providerHandle.IsClosed); _providerHandle = providerHandle; _keyHandle = keyHandle; @@ -28,12 +28,12 @@ private CngKey(SafeNCryptProviderHandle providerHandle, SafeNCryptKeyHandle keyH public void Dispose() { - if (_providerHandle != null) + if (_providerHandle is not null) { _providerHandle.Dispose(); } - if (_keyHandle != null) + if (_keyHandle is not null) { _keyHandle.Dispose(); } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyBlobFormat.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyBlobFormat.cs index 3165a4d9820a3a..9031896f345063 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyBlobFormat.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyBlobFormat.cs @@ -17,7 +17,7 @@ public sealed class CngKeyBlobFormat : IEquatable { public CngKeyBlobFormat(string format) { - if (format == null) + if (format is null) throw new ArgumentNullException(nameof(format)); if (format.Length == 0) throw new ArgumentException(SR.Format(SR.Cryptography_InvalidKeyBlobFormat, format), nameof(format)); @@ -58,7 +58,7 @@ public string Format public override bool Equals(object? obj) { - Debug.Assert(_format != null); + Debug.Assert(_format is not null); return Equals(obj as CngKeyBlobFormat); } @@ -75,13 +75,13 @@ public bool Equals(CngKeyBlobFormat? other) public override int GetHashCode() { - Debug.Assert(_format != null); + Debug.Assert(_format is not null); return _format.GetHashCode(); } public override string ToString() { - Debug.Assert(_format != null); + Debug.Assert(_format is not null); return _format; } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyCreationParameters.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyCreationParameters.cs index 7c5e16c6219e66..263f4f8b127431 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyCreationParameters.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyCreationParameters.cs @@ -55,7 +55,7 @@ public CngProvider Provider set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _provider = value; diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProperty.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProperty.cs index 848b49618e8264..b082ebbd735957 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProperty.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProperty.cs @@ -18,13 +18,13 @@ public struct CngProperty : IEquatable public CngProperty(string name, byte[]? value, CngPropertyOptions options) : this() { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); Name = name; Options = options; _lazyHashCode = default(int?); - _value = (value == null) ? null : value.CloneByteArray(); + _value = (value is null) ? null : value.CloneByteArray(); } /// @@ -38,7 +38,7 @@ public CngProperty(string name, byte[]? value, CngPropertyOptions options) /// public byte[]? GetValue() { - return (_value == null) ? null : _value.CloneByteArray(); + return (_value is null) ? null : _value.CloneByteArray(); } /// @@ -63,10 +63,10 @@ public bool Equals(CngProperty other) if (Options != other.Options) return false; - if (_value == null) - return other._value == null; + if (_value is null) + return other._value is null; - if (other._value == null) + if (other._value is null) return false; if (_value.Length != other._value.Length) @@ -89,7 +89,7 @@ public override int GetHashCode() // The hash code for a byte is just the value of that byte. Since this will only modify the // lower bits of the hash code, we'll xor each byte into different sections of the hash code - if (_value != null) + if (_value is not null) { for (int i = 0; i < _value.Length; i++) { diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProvider.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProvider.cs index 3547b0f429ae94..c9d492ae1bca92 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProvider.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngProvider.cs @@ -16,7 +16,7 @@ public sealed class CngProvider : IEquatable { public CngProvider(string provider) { - if (provider == null) + if (provider is null) throw new ArgumentNullException(nameof(provider)); if (provider.Length == 0) throw new ArgumentException(SR.Format(SR.Cryptography_InvalidProviderName, provider), nameof(provider)); @@ -55,7 +55,7 @@ public string Provider public override bool Equals(object? obj) { - Debug.Assert(_provider != null); + Debug.Assert(_provider is not null); return Equals(obj as CngProvider); } @@ -72,13 +72,13 @@ public bool Equals(CngProvider? other) public override int GetHashCode() { - Debug.Assert(_provider != null); + Debug.Assert(_provider is not null); return _provider.GetHashCode(); } public override string ToString() { - Debug.Assert(_provider != null); + Debug.Assert(_provider is not null); return _provider.ToString(); } diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.Key.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.Key.cs index 919338a8998399..14e1c34f39a34a 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.Key.cs @@ -28,7 +28,7 @@ public CngKey Key private set { CngKey key = value; - Debug.Assert(key != null, "key != null"); + Debug.Assert(key is not null, "key is not null"); if (key.AlgorithmGroup != CngAlgorithmGroup.Dsa) throw new ArgumentException(SR.Cryptography_ArgDSARequiresDSAKey, nameof(value)); _core.SetKey(key); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.cs index b01714761966d1..a3abacbaacaffd 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/DSACng.cs @@ -20,7 +20,7 @@ public sealed partial class DSACng : DSA /// if is null. public DSACng(CngKey key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (key.AlgorithmGroup != CngAlgorithmGroup.Dsa) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs index deca9cfd932eeb..49f0861bed8a90 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs @@ -10,7 +10,7 @@ public sealed partial class ECDiffieHellmanCng : ECDiffieHellman { public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) { - if (otherPartyPublicKey == null) + if (otherPartyPublicKey is null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) @@ -42,7 +42,7 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey) { - if (otherPartyPublicKey == null) + if (otherPartyPublicKey is null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(otherPartyPublicKey)); @@ -75,7 +75,7 @@ public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey) _secretAppend, flags); case ECDiffieHellmanKeyDerivationFunction.Tls: - if (_label == null || _seed == null) + if (_label is null || _seed is null) { throw new InvalidOperationException(SR.Cryptography_TlsRequiresLabelAndSeed); } @@ -98,7 +98,7 @@ public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey) /// public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicKey otherPartyPublicKey) { - if (otherPartyPublicKey == null) + if (otherPartyPublicKey is null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) @@ -128,7 +128,7 @@ public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicK /// public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey) { - if (otherPartyPublicKey == null) + if (otherPartyPublicKey is null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(otherPartyPublicKey)); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs index defa12719ebf31..dded8aa34ec1e6 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs @@ -36,7 +36,7 @@ public CngKey Key private set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(value)); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.cs index c6baf43ef1aec6..4fb1c1efc798de 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.cs @@ -31,7 +31,7 @@ public sealed partial class ECDiffieHellmanCng : ECDiffieHellman public ECDiffieHellmanCng(CngKey key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (key.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) @@ -52,7 +52,7 @@ public CngAlgorithm HashAlgorithm set { - if (_hashAlgorithm == null) + if (_hashAlgorithm is null) { throw new ArgumentNullException(nameof(value)); } @@ -132,7 +132,7 @@ public byte[]? Seed /// public bool UseSecretAgreementAsHmacKey { - get { return HmacKey == null; } + get { return HmacKey is null; } } protected override void Dispose(bool disposing) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs index 0ae53b69204131..dadad7ab1276c2 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs @@ -58,9 +58,9 @@ public CngKeyBlobFormat BlobFormat /// public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, CngKeyBlobFormat format) { - if (publicKeyBlob == null) + if (publicKeyBlob is null) throw new ArgumentNullException(nameof(publicKeyBlob)); - if (format == null) + if (format is null) throw new ArgumentNullException(nameof(format)); // Verify that the key can import successfully, because we did in the past. diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs index 549e1e9aeaf998..3a585af285fcf5 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs @@ -25,7 +25,7 @@ public CngKey Key private set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!IsEccAlgorithmGroup(value.AlgorithmGroup)) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.cs index 19dd910a4cc885..4992504a150e4e 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.cs @@ -37,7 +37,7 @@ public CngAlgorithm HashAlgorithm /// if is null. public ECDsaCng(CngKey key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (!IsEccAlgorithmGroup(key.AlgorithmGroup)) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.Key.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.Key.cs index 7d4f326846ad5c..5af883431011a6 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.Key.cs @@ -28,7 +28,7 @@ public CngKey Key private set { CngKey key = value; - Debug.Assert(key != null, "key != null"); + Debug.Assert(key is not null, "key is not null"); if (key.AlgorithmGroup != CngAlgorithmGroup.Rsa) throw new ArgumentException(SR.Cryptography_ArgRSARequiresRSAKey, nameof(value)); _core.SetKey(key); diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.cs index 8910ab5453dc11..e6c9be4d018f0c 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/RSACng.cs @@ -20,7 +20,7 @@ public sealed partial class RSACng : RSA /// if is null. public RSACng(CngKey key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (key.AlgorithmGroup != CngAlgorithmGroup.Rsa) diff --git a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs index 892df2169b88c8..ba0899b32cfd7c 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs @@ -31,7 +31,7 @@ public BasicSymmetricCipherCsp(int algId, CipherMode cipherMode, int blockSizeIn } byte[]? currentIv = cipherMode.GetCipherIv(iv); - if (currentIv != null) + if (currentIv is not null) { SetKeyParameter(_hKey, CryptGetKeyParamQueryType.KP_IV, currentIv); } @@ -48,14 +48,14 @@ protected override void Dispose(bool disposing) { SafeKeyHandle hKey = _hKey; _hKey = null!; - if (hKey != null) + if (hKey is not null) { hKey.Dispose(); } SafeProvHandle hProvider = _hProvider; _hProvider = null!; - if (hProvider != null) + if (hProvider is not null) { hProvider.Dispose(); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Helpers.cs b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Helpers.cs index 9b70db3eff4195..ea76a857df3221 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Helpers.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Helpers.cs @@ -17,7 +17,7 @@ public static bool UsesIv(this CipherMode cipherMode) { if (cipherMode.UsesIv()) { - if (iv == null) + if (iv is null) { throw new CryptographicException(SR.Cryptography_MissingIV); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs index 05ef0d091e1cbf..67532cc2b6dee0 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs @@ -23,7 +23,7 @@ internal static class HashAlgorithmNames // For backwards compat with CapiHelper.ObjToHashAlgorithm, use "hashAlg" as name public static HashAlgorithmName ObjToHashAlgorithmName(object hashAlg) { - if (hashAlg == null) + if (hashAlg is null) throw new ArgumentNullException(nameof(hashAlg)); HashAlgorithmName? name = null; @@ -53,7 +53,7 @@ public static HashAlgorithmName NameOrOidToHashAlgorithmName(string nameOrOid) { HashAlgorithmName? name = null; - if (nameOrOid == null) + if (nameOrOid is null) { // Default Algorithm Id is CALG_SHA1 name = HashAlgorithmName.SHA1; @@ -61,7 +61,7 @@ public static HashAlgorithmName NameOrOidToHashAlgorithmName(string nameOrOid) else { string? oidValue = CryptoConfig.MapNameToOID(nameOrOid); - if (oidValue == null) + if (oidValue is null) oidValue = nameOrOid; // we were probably passed an OID value directly name = OidToHashAlgorithmName(oidValue); diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs index 4e6b8e0577889f..950c0d87a897d1 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs @@ -24,34 +24,34 @@ internal static byte[] ToKeyBlob(this DSAParameters dsaParameters) { // Validate the DSA structure first // P and Q are required. Q is a 160 bit divisor of P-1. - if (dsaParameters.P == null || dsaParameters.P.Length == 0 || dsaParameters.Q == null || dsaParameters.Q.Length != DSS_Q_LEN) + if (dsaParameters.P is null || dsaParameters.P.Length == 0 || dsaParameters.Q is null || dsaParameters.Q.Length != DSS_Q_LEN) throw GetBadDataException(); // G is required. G is an element of Z_p - if (dsaParameters.G == null || dsaParameters.G.Length != dsaParameters.P.Length) + if (dsaParameters.G is null || dsaParameters.G.Length != dsaParameters.P.Length) throw GetBadDataException(); // If J is present, it should be less than the size of P: J = (P-1) / Q // This is only a sanity check. Not doing it here is not really an issue as CAPI will fail. - if (dsaParameters.J != null && dsaParameters.J.Length >= dsaParameters.P.Length) + if (dsaParameters.J is not null && dsaParameters.J.Length >= dsaParameters.P.Length) throw GetBadDataException(); // Y is present for V3 DSA key blobs, Y = g^j mod P - if (dsaParameters.Y != null && dsaParameters.Y.Length != dsaParameters.P.Length) + if (dsaParameters.Y is not null && dsaParameters.Y.Length != dsaParameters.P.Length) throw GetBadDataException(); // The seed is always a 20 byte array - if (dsaParameters.Seed != null && dsaParameters.Seed.Length != 20) + if (dsaParameters.Seed is not null && dsaParameters.Seed.Length != 20) throw GetBadDataException(); - bool isPrivate = (dsaParameters.X != null && dsaParameters.X.Length > 0); + bool isPrivate = (dsaParameters.X is not null && dsaParameters.X.Length > 0); // The private key should be the same length as Q if (isPrivate && dsaParameters.X!.Length != DSS_Q_LEN) throw GetBadDataException(); uint bitLenP = (uint)dsaParameters.P.Length * 8; - uint bitLenJ = dsaParameters.J == null ? 0 : (uint)dsaParameters.J.Length * 8; + uint bitLenJ = dsaParameters.J is null ? 0 : (uint)dsaParameters.J.Length * 8; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) @@ -131,7 +131,7 @@ internal static byte[] ToKeyBlob(this DSAParameters dsaParameters) } else { - Debug.Assert(dsaParameters.Y != null); + Debug.Assert(dsaParameters.Y is not null); bw.WriteReversed(dsaParameters.Y); } @@ -161,7 +161,7 @@ internal static DSAParameters ToDSAParameters(this byte[] cspBlob, bool includeP if (bVersion > 2) { - Debug.Assert(cspPublicBlob == null); + Debug.Assert(cspPublicBlob is null); // We need to read a key blob (DSSPUBKEY_VER3 or DSSPRIVKEY_VER3) as follows: // DWORD magic @@ -246,7 +246,7 @@ internal static DSAParameters ToDSAParameters(this byte[] cspBlob, bool includeP // This can only happen if a v2 private blob was obtained directly through // CAPI and saved away for later use, because exporting a private blob with ExportCspBlob // will always export a v3 blob which contains both public and private keys. - if (cspPublicBlob == null) + if (cspPublicBlob is null) throw new CryptographicUnexpectedOperationException(); // Since DSSPUBKEY is used for either public or private key, we got X @@ -295,8 +295,8 @@ private static void WriteKeyBlobHeader(DSAParameters dsaParameters, BinaryWriter // If Y is present and this is a private key, // or Y and J are present and this is a public key, this should be a v3 blob. byte version = BLOBHEADER_CURRENT_BVERSION; - if (((dsaParameters.Y != null) && isPrivate) || - ((dsaParameters.Y != null) && (dsaParameters.J != null))) + if (((dsaParameters.Y is not null) && isPrivate) || + ((dsaParameters.Y is not null) && (dsaParameters.J is not null))) { Debug.Assert(dsaParameters.Y.Length > 0); isV3 = true; @@ -338,7 +338,7 @@ private static void ReadDSSSeed(DSAParameters dsaParameters, BinaryReader br, bo private static void WriteDSSSeed(DSAParameters dsaParameters, BinaryWriter bw) { - if (dsaParameters.Seed == null || dsaParameters.Seed.Length == 0) + if (dsaParameters.Seed is null || dsaParameters.Seed.Length == 0) { bw.Write(0xFFFFFFFF); // counter diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Shared.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Shared.cs index a75758092ef179..327c93813f00f5 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Shared.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Shared.cs @@ -71,38 +71,38 @@ internal enum ProviderType : int internal static byte[] ToKeyBlob(this RSAParameters rsaParameters) { // Validate the RSA structure first. - if (rsaParameters.Modulus == null) + if (rsaParameters.Modulus is null) throw GetBadDataException(); - if (rsaParameters.Exponent == null || rsaParameters.Exponent.Length > 4) + if (rsaParameters.Exponent is null || rsaParameters.Exponent.Length > 4) throw GetBadDataException(); int modulusLength = rsaParameters.Modulus.Length; int halfModulusLength = (modulusLength + 1) / 2; - // We assume that if P != null, then so are Q, DP, DQ, InverseQ and D - if (rsaParameters.P != null) + // We assume that if P is not null, then so are Q, DP, DQ, InverseQ and D + if (rsaParameters.P is not null) { if (rsaParameters.P.Length != halfModulusLength) throw GetBadDataException(); - if (rsaParameters.Q == null || rsaParameters.Q.Length != halfModulusLength) + if (rsaParameters.Q is null || rsaParameters.Q.Length != halfModulusLength) throw GetBadDataException(); - if (rsaParameters.DP == null || rsaParameters.DP.Length != halfModulusLength) + if (rsaParameters.DP is null || rsaParameters.DP.Length != halfModulusLength) throw GetBadDataException(); - if (rsaParameters.DQ == null || rsaParameters.DQ.Length != halfModulusLength) + if (rsaParameters.DQ is null || rsaParameters.DQ.Length != halfModulusLength) throw GetBadDataException(); - if (rsaParameters.InverseQ == null || rsaParameters.InverseQ.Length != halfModulusLength) + if (rsaParameters.InverseQ is null || rsaParameters.InverseQ.Length != halfModulusLength) throw GetBadDataException(); - if (rsaParameters.D == null || rsaParameters.D.Length != modulusLength) + if (rsaParameters.D is null || rsaParameters.D.Length != modulusLength) throw GetBadDataException(); } - bool isPrivate = (rsaParameters.P != null && rsaParameters.P.Length != 0); + bool isPrivate = (rsaParameters.P is not null && rsaParameters.P.Length != 0); MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs index 47d67ae2ae6b0f..12de14084ad319 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -111,7 +111,7 @@ internal static string GetDefaultProvider(int dwType) wszUpgrade = UpgradeDSS(dwType, providerNameString); } - return wszUpgrade != null ? + return wszUpgrade is not null ? wszUpgrade : // Overwrite the provider name with the upgraded provider name providerNameString; } @@ -175,8 +175,8 @@ private static int AcquireCryptContext(out SafeProvHandle safeProvHandle, string /// Safe provider handle internal static void AcquireCsp(CspParameters cspParameters, out SafeProvHandle safeProvHandle) { - Debug.Assert(cspParameters != null); - Debug.Assert(cspParameters.KeyContainerName == null); + Debug.Assert(cspParameters is not null); + Debug.Assert(cspParameters.KeyContainerName is null); SafeProvHandle hProv; // @@ -200,7 +200,7 @@ public static int OpenCSP(CspParameters cspParameters, uint flags, out SafeProvH { string providerName; string? containerName = null; - if (null == cspParameters) + if (cspParameters is null) { throw new ArgumentException(SR.Format(SR.CspParameter_invalid, nameof(cspParameters))); } @@ -210,7 +210,7 @@ public static int OpenCSP(CspParameters cspParameters, uint flags, out SafeProvH //look for provider name in the cspParamters //if CSP provider is not null then use the provider name from cspParameters - if (null != cspParameters.ProviderName) + if (cspParameters.ProviderName is not null) { providerName = cspParameters.ProviderName; } @@ -229,7 +229,7 @@ public static int OpenCSP(CspParameters cspParameters, uint flags, out SafeProvH if (!IsFlagBitSet((uint)cspProviderFlags, (uint)CspProviderFlags.UseDefaultKeyContainer)) { //look for key container name in the cspParameters - if (null != cspParameters.KeyContainerName) + if (cspParameters.KeyContainerName is not null) { containerName = cspParameters.KeyContainerName; } @@ -302,7 +302,7 @@ internal static SafeProvHandle CreateProvHandle(CspParameters parameters, bool r } } - if (parameters.KeyPassword != null) + if (parameters.KeyPassword is not null) { IntPtr password = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword); try @@ -349,7 +349,7 @@ internal static int GetProviderParameterWorker(SafeProvHandle safeProvHandle, by { throw GetErrorCode().ToCryptographicException(); } - if (null != impType && cb == Constants.SIZE_OF_DWORD) + if (impType is not null && cb == Constants.SIZE_OF_DWORD) { impTypeReturn = BitConverter.ToInt32(impType, 0); } @@ -664,7 +664,7 @@ internal static CspParameters SaveCspParameters( out bool randomKeyContainer) { CspParameters parameters; - if (userParameters == null) + if (userParameters is null) { parameters = new CspParameters(keyType == CspAlgorithmType.Dss ? DefaultDssProviderType : DefaultRsaProviderType, @@ -692,7 +692,7 @@ internal static CspParameters SaveCspParameters( // to generate an ephemeral key randomKeyContainer = IsFlagBitSet((uint)parameters.Flags, (uint)CspProviderFlags.CreateEphemeralKey); - if (parameters.KeyContainerName == null && !IsFlagBitSet((uint)parameters.Flags, + if (parameters.KeyContainerName is null && !IsFlagBitSet((uint)parameters.Flags, (uint)CspProviderFlags.UseDefaultKeyContainer)) { parameters.Flags |= CspProviderFlags.CreateEphemeralKey; @@ -815,7 +815,7 @@ internal static void SetPersistKeyInCsp(SafeProvHandle safeProvHandle, bool fPer internal static void DecryptKey(SafeKeyHandle safeKeyHandle, byte[] encryptedData, int encryptedDataLength, bool fOAEP, out byte[] decryptedData) { VerifyValidHandle(safeKeyHandle); - Debug.Assert(encryptedData != null, "Encrypted Data is null"); + Debug.Assert(encryptedData is not null, "Encrypted Data is null"); Debug.Assert(encryptedDataLength >= 0, "Encrypted data length is less than 0"); byte[] dataToBeDecrypted = new byte[encryptedDataLength]; @@ -875,7 +875,7 @@ internal static void DecryptKey(SafeKeyHandle safeKeyHandle, byte[] encryptedDat internal static void EncryptKey(SafeKeyHandle safeKeyHandle, byte[] pbKey, int cbKey, bool foep, [NotNull] ref byte[]? pbEncryptedKey) { VerifyValidHandle(safeKeyHandle); - Debug.Assert(pbKey != null, "pbKey is null"); + Debug.Assert(pbKey is not null, "pbKey is null"); Debug.Assert(cbKey >= 0, $"cbKey is less than 0 ({cbKey})"); int dwEncryptFlags = foep ? (int)Interop.Advapi32.CryptDecryptFlags.CRYPT_OAEP : 0; @@ -1033,11 +1033,11 @@ internal static byte[] ExportKeyBlob(bool includePrivateParameters, SafeKeyHandl public static int NameOrOidToHashAlgId(string? nameOrOid, OidGroup oidGroup) { // Default Algorithm Id is CALG_SHA1 - if (nameOrOid == null) + if (nameOrOid is null) return CapiHelper.CALG_SHA1; string? oidValue = CryptoConfig.MapNameToOID(nameOrOid); - if (oidValue == null) + if (oidValue is null) oidValue = nameOrOid; // we were probably passed an OID value directly int algId = GetAlgIdFromOid(oidValue, oidGroup); @@ -1052,11 +1052,11 @@ public static int NameOrOidToHashAlgId(string? nameOrOid, OidGroup oidGroup) /// public static int ObjToHashAlgId(object hashAlg) { - if (hashAlg == null) + if (hashAlg is null) throw new ArgumentNullException(nameof(hashAlg)); string? hashAlgString = hashAlg as string; - if (hashAlgString != null) + if (hashAlgString is not null) { int algId = NameOrOidToHashAlgId(hashAlgString, OidGroup.HashAlgorithm); return algId; @@ -1124,7 +1124,7 @@ internal static HashAlgorithm ObjToHashAlgorithm(object hashAlg) => /// private static int GetAlgIdFromOid(string oid, OidGroup oidGroup) { - Debug.Assert(oid != null); + Debug.Assert(oid is not null); // CAPI does not have ALGID mappings for all of the hash algorithms - see if we know the mapping // first to avoid doing an AD lookup on these values @@ -1392,7 +1392,7 @@ private static SafeHashHandle CreateHashHandle(this SafeProvHandle hProv, byte[] } finally { - if (hHash != null) + if (hHash is not null) { hHash.Dispose(); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CspKeyContainerInfo.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CspKeyContainerInfo.Windows.cs index ce73894fb36e0c..6f33f212ba4096 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CspKeyContainerInfo.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CspKeyContainerInfo.Windows.cs @@ -51,7 +51,7 @@ public bool Accessible { object? retVal = ReadKeyParameterSilent(Constants.CLR_ACCESSIBLE, throwOnNotFound: false); - if (retVal == null) + if (retVal is null) { // The key wasn't found, so consider it to be not accessible. return false; diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs index abfc5004ce863e..ece5c38ade1d02 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs @@ -44,7 +44,7 @@ public override ICryptoTransform CreateDecryptor() [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DES")] public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { - return CreateTransform(rgbKey, rgbIV == null ? null : rgbIV.CloneByteArray(), encrypting: false); + return CreateTransform(rgbKey, rgbIV is null ? null : rgbIV.CloneByteArray(), encrypting: false); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DES")] @@ -56,7 +56,7 @@ public override ICryptoTransform CreateEncryptor() [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DES")] public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { - return CreateTransform(rgbKey, rgbIV == null ? null : rgbIV.CloneByteArray(), encrypting: true); + return CreateTransform(rgbKey, rgbIV is null ? null : rgbIV.CloneByteArray(), encrypting: true); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DES")] @@ -64,7 +64,7 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) + if (rgbKey is null) throw new ArgumentNullException(nameof(rgbKey)); long keySize = rgbKey.Length * (long)BitsPerByte; @@ -76,7 +76,7 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr if (IsSemiWeakKey(rgbKey)) throw new CryptographicException(SR.Cryptography_InvalidKey_SemiWeak, "DES"); - if (rgbIV == null) + if (rgbIV is null) { if (Mode.UsesIv()) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs index 575055f336116f..ea66c675015ccd 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs @@ -115,12 +115,12 @@ public void ImportCspBlob(byte[] keyBlob) public override void ImportParameters(DSAParameters parameters) { // Although _impl supports key sizes > 1024, limit here for compat. - if (parameters.Y != null && parameters.Y.Length > 1024 / 8) + if (parameters.Y is not null && parameters.Y.Length > 1024 / 8) throw new CryptographicException(SR.Argument_InvalidValue); _impl.ImportParameters(parameters); - _publicOnly = (parameters.X == null); + _publicOnly = (parameters.X is null); } public override void ImportEncryptedPkcs8PrivateKey( @@ -211,7 +211,7 @@ public override bool TrySignData(ReadOnlySpan data, Span destination [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DSACryptoServiceProvider")] public byte[] SignHash(byte[] rgbHash, string str) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -219,7 +219,7 @@ public byte[] SignHash(byte[] rgbHash, string str) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHashSize, "SHA1", SHA1_HASHSIZE)); // Only SHA1 allowed; the default value is SHA1 - if (str != null && !string.Equals(str, "SHA1", StringComparison.OrdinalIgnoreCase)) + if (str is not null && !string.Equals(str, "SHA1", StringComparison.OrdinalIgnoreCase)) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, str); return CreateSignature(rgbHash); @@ -230,15 +230,15 @@ public bool VerifyData(byte[] rgbData, byte[] rgbSignature) => public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) + if (rgbSignature is null) throw new ArgumentNullException(nameof(rgbSignature)); // For compat with Windows, no check for rgbHash.Length != SHA1_HASHSIZE // Only SHA1 allowed; the default value is SHA1 - if (str != null && !string.Equals(str, "SHA1", StringComparison.OrdinalIgnoreCase)) + if (str is not null && !string.Equals(str, "SHA1", StringComparison.OrdinalIgnoreCase)) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, str); return _impl.VerifySignature(rgbHash, rgbSignature); @@ -282,7 +282,7 @@ public override bool VerifySignature(ReadOnlySpan hash, ReadOnlySpan /// private static bool IsPublic(byte[] keyBlob) { - if (keyBlob == null) + if (keyBlob is null) throw new ArgumentNullException(nameof(keyBlob)); // The CAPI DSS public key representation consists of the following sequence: diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs index 186f9c80100c5f..453fac21811c93 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs @@ -84,7 +84,7 @@ public DSACryptoServiceProvider(int dwKeySize, CspParameters? parameters) { // Force-read the SafeKeyHandle property, which will summon it into existence. SafeKeyHandle localHandle = SafeKeyHandle; - Debug.Assert(localHandle != null); + Debug.Assert(localHandle is not null); } } @@ -92,15 +92,15 @@ private SafeProvHandle SafeProvHandle { get { - if (_safeProvHandle == null) + if (_safeProvHandle is null) { lock (_parameters) { - if (_safeProvHandle == null) + if (_safeProvHandle is null) { SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer); - Debug.Assert(hProv != null); + Debug.Assert(hProv is not null); Debug.Assert(!hProv.IsInvalid); Debug.Assert(!hProv.IsClosed); @@ -124,7 +124,7 @@ private SafeProvHandle SafeProvHandle return; } - if (current != null) + if (current is not null) { SafeKeyHandle? keyHandle = _safeKeyHandle; _safeKeyHandle = null; @@ -141,11 +141,11 @@ private SafeKeyHandle SafeKeyHandle { get { - if (_safeKeyHandle == null) + if (_safeKeyHandle is null) { lock (_parameters) { - if (_safeKeyHandle == null) + if (_safeKeyHandle is null) { SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper( CapiHelper.CspAlgorithmType.Dss, @@ -153,7 +153,7 @@ private SafeKeyHandle SafeKeyHandle _keySize, SafeProvHandle); - Debug.Assert(hKey != null); + Debug.Assert(hKey is not null); Debug.Assert(!hKey.IsInvalid); Debug.Assert(!hKey.IsClosed); @@ -193,7 +193,7 @@ public CspKeyContainerInfo CspKeyContainerInfo // .NET Framework compat: Read the SafeKeyHandle property to force the key to load, // because it might throw here. SafeKeyHandle localHandle = SafeKeyHandle; - Debug.Assert(localHandle != null); + Debug.Assert(localHandle is not null); return new CspKeyContainerInfo(_parameters, _randomKeyContainer); } @@ -274,12 +274,12 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) + if (_safeKeyHandle is not null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); } - if (_safeProvHandle != null && !_safeProvHandle.IsClosed) + if (_safeProvHandle is not null && !_safeProvHandle.IsClosed) { _safeProvHandle.Dispose(); } @@ -444,7 +444,7 @@ public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this before calling us - Debug.Assert(data != null); + Debug.Assert(data is not null); Debug.Assert(offset >= 0 && offset <= data.Length); Debug.Assert(count >= 0 && count <= data.Length - offset); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); @@ -460,7 +460,7 @@ protected override byte[] HashData(byte[] data, int offset, int count, HashAlgor protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this before calling us - Debug.Assert(data != null); + Debug.Assert(data is not null); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); if (hashAlgorithm != HashAlgorithmName.SHA1) @@ -479,7 +479,7 @@ protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) /// The DSA signature for the specified hash value. public byte[] SignHash(byte[] rgbHash, string? str) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -507,9 +507,9 @@ public byte[] SignHash(byte[] rgbHash, string? str) /// true if the signature verifies as valid; otherwise, false. public bool VerifyHash(byte[] rgbHash, string? str, byte[] rgbSignature) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) + if (rgbSignature is null) throw new ArgumentNullException(nameof(rgbSignature)); int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); @@ -528,7 +528,7 @@ public bool VerifyHash(byte[] rgbHash, string? str, byte[] rgbSignature) /// private static bool IsPublic(byte[] keyBlob) { - if (keyBlob == null) + if (keyBlob is null) { throw new ArgumentNullException(nameof(keyBlob)); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs index c516653016400e..18986ad3be2166 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs @@ -26,7 +26,7 @@ public byte[] CryptDeriveKey(string? algname, string? alghashname, int keySize, if (algid == 0) throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_InvalidAlgorithm); - if (rgbIV == null) + if (rgbIV is null) throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_InvalidIV); byte[]? key = null; @@ -38,11 +38,11 @@ private SafeProvHandle ProvHandle { get { - if (_safeProvHandle == null) + if (_safeProvHandle is null) { lock (this) { - if (_safeProvHandle == null) + if (_safeProvHandle is null) { SafeProvHandle safeProvHandle = AcquireSafeProviderHandle(_cspParams); System.Threading.Thread.MemoryBarrier(); @@ -56,7 +56,7 @@ private SafeProvHandle ProvHandle private static SafeProvHandle AcquireSafeProviderHandle(CspParameters? cspParams) { - if (cspParams == null) + if (cspParams is null) { cspParams = new CspParameters(CapiHelper.DefaultRsaProviderType); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs index 4b5e73dc340ebc..7c0a4c0f83593c 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs @@ -58,7 +58,7 @@ public string HashName get { return _hashName!; } set { - if (_baseValue != null) + if (_baseValue is not null) throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(HashName)); _hashName = value; @@ -73,7 +73,7 @@ public int IterationCount { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedPosNum); - if (_baseValue != null) + if (_baseValue is not null) throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(IterationCount)); _iterations = value; @@ -88,7 +88,7 @@ public byte[]? Salt } set { - if (_baseValue != null) + if (_baseValue is not null) throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(Salt)); _salt = (byte[]?)value?.Clone(); @@ -103,11 +103,11 @@ public override byte[] GetBytes(int cb) byte[] rgb; byte[] rgbOut = new byte[cb]; - if (_baseValue == null) + if (_baseValue is null) { ComputeBaseValue(); } - else if (_extra != null) + else if (_extra is not null) { ib = _extra.Length - _extraCount; if (ib >= cb) @@ -160,22 +160,22 @@ protected override void Dispose(bool disposing) { _hash?.Dispose(); - if (_baseValue != null) + if (_baseValue is not null) { Array.Clear(_baseValue, 0, _baseValue.Length); } - if (_extra != null) + if (_extra is not null) { Array.Clear(_extra, 0, _extra.Length); } - if (_password != null) + if (_password is not null) { Array.Clear(_password, 0, _password.Length); } - if (_salt != null) + if (_salt is not null) { Array.Clear(_salt, 0, _salt.Length); } @@ -184,11 +184,11 @@ protected override void Dispose(bool disposing) private byte[] ComputeBaseValue() { - Debug.Assert(_hash != null); + Debug.Assert(_hash is not null); _hash.Initialize(); _hash.TransformBlock(_password, 0, _password.Length, _password, 0); - if (_salt != null) + if (_salt is not null) { _hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RC2CryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RC2CryptoServiceProvider.Windows.cs index 97f01feb15a104..021666131451c6 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RC2CryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RC2CryptoServiceProvider.Windows.cs @@ -54,13 +54,13 @@ public bool UseSalt [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of RC2")] public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { - return CreateTransform(rgbKey, rgbIV == null ? null : rgbIV.CloneByteArray(), encrypting: true); + return CreateTransform(rgbKey, rgbIV is null ? null : rgbIV.CloneByteArray(), encrypting: true); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of RC2")] public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { - return CreateTransform(rgbKey, rgbIV == null ? null : rgbIV.CloneByteArray(), encrypting: false); + return CreateTransform(rgbKey, rgbIV is null ? null : rgbIV.CloneByteArray(), encrypting: false); } public override void GenerateKey() @@ -83,7 +83,7 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(this.LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); - if (rgbIV == null) + if (rgbIV is null) { if (Mode.UsesIv()) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RNGCryptoServiceProvider.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RNGCryptoServiceProvider.cs index 46766f1ecfd307..b8361c47842af2 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RNGCryptoServiceProvider.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RNGCryptoServiceProvider.cs @@ -16,7 +16,7 @@ public RNGCryptoServiceProvider(byte[] rgb) : this((CspParameters?)null) { } public RNGCryptoServiceProvider(CspParameters? cspParams) { - if (cspParams != null) + if (cspParams is not null) throw new PlatformNotSupportedException(); // This class wraps RandomNumberGenerator.Create() from Algorithms assembly diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs index 168a456800e5bc..1b7910b00aa2f9 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs @@ -41,7 +41,7 @@ public RSACryptoServiceProvider(CspParameters parameters) => public byte[] Decrypt(byte[] rgb, bool fOAEP) { - if (rgb == null) + if (rgb is null) throw new ArgumentNullException(nameof(rgb)); // size check -- must be exactly the modulus size @@ -53,9 +53,9 @@ public byte[] Decrypt(byte[] rgb, bool fOAEP) public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); return @@ -66,7 +66,7 @@ public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) public override bool TryDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); if (data.Length != (KeySize / 8)) throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); @@ -87,7 +87,7 @@ protected override void Dispose(bool disposing) public byte[] Encrypt(byte[] rgb, bool fOAEP) { - if (rgb == null) + if (rgb is null) throw new ArgumentNullException(nameof(rgb)); return _impl.Encrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1); @@ -95,9 +95,9 @@ public byte[] Encrypt(byte[] rgb, bool fOAEP) public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); return @@ -108,7 +108,7 @@ public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) throw PaddingModeNotSupported(); @@ -145,13 +145,13 @@ public void ImportCspBlob(byte[] keyBlob) public override void ImportParameters(RSAParameters parameters) { // Although _impl supports larger Exponent, limit here for compat. - if (parameters.Exponent == null || parameters.Exponent.Length > 4) + if (parameters.Exponent is null || parameters.Exponent.Length > 4) throw new CryptographicException(SR.Argument_InvalidValue); _impl.ImportParameters(parameters); // P was verified in ImportParameters - _publicOnly = (parameters.P == null || parameters.P.Length == 0); + _publicOnly = (parameters.P is null || parameters.P.Length == 0); } public override void ImportEncryptedPkcs8PrivateKey( @@ -190,17 +190,17 @@ public override int KeySize public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.SignData(data, hashAlgorithm, padding); public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.SignData(data, offset, count, hashAlgorithm, padding); public override bool TrySignData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.TrySignData(data, destination, hashAlgorithm, padding, out bytesWritten); @@ -214,18 +214,18 @@ public byte[] SignData(Stream inputStream, object halg) => _impl.SignData(inputStream, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.SignHash(hash, hashAlgorithm, padding); public override bool TrySignHash(ReadOnlySpan hash, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.TrySignHash(hash, destination, hashAlgorithm, padding, out bytesWritten); public byte[] SignHash(byte[] rgbHash, string str) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -240,22 +240,22 @@ public bool VerifyData(byte[] buffer, object halg, byte[] signature) => _impl.VerifyData(buffer, signature, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding); public override bool VerifyData(ReadOnlySpan data, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.VerifyData(data, signature, hashAlgorithm, padding); public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) + if (hash is null) { throw new ArgumentNullException(nameof(hash)); } - if (signature == null) + if (signature is null) { throw new ArgumentNullException(nameof(signature)); } @@ -264,17 +264,17 @@ public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName } public override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + padding is null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.VerifyHash(hash, signature, hashAlgorithm, padding); public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { - if (rgbHash == null) + if (rgbHash is null) { throw new ArgumentNullException(nameof(rgbHash)); } - if (rgbSignature == null) + if (rgbSignature is null) { throw new ArgumentNullException(nameof(rgbSignature)); } @@ -297,7 +297,7 @@ private static Exception PaddingModeNotSupported() /// private static bool IsPublic(byte[] keyBlob) { - if (keyBlob == null) + if (keyBlob is null) throw new ArgumentNullException(nameof(keyBlob)); // The CAPI RSA public key representation consists of the following sequence: diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs index 6843a3aa30fca2..d41e0fe14df117 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs @@ -73,7 +73,7 @@ private RSACryptoServiceProvider(int keySize, CspParameters? parameters, bool us { // Force-read the SafeKeyHandle property, which will summon it into existence. SafeKeyHandle localHandle = SafeKeyHandle; - Debug.Assert(localHandle != null); + Debug.Assert(localHandle is not null); } } @@ -81,15 +81,15 @@ private SafeProvHandle SafeProvHandle { get { - if (_safeProvHandle == null) + if (_safeProvHandle is null) { lock (_parameters) { - if (_safeProvHandle == null) + if (_safeProvHandle is null) { SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer); - Debug.Assert(hProv != null); + Debug.Assert(hProv is not null); Debug.Assert(!hProv.IsInvalid); Debug.Assert(!hProv.IsClosed); @@ -113,7 +113,7 @@ private SafeProvHandle SafeProvHandle return; } - if (current != null) + if (current is not null) { SafeKeyHandle? keyHandle = _safeKeyHandle; _safeKeyHandle = null; @@ -130,11 +130,11 @@ private SafeKeyHandle SafeKeyHandle { get { - if (_safeKeyHandle == null) + if (_safeKeyHandle is null) { lock (_parameters) { - if (_safeKeyHandle == null) + if (_safeKeyHandle is null) { SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper( CapiHelper.CspAlgorithmType.Rsa, @@ -142,7 +142,7 @@ private SafeKeyHandle SafeKeyHandle _keySize, SafeProvHandle); - Debug.Assert(hKey != null); + Debug.Assert(hKey is not null); Debug.Assert(!hKey.IsInvalid); Debug.Assert(!hKey.IsClosed); @@ -182,7 +182,7 @@ public CspKeyContainerInfo CspKeyContainerInfo // .NET Framework compat: Read the SafeKeyHandle property to force the key to load, // because it might throw here. SafeKeyHandle localHandle = SafeKeyHandle; - Debug.Assert(localHandle != null); + Debug.Assert(localHandle is not null); return new CspKeyContainerInfo(_parameters, _randomKeyContainer); } @@ -264,7 +264,7 @@ public static bool UseMachineKeyStore /// decrypted data public byte[] Decrypt(byte[] rgb, bool fOAEP) { - if (rgb == null) + if (rgb is null) { throw new ArgumentNullException(nameof(rgb)); } @@ -295,12 +295,12 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) + if (_safeKeyHandle is not null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); } - if (_safeProvHandle != null && !_safeProvHandle.IsClosed) + if (_safeProvHandle is not null && !_safeProvHandle.IsClosed) { _safeProvHandle.Dispose(); } @@ -322,7 +322,7 @@ protected override void Dispose(bool disposing) /// Encrypted key public byte[] Encrypt(byte[] rgb, bool fOAEP) { - if (rgb == null) + if (rgb is null) { throw new ArgumentNullException(nameof(rgb)); } @@ -487,7 +487,7 @@ public byte[] SignData(Stream inputStream, object halg) /// The RSA signature for the specified data. public byte[] SignHash(byte[] rgbHash, string? str) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -506,7 +506,7 @@ public byte[] SignHash(byte[] rgbHash, string? str) /// The RSA signature for the specified data. private byte[] SignHash(byte[] rgbHash, int calgHash) { - Debug.Assert(rgbHash != null); + Debug.Assert(rgbHash is not null); return CapiHelper.SignValue( SafeProvHandle, @@ -533,9 +533,9 @@ public bool VerifyData(byte[] buffer, object halg, byte[] signature) /// public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { - if (rgbHash == null) + if (rgbHash is null) throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) + if (rgbSignature is null) throw new ArgumentNullException(nameof(rgbSignature)); int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); @@ -561,7 +561,7 @@ private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature) /// private static bool IsPublic(byte[] keyBlob) { - if (keyBlob == null) + if (keyBlob is null) { throw new ArgumentNullException(nameof(keyBlob)); } @@ -584,7 +584,7 @@ private static bool IsPublic(byte[] keyBlob) protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already - Debug.Assert(data != null); + Debug.Assert(data is not null); Debug.Assert(count >= 0 && count <= data.Length); Debug.Assert(offset >= 0 && offset <= data.Length - count); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); @@ -598,7 +598,7 @@ protected override byte[] HashData(byte[] data, int offset, int count, HashAlgor protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already - Debug.Assert(data != null); + Debug.Assert(data is not null); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm)) @@ -633,9 +633,9 @@ private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm) => public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); if (padding == RSAEncryptionPadding.Pkcs1) @@ -654,9 +654,9 @@ public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); if (padding == RSAEncryptionPadding.Pkcs1) @@ -678,11 +678,11 @@ public override byte[] SignHash( HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) + if (hash is null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); @@ -696,13 +696,13 @@ public override bool VerifyHash( HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) + if (hash is null) throw new ArgumentNullException(nameof(hash)); - if (signature == null) + if (signature is null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); - if (padding == null) + if (padding is null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.OSX.cs b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.OSX.cs index d2238ebdb62494..b22810cf24fbda 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.OSX.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.OSX.cs @@ -18,7 +18,7 @@ internal class AppleAsnFormatter : AsnFormatter { protected override string? FormatNative(Oid? oid, byte[] rawData, bool multiLine) { - if (oid == null || string.IsNullOrEmpty(oid.Value)) + if (oid is null || string.IsNullOrEmpty(oid.Value)) { return EncodeSpaceSeparatedHexString(rawData); } @@ -61,31 +61,31 @@ internal class AppleAsnFormatter : AsnFormatter { output.Append("othername:"); } - else if (generalName.Rfc822Name != null) + else if (generalName.Rfc822Name is not null) { output.Append("email:"); output.Append(generalName.Rfc822Name); } - else if (generalName.DnsName != null) + else if (generalName.DnsName is not null) { output.Append("DNS:"); output.Append(generalName.DnsName); } - else if (generalName.X400Address != null) + else if (generalName.X400Address is not null) { output.Append("X400Name:"); } - else if (generalName.DirectoryName != null) + else if (generalName.DirectoryName is not null) { // OpenSSL supports printing one of these, but the logic lives in X509Certificates, // and it isn't very common. So we'll skip this one until someone asks for it. output.Append("DirName:"); } - else if (generalName.EdiPartyName != null) + else if (generalName.EdiPartyName is not null) { output.Append("EdiPartyName:"); } - else if (generalName.Uri != null) + else if (generalName.Uri is not null) { output.Append("URI:"); output.Append(generalName.Uri); @@ -117,7 +117,7 @@ internal class AppleAsnFormatter : AsnFormatter output.Append(":"); } } - else if (generalName.RegisteredId != null) + else if (generalName.RegisteredId is not null) { output.Append("Registered ID:"); output.Append(generalName.RegisteredId); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.cs b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.cs index b83af59e0d2979..0bd00900a7c5cb 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/AsnFormatter.cs @@ -20,7 +20,7 @@ public string Format(Oid? oid, byte[] rawData, bool multiLine) protected static string EncodeSpaceSeparatedHexString(byte[] sArray) { - Debug.Assert(sArray != null && sArray.Length != 0); + Debug.Assert(sArray is not null && sArray.Length != 0); int length = (sArray.Length * 3) - 1; // two chars per byte, plus 1 space between each diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/CngAsnFormatter.cs b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/CngAsnFormatter.cs index 47e30eee50251e..35c1fdadb9ec66 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/CngAsnFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/CngAsnFormatter.cs @@ -17,7 +17,7 @@ internal sealed class CngAsnFormatter : AsnFormatter // If OID is not present, then we can force CryptFormatObject // to use hex formatting by providing an empty OID string. string oidValue = string.Empty; - if (oid != null && oid.Value != null) + if (oid is not null && oid.Value is not null) { oidValue = oid.Value; } @@ -49,7 +49,7 @@ internal sealed class CngAsnFormatter : AsnFormatter finally { Marshal.FreeHGlobal(oidValuePtr); - if (pooledarray != null) + if (pooledarray is not null) { ArrayPool.Shared.Return(pooledarray); } diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.cs b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.cs index a3fb3cf9acda49..6bf1c4dcf01e3c 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.cs @@ -22,7 +22,7 @@ internal static partial class OidLookup // public static string? ToFriendlyName(string oid, OidGroup oidGroup, bool fallBackToAllGroups) { - if (oid == null) + if (oid is null) throw new ArgumentNullException(nameof(oid)); string? mappedName; @@ -45,7 +45,7 @@ internal static partial class OidLookup mappedName = NativeOidToFriendlyName(oid, oidGroup, fallBackToAllGroups); - if (shouldUseCache && mappedName != null) + if (shouldUseCache && mappedName is not null) { s_lateBoundOidToFriendlyName.TryAdd(oid, mappedName); @@ -61,7 +61,7 @@ internal static partial class OidLookup // public static string? ToOid(string friendlyName, OidGroup oidGroup, bool fallBackToAllGroups) { - if (friendlyName == null) + if (friendlyName is null) throw new ArgumentNullException(nameof(friendlyName)); if (friendlyName.Length == 0) return null; @@ -80,7 +80,7 @@ internal static partial class OidLookup mappedOid = NativeFriendlyNameToOid(friendlyName, oidGroup, fallBackToAllGroups); - if (shouldUseCache && mappedOid != null) + if (shouldUseCache && mappedOid is not null) { s_lateBoundFriendlyNameToOid.TryAdd(friendlyName, mappedOid); @@ -141,7 +141,7 @@ static void AddEntry(string oid, string primaryFriendlyName, string[]? additiona s_oidToFriendlyName.Add(oid, primaryFriendlyName); s_friendlyNameToOid.Add(primaryFriendlyName, oid); - if (additionalFriendlyNames != null) + if (additionalFriendlyNames is not null) { foreach (var additionalName in additionalFriendlyNames) { diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OpenSslAsnFormatter.cs b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OpenSslAsnFormatter.cs index e033844c9d9cdc..aae4d4dfca3782 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OpenSslAsnFormatter.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OpenSslAsnFormatter.cs @@ -12,7 +12,7 @@ internal sealed class OpenSslAsnFormatter : AsnFormatter { protected override string? FormatNative(Oid? oid, byte[] rawData, bool multiLine) { - if (oid == null || string.IsNullOrEmpty(oid.Value)) + if (oid is null || string.IsNullOrEmpty(oid.Value)) { return EncodeSpaceSeparatedHexString(rawData); } diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedData.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedData.cs index 0a1555d698c9d8..3f7f520f43686a 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedData.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedData.cs @@ -34,7 +34,7 @@ public AsnEncodedData(ReadOnlySpan rawData) public AsnEncodedData(AsnEncodedData asnEncodedData) { - if (asnEncodedData == null) + if (asnEncodedData is null) throw new ArgumentNullException(nameof(asnEncodedData)); Reset(asnEncodedData._oid, asnEncodedData._rawData); } @@ -96,7 +96,7 @@ public byte[] RawData [MemberNotNull(nameof(_rawData))] set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _rawData = value.CloneByteArray(); } @@ -104,7 +104,7 @@ public byte[] RawData public virtual void CopyFrom(AsnEncodedData asnEncodedData) { - if (asnEncodedData == null) + if (asnEncodedData is null) throw new ArgumentNullException(nameof(asnEncodedData)); Reset(asnEncodedData._oid, asnEncodedData._rawData); } @@ -112,7 +112,7 @@ public virtual void CopyFrom(AsnEncodedData asnEncodedData) public virtual string Format(bool multiLine) { // Return empty string if no data to format. - if (_rawData == null || _rawData.Length == 0) + if (_rawData is null || _rawData.Length == 0) return string.Empty; return AsnFormatter.Instance.Format(_oid, _rawData, multiLine); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedDataCollection.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedDataCollection.cs index a726efe6850430..7abeffff96d2da 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedDataCollection.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/AsnEncodedDataCollection.cs @@ -23,7 +23,7 @@ public AsnEncodedDataCollection(AsnEncodedData asnEncodedData) public int Add(AsnEncodedData asnEncodedData) { - if (asnEncodedData == null) + if (asnEncodedData is null) throw new ArgumentNullException(nameof(asnEncodedData)); int indexOfNewItem = _list.Count; @@ -33,7 +33,7 @@ public int Add(AsnEncodedData asnEncodedData) public void Remove(AsnEncodedData asnEncodedData) { - if (asnEncodedData == null) + if (asnEncodedData is null) throw new ArgumentNullException(nameof(asnEncodedData)); _list.Remove(asnEncodedData); } @@ -66,7 +66,7 @@ IEnumerator IEnumerable.GetEnumerator() void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -87,7 +87,7 @@ public void CopyTo(AsnEncodedData[] array, int index) // Need to do part of the argument validation ourselves as AsnEncodedDataCollection throws // ArgumentOutOfRangeException where List<>.CopyTo() throws ArgumentException. - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Base64Transforms.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Base64Transforms.cs index 02ec934c51febe..f9518f7a8f8bff 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Base64Transforms.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Base64Transforms.cs @@ -31,7 +31,7 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b // inputCount < InputBlockSize is not allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount, InputBlockSize); - if (outputBuffer == null) + if (outputBuffer is null) ThrowHelper.ThrowArgumentNull(ThrowHelper.ExceptionArgument.outputBuffer); // For now, only convert 3 bytes to 4 @@ -134,10 +134,10 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b // inputCount != InputBlockSize is allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount); - if (_inputBuffer == null) + if (_inputBuffer is null) ThrowHelper.ThrowObjectDisposed(); - if (outputBuffer == null) + if (outputBuffer is null) ThrowHelper.ThrowArgumentNull(ThrowHelper.ExceptionArgument.outputBuffer); // The common case is inputCount = InputBlockSize @@ -175,7 +175,7 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input // inputCount != InputBlockSize is allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount); - if (_inputBuffer == null) + if (_inputBuffer is null) { ThrowHelper.ThrowObjectDisposed(); } @@ -326,7 +326,7 @@ private void ConvertFromBase64(Span tmpBuffer, Span outputBuffer, ou private void ReturnToCryptoPool(byte[]? array, int clearSize) { - if (array != null) + if (array is not null) { CryptoPool.Return(array, clearSize); } @@ -356,7 +356,7 @@ protected virtual void Dispose(bool disposing) // we always want to clear the input buffer if (disposing) { - if (_inputBuffer != null) + if (_inputBuffer is not null) { CryptographicOperations.ZeroMemory(_inputBuffer); _inputBuffer = null!; @@ -377,7 +377,7 @@ internal class ThrowHelper [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount) { - if (inputBuffer == null) + if (inputBuffer is null) ThrowArgumentNull(ExceptionArgument.inputBuffer); if ((uint)inputCount > inputBuffer.Length) diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Oid.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Oid.cs index c3f6a28ff077b9..74d02e93297f6e 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Oid.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/Oid.cs @@ -16,7 +16,7 @@ public Oid(string oid) { // If we were passed the friendly name, retrieve the value String. string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false); - if (oidValue == null) + if (oidValue is null) { oidValue = oid; } @@ -29,12 +29,12 @@ public Oid(string? value, string? friendlyName) { _value = value; _friendlyName = friendlyName; - _hasInitializedFriendlyName = friendlyName != null; + _hasInitializedFriendlyName = friendlyName is not null; } public Oid(Oid oid) { - if (oid == null) + if (oid is null) throw new ArgumentNullException(nameof(oid)); _value = oid._value; _friendlyName = oid._friendlyName; @@ -44,13 +44,13 @@ public Oid(Oid oid) public static Oid FromFriendlyName(string friendlyName, OidGroup group) { - if (friendlyName == null) + if (friendlyName is null) { throw new ArgumentNullException(nameof(friendlyName)); } string? oidValue = OidLookup.ToOid(friendlyName, group, fallBackToAllGroups: false); - if (oidValue == null) + if (oidValue is null) throw new CryptographicException(SR.Cryptography_Oid_InvalidName); return new Oid(oidValue, friendlyName, group); @@ -58,11 +58,11 @@ public static Oid FromFriendlyName(string friendlyName, OidGroup group) public static Oid FromOidValue(string oidValue, OidGroup group) { - if (oidValue == null) + if (oidValue is null) throw new ArgumentNullException(nameof(oidValue)); string? friendlyName = OidLookup.ToFriendlyName(oidValue, group, fallBackToAllGroups: false); - if (friendlyName == null) + if (friendlyName is null) throw new CryptographicException(SR.Cryptography_Oid_InvalidValue); return new Oid(oidValue, friendlyName, group); @@ -75,7 +75,7 @@ public string? Value { // If _value has not been set, permit it to be set once, or to // the same value for "initialize once" behavior. - if (_value != null && !_value.Equals(value, StringComparison.Ordinal)) + if (_value is not null && !_value.Equals(value, StringComparison.Ordinal)) { throw new PlatformNotSupportedException(SR.Cryptography_Oid_SetOnceValue); } @@ -88,7 +88,7 @@ public string? FriendlyName { get { - if (!_hasInitializedFriendlyName && _value != null) + if (!_hasInitializedFriendlyName && _value is not null) { _friendlyName = OidLookup.ToFriendlyName(_value, _group, fallBackToAllGroups: true); _hasInitializedFriendlyName = true; @@ -102,8 +102,8 @@ public string? FriendlyName // the same value for "initialize once" behavior. if (_hasInitializedFriendlyName) { - if ((_friendlyName != null && !_friendlyName.Equals(value, StringComparison.Ordinal)) || - (_friendlyName is null && value != null)) + if ((_friendlyName is not null && !_friendlyName.Equals(value, StringComparison.Ordinal)) || + (_friendlyName is null && value is not null)) { throw new PlatformNotSupportedException(SR.Cryptography_Oid_SetOnceFriendlyName); } @@ -113,16 +113,16 @@ public string? FriendlyName } // If we can find the matching OID value, then update it as well - if (value != null) + if (value is not null) { // If FindOidInfo fails, we return a null String string? oidValue = OidLookup.ToOid(value, _group, fallBackToAllGroups: true); - if (oidValue != null) + if (oidValue is not null) { // If the OID value has not been initialized, set it // to the lookup value. - if (_value == null) + if (_value is null) { _value = oidValue; } @@ -146,8 +146,8 @@ public string? FriendlyName private Oid(string value, string friendlyName, OidGroup group) { - Debug.Assert(value != null); - Debug.Assert(friendlyName != null); + Debug.Assert(value is not null); + Debug.Assert(friendlyName is not null); _value = value; _friendlyName = friendlyName; diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/OidCollection.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/OidCollection.cs index 4b76860a983ba7..0adbb9aca1f8ef 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/OidCollection.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/OidCollection.cs @@ -46,7 +46,7 @@ public Oid? this[string oid] { // If we were passed the friendly name, retrieve the value String. string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false); - if (oidValue == null) + if (oidValue is null) { oidValue = oid; } @@ -68,7 +68,7 @@ public Oid? this[string oid] void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -89,7 +89,7 @@ public void CopyTo(Oid[] array, int index) // Need to do part of the argument validation ourselves as OidCollection throws // ArgumentOutOfRangeException where List<>.CopyTo() throws ArgumentException. - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); diff --git a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/DSAOpenSsl.cs b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/DSAOpenSsl.cs index f0bef49360ea8f..0c5dfe7d930566 100644 --- a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/DSAOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/DSAOpenSsl.cs @@ -26,7 +26,7 @@ public DSAOpenSsl(DSAParameters parameters) /// is not a valid enveloped DSA* public DSAOpenSsl(SafeEvpPKeyHandle pkeyHandle) { - if (pkeyHandle == null) + if (pkeyHandle is null) throw new ArgumentNullException(nameof(pkeyHandle)); if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs index 09d0809b6b64da..b1124d13e50d8b 100644 --- a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs @@ -18,7 +18,7 @@ public sealed partial class ECDiffieHellmanOpenSsl : ECDiffieHellman /// is not a valid enveloped EC_KEY* public ECDiffieHellmanOpenSsl(SafeEvpPKeyHandle pkeyHandle) { - if (pkeyHandle == null) + if (pkeyHandle is null) throw new ArgumentNullException(nameof(pkeyHandle)); if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDsaOpenSsl.cs b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDsaOpenSsl.cs index 2bf99c2315dab2..77be863ba0a0fb 100644 --- a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDsaOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/ECDsaOpenSsl.cs @@ -18,7 +18,7 @@ public sealed partial class ECDsaOpenSsl : ECDsa /// is not a valid enveloped EC_KEY* public ECDsaOpenSsl(SafeEvpPKeyHandle pkeyHandle) { - if (pkeyHandle == null) + if (pkeyHandle is null) throw new ArgumentNullException(nameof(pkeyHandle)); if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/RSAOpenSsl.cs b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/RSAOpenSsl.cs index a666cfc65472ae..788e88732de814 100644 --- a/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/RSAOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography.OpenSsl/src/System/Security/Cryptography/RSAOpenSsl.cs @@ -49,7 +49,7 @@ public RSAOpenSsl(IntPtr handle) /// is not a valid enveloped RSA* public RSAOpenSsl(SafeEvpPKeyHandle pkeyHandle) { - if (pkeyHandle == null) + if (pkeyHandle is null) throw new ArgumentNullException(nameof(pkeyHandle)); if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/AsnHelpers.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/AsnHelpers.cs index a9df02585bb77b..779cfe309db402 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/AsnHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/AsnHelpers.cs @@ -60,7 +60,7 @@ internal static AlgorithmIdentifier ToPresentationObject(this AlgorithmIdentifie { case Oids.Rc2Cbc: { - if (asn.Parameters == null) + if (asn.Parameters is null) { keyLength = 0; break; @@ -90,7 +90,7 @@ internal static AlgorithmIdentifier ToPresentationObject(this AlgorithmIdentifie } case Oids.Rc4: { - if (asn.Parameters == null) + if (asn.Parameters is null) { keyLength = 0; break; @@ -138,7 +138,7 @@ internal static AlgorithmIdentifier ToPresentationObject(this AlgorithmIdentifie break; case Oids.RsaOaep when !asn.HasNullEquivalentParameters(): keyLength = 0; - Debug.Assert(asn.Parameters != null); + Debug.Assert(asn.Parameters is not null); parameters = asn.Parameters.Value.ToArray(); break; default: diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decode.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decode.cs index 6e934628ad7337..52119b011eef03 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decode.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decode.cs @@ -39,11 +39,11 @@ public override DecryptorPal Decode( originatorCerts = new X509Certificate2Collection(); - if (data.OriginatorInfo.HasValue && data.OriginatorInfo.Value.CertificateSet != null) + if (data.OriginatorInfo.HasValue && data.OriginatorInfo.Value.CertificateSet is not null) { foreach (CertificateChoiceAsn certChoice in data.OriginatorInfo.Value.CertificateSet) { - if (certChoice.Certificate != null) + if (certChoice.Certificate is not null) { originatorCerts.Add(new X509Certificate2(certChoice.Certificate.Value.ToArray())); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs index bfb2ef363086ff..6c1b05f13993dd 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs @@ -40,13 +40,13 @@ public ManagedDecryptorPal( // When encryptedContent is null Windows seems to decrypt the CEK first, // then return a 0 byte answer. - Debug.Assert((cert != null) ^ (privateKey != null)); + Debug.Assert((cert is not null) ^ (privateKey is not null)); if (recipientInfo.Pal is ManagedKeyTransPal ktri) { RSA? key = privateKey as RSA; - if (privateKey != null && key == null) + if (privateKey is not null && key is null) { exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired); return null; @@ -58,7 +58,7 @@ public ManagedDecryptorPal( { try { - if (exception != null) + if (exception is not null) { return null; } @@ -72,7 +72,7 @@ public ManagedDecryptorPal( } finally { - if (cek != null) + if (cek is not null) { Array.Clear(cek, 0, cek.Length); } @@ -96,7 +96,7 @@ public ManagedDecryptorPal( AlgorithmIdentifierAsn contentEncryptionAlgorithm, out Exception? exception) { - if (content == null) + if (content is null) { exception = null; @@ -107,7 +107,7 @@ public ManagedDecryptorPal( byte[]? decrypted = DecryptContent(content.Value, cek, contentEncryptionAlgorithm, out exception); - if (exception != null) + if (exception is not null) { return null; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs index c5b544d8cd3cff..751df85379b5b1 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs @@ -76,14 +76,14 @@ private byte[] Encrypt( }, }; - if (unprotectedAttributes != null && unprotectedAttributes.Count > 0) + if (unprotectedAttributes is not null && unprotectedAttributes.Count > 0) { List attrList = CmsSigner.BuildAttributes(unprotectedAttributes); envelopedData.UnprotectedAttributes = PkcsHelpers.NormalizeAttributeSet(attrList.ToArray()); } - if (originatorCerts != null && originatorCerts.Count > 0) + if (originatorCerts is not null && originatorCerts.Count > 0) { CertificateChoiceAsn[] certs = new CertificateChoiceAsn[originatorCerts.Count]; @@ -134,9 +134,9 @@ private byte[] Encrypt( // v0 (RFC 2315): // * Anything not already matched - if (envelopedData.OriginatorInfo != null || + if (envelopedData.OriginatorInfo is not null || !allRecipientsVersion0 || - envelopedData.UnprotectedAttributes != null) + envelopedData.UnprotectedAttributes is not null) { envelopedData.Version = 2; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyAgree.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyAgree.cs index 56dfa70534e10d..162c76bbd64213 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyAgree.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyAgree.cs @@ -78,7 +78,7 @@ public override CryptographicAttributeObject? OtherKeyAttribute Oid oid = new Oid(rid.RKeyId.Value.Other.Value.KeyAttrId); byte[] rawData = Array.Empty(); - if (rid.RKeyId.Value.Other.Value.KeyAttr != null) + if (rid.RKeyId.Value.Other.Value.KeyAttr is not null) { rawData = rid.RKeyId.Value.Other.Value.KeyAttr!.Value.ToArray(); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyTrans.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyTrans.cs index e95be29e999099..565d1137f8ac1a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyTrans.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyTrans.cs @@ -40,7 +40,7 @@ internal ManagedKeyTransPal(KeyTransRecipientInfoAsn asn) switch (keyEncryptionAlgorithm) { case Oids.Rsa: - if (parameters != null && + if (parameters is not null && !parameters.Value.Span.SequenceEqual(s_rsaPkcsParameters)) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); @@ -89,13 +89,13 @@ internal ManagedKeyTransPal(KeyTransRecipientInfoAsn asn) return null; } - if (privateKey != null) + if (privateKey is not null) { return DecryptKey(privateKey, encryptionPadding, encryptedKey, out exception); } else { - Debug.Assert(cert != null); + Debug.Assert(cert is not null); using (RSA? rsa = cert.GetRSAPrivateKey()) { return DecryptKey(rsa, encryptionPadding, encryptedKey, out exception); @@ -183,7 +183,7 @@ private KeyTransRecipientInfoAsn MakeKtri( ReadOnlySpan encryptedKey, out Exception? exception) { - if (privateKey == null) + if (privateKey is null) { exception = new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey); return null; @@ -214,7 +214,7 @@ private KeyTransRecipientInfoAsn MakeKtri( } finally { - if (cek != null) + if (cek is not null) { CryptoPool.Return(cek, cekLength); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs index 94e8c460e4ce52..a55409333640e4 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs @@ -31,11 +31,11 @@ public override void AddCertsFromStoreForDecryption(X509Certificate2Collection c public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate) { - Debug.Assert(certificate != null); + Debug.Assert(certificate is not null); X509Extension? extension = certificate.Extensions[Oids.SubjectKeyIdentifier]; - if (extension == null) + if (extension is null) { // Construct the value from the public key info. extension = new X509SubjectKeyIdentifierExtension( @@ -98,7 +98,7 @@ private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEn if (alg is RC2) { - if (contentEncryptionAlgorithm.Parameters == null) + if (contentEncryptionAlgorithm.Parameters is null) { // Windows issues CRYPT_E_BAD_DECODE throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); @@ -113,7 +113,7 @@ private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEn } else { - if (contentEncryptionAlgorithm.Parameters == null) + if (contentEncryptionAlgorithm.Parameters is null) { // Windows issues CRYPT_E_BAD_DECODE throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); @@ -159,7 +159,7 @@ private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIde private static SymmetricAlgorithm OpenAlgorithm(string algorithmIdentifier) { - Debug.Assert(algorithmIdentifier != null); + Debug.Assert(algorithmIdentifier is not null); SymmetricAlgorithm alg; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decode.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decode.cs index d2df673bdd6733..a41c34506b4b14 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decode.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decode.cs @@ -26,7 +26,7 @@ out CryptographicAttributeObjectCollection unprotectedAttributes ) { SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToDecode(MsgEncodingType.All, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); - if (hCryptMsg == null || hCryptMsg.IsInvalid) + if (hCryptMsg is null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); if (!Interop.Crypt32.CryptMsgUpdate( diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decrypt.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decrypt.cs index 8ab01da453d0ce..c7498cc9b42252 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decrypt.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decrypt.cs @@ -24,13 +24,13 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal X509Certificate2Collection extraStore, out Exception? exception) { - Debug.Assert((cert != null) ^ (privateKey != null)); + Debug.Assert((cert is not null) ^ (privateKey is not null)); - if (privateKey != null) + if (privateKey is not null) { RSA? key = privateKey as RSA; - if (key == null) + if (key is null) { exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired); return null; @@ -50,7 +50,7 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal { try { - if (exception != null) + if (exception is not null) { return null; } @@ -64,7 +64,7 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal } finally { - if (cek != null) + if (cek is not null) { Array.Clear(cek, 0, cek.Length); } @@ -72,14 +72,14 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal } } - Debug.Assert(recipientInfo != null); - Debug.Assert(cert != null); - Debug.Assert(originatorCerts != null); - Debug.Assert(extraStore != null); + Debug.Assert(recipientInfo is not null); + Debug.Assert(cert is not null); + Debug.Assert(originatorCerts is not null); + Debug.Assert(extraStore is not null); CryptKeySpec keySpec; exception = TryGetKeySpecForCertificate(cert, out keySpec); - if (exception != null) + if (exception is not null) return null; // .NET Framework compat: We pass false for "silent" here (thus allowing crypto providers to display UI.) @@ -90,7 +90,7 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal const bool PreferNCrypt = false; using (SafeProvOrNCryptKeyHandle? hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception)) { - if (hKey == null) + if (hKey is null) return null; RecipientInfoType type = recipientInfo.Type; @@ -111,7 +111,7 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal throw new NotSupportedException(); } - if (exception != null) + if (exception is not null) return null; // If we got here, we successfully decrypted. Return the decrypted content. @@ -206,7 +206,7 @@ internal sealed partial class DecryptorPalWindows : DecryptorPal candidateCerts.AddRange(extraStore); SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier(); X509Certificate2? originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId); - if (originatorCert == null) + if (originatorCert is null) return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException(); using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle()) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.cs index 1d7b37cf4bd589..ca375a8a625f0a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.cs @@ -21,7 +21,7 @@ private DecryptorPalWindows( public sealed override void Dispose() { - if (_hCryptMsg != null && !_hCryptMsg.IsInvalid) + if (_hCryptMsg is not null && !_hCryptMsg.IsInvalid) { _hCryptMsg.Dispose(); _hCryptMsg = null!; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HeapBlockRetainer.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HeapBlockRetainer.cs index 98f720ed946959..c389fb7cf9cb67 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HeapBlockRetainer.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HeapBlockRetainer.cs @@ -68,7 +68,7 @@ public void KeepAlive(object o) public void Dispose() { - if (_blocks != null) + if (_blocks is not null) { foreach (SafeHeapAllocHandle h in _blocks) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs index ac5a28e7801323..43094e84312e6d 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs @@ -407,7 +407,7 @@ public static CspParameters GetProvParameters(this SafeProvOrNCryptKeyHandle han string keyName = GetStringProvParam(handle, CryptProvParam.PP_CONTAINER, ref asciiStringBuf, ref rented, maxClear); maxClear = Math.Max(maxClear, keyName.Length); - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, maxClear); } @@ -434,7 +434,7 @@ private static string GetStringProvParam( { if (len > buf.Length) { - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, clearLen); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/KeyAgreeRecipientInfoPalWindows.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/KeyAgreeRecipientInfoPalWindows.cs index acd8f805d6e34d..73a0ecf38d3c82 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/KeyAgreeRecipientInfoPalWindows.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/KeyAgreeRecipientInfoPalWindows.cs @@ -145,7 +145,7 @@ public sealed override CryptographicAttributeObject? OtherKeyAttribute { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; CRYPT_ATTRIBUTE_TYPE_VALUE* pCryptAttributeTypeValue = pEncryptedKeyInfo->pOtherAttr; - if (pCryptAttributeTypeValue == null) + if (pCryptAttributeTypeValue is null) return null; string oidValue = pCryptAttributeTypeValue->pszObjId.ToStringAnsi(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.Encrypt.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.Encrypt.cs index 761d1bbdbbb936..6160af62467439 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.Encrypt.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.Encrypt.cs @@ -121,7 +121,7 @@ public static SafeCryptMsgHandle CreateCryptMsgHandleToEncode(CmsRecipientCollec { CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = CreateCmsEnvelopedEncodeInfo(recipients, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes, hb); SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value!, IntPtr.Zero); - if (hCryptMsg == null || hCryptMsg.IsInvalid) + if (hCryptMsg is null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); return hCryptMsg; @@ -266,7 +266,7 @@ private static CMSG_RECIPIENT_ENCODE_INFO EncodeRecipientInfo(CmsRecipient recip { byte[] parameters = recipient.Certificate.GetKeyAlgorithmParameters(); - if (parameters == null || parameters.Length == 0) + if (parameters is null || parameters.Length == 0) { padding = RSAEncryptionPadding.OaepSHA1; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs index a5ec578a291b75..8e6c952b83466e 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs @@ -32,7 +32,7 @@ public sealed override Oid GetEncodedMessageType(ReadOnlySpan encodedMessa { using (SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToDecode(MsgEncodingType.All, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) { - if (hCryptMsg == null || hCryptMsg.IsInvalid) + if (hCryptMsg is null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, ref MemoryMarshal.GetReference(encodedMessage), encodedMessage.Length, fFinal: true)) @@ -117,9 +117,9 @@ public sealed override byte[] GetSubjectKeyIdentifier(X509Certificate2 certifica using (handle) { - if (handle == null || handle.IsInvalid) + if (handle is null || handle.IsInvalid) { - if (exception != null) + if (exception is not null) { throw exception; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsHelpers.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsHelpers.cs index bb0e6ee90f427b..0d98d69a36c4f6 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsHelpers.cs @@ -46,7 +46,7 @@ internal static void AppendData(this IncrementalHash hasher, ReadOnlySpan internal static HashAlgorithmName GetDigestAlgorithm(Oid oid) { - Debug.Assert(oid != null); + Debug.Assert(oid is not null); return GetDigestAlgorithm(oid.Value); } @@ -107,7 +107,7 @@ public static byte[] Resize(this byte[] a, int size) public static void RemoveAt(ref T[] arr, int idx) { - Debug.Assert(arr != null); + Debug.Assert(arr is not null); Debug.Assert(idx >= 0); Debug.Assert(idx < arr.Length); @@ -149,7 +149,7 @@ public static AttributeAsn[] NormalizeAttributeSet( writer.PopSetOf(); normalizedValue = writer.Encode(); - if (encodedValueProcessor != null) + if (encodedValueProcessor is not null) { encodedValueProcessor(normalizedValue); } @@ -643,7 +643,7 @@ public static bool TryGetRsaOaepEncryptionPadding( exception = null; rsaEncryptionPadding = null; - if (parameters == null || parameters.Value.IsEmpty) + if (parameters is null || parameters.Value.IsEmpty) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return false; @@ -654,7 +654,7 @@ public static bool TryGetRsaOaepEncryptionPadding( OaepParamsAsn oaepParameters = OaepParamsAsn.Decode(parameters.Value, AsnEncodingRules.DER); if (oaepParameters.MaskGenFunc.Algorithm != Oids.Mgf1 || - oaepParameters.MaskGenFunc.Parameters == null || + oaepParameters.MaskGenFunc.Parameters is null || oaepParameters.PSourceFunc.Algorithm != Oids.PSpecified ) { @@ -672,7 +672,7 @@ public static bool TryGetRsaOaepEncryptionPadding( ReadOnlySpan pSpecifiedDefaultParameters = new byte[] { 0x04, 0x00 }; - if (oaepParameters.PSourceFunc.Parameters != null && + if (oaepParameters.PSourceFunc.Parameters is not null && !oaepParameters.PSourceFunc.Parameters.Value.Span.SequenceEqual(pSpecifiedDefaultParameters)) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Microsoft/Win32/SafeHandles/SafeProvOrNCryptKeyHandleUwp.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Microsoft/Win32/SafeHandles/SafeProvOrNCryptKeyHandleUwp.cs index a1ac99fff12498..e39c41558dc546 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Microsoft/Win32/SafeHandles/SafeProvOrNCryptKeyHandleUwp.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Microsoft/Win32/SafeHandles/SafeProvOrNCryptKeyHandleUwp.cs @@ -18,7 +18,7 @@ internal sealed class SafeProvOrNCryptKeyHandleUwp : SafeProvOrNCryptKeyHandle internal SafeProvOrNCryptKeyHandleUwp(IntPtr handle, SafeHandle parentHandle) : this(handle, true, true) { - Debug.Assert(parentHandle != null && !parentHandle.IsClosed && !parentHandle.IsInvalid); + Debug.Assert(parentHandle is not null && !parentHandle.IsClosed && !parentHandle.IsInvalid); // If the provided handle value wasn't valid we won't call dispose, so we shouldn't be doing this. Debug.Assert(!IsInvalid); @@ -36,7 +36,7 @@ internal SafeProvOrNCryptKeyHandleUwp(IntPtr handle, bool ownsHandle, bool isNcr protected sealed override bool ReleaseHandle() { - if (_parentHandle != null) + if (_parentHandle is not null) { _parentHandle.DangerousRelease(); _parentHandle = null; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObject.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObject.cs index 16b6ffecd62ed2..cff79ffa761400 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObject.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObject.cs @@ -21,7 +21,7 @@ public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection? values) { _oid = oid.CopyOid(); - if (values == null) + if (values is null) { Values = new AsnEncodedDataCollection(); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs index 7386c67b655fa0..3961232ea882dc 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs @@ -25,7 +25,7 @@ public CryptographicAttributeObjectCollection(CryptographicAttributeObject attri public int Add(AsnEncodedData asnEncodedData) { - if (asnEncodedData == null) + if (asnEncodedData is null) throw new ArgumentNullException(nameof(asnEncodedData)); return Add(new CryptographicAttributeObject(asnEncodedData.Oid!, new AsnEncodedDataCollection(asnEncodedData))); @@ -33,7 +33,7 @@ public int Add(AsnEncodedData asnEncodedData) public int Add(CryptographicAttributeObject attribute) { - if (attribute == null) + if (attribute is null) throw new ArgumentNullException(nameof(attribute)); // @@ -73,13 +73,13 @@ public int Add(CryptographicAttributeObject attribute) internal void AddWithoutMerge(CryptographicAttributeObject attribute) { - Debug.Assert(attribute != null); + Debug.Assert(attribute is not null); _list.Add(attribute); } public void Remove(CryptographicAttributeObject attribute) { - if (attribute == null) + if (attribute is null) throw new ArgumentNullException(nameof(attribute)); _list.Remove(attribute); @@ -129,7 +129,7 @@ IEnumerator IEnumerable.GetEnumerator() void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -147,7 +147,7 @@ void ICollection.CopyTo(Array array, int index) public void CopyTo(CryptographicAttributeObject[] array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/EnvelopedDataAsn.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/EnvelopedDataAsn.xml.cs index 0b53dbf283196a..2ab6ee2972b363 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/EnvelopedDataAsn.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/EnvelopedDataAsn.xml.cs @@ -44,7 +44,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) EncryptedContentInfo.Encode(writer); - if (UnprotectedAttributes != null) + if (UnprotectedAttributes is not null) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, 1)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/OriginatorInfoAsn.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/OriginatorInfoAsn.xml.cs index 1ccd9a508e268f..303e67dc2f0f62 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/OriginatorInfoAsn.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/OriginatorInfoAsn.xml.cs @@ -25,7 +25,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) writer.PushSequence(tag); - if (CertificateSet != null) + if (CertificateSet is not null) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, 0)); @@ -38,7 +38,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) } - if (RevocationInfoChoices != null) + if (RevocationInfoChoices is not null) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, 1)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/PolicyInformation.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/PolicyInformation.xml.cs index 4a4c855480b17c..9d5c0c89cea678 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/PolicyInformation.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/PolicyInformation.xml.cs @@ -33,7 +33,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } - if (PolicyQualifiers != null) + if (PolicyQualifiers is not null) { writer.PushSequence(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TimeStampReq.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TimeStampReq.xml.cs index 0d969469d17103..d28d7ceb649e6f 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TimeStampReq.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TimeStampReq.xml.cs @@ -45,7 +45,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) writer.WriteInteger(Version); MessageImprint.Encode(writer); - if (ReqPolicy != null) + if (ReqPolicy is not null) { try { @@ -76,7 +76,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) } - if (Extensions != null) + if (Extensions is not null) { writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TstInfo.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TstInfo.xml.cs index 91978b9a29f453..711242842946a1 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TstInfo.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TstInfo.xml.cs @@ -91,7 +91,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) } - if (Extensions != null) + if (Extensions is not null) { writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 1)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedAttributesSet.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedAttributesSet.xml.cs index b56e8cf6fa58d0..a87d0519486951 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedAttributesSet.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedAttributesSet.xml.cs @@ -36,7 +36,7 @@ internal void Encode(AsnWriter writer) { bool wroteValue = false; - if (SignedAttributes != null) + if (SignedAttributes is not null) { if (wroteValue) throw new CryptographicException(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedDataAsn.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedDataAsn.xml.cs index b538c4f643035f..a0742215318751 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedDataAsn.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedDataAsn.xml.cs @@ -39,7 +39,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) EncapContentInfo.Encode(writer); - if (CertificateSet != null) + if (CertificateSet is not null) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, 0)); @@ -52,7 +52,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) } - if (Crls != null) + if (Crls is not null) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, 1)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignerInfoAsn.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignerInfoAsn.xml.cs index dff84cad21cd4b..1d6ebf756134b4 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignerInfoAsn.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignerInfoAsn.xml.cs @@ -57,7 +57,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) SignatureAlgorithm.Encode(writer); writer.WriteOctetString(SignatureValue.Span); - if (UnsignedAttributes != null) + if (UnsignedAttributes is not null) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, 1)); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateAsn.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateAsn.xml.cs index 0489040a98bc7f..2185871b0ee660 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateAsn.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateAsn.xml.cs @@ -33,7 +33,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) writer.PopSequence(); - if (Policies != null) + if (Policies is not null) { writer.PushSequence(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateV2Asn.xml.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateV2Asn.xml.cs index 5cfe07ae35919f..1281911e9f6896 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateV2Asn.xml.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SigningCertificateV2Asn.xml.cs @@ -33,7 +33,7 @@ internal void Encode(AsnWriter writer, Asn1Tag tag) writer.PopSequence(); - if (Policies != null) + if (Policies is not null) { writer.PushSequence(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs index 3c4188f44c03e7..9cfc56b75e145b 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs @@ -40,7 +40,7 @@ public CmsRecipient(X509Certificate2 certificate) public CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate) { - if (certificate == null) + if (certificate is null) throw new ArgumentNullException(nameof(certificate)); switch (recipientIdentifierType) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs index 9a040572e4884c..b085f71721704a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs @@ -24,7 +24,7 @@ public CmsRecipientCollection(CmsRecipient recipient) public CmsRecipientCollection(SubjectIdentifierType recipientIdentifierType, X509Certificate2Collection certificates) { - if (certificates == null) + if (certificates is null) throw new NullReferenceException(); //Desktop compat: this is the wrong exception to throw but it is the compatible one. _recipients = new List(certificates.Count); @@ -55,7 +55,7 @@ public int Count public int Add(CmsRecipient recipient) { - if (recipient == null) + if (recipient is null) throw new ArgumentNullException(nameof(recipient)); int indexOfNewItem = _recipients.Count; @@ -65,7 +65,7 @@ public int Add(CmsRecipient recipient) public void Remove(CmsRecipient recipient) { - if (recipient == null) + if (recipient is null) throw new ArgumentNullException(nameof(recipient)); _recipients.Remove(recipient); @@ -83,7 +83,7 @@ IEnumerator IEnumerable.GetEnumerator() public void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -101,7 +101,7 @@ public void CopyTo(Array array, int index) public void CopyTo(CmsRecipient[] array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.DSA.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.DSA.cs index 40b0b6e4103359..97ab5c2791a257 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.DSA.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.DSA.cs @@ -33,7 +33,7 @@ internal DSACmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedD protected override bool VerifyKeyType(AsymmetricAlgorithm key) { - return (key as DSA) != null; + return (key as DSA) is not null; } internal override bool VerifySignature( @@ -60,7 +60,7 @@ internal override bool VerifySignature( DSA? dsa = certificate.GetDSAPublicKey(); - if (dsa == null) + if (dsa is null) { return false; } @@ -110,7 +110,7 @@ protected override bool Sign( PkcsPal.Instance.GetPrivateKeyForSigning(certificate, silent) ?? certificate.GetDSAPublicKey(); - if (dsa == null) + if (dsa is null) { signatureAlgorithm = null; signatureValue = null; @@ -124,7 +124,7 @@ protected override bool Sign( hashAlgorithmName == HashAlgorithmName.SHA512 ? Oids.DsaWithSha512 : null; - if (oidValue == null) + if (oidValue is null) { signatureAlgorithm = null; signatureValue = null; @@ -144,7 +144,7 @@ protected override bool Sign( { var signature = new ReadOnlySpan(rented, 0, bytesWritten); - if (key != null && !certificate.GetDSAPublicKey()!.VerifySignature(dataHash, signature)) + if (key is not null && !certificate.GetDSAPublicKey()!.VerifySignature(dataHash, signature)) { // key did not match certificate signatureValue = null; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.ECDsa.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.ECDsa.cs index 9a4a92a65a6b49..e3bffb9ecb231a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.ECDsa.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.ECDsa.cs @@ -33,7 +33,7 @@ internal ECDsaCmsSignature(string? signatureAlgorithm, HashAlgorithmName expecte protected override bool VerifyKeyType(AsymmetricAlgorithm key) { - return (key as ECDsa) != null; + return (key as ECDsa) is not null; } internal override bool VerifySignature( @@ -60,7 +60,7 @@ internal override bool VerifySignature( ECDsa? key = certificate.GetECDsaPublicKey(); - if (key == null) + if (key is null) { return false; } @@ -115,7 +115,7 @@ protected override bool Sign( PkcsPal.Instance.GetPrivateKeyForSigning(certificate, silent) ?? certificate.GetECDsaPublicKey(); - if (key == null) + if (key is null) { signatureAlgorithm = null; signatureValue = null; @@ -129,7 +129,7 @@ protected override bool Sign( hashAlgorithmName == HashAlgorithmName.SHA512 ? Oids.ECDsaWithSha512 : null; - if (oidValue == null) + if (oidValue is null) { signatureAlgorithm = null; signatureValue = null; @@ -156,7 +156,7 @@ protected override bool Sign( { var signedHash = new ReadOnlySpan(rented, 0, bytesWritten); - if (key != null && !certificate.GetECDsaPublicKey()!.VerifyHash(dataHash, signedHash)) + if (key is not null && !certificate.GetECDsaPublicKey()!.VerifyHash(dataHash, signedHash)) { // key did not match certificate signatureValue = null; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs index cc3b8ef6963493..dea692fb0d6901 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs @@ -36,7 +36,7 @@ protected RSACmsSignature(string? signatureAlgorithm, HashAlgorithmName? expecte protected override bool VerifyKeyType(AsymmetricAlgorithm key) { - return (key as RSA) != null; + return (key as RSA) is not null; } internal override bool VerifySignature( @@ -69,7 +69,7 @@ internal override bool VerifySignature( RSA? publicKey = certificate.GetRSAPublicKey(); - if (publicKey == null) + if (publicKey is null) { return false; } @@ -105,7 +105,7 @@ protected override RSASignaturePadding GetSignaturePadding( HashAlgorithmName digestAlgorithmName, int digestValueLength) { - if (signatureParameters == null) + if (signatureParameters is null) { return RSASignaturePadding.Pkcs1; } @@ -142,7 +142,7 @@ protected override bool Sign( PkcsPal.Instance.GetPrivateKeyForSigning(certificate, silent) ?? certPublicKey; - if (privateKey == null) + if (privateKey is null) { signatureAlgorithm = null; signatureValue = null; @@ -165,7 +165,7 @@ protected override bool Sign( { signatureValue = signature; - if (key != null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1)) + if (key is not null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1)) { // key did not match certificate signatureValue = null; @@ -184,7 +184,7 @@ protected override bool Sign( hashAlgorithmName, RSASignaturePadding.Pkcs1); - if (key != null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1)) + if (key is not null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1)) { // key did not match certificate signatureValue = null; @@ -207,7 +207,7 @@ protected override RSASignaturePadding GetSignaturePadding( HashAlgorithmName digestAlgorithmName, int digestValueLength) { - if (signatureParameters == null) + if (signatureParameters is null) { throw new CryptographicException(SR.Cryptography_Pkcs_PssParametersMissing); } @@ -244,7 +244,7 @@ protected override RSASignaturePadding GetSignaturePadding( pssParams.MaskGenAlgorithm.Algorithm); } - if (pssParams.MaskGenAlgorithm.Parameters == null) + if (pssParams.MaskGenAlgorithm.Parameters is null) { throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs index bb6680465d93d9..17d849e45f295b 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs @@ -58,7 +58,7 @@ protected abstract bool Sign( { if (s_lookup.TryGetValue(signatureAlgorithmOid, out CmsSignature? processor)) { - if (key != null && !processor.VerifyKeyType(key)) + if (key is not null && !processor.VerifyKeyType(key)) { return null; } @@ -84,7 +84,7 @@ internal static bool Sign( { CmsSignature? processor = ResolveAndVerifyKeyType(certificate.GetKeyAlgorithm(), key); - if (processor == null) + if (processor is null) { oid = null; signatureValue = default; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs index d3d1cc650e85da..27042fc6532c39 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs @@ -104,12 +104,12 @@ internal void CheckCertificateValue() return; } - if (Certificate == null) + if (Certificate is null) { throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert); } - if (PrivateKey == null && !Certificate.HasPrivateKey) + if (PrivateKey is null && !Certificate.HasPrivateKey) { throw new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey); } @@ -147,7 +147,7 @@ internal SignerInfoAsn Sign( AttrValues = new[] { new ReadOnlyMemory(writer.Encode()) }, }); - if (contentTypeOid != null) + if (contentTypeOid is not null) { writer.Reset(); writer.WriteObjectIdentifierForCrypto(contentTypeOid); @@ -207,7 +207,7 @@ internal SignerInfoAsn Sign( throw new CryptographicException(); } - if (UnsignedAttributes != null && UnsignedAttributes.Count > 0) + if (UnsignedAttributes is not null && UnsignedAttributes.Count > 0) { List attrs = BuildAttributes(UnsignedAttributes); @@ -304,7 +304,7 @@ internal static List BuildAttributes(CryptographicAttributeObjectC { List signedAttrs = new List(); - if (attributes == null || attributes.Count == 0) + if (attributes is null || attributes.Count == 0) { return signedAttrs; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs index cb5d774908f2c4..cf3b3914f67be2 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs @@ -21,9 +21,9 @@ public ContentInfo(byte[] content) public ContentInfo(Oid contentType, byte[] content) { - if (contentType == null) + if (contentType is null) throw new ArgumentNullException(nameof(contentType)); - if (content == null) + if (content is null) throw new ArgumentNullException(nameof(content)); ContentType = contentType; @@ -36,7 +36,7 @@ public ContentInfo(Oid contentType, byte[] content) public static Oid GetContentType(byte[] encodedMessage) { - if (encodedMessage == null) + if (encodedMessage is null) throw new ArgumentNullException(nameof(encodedMessage)); return PkcsPal.Instance.GetEncodedMessageType(encodedMessage); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs index eb99ba364cfeb1..5e140cdfc337c9 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs @@ -27,9 +27,9 @@ public EnvelopedCms(ContentInfo contentInfo) public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) { - if (contentInfo == null) + if (contentInfo is null) throw new ArgumentNullException(nameof(contentInfo)); - if (encryptionAlgorithm == null) + if (encryptionAlgorithm is null) throw new ArgumentNullException(nameof(encryptionAlgorithm)); Version = 0; // It makes little sense to ask for a version before you've decoded, but since the .NET Framework returns 0 in that case, we will too. @@ -71,7 +71,7 @@ public RecipientInfoCollection RecipientInfos case LastCall.Decode: case LastCall.Decrypt: - Debug.Assert(_decryptorPal != null); + Debug.Assert(_decryptorPal is not null); return _decryptorPal.RecipientInfos; default: @@ -86,7 +86,7 @@ public RecipientInfoCollection RecipientInfos // public void Encrypt(CmsRecipient recipient) { - if (recipient == null) + if (recipient is null) throw new ArgumentNullException(nameof(recipient)); Encrypt(new CmsRecipientCollection(recipient)); @@ -94,14 +94,14 @@ public void Encrypt(CmsRecipient recipient) public void Encrypt(CmsRecipientCollection recipients) { - if (recipients == null) + if (recipients is null) throw new ArgumentNullException(nameof(recipients)); // .NET Framework compat note: Unlike the desktop, we don't provide a free UI to select the recipient. The app must give it to us programmatically. if (recipients.Count == 0) throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoRecipients); - if (_decryptorPal != null) + if (_decryptorPal is not null) { _decryptorPal.Dispose(); _decryptorPal = null; @@ -115,7 +115,7 @@ public void Encrypt(CmsRecipientCollection recipients) // public byte[] Encode() { - if (_encodedMessage == null) + if (_encodedMessage is null) throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotEncrypted); return _encodedMessage.CloneByteArray(); @@ -126,7 +126,7 @@ public byte[] Encode() // public void Decode(byte[] encodedMessage) { - if (encodedMessage == null) + if (encodedMessage is null) throw new ArgumentNullException(nameof(encodedMessage)); Decode(new ReadOnlySpan(encodedMessage)); @@ -143,7 +143,7 @@ public void Decode(byte[] encodedMessage) /// public void Decode(ReadOnlySpan encodedMessage) { - if (_decryptorPal != null) + if (_decryptorPal is not null) { _decryptorPal.Dispose(); _decryptorPal = null; @@ -177,7 +177,7 @@ public void Decrypt() public void Decrypt(RecipientInfo recipientInfo) { - if (recipientInfo == null) + if (recipientInfo is null) throw new ArgumentNullException(nameof(recipientInfo)); DecryptContent(new RecipientInfoCollection(recipientInfo), null); @@ -185,10 +185,10 @@ public void Decrypt(RecipientInfo recipientInfo) public void Decrypt(RecipientInfo recipientInfo, X509Certificate2Collection extraStore) { - if (recipientInfo == null) + if (recipientInfo is null) throw new ArgumentNullException(nameof(recipientInfo)); - if (extraStore == null) + if (extraStore is null) throw new ArgumentNullException(nameof(extraStore)); DecryptContent(new RecipientInfoCollection(recipientInfo), extraStore); @@ -196,7 +196,7 @@ public void Decrypt(RecipientInfo recipientInfo, X509Certificate2Collection extr public void Decrypt(X509Certificate2Collection extraStore) { - if (extraStore == null) + if (extraStore is null) throw new ArgumentNullException(nameof(extraStore)); DecryptContent(RecipientInfos, extraStore); @@ -204,7 +204,7 @@ public void Decrypt(X509Certificate2Collection extraStore) public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm? privateKey) { - if (recipientInfo == null) + if (recipientInfo is null) throw new ArgumentNullException(nameof(recipientInfo)); CheckStateForDecryption(); @@ -218,7 +218,7 @@ public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm? privateKey extraStore, out Exception? exception); - if (exception != null) + if (exception is not null) throw exception; SetContentInfo(contentInfo!); @@ -240,7 +240,7 @@ private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certific foreach (RecipientInfo recipientInfo in recipientInfos) { X509Certificate2? cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier); - if (cert == null) + if (cert is null) { exception = PkcsPal.Instance.CreateRecipientsNotFoundException(); continue; @@ -254,13 +254,13 @@ private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certific extraStore, out exception); - if (exception != null) + if (exception is not null) continue; break; } - if (exception != null) + if (exception is not null) throw exception; SetContentInfo(newContentInfo!); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs index e7c4e8c4deb85f..f6270a43f9e7ad 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs @@ -34,9 +34,9 @@ public void AddSafeContentsEncrypted( ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (safeContents == null) + if (safeContents is null) throw new ArgumentNullException(nameof(safeContents)); - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); @@ -52,7 +52,7 @@ public void AddSafeContentsEncrypted( byte[] encrypted = safeContents.Encrypt(ReadOnlySpan.Empty, passwordBytes, pbeParameters); - if (_contents == null) + if (_contents is null) { _contents = new List(); } @@ -82,9 +82,9 @@ public void AddSafeContentsEncrypted( ReadOnlySpan password, PbeParameters pbeParameters) { - if (safeContents == null) + if (safeContents is null) throw new ArgumentNullException(nameof(safeContents)); - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); @@ -100,7 +100,7 @@ public void AddSafeContentsEncrypted( byte[] encrypted = safeContents.Encrypt(password, ReadOnlySpan.Empty, pbeParameters); - if (_contents == null) + if (_contents is null) { _contents = new List(); } @@ -115,12 +115,12 @@ public void AddSafeContentsEncrypted( public void AddSafeContentsUnencrypted(Pkcs12SafeContents safeContents) { - if (safeContents == null) + if (safeContents is null) throw new ArgumentNullException(nameof(safeContents)); if (IsSealed) throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed); - if (_contents == null) + if (_contents is null) { _contents = new List(); } @@ -173,7 +173,7 @@ public void SealWithMac( using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithm)) { contentsWriter.PushSequence(); - if (_contents != null) + if (_contents is not null) { foreach (ContentInfoAsn contentInfo in _contents) { @@ -292,13 +292,13 @@ public void SealWithMac( CryptographicOperations.ZeroMemory(macSpan); CryptographicOperations.ZeroMemory(authSafeSpan); - if (rentedMac != null) + if (rentedMac is not null) { // Already cleared CryptoPool.Return(rentedMac, clearSize: 0); } - if (rentedAuthSafe != null) + if (rentedAuthSafe is not null) { // Already cleared CryptoPool.Return(rentedAuthSafe, clearSize: 0); @@ -315,7 +315,7 @@ public void SealWithoutIntegrity() AsnWriter writer = new AsnWriter(AsnEncodingRules.BER); { contentsWriter.PushSequence(); - if (_contents != null) + if (_contents is not null) { foreach (ContentInfoAsn contentInfo in _contents) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs index 8504678bd0c2e5..96cfdaca52545a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs @@ -62,7 +62,7 @@ internal Pkcs12CertBag(X509Certificate2 cert) public Oid GetCertificateType() { - if (_certTypeOid == null) + if (_certTypeOid is null) { _certTypeOid = new Oid(_decoded.CertId); } @@ -84,9 +84,9 @@ public X509Certificate2 GetCertificate() private static byte[] EncodeBagValue(Oid certificateType, ReadOnlyMemory encodedCertificate) { - if (certificateType == null) + if (certificateType is null) throw new ArgumentNullException(nameof(certificateType)); - if (certificateType.Value == null) + if (certificateType.Value is null) throw new CryptographicException(SR.Argument_InvalidOidValue); return EncodeBagValue(certificateType.Value, encodedCertificate); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs index e2dcd03f6dc8c6..ab0eced8003325 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs @@ -21,7 +21,7 @@ public CryptographicAttributeObjectCollection Attributes { get { - if (_attributes == null) + if (_attributes is null) { _attributes = new CryptographicAttributeObjectCollection(); } @@ -31,7 +31,7 @@ public CryptographicAttributeObjectCollection Attributes internal set { - Debug.Assert(value != null); + Debug.Assert(value is not null); _attributes = value; } } @@ -56,7 +56,7 @@ public byte[] Encode() public Oid GetBagId() { - if (_bagOid == null) + if (_bagOid is null) { _bagOid = new Oid(_bagIdValue); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs index 03fc39cb90f9c6..c1273a2aad5347 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs @@ -57,12 +57,12 @@ internal Pkcs12SafeContents(ContentInfoAsn contentInfoAsn) public void AddSafeBag(Pkcs12SafeBag safeBag) { - if (safeBag == null) + if (safeBag is null) throw new ArgumentNullException(nameof(safeBag)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); - if (_bags == null) + if (_bags is null) { _bags = new List(); } @@ -72,7 +72,7 @@ public void AddSafeBag(Pkcs12SafeBag safeBag) public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) { - if (certificate == null) + if (certificate is null) throw new ArgumentNullException(nameof(certificate)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -84,7 +84,7 @@ public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -97,7 +97,7 @@ public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) public Pkcs12SafeContentsBag AddNestedContents(Pkcs12SafeContents safeContents) { - if (safeContents == null) + if (safeContents is null) throw new ArgumentNullException(nameof(safeContents)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents)); @@ -126,7 +126,7 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -154,7 +154,7 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( ReadOnlySpan password, PbeParameters pbeParameters) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -167,7 +167,7 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( public Pkcs12SecretBag AddSecret(Oid secretType, ReadOnlyMemory secretValue) { - if (secretType == null) + if (secretType is null) throw new ArgumentNullException(nameof(secretType)); // Read to ensure that there is precisely one legally encoded value. @@ -268,7 +268,7 @@ public IEnumerable GetBags() throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsEncrypted); } - if (_bags == null) + if (_bags is null) { return Enumerable.Empty(); } @@ -340,7 +340,7 @@ private static List ReadBags(ReadOnlyMemory serialized) { } - if (bag == null) + if (bag is null) { bag = new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue); } @@ -357,7 +357,7 @@ internal byte[] Encrypt( ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - Debug.Assert(pbeParameters != null); + Debug.Assert(pbeParameters is not null); Debug.Assert(pbeParameters.IterationCount >= 1); AsnWriter contentsWriter = Encode(); @@ -447,7 +447,7 @@ internal AsnWriter Encode() writer.PushSequence(); - if (_bags != null) + if (_bags is not null) { foreach (Pkcs12SafeBag safeBag in _bags) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContentsBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContentsBag.cs index 5903ba5b054c82..5a3bfefe512c77 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContentsBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContentsBag.cs @@ -17,7 +17,7 @@ private Pkcs12SafeContentsBag(ReadOnlyMemory encoded) internal static Pkcs12SafeContentsBag Create(Pkcs12SafeContents copyFrom) { - Debug.Assert(copyFrom != null); + Debug.Assert(copyFrom is not null); Debug.Assert(copyFrom.ConfidentialityMode == Pkcs12ConfidentialityMode.None); AsnWriter writer = copyFrom.Encode(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs index 7709f27016b0fa..73044ecd6d4275 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs @@ -36,7 +36,7 @@ private Pkcs12SecretBag(SecretBagAsn secretBagAsn, ReadOnlyMemory encodedB public Oid GetSecretType() { - if (_secretTypeOid == null) + if (_secretTypeOid is null) { _secretTypeOid = new Oid(_decoded.SecretTypeId); } @@ -46,7 +46,7 @@ public Oid GetSecretType() private static byte[] EncodeBagValue(Oid secretTypeOid, in ReadOnlyMemory secretValue) { - Debug.Assert(secretTypeOid != null && secretTypeOid.Value != null); + Debug.Assert(secretTypeOid is not null && secretTypeOid.Value is not null); SecretBagAsn secretBagAsn = new SecretBagAsn { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs index 57d5c6cbc00bdc..e27a664bea3082 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs @@ -22,7 +22,7 @@ public Pkcs8PrivateKeyInfo( ReadOnlyMemory privateKey, bool skipCopies = false) { - if (algorithmId == null) + if (algorithmId is null) throw new ArgumentNullException(nameof(algorithmId)); if (algorithmParameters?.Length > 0) @@ -43,7 +43,7 @@ private Pkcs8PrivateKeyInfo( ReadOnlyMemory privateKey, CryptographicAttributeObjectCollection attributes) { - Debug.Assert(algorithmId != null); + Debug.Assert(algorithmId is not null); AlgorithmId = algorithmId; AlgorithmParameters = algorithmParameters; @@ -53,7 +53,7 @@ private Pkcs8PrivateKeyInfo( public static Pkcs8PrivateKeyInfo Create(AsymmetricAlgorithm privateKey) { - if (privateKey == null) + if (privateKey is null) throw new ArgumentNullException(nameof(privateKey)); byte[] pkcs8 = privateKey.ExportPkcs8PrivateKey(); @@ -96,7 +96,7 @@ public byte[] Encode() public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -113,7 +113,7 @@ public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) public byte[] Encrypt(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -138,7 +138,7 @@ public bool TryEncrypt( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( @@ -157,7 +157,7 @@ public bool TryEncrypt( Span destination, out int bytesWritten) { - if (pbeParameters == null) + if (pbeParameters is null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs index b0696f9b9ec0bd..001947778f884f 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs @@ -30,10 +30,10 @@ public Pkcs9AttributeObject(Oid oid, byte[] encodedData) public Pkcs9AttributeObject(AsnEncodedData asnEncodedData) : base(asnEncodedData) { - if (asnEncodedData.Oid == null) + if (asnEncodedData.Oid is null) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "asnEncodedData.Oid"), nameof(asnEncodedData)); string? szOid = base.Oid!.Value; - if (szOid == null) + if (szOid is null) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(asnEncodedData)); if (szOid.Length == 0) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(asnEncodedData)); @@ -58,7 +58,7 @@ internal Pkcs9AttributeObject(Oid oid) public override void CopyFrom(AsnEncodedData asnEncodedData) { - if (asnEncodedData == null) + if (asnEncodedData is null) throw new ArgumentNullException(nameof(asnEncodedData)); if (!(asnEncodedData is Pkcs9AttributeObject)) throw new ArgumentException(SR.Cryptography_Pkcs9_AttributeMismatch); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9ContentType.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9ContentType.cs index 4215ae82d9cb46..085489045ef4ba 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9ContentType.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9ContentType.cs @@ -44,7 +44,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) [return: NotNullIfNotNull("rawData")] private static Oid? Decode(byte[]? rawData) { - if (rawData == null) + if (rawData is null) return null; string contentTypeValue = PkcsHelpers.DecodeOid(rawData); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs index 4624b91bcd23f7..c7799837333956 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs @@ -55,7 +55,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) [return: NotNullIfNotNull("rawData")] private static string? Decode(byte[]? rawData) { - if (rawData == null) + if (rawData is null) return null; byte[] octets = PkcsHelpers.DecodeOctetString(rawData); @@ -64,7 +64,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) private static byte[] Encode(string documentDescription) { - if (documentDescription == null) + if (documentDescription is null) throw new ArgumentNullException(nameof(documentDescription)); byte[] octets = documentDescription.UnicodeToOctetString(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs index 889c98010bf52a..356607f460d060 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs @@ -55,7 +55,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) [return: NotNullIfNotNull("rawData")] private static string? Decode(byte[]? rawData) { - if (rawData == null) + if (rawData is null) return null; byte[] octets = PkcsHelpers.DecodeOctetString(rawData); @@ -64,7 +64,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) private static byte[] Encode(string documentName) { - if (documentName == null) + if (documentName is null) throw new ArgumentNullException(nameof(documentName)); byte[] octets = documentName.UnicodeToOctetString(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9LocalKeyId.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9LocalKeyId.cs index 1f6666c0c7e0d3..3e9a64113cb5f4 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9LocalKeyId.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9LocalKeyId.cs @@ -42,7 +42,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) [return: NotNullIfNotNull("rawData")] private static byte[]? Decode(byte[]? rawData) { - if (rawData == null) + if (rawData is null) { return null; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9MessageDigest.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9MessageDigest.cs index 8a8e19ff465217..0ecfc8f19d0dcf 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9MessageDigest.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9MessageDigest.cs @@ -50,7 +50,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) [return: NotNullIfNotNull("rawData")] private static byte[]? Decode(byte[]? rawData) { - if (rawData == null) + if (rawData is null) return null; return PkcsHelpers.DecodeOctetString(rawData); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9SigningTime.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9SigningTime.cs index c75466c799736f..306fac51c38ba8 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9SigningTime.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9SigningTime.cs @@ -60,7 +60,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) private static DateTime Decode(byte[]? rawData) { - if (rawData == null) + if (rawData is null) return default(DateTime); return PkcsHelpers.DecodeUtcTime(rawData); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/PublicKeyInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/PublicKeyInfo.cs index da8726f769a51d..82962023367a8d 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/PublicKeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/PublicKeyInfo.cs @@ -10,8 +10,8 @@ public sealed class PublicKeyInfo { internal PublicKeyInfo(AlgorithmIdentifier algorithm, byte[] keyValue) { - Debug.Assert(algorithm != null); - Debug.Assert(keyValue != null); + Debug.Assert(algorithm is not null); + Debug.Assert(keyValue is not null); Algorithm = algorithm; KeyValue = keyValue; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs index 62397bdc0fba96..1690af37d670a4 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs @@ -56,7 +56,7 @@ IEnumerator IEnumerable.GetEnumerator() public void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -73,7 +73,7 @@ public void CopyTo(Array array, int index) public void CopyTo(RecipientInfo[] array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs index 68f22657bf291c..8ed597140dad63 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs @@ -26,7 +26,7 @@ private Rfc3161TimestampRequest() public int Version => _parsedData.Version; public ReadOnlyMemory GetMessageHash() => _parsedData.MessageImprint.HashedMessage; public Oid HashAlgorithmId => (_hashAlgorithmId ??= new Oid(_parsedData.MessageImprint.HashAlgorithm.Algorithm, null)); - public Oid? RequestedPolicyId => _parsedData.ReqPolicy == null ? null : (_requestedPolicyId ??= new Oid(_parsedData.ReqPolicy, null)); + public Oid? RequestedPolicyId => _parsedData.ReqPolicy is null ? null : (_requestedPolicyId ??= new Oid(_parsedData.ReqPolicy, null)); public bool RequestSignerCertificate => _parsedData.CertReq; public ReadOnlyMemory? GetNonce() => _parsedData.Nonce; public bool HasExtensions => _parsedData.Extensions?.Length > 0; @@ -170,7 +170,7 @@ public static Rfc3161TimestampRequest CreateFromSignerInfo( bool requestSignerCertificates = false, X509ExtensionCollection? extensions = null) { - if (signerInfo == null) + if (signerInfo is null) { throw new ArgumentNullException(nameof(signerInfo)); } @@ -315,7 +315,7 @@ public static Rfc3161TimestampRequest CreateFromHash( Nonce = nonce, }; - if (extensions != null) + if (extensions is not null) { req.Extensions = extensions.OfType().Select(e => new X509ExtensionAsn(e)).ToArray(); @@ -384,7 +384,7 @@ private Rfc3161RequestResponseStatus ValidateResponse( Rfc3161TimestampToken token, bool shouldThrow) { - Debug.Assert(token != null); + Debug.Assert(token is not null); // This method validates the acceptance criteria sprinkled throughout the // field descriptions in https://tools.ietf.org/html/rfc3161#section-2.4.1 and @@ -423,9 +423,9 @@ private Rfc3161RequestResponseStatus ValidateResponse( // // It does not say that if no nonce was requested that the response MUST NOT include one, so // don't check anything if no nonce was requested. - if (requestNonce != null) + if (requestNonce is not null) { - if (responseNonce == null || + if (responseNonce is null || !requestNonce.Value.Span.SequenceEqual(responseNonce.Value.Span)) { if (shouldThrow) @@ -447,7 +447,7 @@ private Rfc3161RequestResponseStatus ValidateResponse( // // Other certificates are permitted, and will not be validated. - if (tokenCms.SignerInfos[0].Certificate == null) + if (tokenCms.SignerInfos[0].Certificate is null) { if (shouldThrow) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs index dde7077c699b96..4ed5b5db68a1bd 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs @@ -42,10 +42,10 @@ private Rfc3161TimestampToken() private X509Certificate2? GetSignerCertificate(X509Certificate2Collection? extraCandidates) { - Debug.Assert(_signerInfo != null, "_signerInfo != null"); + Debug.Assert(_signerInfo is not null, "_signerInfo is not null"); X509Certificate2? signerCert = _signerInfo.Certificate; - if (signerCert != null) + if (signerCert is not null) { if (CheckCertificate(signerCert, _signerInfo, in _essCertId, in _essCertIdV2, TokenInfo)) { @@ -56,7 +56,7 @@ private Rfc3161TimestampToken() return null; } - if (extraCandidates == null || extraCandidates.Count == 0) + if (extraCandidates is null || extraCandidates.Count == 0) { return null; } @@ -81,7 +81,7 @@ public bool VerifySignatureForData( X509Certificate2? cert = GetSignerCertificate(extraCandidates); - if (cert == null) + if (cert is null) { return false; } @@ -105,7 +105,7 @@ public bool VerifySignatureForHash( X509Certificate2? cert = GetSignerCertificate(extraCandidates); - if (cert == null) + if (cert is null) { return false; } @@ -125,7 +125,7 @@ public bool VerifySignatureForHash( [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { - if (hashAlgorithmId == null) + if (hashAlgorithmId is null) { throw new ArgumentNullException(nameof(hashAlgorithmId)); } @@ -134,7 +134,7 @@ public bool VerifySignatureForHash( X509Certificate2? cert = GetSignerCertificate(extraCandidates); - if (cert == null) + if (cert is null) { return false; } @@ -157,7 +157,7 @@ public bool VerifySignatureForSignerInfo( [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { - if (signerInfo == null) + if (signerInfo is null) { throw new ArgumentNullException(nameof(signerInfo)); } @@ -208,9 +208,9 @@ private static bool CheckCertificate( in EssCertIdV2? certId2, Rfc3161TimestampTokenInfo tokenInfo) { - Debug.Assert(tsaCertificate != null); - Debug.Assert(signer != null); - Debug.Assert(tokenInfo != null); + Debug.Assert(tsaCertificate is not null); + Debug.Assert(signer is not null); + Debug.Assert(tokenInfo is not null); // certId and certId2 are allowed to be null, they get checked in CertMatchesIds. if (!CertMatchesIds(tsaCertificate, certId, certId2)) @@ -361,14 +361,14 @@ public static bool TryDecode(ReadOnlyMemory source, [NotNullWhen(true)] ou X509Certificate2? signerCert = signer.Certificate; - if (signerCert == null && + if (signerCert is null && signer.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber) { // If the cert wasn't provided, but the identifier was IssuerAndSerialNumber, // and the ESSCertId(V2) has specified an issuerSerial value, ensure it's a match. X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value!; - if (certId.HasValue && certId.Value.IssuerSerial != null) + if (certId.HasValue && certId.Value.IssuerSerial is not null) { if (!IssuerAndSerialMatch( certId.Value.IssuerSerial.Value, @@ -379,7 +379,7 @@ public static bool TryDecode(ReadOnlyMemory source, [NotNullWhen(true)] ou } } - if (certId2.HasValue && certId2.Value.IssuerSerial != null) + if (certId2.HasValue && certId2.Value.IssuerSerial is not null) { if (!IssuerAndSerialMatch( certId2.Value.IssuerSerial.Value, @@ -393,7 +393,7 @@ public static bool TryDecode(ReadOnlyMemory source, [NotNullWhen(true)] ou if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out Rfc3161TimestampTokenInfo? tokenInfo, out _)) { - if (signerCert != null && + if (signerCert is not null && !CheckCertificate(signerCert, signer, in certId, in certId2, tokenInfo)) { return false; @@ -429,14 +429,14 @@ private static bool IssuerAndSerialMatch( { GeneralNameAsn[] issuerNames = issuerSerial.Issuer; - if (issuerNames == null || issuerNames.Length != 1) + if (issuerNames is null || issuerNames.Length != 1) { return false; } GeneralNameAsn requiredName = issuerNames[0]; - if (requiredName.DirectoryName == null) + if (requiredName.DirectoryName is null) { return false; } @@ -456,14 +456,14 @@ private static bool IssuerAndSerialMatch( { GeneralNameAsn[] issuerNames = issuerSerial.Issuer; - if (issuerNames == null || issuerNames.Length != 1) + if (issuerNames is null || issuerNames.Length != 1) { return false; } GeneralNameAsn requiredName = issuerNames[0]; - if (requiredName.DirectoryName == null) + if (requiredName.DirectoryName is null) { return false; } @@ -478,7 +478,7 @@ private static bool IssuerAndSerialMatch( private static bool CertMatchesIds(X509Certificate2 signerCert, in EssCertId? certId, in EssCertIdV2? certId2) { - Debug.Assert(signerCert != null); + Debug.Assert(signerCert is not null); Debug.Assert(certId.HasValue || certId2.HasValue); byte[]? serialNumber = null; @@ -542,7 +542,7 @@ private static bool CertMatchesIds(X509Certificate2 signerCert, in EssCertId? ce if (certId2.Value.IssuerSerial.HasValue) { - if (serialNumber == null) + if (serialNumber is null) { serialNumber = signerCert.GetSerialNumber(); Array.Reverse(serialNumber); @@ -575,7 +575,7 @@ private static bool TryGetCertIds(SignerInfo signer, out EssCertId? certId, out { string? setOid = attrSet.Oid?.Value; - if (setOid != null && + if (setOid is not null && setOid != Oids.SigningCertificate && setOid != Oids.SigningCertificateV2) { @@ -588,7 +588,7 @@ private static bool TryGetCertIds(SignerInfo signer, out EssCertId? certId, out if (attrOid == Oids.SigningCertificate) { - if (certId != null) + if (certId is not null) { return false; } @@ -615,7 +615,7 @@ private static bool TryGetCertIds(SignerInfo signer, out EssCertId? certId, out if (attrOid == Oids.SigningCertificateV2) { - if (certId2 != null) + if (certId2 is not null) { return false; } @@ -642,7 +642,7 @@ private static bool TryGetCertIds(SignerInfo signer, out EssCertId? certId, out } } - return certId2 != null || certId != null; + return certId2 is not null || certId is not null; } } } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs index b5f87e5513338f..929f64da38b9bc 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs @@ -70,11 +70,11 @@ private Rfc3161TimestampTokenInfo(byte[] copiedBytes, Rfc3161TstInfo tstInfo) public ReadOnlyMemory? GetTimestampAuthorityName() { - if (_tsaNameBytes == null) + if (_tsaNameBytes is null) { GeneralNameAsn? tsaName = _parsedData.Tsa; - if (tsaName == null) + if (tsaName is null) { return null; } @@ -226,9 +226,9 @@ private static byte[] Encode( ReadOnlyMemory? tsaName, X509ExtensionCollection? extensions) { - if (policyId == null) + if (policyId is null) throw new ArgumentNullException(nameof(policyId)); - if (hashAlgorithmId == null) + if (hashAlgorithmId is null) throw new ArgumentNullException(nameof(hashAlgorithmId)); var tstInfo = new Rfc3161TstInfo @@ -252,17 +252,17 @@ private static byte[] Encode( Nonce = nonce, }; - if (accuracyInMicroseconds != null) + if (accuracyInMicroseconds is not null) { tstInfo.Accuracy = new Rfc3161Accuracy(accuracyInMicroseconds.Value); } - if (tsaName != null) + if (tsaName is not null) { tstInfo.Tsa = GeneralNameAsn.Decode(tsaName.Value, AsnEncodingRules.DER); } - if (extensions != null) + if (extensions is not null) { tstInfo.Extensions = extensions.OfType(). Select(ex => new X509ExtensionAsn(ex)).ToArray(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs index 188ca0039a3c96..4e75a2d7e5d092 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs @@ -42,9 +42,9 @@ public sealed partial class SignedCms public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached) { - if (contentInfo == null) + if (contentInfo is null) throw new ArgumentNullException(nameof(contentInfo)); - if (contentInfo.Content == null) + if (contentInfo.Content is null) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "contentInfo.Content"), nameof(contentInfo)); // Normalize the subject identifier type the same way as .NET Framework. @@ -82,7 +82,7 @@ public X509Certificate2Collection Certificates CertificateChoiceAsn[]? certChoices = _signedData.CertificateSet; - if (certChoices == null) + if (certChoices is null) { return coll; } @@ -136,7 +136,7 @@ public byte[] Encode() SignedDataAsn copy = _signedData; copy.EncapContentInfo.Content = null; - Debug.Assert(_signedData.EncapContentInfo.Content != null); + Debug.Assert(_signedData.EncapContentInfo.Content is not null); AsnWriter detachedWriter = new AsnWriter(AsnEncodingRules.DER); copy.Encode(detachedWriter); @@ -152,7 +152,7 @@ public byte[] Encode() public void Decode(byte[] encodedMessage) { - if (encodedMessage == null) + if (encodedMessage is null) throw new ArgumentNullException(nameof(encodedMessage)); Decode(new ReadOnlySpan(encodedMessage)); @@ -275,7 +275,7 @@ internal static ReadOnlyMemory GetContent( } finally { - if (rented != null) + if (rented is not null) { CryptoPool.Return(rented, bytesWritten); } @@ -292,7 +292,7 @@ internal static ReadOnlyMemory GetContent( public void ComputeSignature(CmsSigner signer, bool silent) { - if (signer == null) + if (signer is null) { throw new ArgumentNullException(nameof(signer)); } @@ -314,7 +314,7 @@ public void ComputeSignature(CmsSigner signer, bool silent) throw new CryptographicException(SR.Cryptography_Cms_Sign_No_Signature_First_Signer); } - if (signer.Certificate == null && signer.SignerIdentifierType != SubjectIdentifierType.NoSignature) + if (signer.Certificate is null && signer.SignerIdentifierType != SubjectIdentifierType.NoSignature) { if (silent) { @@ -375,7 +375,7 @@ public void ComputeSignature(CmsSigner signer, bool silent) { Reencode(); - Debug.Assert(_heldContent != null); + Debug.Assert(_heldContent is not null); Debug.Assert(_contentType == contentType); } } @@ -401,7 +401,7 @@ public void RemoveSignature(int index) public void RemoveSignature(SignerInfo signerInfo) { - if (signerInfo == null) + if (signerInfo is null) throw new ArgumentNullException(nameof(signerInfo)); int idx = SignerInfos.FindIndexForSigner(signerInfo); @@ -462,7 +462,7 @@ internal void Reencode() } Decode(encoded); - Debug.Assert(_heldContent != null); + Debug.Assert(_heldContent is not null); } finally { @@ -576,7 +576,7 @@ internal void UpdateCertificatesFromAddition(X509Certificate2Collection newCerts return; } - if (_signedData.CertificateSet == null) + if (_signedData.CertificateSet is null) { _signedData.CertificateSet = new CertificateChoiceAsn[newCerts.Count]; } @@ -601,7 +601,7 @@ public void CheckSignature(X509Certificate2Collection extraStore, bool verifySig { if (!_hasData) throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned); - if (extraStore == null) + if (extraStore is null) throw new ArgumentNullException(nameof(extraStore)); CheckSignatures(SignerInfos, extraStore, verifySignatureOnly); @@ -612,7 +612,7 @@ private static void CheckSignatures( X509Certificate2Collection extraStore, bool verifySignatureOnly) { - Debug.Assert(signers != null); + Debug.Assert(signers is not null); if (signers.Count < 1) { @@ -638,7 +638,7 @@ public void CheckHash() throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned); SignerInfoCollection signers = SignerInfos; - Debug.Assert(signers != null); + Debug.Assert(signers is not null); if (signers.Count < 1) { @@ -676,7 +676,7 @@ public void AddCertificate(X509Certificate2 certificate) } } - if (_signedData.CertificateSet == null) + if (_signedData.CertificateSet is null) { _signedData.CertificateSet = new CertificateChoiceAsn[1]; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs index 52888eca998669..6605e9edc5cad0 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs @@ -51,7 +51,7 @@ internal SignerInfo(ref SignerInfoAsn parsedData, SignedCms ownerDocument) AsnEncodingRules.BER); _signedAttributes = signedSet.SignedAttributes; - Debug.Assert(_signedAttributes != null); + Debug.Assert(_signedAttributes is not null); } _document = ownerDocument; @@ -61,7 +61,7 @@ public CryptographicAttributeObjectCollection SignedAttributes { get { - if (_parsedSignedAttrs == null) + if (_parsedSignedAttrs is null) { _parsedSignedAttrs = MakeAttributeCollection(_signedAttributes); } @@ -74,7 +74,7 @@ public CryptographicAttributeObjectCollection UnsignedAttributes { get { - if (_parsedUnsignedAttrs == null) + if (_parsedUnsignedAttrs is null) { _parsedUnsignedAttrs = MakeAttributeCollection(_unsignedAttributes); } @@ -91,7 +91,7 @@ public X509Certificate2? Certificate { get { - if (_signerCertificate == null) + if (_signerCertificate is null) { _signerCertificate = FindSignerCertificate(); } @@ -105,8 +105,8 @@ public SignerInfoCollection CounterSignerInfos get { // We only support one level of counter signing. - if (_parentSignerInfo != null || - _unsignedAttributes == null || + if (_parentSignerInfo is not null || + _unsignedAttributes is null || _unsignedAttributes.Length == 0) { return new SignerInfoCollection(); @@ -124,7 +124,7 @@ public SignerInfoCollection CounterSignerInfos private void WithSelfInfo(WithSelfInfoDelegate action) { - if (_parentSignerInfo == null) + if (_parentSignerInfo is null) { int myIdx = _document.SignerInfos.FindIndexForSigner(this); @@ -154,7 +154,7 @@ private void WithSelfInfo(WithSelfInfoDelegate action) ref SignedDataAsn documentData = ref _document.GetRawData(); ref SignerInfoAsn parentData = ref documentData.SignerInfos[parentIdx]; - if (parentData.UnsignedAttributes == null) + if (parentData.UnsignedAttributes is null) { throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex); } @@ -206,7 +206,7 @@ public void AddUnsignedAttribute(AsnEncodedData unsignedAttribute) private static void AddUnsignedAttribute(ref SignerInfoAsn mySigner, AsnEncodedData unsignedAttribute) { - int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid!); + int existingAttribute = mySigner.UnsignedAttributes is null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid!); if (existingAttribute == -1) { @@ -214,7 +214,7 @@ private static void AddUnsignedAttribute(ref SignerInfoAsn mySigner, AsnEncodedD AttributeAsn newUnsignedAttr = new AttributeAsn(unsignedAttribute); int newAttributeIdx; - if (mySigner.UnsignedAttributes == null) + if (mySigner.UnsignedAttributes is null) { newAttributeIdx = 0; mySigner.UnsignedAttributes = new AttributeAsn[1]; @@ -298,9 +298,9 @@ public void ComputeCounterSignature() public void ComputeCounterSignature(CmsSigner signer) { - if (_parentSignerInfo != null) + if (_parentSignerInfo is not null) throw new CryptographicException(SR.Cryptography_Cms_NoCounterCounterSigner); - if (signer == null) + if (signer is null) throw new ArgumentNullException(nameof(signer)); signer.CheckCertificateValue(); @@ -333,7 +333,7 @@ public void ComputeCounterSignature(CmsSigner signer) int newExtensionIdx; - if (mySigner.UnsignedAttributes == null) + if (mySigner.UnsignedAttributes is null) { mySigner.UnsignedAttributes = new AttributeAsn[1]; newExtensionIdx = 0; @@ -373,7 +373,7 @@ public void RemoveCounterSignature(int index) ref SignedDataAsn parentData = ref _document.GetRawData(); ref SignerInfoAsn myData = ref parentData.SignerInfos[myIdx]; - if (myData.UnsignedAttributes == null) + if (myData.UnsignedAttributes is null) { throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex); } @@ -432,7 +432,7 @@ public void RemoveCounterSignature(int index) public void RemoveCounterSignature(SignerInfo counterSignerInfo) { - if (counterSignerInfo == null) + if (counterSignerInfo is null) throw new ArgumentNullException(nameof(counterSignerInfo)); SignerInfoCollection docSigners = _document.SignerInfos; @@ -459,16 +459,16 @@ public void CheckSignature(bool verifySignatureOnly) => public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly) { - if (extraStore == null) + if (extraStore is null) throw new ArgumentNullException(nameof(extraStore)); X509Certificate2? certificate = Certificate; - if (certificate == null) + if (certificate is null) { certificate = FindSignerCertificate(SignerIdentifier, extraStore); - if (certificate == null) + if (certificate is null) { throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound); } @@ -494,7 +494,7 @@ private bool CheckHash(bool compatMode) { using (IncrementalHash? hasher = PrepareDigest(compatMode)) { - if (hasher == null) + if (hasher is null) { Debug.Assert(compatMode, $"{nameof(PrepareDigest)} returned null for the primary check"); return false; @@ -514,7 +514,7 @@ private bool CheckHash(bool compatMode) SubjectIdentifier signerIdentifier, X509Certificate2Collection? extraStore) { - if (extraStore == null || extraStore.Count == 0) + if (extraStore is null || extraStore.Count == 0) { return null; } @@ -553,7 +553,7 @@ private bool CheckHash(bool compatMode) } } - if (filtered != null) + if (filtered is not null) { foreach (X509Certificate2 cert in filtered) { @@ -573,7 +573,7 @@ private bool CheckHash(bool compatMode) IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName); - if (_parentSignerInfo == null) + if (_parentSignerInfo is null) { // Windows compatibility: If a document was loaded in detached mode, // but had content, hash both parts of the content. @@ -582,7 +582,7 @@ private bool CheckHash(bool compatMode) ref SignedDataAsn documentData = ref _document.GetRawData(); ReadOnlyMemory? embeddedContent = documentData.EncapContentInfo.Content; - if (embeddedContent != null) + if (embeddedContent is not null) { // Unwrap the OCTET STRING manually, because of PKCS#7 compatibility. // https://tools.ietf.org/html/rfc5652#section-5.2.1 @@ -603,9 +603,9 @@ private bool CheckHash(bool compatMode) // A Counter-Signer always requires signed attributes. // If any signed attributes are present, message-digest is required. - bool invalid = _parentSignerInfo != null || _signedAttributes != null; + bool invalid = _parentSignerInfo is not null || _signedAttributes is not null; - if (_signedAttributes != null) + if (_signedAttributes is not null) { byte[] contentDigest = hasher.GetHashAndReset(); @@ -689,7 +689,7 @@ private void Verify( { CmsSignature? signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value!, key: null); - if (signatureProcessor == null) + if (signatureProcessor is null) { throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, SignatureAlgorithm.Value); } @@ -747,7 +747,7 @@ private bool VerifySignature( { using (IncrementalHash? hasher = PrepareDigest(compatMode)) { - if (hasher == null) + if (hasher is null) { Debug.Assert(compatMode, $"{nameof(PrepareDigest)} returned null for the primary check"); return false; @@ -791,7 +791,7 @@ internal static CryptographicAttributeObjectCollection MakeAttributeCollection(A { var coll = new CryptographicAttributeObjectCollection(); - if (attributes == null) + if (attributes is null) return coll; foreach (AttributeAsn attribute in attributes) @@ -817,7 +817,7 @@ private static CryptographicAttributeObject MakeAttribute(AttributeAsn attribute private static int FindAttributeIndexByOid(AttributeAsn[] attributes, Oid oid, int startIndex = 0) { - if (attributes != null) + if (attributes is not null) { for (int i = startIndex; i < attributes.Length; i++) { @@ -833,7 +833,7 @@ private static int FindAttributeIndexByOid(AttributeAsn[] attributes, Oid oid, i private static int FindAttributeValueIndexByEncodedData(ReadOnlyMemory[] attributeValues, ReadOnlySpan asnEncodedData, out bool isOnlyValue) { - if (attributeValues != null) + if (attributeValues is not null) { for (int i = 0; i < attributeValues.Length; i++) { @@ -852,7 +852,7 @@ private static int FindAttributeValueIndexByEncodedData(ReadOnlyMemory[] a private static (int, int) FindAttributeLocation(AttributeAsn[]? attributes, AsnEncodedData attribute, out bool isOnlyValue) { - if (attributes != null) + if (attributes is not null) { for (int outerIndex = 0; ; outerIndex++) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs index 27193a75102844..786956bf65050f 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs @@ -19,14 +19,14 @@ internal SignerInfoCollection() internal SignerInfoCollection(SignerInfo[] signerInfos) { - Debug.Assert(signerInfos != null); + Debug.Assert(signerInfos is not null); _signerInfos = signerInfos; } internal SignerInfoCollection(SignerInfoAsn[] signedDataSignerInfos, SignedCms ownerDocument) { - Debug.Assert(signedDataSignerInfos != null); + Debug.Assert(signedDataSignerInfos is not null); _signerInfos = new SignerInfo[signedDataSignerInfos.Length]; @@ -53,7 +53,7 @@ public SignerInfo this[int index] public void CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -77,7 +77,7 @@ public void CopyTo(Array array, int index) private static int FindIndexForSigner(SignerInfo[] signerInfos, SignerInfo signer) { - Debug.Assert(signer != null); + Debug.Assert(signer is not null); SubjectIdentifier id = signer.SignerIdentifier; for (int i = 0; i < signerInfos.Length; i++) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoEnumerator.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoEnumerator.cs index 830333bd1e15b4..a60a47736d43fa 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoEnumerator.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoEnumerator.cs @@ -13,7 +13,7 @@ public sealed class SignerInfoEnumerator : IEnumerator internal SignerInfoEnumerator(SignerInfoCollection signerInfos) { - Debug.Assert(signerInfos != null); + Debug.Assert(signerInfos is not null); _signerInfos = signerInfos; _position = -1; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifier.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifier.cs index d6747d06c3ace0..100e29ff8dace8 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifier.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifier.cs @@ -19,7 +19,7 @@ public sealed class SubjectIdentifier internal SubjectIdentifier(SubjectIdentifierType type, object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); #if DEBUG switch (type) { @@ -82,7 +82,7 @@ internal SubjectIdentifier( Value = new X509IssuerSerial(name.Name, serial.ToBigEndianHex()); } } - else if (subjectKeyIdentifier != null) + else if (subjectKeyIdentifier is not null) { Type = SubjectIdentifierType.SubjectKeyIdentifier; Value = subjectKeyIdentifier.Value.Span.ToBigEndianHex(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifierOrKey.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifierOrKey.cs index 974f9dca7c5d02..17e3de4f8634e0 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifierOrKey.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifierOrKey.cs @@ -11,7 +11,7 @@ public sealed class SubjectIdentifierOrKey { internal SubjectIdentifierOrKey(SubjectIdentifierOrKeyType type, object value) { - Debug.Assert(value != null); + Debug.Assert(value is not null); #if DEBUG switch (type) { diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoConfigForwarder.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoConfigForwarder.cs index 9ddf02cbfab2cb..893b306ef8bc3d 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoConfigForwarder.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoConfigForwarder.cs @@ -19,7 +19,7 @@ internal static class CryptoConfigForwarder Type t = Type.GetType(CryptoConfigTypeName, throwOnError: true)!; MethodInfo? createFromName = t.GetMethod(CreateFromNameMethodName, new[] { typeof(string) }); - if (createFromName == null) + if (createFromName is null) { throw new MissingMethodException(t.FullName, CreateFromNameMethodName); } diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoStream.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoStream.cs index 2e426cc4185381..30f1d79260a927 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoStream.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CryptoStream.cs @@ -159,9 +159,9 @@ private async ValueTask FlushFinalBlockAsync(bool useAsync, CancellationToken ca } // zeroize plain text material before returning - if (_inputBuffer != null) + if (_inputBuffer is not null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); - if (_outputBuffer != null) + if (_outputBuffer is not null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); } @@ -234,7 +234,7 @@ public override int ReadByte() // does in Read. If/when that's fixed for Read, it should be fixed here, too.) if (_outputBufferIndex > 1) { - Debug.Assert(_outputBuffer != null); + Debug.Assert(_outputBuffer is not null); byte b = _outputBuffer[0]; Buffer.BlockCopy(_outputBuffer, 1, _outputBuffer, 0, _outputBufferIndex - 1); _outputBufferIndex -= 1; @@ -288,7 +288,7 @@ private async Task ReadAsyncCore(byte[] buffer, int offset, int count, Canc // no bytes ready or we've delivered enough. int bytesToDeliver = count; int currentOutputIndex = offset; - Debug.Assert(_outputBuffer != null); + Debug.Assert(_outputBuffer is not null); if (_outputBufferIndex != 0) { // we have some already-transformed bytes in the output buffer @@ -329,7 +329,7 @@ private async Task ReadAsyncCore(byte[] buffer, int offset, int count, Canc // OK, see first if it's a multi-block transform and we can speed up things int blocksToProcess = bytesToDeliver / _outputBlockSize; - Debug.Assert(_inputBuffer != null); + Debug.Assert(_inputBuffer is not null); if (blocksToProcess > 1 && _transform.CanTransformMultipleBlocks) { int numWholeBlocksInBytes = blocksToProcess * _inputBlockSize; @@ -393,7 +393,7 @@ await _stream.ReadAsync(new Memory(tempInputBuffer, _inputBufferIndex, num { // If we rented and then an exception happened we don't know how much was written to, // clear the whole thing and let it get reclaimed by the GC. - if (tempOutputBuffer != null) + if (tempOutputBuffer is not null) { CryptographicOperations.ZeroMemory(tempOutputBuffer); tempOutputBuffer = null; @@ -401,7 +401,7 @@ await _stream.ReadAsync(new Memory(tempInputBuffer, _inputBufferIndex, num // For the input buffer we know how much was written, so clear that. // But still let it get reclaimed by the GC. - if (tempInputBuffer != null) + if (tempInputBuffer is not null) { CryptographicOperations.ZeroMemory(new Span(tempInputBuffer, 0, numWholeBlocksInBytes)); tempInputBuffer = null; @@ -537,7 +537,7 @@ private async ValueTask WriteAsyncCore(byte[] buffer, int offset, int count, Can // so let's try to make an entire block out of it if (_inputBufferIndex > 0) { - Debug.Assert(_inputBuffer != null); + Debug.Assert(_inputBuffer is not null); if (count >= _inputBlockSize - _inputBufferIndex) { // we have enough to transform at least a block, so fill the input block @@ -563,7 +563,7 @@ private async ValueTask WriteAsyncCore(byte[] buffer, int offset, int count, Can int numOutputBytes; if (_inputBufferIndex == _inputBlockSize) { - Debug.Assert(_inputBuffer != null && _outputBuffer != null); + Debug.Assert(_inputBuffer is not null && _outputBuffer is not null); numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); // write out the bytes we just got if (useAsync) @@ -619,7 +619,7 @@ private async ValueTask WriteAsyncCore(byte[] buffer, int offset, int count, Can } else { - Debug.Assert(_outputBuffer != null); + Debug.Assert(_outputBuffer is not null); // do it the slow way numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, _inputBlockSize, _outputBuffer, 0); @@ -634,7 +634,7 @@ private async ValueTask WriteAsyncCore(byte[] buffer, int offset, int count, Can } else { - Debug.Assert(_inputBuffer != null); + Debug.Assert(_inputBuffer is not null); // In this case, we don't have an entire block's worth left, so store it up in the // input buffer, which by now must be empty. Buffer.BlockCopy(buffer, currentInputIndex, _inputBuffer, 0, bytesToWrite); @@ -674,9 +674,9 @@ protected override void Dispose(bool disposing) // since it's null after this _finalBlockTransformed = true; // we need to clear all the internal buffers - if (_inputBuffer != null) + if (_inputBuffer is not null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); - if (_outputBuffer != null) + if (_outputBuffer is not null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); _inputBuffer = null; @@ -720,12 +720,12 @@ private async ValueTask DisposeAsyncCore() _finalBlockTransformed = true; // we need to clear all the internal buffers - if (_inputBuffer != null) + if (_inputBuffer is not null) { Array.Clear(_inputBuffer, 0, _inputBuffer.Length); } - if (_outputBuffer != null) + if (_outputBuffer is not null) { Array.Clear(_outputBuffer, 0, _outputBuffer.Length); } @@ -741,7 +741,7 @@ private async ValueTask DisposeAsyncCore() private void InitializeBuffer() { - if (_transform != null) + if (_transform is not null) { _inputBlockSize = _transform.InputBlockSize; _inputBuffer = new byte[_inputBlockSize]; diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HMAC.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HMAC.cs index 4268cd99a4424f..84c35fc7a5e70e 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HMAC.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HMAC.cs @@ -28,7 +28,7 @@ public string HashName get => _hashName; set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(HashName)); } @@ -40,7 +40,7 @@ public string HashName // We still have to allow setting it the first time as the contract provides no other way to do so. // Since the set is public, ensure that hmac.HashName = hmac.HashName works without throwing. - if (_hashName != null && value != _hashName) + if (_hashName is not null && value != _hashName) { throw new PlatformNotSupportedException(SR.HashNameMultipleSetNotSupported); } diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithm.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithm.cs index 31d64ebd0157f1..e2e025b5e1c427 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithm.cs @@ -43,7 +43,7 @@ public byte[] ComputeHash(byte[] buffer) { if (_disposed) throw new ObjectDisposedException(null); - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); HashCore(buffer, 0, buffer.Length); @@ -78,7 +78,7 @@ public bool TryComputeHash(ReadOnlySpan source, Span destination, ou public byte[] ComputeHash(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -124,7 +124,7 @@ public Task ComputeHashAsync( Stream inputStream, CancellationToken cancellationToken = default) { - if (inputStream == null) + if (inputStream is null) throw new ArgumentNullException(nameof(inputStream)); if (_disposed) throw new ObjectDisposedException(null); @@ -207,7 +207,7 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b State = 1; HashCore(inputBuffer, inputOffset, inputCount); - if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))) + if ((outputBuffer is not null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))) { // We let BlockCopy do the destination array validation Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); @@ -240,7 +240,7 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount) { - if (inputBuffer == null) + if (inputBuffer is null) throw new ArgumentNullException(nameof(inputBuffer)); if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithmName.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithmName.cs index 1c9c95904ebc17..961757175fac6a 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithmName.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/HashAlgorithmName.cs @@ -91,7 +91,7 @@ public bool Equals(HashAlgorithmName other) public override int GetHashCode() { - return _name == null ? 0 : _name.GetHashCode(); + return _name is null ? 0 : _name.GetHashCode(); } public static bool operator ==(HashAlgorithmName left, HashAlgorithmName right) diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/KeyedHashAlgorithm.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/KeyedHashAlgorithm.cs index 2088346bbe074c..a99e023126c283 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/KeyedHashAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/KeyedHashAlgorithm.cs @@ -34,7 +34,7 @@ protected override void Dispose(bool disposing) // For keyed hash algorithms, we always want to zero out the key value if (disposing) { - if (KeyValue != null) + if (KeyValue is not null) { Array.Clear(KeyValue, 0, KeyValue.Length); } diff --git a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/SymmetricAlgorithm.cs b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/SymmetricAlgorithm.cs index 9ad7b01d7b6cf5..0f13d620078a5a 100644 --- a/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/SymmetricAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/SymmetricAlgorithm.cs @@ -62,14 +62,14 @@ public virtual byte[] IV { get { - if (IVValue == null) + if (IVValue is null) GenerateIV(); return IVValue.CloneByteArray()!; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length != this.BlockSize / 8) throw new CryptographicException(SR.Cryptography_InvalidIVSize); @@ -82,14 +82,14 @@ public virtual byte[] Key { get { - if (KeyValue == null) + if (KeyValue is null) GenerateKey(); return KeyValue.CloneByteArray()!; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); long bitLength = value.Length * 8L; @@ -197,12 +197,12 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (KeyValue != null) + if (KeyValue is not null) { Array.Clear(KeyValue, 0, KeyValue.Length); KeyValue = null; } - if (IVValue != null) + if (IVValue is not null) { Array.Clear(IVValue, 0, IVValue.Length); IVValue = null; @@ -217,7 +217,7 @@ protected virtual void Dispose(bool disposing) public bool ValidKeySize(int bitLength) { KeySizes[] validSizes = this.LegalKeySizes; - if (validSizes == null) + if (validSizes is null) return false; return bitLength.IsLegalSize(validSizes); } diff --git a/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs b/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs index 0e6b65bea16644..6834e1859da06d 100644 --- a/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs +++ b/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs @@ -16,7 +16,7 @@ public static partial class ProtectedData public static byte[] Protect(byte[] userData, byte[]? optionalEntropy, DataProtectionScope scope) { - if (userData == null) + if (userData is null) throw new ArgumentNullException(nameof(userData)); return ProtectOrUnprotect(userData, optionalEntropy, scope, protect: true); @@ -24,7 +24,7 @@ public static byte[] Protect(byte[] userData, byte[]? optionalEntropy, DataProte public static byte[] Unprotect(byte[] encryptedData, byte[]? optionalEntropy, DataProtectionScope scope) { - if (encryptedData == null) + if (encryptedData is null) throw new ArgumentNullException(nameof(encryptedData)); return ProtectOrUnprotect(encryptedData, optionalEntropy, scope, protect: false); @@ -34,7 +34,7 @@ private static byte[] ProtectOrUnprotect(byte[] inputData, byte[]? optionalEntro { unsafe { - // The Win32 API will reject pbData == nullptr, and the fixed statement + // The Win32 API will reject pbData is nullptr, and the fixed statement // maps empty arrays to nullptr... so when the input is empty use the address of a // different array, but still assign cbData to 0. byte[] relevantData = inputData.Length == 0 ? s_nonEmpty : inputData; @@ -43,7 +43,7 @@ private static byte[] ProtectOrUnprotect(byte[] inputData, byte[]? optionalEntro { DATA_BLOB userDataBlob = new DATA_BLOB((IntPtr)pInputData, (uint)(inputData.Length)); DATA_BLOB optionalEntropyBlob = default(DATA_BLOB); - if (optionalEntropy != null) + if (optionalEntropy is not null) { optionalEntropyBlob = new DATA_BLOB((IntPtr)pOptionalEntropy, (uint)(optionalEntropy.Length)); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs index 362ad7412ce1e8..e3ca9d4bd5df60 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs @@ -26,7 +26,7 @@ protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPr depth = -1; for (int i = _ancestorStack.Count - 1; i >= 0; i--) { - if ((attr = GetScopeAt(i).GetRendered(nsPrefix)) != null) + if ((attr = GetScopeAt(i).GetRendered(nsPrefix)) is not null) { depth = i; return attr; @@ -41,7 +41,7 @@ protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string ns depth = -1; for (int i = _ancestorStack.Count - 1; i >= 0; i--) { - if ((attr = GetScopeAt(i).GetUnrendered(nsPrefix)) != null) + if ((attr = GetScopeAt(i).GetUnrendered(nsPrefix)) is not null) { depth = i; return attr; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs index 3c40f356f5fadd..7a1c6c14a1a025 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs @@ -15,7 +15,7 @@ public int Compare(object a, object b) { XmlNode nodeA = a as XmlNode; XmlNode nodeB = b as XmlNode; - if ((nodeA == null) || (nodeB == null)) + if ((nodeA is null) || (nodeB is null)) throw new ArgumentException(); int namespaceCompare = string.CompareOrdinal(nodeA.NamespaceURI, nodeB.NamespaceURI); if (namespaceCompare != 0) return namespaceCompare; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs index 88574cc22f47c8..aa17f92429f73a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs @@ -28,7 +28,7 @@ private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, int rDepth; XmlAttribute local = (XmlAttribute)nsLocallyDeclared[nsPrefix]; XmlAttribute rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out rDepth); - if (local != null) + if (local is not null) { if (Utils.IsNonRedundantNamespaceDecl(local, rAncestral)) { @@ -43,7 +43,7 @@ private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, { int uDepth; XmlAttribute uAncestral = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out uDepth); - if (uAncestral != null && uDepth > rDepth && Utils.IsNonRedundantNamespaceDecl(uAncestral, rAncestral)) + if (uAncestral is not null && uDepth > rDepth && Utils.IsNonRedundantNamespaceDecl(uAncestral, rAncestral)) { if (Utils.IsXmlNamespaceNode(uAncestral)) attrListToRender.Add(uAncestral, null); @@ -78,7 +78,7 @@ internal override void GetNamespacesToRender(XmlElement element, SortedList attr foreach (object a in GetScopeAt(i).GetUnrendered().Values) { attrib = (XmlAttribute)a; - if (attrib != null) + if (attrib is not null) GetNamespaceToRender(Utils.GetNamespacePrefix(attrib), attrListToRender, nsListToRender, nsLocallyDeclared); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs index 3ccf5ccecd8787..895ef484732b7e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs @@ -19,7 +19,7 @@ internal class CanonicalXml internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver resolver, string strBaseUri) { - if (inputStream == null) + if (inputStream is null) throw new ArgumentNullException(nameof(inputStream)); _c14nDoc = new CanonicalXmlDocument(true, includeComments); @@ -31,7 +31,7 @@ internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver reso internal CanonicalXml(XmlDocument document, XmlResolver resolver) : this(document, resolver, false) { } internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeComments) { - if (document == null) + if (document is null) throw new ArgumentNullException(nameof(document)); _c14nDoc = new CanonicalXmlDocument(true, includeComments); @@ -42,11 +42,11 @@ internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeCo internal CanonicalXml(XmlNodeList nodeList, XmlResolver resolver, bool includeComments) { - if (nodeList == null) + if (nodeList is null) throw new ArgumentNullException(nameof(nodeList)); XmlDocument doc = Utils.GetOwnerDocument(nodeList); - if (doc == null) + if (doc is null) throw new ArgumentException(nameof(nodeList)); _c14nDoc = new CanonicalXmlDocument(false, includeComments); @@ -88,7 +88,7 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument } XmlAttributeCollection attribNodes = childNodes[i].Attributes; - if (attribNodes != null) + if (attribNodes is not null) { for (int j = 0; j < attribNodes.Count; j++) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs index 3b876fc4e6f430..d33d2da9ba89ee 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs @@ -31,7 +31,7 @@ public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespa SortedList attrListToRender = new SortedList(new AttributeSortOrder()); XmlAttributeCollection attrList = Attributes; - if (attrList != null) + if (attrList is not null) { foreach (XmlAttribute attr in attrList) { @@ -104,7 +104,7 @@ public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespace byte[] rgbData; XmlAttributeCollection attrList = Attributes; - if (attrList != null) + if (attrList is not null) { foreach (XmlAttribute attr in attrList) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs index af0939e8a7ade3..e0d8689982da5b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs @@ -32,7 +32,7 @@ public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespa strBuilder.Append((char)10); strBuilder.Append(" 0)) + if ((Value is not null) && (Value.Length > 0)) strBuilder.Append(" " + Value); strBuilder.Append("?>"); if (docPos == DocPosition.BeforeRootElement) @@ -55,7 +55,7 @@ public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespace hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); rgbData = utf8.GetBytes((Name)); hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); - if ((Value != null) && (Value.Length > 0)) + if ((Value is not null) && (Value.Length > 0)) { rgbData = utf8.GetBytes(" " + Value); hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs index 80a8f8affa010a..36c2a2c3547698 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs @@ -26,7 +26,7 @@ public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition doc public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); XmlNodeList childNodes = node.ChildNodes; @@ -50,7 +50,7 @@ public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPo public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); XmlNodeList childNodes = node.ChildNodes; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs index 4283eed5cd3818..56146385daabfc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs @@ -27,7 +27,7 @@ private bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -36,9 +36,9 @@ public CipherReference CipherReference get { return _cipherReference; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (CipherValue != null) + if (CipherValue is not null) throw new CryptographicException(SR.Cryptography_Xml_CipherValueElementRequired); _cipherReference = value; @@ -51,9 +51,9 @@ public byte[] CipherValue get { return _cipherValue; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (CipherReference != null) + if (CipherReference is not null) throw new CryptographicException(SR.Cryptography_Xml_CipherValueElementRequired); _cipherValue = (byte[])value.Clone(); @@ -74,7 +74,7 @@ internal XmlElement GetXml(XmlDocument document) { // Create the CipherData element XmlElement cipherDataElement = (XmlElement)document.CreateElement("CipherData", EncryptedXml.XmlEncNamespaceUrl); - if (CipherValue != null) + if (CipherValue is not null) { XmlElement cipherValueElement = document.CreateElement("CipherValue", EncryptedXml.XmlEncNamespaceUrl); cipherValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(CipherValue))); @@ -83,7 +83,7 @@ internal XmlElement GetXml(XmlDocument document) else { // No CipherValue specified, see if there is a CipherReference - if (CipherReference == null) + if (CipherReference is null) throw new CryptographicException(SR.Cryptography_Xml_CipherValueElementRequired); cipherDataElement.AppendChild(CipherReference.GetXml(document)); } @@ -92,7 +92,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); @@ -100,13 +100,13 @@ public void LoadXml(XmlElement value) XmlNode cipherValueNode = value.SelectSingleNode("enc:CipherValue", nsm); XmlNode cipherReferenceNode = value.SelectSingleNode("enc:CipherReference", nsm); - if (cipherValueNode != null) + if (cipherValueNode is not null) { - if (cipherReferenceNode != null) + if (cipherReferenceNode is not null) throw new CryptographicException(SR.Cryptography_Xml_CipherValueElementRequired); _cipherValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(cipherValueNode.InnerText)); } - else if (cipherReferenceNode != null) + else if (cipherReferenceNode is not null) { _cipherReference = new CipherReference(); _cipherReference.LoadXml((XmlElement)cipherReferenceNode); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs index d8be38d6a3762f..0afd4b0328088a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs @@ -50,7 +50,7 @@ public override XmlElement GetXml() internal new XmlElement GetXml(XmlDocument document) { - if (ReferenceType == null) + if (ReferenceType is null) throw new CryptographicException(SR.Cryptography_Xml_ReferenceTypeRequired); // Create the Reference @@ -67,7 +67,7 @@ public override XmlElement GetXml() public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); ReferenceType = value.LocalName; @@ -78,7 +78,7 @@ public override void LoadXml(XmlElement value) XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNode transformsNode = value.SelectSingleNode("enc:Transforms", nsm); - if (transformsNode != null) + if (transformsNode is not null) TransformChain.LoadXml(transformsNode as XmlElement); // cache the Xml diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs index fb86b4c4b82847..4f8005a62e4cf6 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs @@ -38,7 +38,7 @@ public static object CreateFromKnownName(string name) => public static T CreateFromName(string name) where T : class { - if (name == null || name.IndexOfAny(_invalidChars) >= 0) + if (name is null || name.IndexOfAny(_invalidChars) >= 0) { return null; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs index a1a7e097fa9fe2..358bf1ea552ada 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs @@ -97,14 +97,14 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) dsaKeyValueElement.AppendChild(yElement); // Add optional components if present - if (dsaParams.J != null) + if (dsaParams.J is not null) { XmlElement jElement = xmlDocument.CreateElement(JElementName, SignedXml.XmlDsigNamespaceUrl); jElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.J))); dsaKeyValueElement.AppendChild(jElement); } - if (dsaParams.Seed != null) + if (dsaParams.Seed is not null) { // note we assume counter is correct if Seed is present XmlElement seedElement = xmlDocument.CreateElement(SeedElementName, SignedXml.XmlDsigNamespaceUrl); seedElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Seed))); @@ -137,7 +137,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) /// public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -152,19 +152,19 @@ public override void LoadXml(XmlElement value) xmlNamespaceManager.AddNamespace(xmlDsigNamespacePrefix, SignedXml.XmlDsigNamespaceUrl); XmlNode dsaKeyValueElement = value.SelectSingleNode($"{xmlDsigNamespacePrefix}:{DSAKeyValueElementName}", xmlNamespaceManager); - if (dsaKeyValueElement == null) + if (dsaKeyValueElement is null) { throw new CryptographicException($"{KeyValueElementName} must contain child element {DSAKeyValueElementName}"); } XmlNode yNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{YElementName}", xmlNamespaceManager); - if (yNode == null) + if (yNode is null) throw new CryptographicException($"{YElementName} is missing"); XmlNode pNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{PElementName}", xmlNamespaceManager); XmlNode qNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{QElementName}", xmlNamespaceManager); - if ((pNode == null && qNode != null) || (pNode != null && qNode == null)) + if ((pNode is null && qNode is not null) || (pNode is not null && qNode is null)) throw new CryptographicException($"{PElementName} and {QElementName} can only occur in combination"); @@ -173,20 +173,20 @@ public override void LoadXml(XmlElement value) XmlNode seedNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{SeedElementName}", xmlNamespaceManager); XmlNode pgenCounterNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{PgenCounterElementName}", xmlNamespaceManager); - if ((seedNode == null && pgenCounterNode != null) || (seedNode != null && pgenCounterNode == null)) + if ((seedNode is null && pgenCounterNode is not null) || (seedNode is not null && pgenCounterNode is null)) throw new CryptographicException($"{SeedElementName} and {PgenCounterElementName} can only occur in combination"); try { Key.ImportParameters(new DSAParameters { - P = (pNode != null) ? Convert.FromBase64String(pNode.InnerText) : null, - Q = (qNode != null) ? Convert.FromBase64String(qNode.InnerText) : null, - G = (gNode != null) ? Convert.FromBase64String(gNode.InnerText) : null, + P = (pNode is not null) ? Convert.FromBase64String(pNode.InnerText) : null, + Q = (qNode is not null) ? Convert.FromBase64String(qNode.InnerText) : null, + G = (gNode is not null) ? Convert.FromBase64String(gNode.InnerText) : null, Y = Convert.FromBase64String(yNode.InnerText), - J = (jNode != null) ? Convert.FromBase64String(jNode.InnerText) : null, - Seed = (seedNode != null) ? Convert.FromBase64String(seedNode.InnerText) : null, - Counter = (pgenCounterNode != null) ? Utils.ConvertByteArrayToInt(Convert.FromBase64String(pgenCounterNode.InnerText)) : 0 + J = (jNode is not null) ? Convert.FromBase64String(jNode.InnerText) : null, + Seed = (seedNode is not null) ? Convert.FromBase64String(seedNode.InnerText) : null, + Counter = (pgenCounterNode is not null) ? Utils.ConvertByteArrayToInt(Convert.FromBase64String(pgenCounterNode.InnerText)) : 0 }); } catch (Exception ex) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs index 498c97a31b25ac..b236862d757123 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs @@ -25,7 +25,7 @@ public DataObject() public DataObject(string id, string mimeType, string encoding, XmlElement data) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); _id = id; @@ -75,7 +75,7 @@ public XmlNodeList Data get { return _elData; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // Reset the node list @@ -92,7 +92,7 @@ private bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -120,7 +120,7 @@ internal XmlElement GetXml(XmlDocument document) if (!string.IsNullOrEmpty(_encoding)) objectElement.SetAttribute("Encoding", _encoding); - if (_elData != null) + if (_elData is not null) { foreach (XmlNode node in _elData) { @@ -133,7 +133,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs index 9d085a5e3c2001..d4ba86a95b7148 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs @@ -9,7 +9,7 @@ public sealed class EncryptedData : EncryptedType { public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); @@ -25,18 +25,18 @@ public override void LoadXml(XmlElement value) // EncryptionMethod EncryptionMethod = new EncryptionMethod(); - if (encryptionMethodNode != null) + if (encryptionMethodNode is not null) EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement); // Key Info KeyInfo = new KeyInfo(); XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); - if (keyInfoNode != null) + if (keyInfoNode is not null) KeyInfo.LoadXml(keyInfoNode as XmlElement); // CipherData XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); - if (cipherDataNode == null) + if (cipherDataNode is null) throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); CipherData = new CipherData(); @@ -44,11 +44,11 @@ public override void LoadXml(XmlElement value) // EncryptionProperties XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); - if (encryptionPropertiesNode != null) + if (encryptionPropertiesNode is not null) { // Select the EncryptionProperty elements inside the EncryptionProperties element XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); - if (encryptionPropertyNodes != null) + if (encryptionPropertyNodes is not null) { foreach (XmlNode node in encryptionPropertyNodes) { @@ -88,7 +88,7 @@ internal XmlElement GetXml(XmlDocument document) encryptedDataElement.SetAttribute("Encoding", Encoding); // EncryptionMethod - if (EncryptionMethod != null) + if (EncryptionMethod is not null) encryptedDataElement.AppendChild(EncryptionMethod.GetXml(document)); // KeyInfo @@ -96,7 +96,7 @@ internal XmlElement GetXml(XmlDocument document) encryptedDataElement.AppendChild(KeyInfo.GetXml(document)); // CipherData is required. - if (CipherData == null) + if (CipherData is null) throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); encryptedDataElement.AppendChild(CipherData.GetXml(document)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs index a379d78f0b9b66..2907ff98595d3f 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs @@ -18,7 +18,7 @@ public string Recipient get { // an unspecified value for an XmlAttribute is string.Empty - if (_recipient == null) + if (_recipient is null) _recipient = string.Empty; return _recipient; } @@ -43,7 +43,7 @@ public ReferenceList ReferenceList { get { - if (_referenceList == null) + if (_referenceList is null) _referenceList = new ReferenceList(); return _referenceList; } @@ -61,7 +61,7 @@ public void AddReference(KeyReference keyReference) public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); @@ -78,18 +78,18 @@ public override void LoadXml(XmlElement value) // EncryptionMethod EncryptionMethod = new EncryptionMethod(); - if (encryptionMethodNode != null) + if (encryptionMethodNode is not null) EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement); // Key Info KeyInfo = new KeyInfo(); XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); - if (keyInfoNode != null) + if (keyInfoNode is not null) KeyInfo.LoadXml(keyInfoNode as XmlElement); // CipherData XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); - if (cipherDataNode == null) + if (cipherDataNode is null) throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); CipherData = new CipherData(); @@ -97,11 +97,11 @@ public override void LoadXml(XmlElement value) // EncryptionProperties XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); - if (encryptionPropertiesNode != null) + if (encryptionPropertiesNode is not null) { // Select the EncryptionProperty elements inside the EncryptionProperties element XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); - if (encryptionPropertyNodes != null) + if (encryptionPropertyNodes is not null) { foreach (XmlNode node in encryptionPropertyNodes) { @@ -114,18 +114,18 @@ public override void LoadXml(XmlElement value) // CarriedKeyName XmlNode carriedKeyNameNode = value.SelectSingleNode("enc:CarriedKeyName", nsm); - if (carriedKeyNameNode != null) + if (carriedKeyNameNode is not null) { CarriedKeyName = carriedKeyNameNode.InnerText; } // ReferenceList XmlNode referenceListNode = value.SelectSingleNode("enc:ReferenceList", nsm); - if (referenceListNode != null) + if (referenceListNode is not null) { // Select the DataReference elements inside the ReferenceList element XmlNodeList dataReferenceNodes = referenceListNode.SelectNodes("enc:DataReference", nsm); - if (dataReferenceNodes != null) + if (dataReferenceNodes is not null) { foreach (XmlNode node in dataReferenceNodes) { @@ -136,7 +136,7 @@ public override void LoadXml(XmlElement value) } // Select the KeyReference elements inside the ReferenceList element XmlNodeList keyReferenceNodes = referenceListNode.SelectNodes("enc:KeyReference", nsm); - if (keyReferenceNodes != null) + if (keyReferenceNodes is not null) { foreach (XmlNode node in keyReferenceNodes) { @@ -178,7 +178,7 @@ internal XmlElement GetXml(XmlDocument document) encryptedKeyElement.SetAttribute("Recipient", Recipient); // EncryptionMethod - if (EncryptionMethod != null) + if (EncryptionMethod is not null) encryptedKeyElement.AppendChild(EncryptionMethod.GetXml(document)); // KeyInfo @@ -186,7 +186,7 @@ internal XmlElement GetXml(XmlDocument document) encryptedKeyElement.AppendChild(KeyInfo.GetXml(document)); // CipherData - if (CipherData == null) + if (CipherData is null) throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); encryptedKeyElement.AppendChild(CipherData.GetXml(document)); @@ -214,7 +214,7 @@ internal XmlElement GetXml(XmlDocument document) } // CarriedKeyName - if (CarriedKeyName != null) + if (CarriedKeyName is not null) { XmlElement carriedKeyNameElement = (XmlElement)document.CreateElement("CarriedKeyName", EncryptedXml.XmlEncNamespaceUrl); XmlText carriedKeyNameText = document.CreateTextNode(CarriedKeyName); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs index 2e356d8df4aff0..fbbe202e33a01a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs @@ -32,7 +32,7 @@ public string Uri get { return _uri; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(SR.Cryptography_Xml_UriRequired); _uri = value; _cachedXml = null; @@ -43,7 +43,7 @@ public TransformChain TransformChain { get { - if (_transformChain == null) + if (_transformChain is null) _transformChain = new TransformChain(); return _transformChain; } @@ -73,7 +73,7 @@ protected internal bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -88,7 +88,7 @@ public virtual XmlElement GetXml() internal XmlElement GetXml(XmlDocument document) { - if (ReferenceType == null) + if (ReferenceType is null) throw new CryptographicException(SR.Cryptography_Xml_ReferenceTypeRequired); // Create the Reference @@ -105,13 +105,13 @@ internal XmlElement GetXml(XmlDocument document) public virtual void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); ReferenceType = value.LocalName; string uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); - if (uri == null) + if (uri is null) throw new ArgumentNullException(SR.Cryptography_Xml_UriRequired); Uri = uri; @@ -119,7 +119,7 @@ public virtual void LoadXml(XmlElement value) XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNode transformsNode = value.SelectSingleNode("ds:Transforms", nsm); - if (transformsNode != null) + if (transformsNode is not null) TransformChain.LoadXml(transformsNode as XmlElement); // cache the Xml diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs index 2e5680f94f37a5..e71d65051c731c 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs @@ -21,7 +21,7 @@ internal bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -69,7 +69,7 @@ public KeyInfo KeyInfo { get { - if (_keyInfo == null) + if (_keyInfo is null) _keyInfo = new KeyInfo(); return _keyInfo; } @@ -90,7 +90,7 @@ public virtual EncryptionPropertyCollection EncryptionProperties { get { - if (_props == null) + if (_props is null) _props = new EncryptionPropertyCollection(); return _props; } @@ -105,14 +105,14 @@ public virtual CipherData CipherData { get { - if (_cipherData == null) + if (_cipherData is null) _cipherData = new CipherData(); return _cipherData; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _cipherData = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index 7762ff97c7f5aa..368e4effd3978a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -167,7 +167,7 @@ public string Recipient get { // an unspecified value for an XmlAttribute is string.Empty - if (_recipient == null) + if (_recipient is null) _recipient = string.Empty; return _recipient; } @@ -180,21 +180,21 @@ public string Recipient private byte[] GetCipherValue(CipherData cipherData) { - if (cipherData == null) + if (cipherData is null) throw new ArgumentNullException(nameof(cipherData)); Stream inputStream = null; - if (cipherData.CipherValue != null) + if (cipherData.CipherValue is not null) { return cipherData.CipherValue; } - else if (cipherData.CipherReference != null) + else if (cipherData.CipherReference is not null) { - if (cipherData.CipherReference.CipherValue != null) + if (cipherData.CipherReference.CipherValue is not null) return cipherData.CipherReference.CipherValue; Stream decInputStream = null; - if (cipherData.CipherReference.Uri == null) + if (cipherData.CipherReference.Uri is null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); } @@ -202,9 +202,9 @@ private byte[] GetCipherValue(CipherData cipherData) if (cipherData.CipherReference.Uri.Length == 0) { // self referenced Uri - string baseUri = (_document == null ? null : _document.BaseURI); + string baseUri = (_document is null ? null : _document.BaseURI); TransformChain tc = cipherData.CipherReference.TransformChain; - if (tc == null) + if (tc is null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); } @@ -215,14 +215,14 @@ private byte[] GetCipherValue(CipherData cipherData) string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri); // Serialize XmlElement idElem = GetIdElement(_document, idref); - if (idElem == null || idElem.OuterXml == null) + if (idElem is null || idElem.OuterXml is null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); } inputStream = new MemoryStream(_encoding.GetBytes(idElem.OuterXml)); - string baseUri = (_document == null ? null : _document.BaseURI); + string baseUri = (_document is null ? null : _document.BaseURI); TransformChain tc = cipherData.CipherReference.TransformChain; - if (tc == null) + if (tc is null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); } @@ -239,7 +239,7 @@ private byte[] GetCipherValue(CipherData cipherData) Utils.Pump(decInputStream, ms); cipherValue = ms.ToArray(); // Close the stream and return - if (inputStream != null) + if (inputStream is not null) inputStream.Close(); decInputStream.Close(); } @@ -266,14 +266,14 @@ public virtual XmlElement GetIdElement(XmlDocument document, string idValue) // default behaviour is to look for the IV in the CipherValue public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri) { - if (encryptedData == null) + if (encryptedData is null) throw new ArgumentNullException(nameof(encryptedData)); int initBytesSize = 0; // If the Uri is not provided by the application, try to get it from the EncryptionMethod - if (symmetricAlgorithmUri == null) + if (symmetricAlgorithmUri is null) { - if (encryptedData.EncryptionMethod == null) + if (encryptedData.EncryptionMethod is null) throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } @@ -302,10 +302,10 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmet // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) { - if (encryptedData == null) + if (encryptedData is null) throw new ArgumentNullException(nameof(encryptedData)); - if (encryptedData.KeyInfo == null) + if (encryptedData.KeyInfo is null) return null; IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator(); KeyInfoRetrievalMethod kiRetrievalMethod; @@ -316,17 +316,17 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; - if (kiName != null) + if (kiName is not null) { // Get the decryption key from the key mapping string keyName = kiName.Value; - if ((SymmetricAlgorithm)_keyNameMapping[keyName] != null) + if ((SymmetricAlgorithm)_keyNameMapping[keyName] is not null) return (SymmetricAlgorithm)_keyNameMapping[keyName]; // try to get it from a CarriedKeyName XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNodeList encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm); - if (encryptedKeyList != null) + if (encryptedKeyList is not null) { foreach (XmlNode encryptedKeyNode in encryptedKeyList) { @@ -343,7 +343,7 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; - if (kiRetrievalMethod != null) + if (kiRetrievalMethod is not null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); @@ -351,7 +351,7 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, break; } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; - if (kiEncKey != null) + if (kiEncKey is not null) { ek = kiEncKey.EncryptedKey; break; @@ -359,22 +359,22 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, } // if we have an EncryptedKey, decrypt to get the symmetric key - if (ek != null) + if (ek is not null) { // now process the EncryptedKey, loop recursively // If the Uri is not provided by the application, try to get it from the EncryptionMethod - if (symmetricAlgorithmUri == null) + if (symmetricAlgorithmUri is null) { - if (encryptedData.EncryptionMethod == null) + if (encryptedData.EncryptionMethod is null) throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } byte[] key = DecryptEncryptedKey(ek); - if (key == null) + if (key is null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName(symmetricAlgorithmUri); - if (symAlg == null) + if (symAlg is null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } @@ -387,9 +387,9 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, // Try to decrypt the EncryptedKey given the key mapping public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { - if (encryptedKey == null) + if (encryptedKey is null) throw new ArgumentNullException(nameof(encryptedKey)); - if (encryptedKey.KeyInfo == null) + if (encryptedKey.KeyInfo is null) return null; IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator(); @@ -403,14 +403,14 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; - if (kiName != null) + if (kiName is not null) { // Get the decryption key from the key mapping string keyName = kiName.Value; object kek = _keyNameMapping[keyName]; - if (kek != null) + if (kek is not null) { - if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) + if (encryptedKey.CipherData is null || encryptedKey.CipherData.CipherValue is null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } @@ -419,26 +419,26 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek); // kek is an RSA key: get fOAEP from the algorithm, default to false - fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); + fOAEP = (encryptedKey.EncryptionMethod is not null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP); } break; } kiX509Data = keyInfoEnum.Current as KeyInfoX509Data; - if (kiX509Data != null) + if (kiX509Data is not null) { X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption); foreach (X509Certificate2 certificate in collection) { using (RSA privateKey = certificate.GetRSAPrivateKey()) { - if (privateKey != null) + if (privateKey is not null) { - if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) + if (encryptedKey.CipherData is null || encryptedKey.CipherData.CipherValue is null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } - fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); + fOAEP = (encryptedKey.EncryptionMethod is not null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP); } } @@ -446,7 +446,7 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; - if (kiRetrievalMethod != null) + if (kiRetrievalMethod is not null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); @@ -472,21 +472,21 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) } } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; - if (kiEncKey != null) + if (kiEncKey is not null) { ek = kiEncKey.EncryptedKey; // recursively process EncryptedKey elements byte[] encryptionKey = DecryptEncryptedKey(ek); - if (encryptionKey != null) + if (encryptionKey is not null) { // this is a symmetric algorithm for sure SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm); - if (symAlg == null) + if (symAlg is null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } symAlg.Key = encryptionKey; - if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) + if (encryptedKey.CipherData is null || encryptedKey.CipherData.CipherValue is null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } @@ -506,9 +506,9 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) // to be an RSA key or a SymmetricAlgorithm public void AddKeyNameMapping(string keyName, object keyObject) { - if (keyName == null) + if (keyName is null) throw new ArgumentNullException(nameof(keyName)); - if (keyObject == null) + if (keyObject is null) throw new ArgumentNullException(nameof(keyObject)); if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA)) @@ -525,14 +525,14 @@ public void ClearKeyNameMappings() // an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly. public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certificate) { - if (inputElement == null) + if (inputElement is null) throw new ArgumentNullException(nameof(inputElement)); - if (certificate == null) + if (certificate is null) throw new ArgumentNullException(nameof(certificate)); using (RSA rsaPublicKey = certificate.GetRSAPublicKey()) { - if (rsaPublicKey == null) + if (rsaPublicKey is null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); // Create the EncryptedData object, using an AES-256 session key by default. @@ -563,16 +563,16 @@ public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certifica // a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly. public EncryptedData Encrypt(XmlElement inputElement, string keyName) { - if (inputElement == null) + if (inputElement is null) throw new ArgumentNullException(nameof(inputElement)); - if (keyName == null) + if (keyName is null) throw new ArgumentNullException(nameof(keyName)); object encryptionKey = null; - if (_keyNameMapping != null) + if (_keyNameMapping is not null) encryptionKey = _keyNameMapping[keyName]; - if (encryptionKey == null) + if (encryptionKey is null) throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey); // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table @@ -586,7 +586,7 @@ public EncryptedData Encrypt(XmlElement inputElement, string keyName) // Include the key name in the EncryptedKey KeyInfo. string encryptionMethod = null; - if (symKey == null) + if (symKey is null) { encryptionMethod = EncryptedXml.XmlEncRSA15Url; } @@ -622,7 +622,7 @@ public EncryptedData Encrypt(XmlElement inputElement, string keyName) // Create a random AES session key and encrypt it with the public key associated with the certificate. RijndaelManaged rijn = new RijndaelManaged(); - ek.CipherData.CipherValue = (symKey == null ? EncryptedXml.EncryptKey(rijn.Key, rsa, false) : EncryptedXml.EncryptKey(rijn.Key, symKey)); + ek.CipherData.CipherValue = (symKey is null ? EncryptedXml.EncryptKey(rijn.Key, rsa, false) : EncryptedXml.EncryptKey(rijn.Key, symKey)); // Encrypt the input element with the random session key that we've created above. KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek); @@ -641,7 +641,7 @@ public void DecryptDocument() XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNodeList encryptedDataList = _document.SelectNodes("//enc:EncryptedData", nsm); - if (encryptedDataList != null) + if (encryptedDataList is not null) { foreach (XmlNode encryptedDataNode in encryptedDataList) { @@ -649,7 +649,7 @@ public void DecryptDocument() EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); SymmetricAlgorithm symAlg = GetDecryptionKey(ed, null); - if (symAlg == null) + if (symAlg is null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); byte[] decrypted = DecryptData(ed, symAlg); ReplaceData(encryptedDataElement, decrypted); @@ -660,9 +660,9 @@ public void DecryptDocument() // encrypts the supplied arbitrary data public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm) { - if (plaintext == null) + if (plaintext is null) throw new ArgumentNullException(nameof(plaintext)); - if (symmetricAlgorithm == null) + if (symmetricAlgorithm is null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); // save the original symmetric algorithm @@ -703,9 +703,9 @@ public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorith // encrypts the supplied input element public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricAlgorithm, bool content) { - if (inputElement == null) + if (inputElement is null) throw new ArgumentNullException(nameof(inputElement)); - if (symmetricAlgorithm == null) + if (symmetricAlgorithm is null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); byte[] plainText = (content ? _encoding.GetBytes(inputElement.InnerXml) : _encoding.GetBytes(inputElement.OuterXml)); @@ -715,9 +715,9 @@ public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricA // decrypts the supplied EncryptedData public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm) { - if (encryptedData == null) + if (encryptedData is null) throw new ArgumentNullException(nameof(encryptedData)); - if (symmetricAlgorithm == null) + if (symmetricAlgorithm is null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); // get the cipher value and decrypt @@ -737,7 +737,7 @@ public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmet try { int lengthIV = 0; - if (decryptionIV != null) + if (decryptionIV is not null) { symmetricAlgorithm.IV = decryptionIV; lengthIV = decryptionIV.Length; @@ -762,9 +762,9 @@ public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmet // This method replaces an EncryptedData element with the decrypted sequence of bytes public void ReplaceData(XmlElement inputElement, byte[] decryptedData) { - if (inputElement == null) + if (inputElement is null) throw new ArgumentNullException(nameof(inputElement)); - if (decryptedData == null) + if (decryptedData is null) throw new ArgumentNullException(nameof(decryptedData)); XmlNode parent = inputElement.ParentNode; @@ -807,7 +807,7 @@ public void ReplaceData(XmlElement inputElement, byte[] decryptedData) XmlNode sibling = inputElement.NextSibling; XmlNode nextChild = null; - while (child != null) + while (child is not null) { nextChild = child.NextSibling; parent.InsertBefore(child, sibling); @@ -832,9 +832,9 @@ public void ReplaceData(XmlElement inputElement, byte[] decryptedData) // replaces the inputElement with the provided EncryptedData public static void ReplaceElement(XmlElement inputElement, EncryptedData encryptedData, bool content) { - if (inputElement == null) + if (inputElement is null) throw new ArgumentNullException(nameof(inputElement)); - if (encryptedData == null) + if (encryptedData is null) throw new ArgumentNullException(nameof(encryptedData)); // First, get the XML representation of the EncryptedData object @@ -858,9 +858,9 @@ public static void ReplaceElement(XmlElement inputElement, EncryptedData encrypt // wraps the supplied input key data using the provided symmetric algorithm public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { - if (keyData == null) + if (keyData is null) throw new ArgumentNullException(nameof(keyData)); - if (symmetricAlgorithm == null) + if (symmetricAlgorithm is null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); if (symmetricAlgorithm is TripleDES) @@ -882,9 +882,9 @@ public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgo // padding or PKCS#1 v1.5 padding as described in the PKCS specification public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) { - if (keyData == null) + if (keyData is null) throw new ArgumentNullException(nameof(keyData)); - if (rsa == null) + if (rsa is null) throw new ArgumentNullException(nameof(rsa)); if (useOAEP) @@ -902,9 +902,9 @@ public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) // decrypts the supplied wrapped key using the provided symmetric algorithm public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { - if (keyData == null) + if (keyData is null) throw new ArgumentNullException(nameof(keyData)); - if (symmetricAlgorithm == null) + if (symmetricAlgorithm is null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); if (symmetricAlgorithm is TripleDES) @@ -925,9 +925,9 @@ public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgo // padding or PKCS#1 v1.5 padding as described in the PKCS specification public static byte[] DecryptKey(byte[] keyData, RSA rsa, bool useOAEP) { - if (keyData == null) + if (keyData is null) throw new ArgumentNullException(nameof(keyData)); - if (rsa == null) + if (rsa is null) throw new ArgumentNullException(nameof(rsa)); if (useOAEP) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs index 215b5697720900..a16c06c77df321 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs @@ -26,7 +26,7 @@ private bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -79,7 +79,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); @@ -89,7 +89,7 @@ public void LoadXml(XmlElement value) _algorithm = Utils.GetAttribute(encryptionMethodElement, "Algorithm", EncryptedXml.XmlEncNamespaceUrl); XmlNode keySizeNode = value.SelectSingleNode("enc:KeySize", nsm); - if (keySizeNode != null) + if (keySizeNode is not null) { KeySize = Convert.ToInt32(Utils.DiscardWhiteSpaces(keySizeNode.InnerText), null); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs index d2f901609718f0..d5a9a3e29facbc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs @@ -17,7 +17,7 @@ public EncryptionProperty() { } public EncryptionProperty(XmlElement elementProperty) { - if (elementProperty == null) + if (elementProperty is null) throw new ArgumentNullException(nameof(elementProperty)); if (elementProperty.LocalName != "EncryptionProperty" || elementProperty.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); @@ -41,7 +41,7 @@ public XmlElement PropertyElement get { return _elemProp; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.LocalName != "EncryptionProperty" || value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); @@ -55,7 +55,7 @@ private bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -75,7 +75,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.LocalName != "EncryptionProperty" || value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs index 93319b74346bad..18a370fcb76c87 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs @@ -37,7 +37,7 @@ private void GatherNamespaceToRender(string nsPrefix, SortedList nsListToRender, XmlAttribute local = (XmlAttribute)nsLocallyDeclared[nsPrefix]; XmlAttribute rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out rDepth); - if (local != null) + if (local is not null) { if (Utils.IsNonRedundantNamespaceDecl(local, rAncestral)) { @@ -49,7 +49,7 @@ private void GatherNamespaceToRender(string nsPrefix, SortedList nsListToRender, { int uDepth; XmlAttribute uAncestral = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out uDepth); - if (uAncestral != null && uDepth > rDepth && Utils.IsNonRedundantNamespaceDecl(uAncestral, rAncestral)) + if (uAncestral is not null && uDepth > rDepth && Utils.IsNonRedundantNamespaceDecl(uAncestral, rAncestral)) { nsListToRender.Add(uAncestral, null); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs index 29488e29688e29..4173faeb34576e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs @@ -14,7 +14,7 @@ internal class ExcCanonicalXml internal ExcCanonicalXml(Stream inputStream, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver, string strBaseUri) { - if (inputStream == null) + if (inputStream is null) throw new ArgumentNullException(nameof(inputStream)); _c14nDoc = new CanonicalXmlDocument(true, includeComments); @@ -25,7 +25,7 @@ internal ExcCanonicalXml(Stream inputStream, bool includeComments, string inclus internal ExcCanonicalXml(XmlDocument document, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) { - if (document == null) + if (document is null) throw new ArgumentNullException(nameof(document)); _c14nDoc = new CanonicalXmlDocument(true, includeComments); @@ -36,11 +36,11 @@ internal ExcCanonicalXml(XmlDocument document, bool includeComments, string incl internal ExcCanonicalXml(XmlNodeList nodeList, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) { - if (nodeList == null) + if (nodeList is null) throw new ArgumentNullException(nameof(nodeList)); XmlDocument doc = Utils.GetOwnerDocument(nodeList); - if (doc == null) + if (doc is null) throw new ArgumentException(nameof(nodeList)); _c14nDoc = new CanonicalXmlDocument(false, includeComments); @@ -94,7 +94,7 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument } XmlAttributeCollection attribNodes = childNodes[i].Attributes; - if (attribNodes != null) + if (attribNodes is not null) { for (int j = 0; j < attribNodes.Count; j++) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs index e69d101f1f907e..a446768c9a420b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs @@ -50,7 +50,7 @@ internal XmlElement GetXml(XmlDocument xmlDocument) for (int i = 0; i < _keyInfoClauses.Count; ++i) { XmlElement xmlElement = ((KeyInfoClause)_keyInfoClauses[i]).GetXml(xmlDocument); - if (xmlElement != null) + if (xmlElement is not null) { keyInfoElement.AppendChild(xmlElement); } @@ -60,7 +60,7 @@ internal XmlElement GetXml(XmlDocument xmlDocument) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlElement keyInfoElement = value; @@ -69,10 +69,10 @@ public void LoadXml(XmlElement value) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo"); XmlNode child = keyInfoElement.FirstChild; - while (child != null) + while (child is not null) { XmlElement elem = child as XmlElement; - if (elem != null) + if (elem is not null) { // Create the right type of KeyInfoClause; we use a combination of the namespace and tag name (local name) string kicString = elem.NamespaceURI + " " + elem.LocalName; @@ -87,7 +87,7 @@ public void LoadXml(XmlElement value) foreach (XmlNode node2 in nodeList2) { XmlElement elem2 = node2 as XmlElement; - if (elem2 != null) + if (elem2 is not null) { kicString += "/" + elem2.LocalName; break; @@ -97,7 +97,7 @@ public void LoadXml(XmlElement value) KeyInfoClause keyInfoClause = CryptoHelpers.CreateFromName(kicString); // if we don't know what kind of KeyInfoClause we're looking at, use a generic KeyInfoNode: - if (keyInfoClause == null) + if (keyInfoClause is null) keyInfoClause = new KeyInfoNode(); // Ask the create clause to fill itself with the corresponding XML diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs index 2ddeee99d99029..cee7962791814a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs @@ -24,14 +24,14 @@ public EncryptedKey EncryptedKey public override XmlElement GetXml() { - if (_encryptedKey == null) + if (_encryptedKey is null) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfoEncryptedKey"); return _encryptedKey.GetXml(); } internal override XmlElement GetXml(XmlDocument xmlDocument) { - if (_encryptedKey == null) + if (_encryptedKey is null) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfoEncryptedKey"); return _encryptedKey.GetXml(xmlDocument); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs index 47ed8746223438..a1d71589e484e2 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs @@ -50,7 +50,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlElement nameElement = value; _keyName = nameElement.InnerText.Trim(); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs index 05af3036e01677..916c68344a2337 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs @@ -65,7 +65,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs index d1127b33f70000..c93d8b266a129f 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs @@ -41,7 +41,7 @@ public KeyInfoX509Data(X509Certificate cert) public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption) { - if (cert == null) + if (cert is null) throw new ArgumentNullException(nameof(cert)); X509Certificate2 certificate = new X509Certificate2(cert); @@ -102,10 +102,10 @@ public ArrayList Certificates public void AddCertificate(X509Certificate certificate) { - if (certificate == null) + if (certificate is null) throw new ArgumentNullException(nameof(certificate)); - if (_certificates == null) + if (_certificates is null) _certificates = new ArrayList(); X509Certificate2 x509 = new X509Certificate2(certificate); @@ -119,14 +119,14 @@ public ArrayList SubjectKeyIds public void AddSubjectKeyId(byte[] subjectKeyId) { - if (_subjectKeyIds == null) + if (_subjectKeyIds is null) _subjectKeyIds = new ArrayList(); _subjectKeyIds.Add(subjectKeyId); } public void AddSubjectKeyId(string subjectKeyId) { - if (_subjectKeyIds == null) + if (_subjectKeyIds is null) _subjectKeyIds = new ArrayList(); _subjectKeyIds.Add(Utils.DecodeHexString(subjectKeyId)); } @@ -138,7 +138,7 @@ public ArrayList SubjectNames public void AddSubjectName(string subjectName) { - if (_subjectNames == null) + if (_subjectNames is null) _subjectNames = new ArrayList(); _subjectNames.Add(subjectName); } @@ -160,7 +160,7 @@ public void AddIssuerSerial(string issuerName, string serialNumber) if (!BigInteger.TryParse(serialNumber, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out h)) throw new ArgumentException(SR.Cryptography_Xml_InvalidX509IssuerSerialNumber, nameof(serialNumber)); - if (_issuerSerials == null) + if (_issuerSerials is null) _issuerSerials = new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, h.ToString())); } @@ -168,7 +168,7 @@ public void AddIssuerSerial(string issuerName, string serialNumber) // When we load an X509Data from Xml, we know the serial number is in decimal representation. internal void InternalAddIssuerSerial(string issuerName, string serialNumber) { - if (_issuerSerials == null) + if (_issuerSerials is null) _issuerSerials = new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, serialNumber)); } @@ -186,10 +186,10 @@ public byte[] CRL private void Clear() { _CRL = null; - if (_subjectKeyIds != null) _subjectKeyIds.Clear(); - if (_subjectNames != null) _subjectNames.Clear(); - if (_issuerSerials != null) _issuerSerials.Clear(); - if (_certificates != null) _certificates.Clear(); + if (_subjectKeyIds is not null) _subjectKeyIds.Clear(); + if (_subjectNames is not null) _subjectNames.Clear(); + if (_issuerSerials is not null) _issuerSerials.Clear(); + if (_certificates is not null) _certificates.Clear(); } // @@ -207,7 +207,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) { XmlElement x509DataElement = xmlDocument.CreateElement("X509Data", SignedXml.XmlDsigNamespaceUrl); - if (_issuerSerials != null) + if (_issuerSerials is not null) { foreach (X509IssuerSerial issuerSerial in _issuerSerials) { @@ -222,7 +222,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) } } - if (_subjectKeyIds != null) + if (_subjectKeyIds is not null) { foreach (byte[] subjectKeyId in _subjectKeyIds) { @@ -232,7 +232,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) } } - if (_subjectNames != null) + if (_subjectNames is not null) { foreach (string subjectName in _subjectNames) { @@ -242,7 +242,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) } } - if (_certificates != null) + if (_certificates is not null) { foreach (X509Certificate certificate in _certificates) { @@ -252,7 +252,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) } } - if (_CRL != null) + if (_CRL is not null) { XmlElement crlElement = xmlDocument.CreateElement("X509CRL", SignedXml.XmlDsigNamespaceUrl); crlElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(_CRL))); @@ -264,7 +264,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) public override void LoadXml(XmlElement element) { - if (element == null) + if (element is null) throw new ArgumentNullException(nameof(element)); XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable); @@ -290,7 +290,7 @@ public override void LoadXml(XmlElement element) { XmlNode x509IssuerNameNode = issuerSerialNode.SelectSingleNode("ds:X509IssuerName", nsm); XmlNode x509SerialNumberNode = issuerSerialNode.SelectSingleNode("ds:X509SerialNumber", nsm); - if (x509IssuerNameNode == null || x509SerialNumberNode == null) + if (x509IssuerNameNode is null || x509SerialNumberNode is null) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "IssuerSerial"); InternalAddIssuerSerial(x509IssuerNameNode.InnerText.Trim(), x509SerialNumberNode.InnerText.Trim()); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs index 9973abc00fa8a0..1f2fca3f966599 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs @@ -14,7 +14,7 @@ public int Compare(object a, object b) { XmlNode nodeA = a as XmlNode; XmlNode nodeB = b as XmlNode; - if ((nodeA == null) || (nodeB == null)) + if ((nodeA is null) || (nodeB is null)) throw new ArgumentException(); bool nodeAdefault = Utils.IsDefaultNamespaceNode(nodeA); bool nodeBdefault = Utils.IsDefaultNamespaceNode(nodeB); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs index b5a95e8d7a4141..bcde2fc79000fd 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs @@ -95,7 +95,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) /// public override void LoadXml(XmlElement value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -110,7 +110,7 @@ public override void LoadXml(XmlElement value) xmlNamespaceManager.AddNamespace(xmlDsigNamespacePrefix, SignedXml.XmlDsigNamespaceUrl); XmlNode rsaKeyValueElement = value.SelectSingleNode($"{xmlDsigNamespacePrefix}:{RSAKeyValueElementName}", xmlNamespaceManager); - if (rsaKeyValueElement == null) + if (rsaKeyValueElement is null) { throw new CryptographicException($"{KeyValueElementName} must contain child element {RSAKeyValueElementName}"); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs index 581e8dc21afbda..99afcb4202dac2 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs @@ -119,7 +119,7 @@ public TransformChain TransformChain { get { - if (_transformChain == null) + if (_transformChain is null) _transformChain = new TransformChain(); return _transformChain; } @@ -134,7 +134,7 @@ internal bool CacheValid { get { - return (_cachedXml != null); + return (_cachedXml is not null); } } @@ -173,7 +173,7 @@ internal XmlElement GetXml(XmlDocument document) if (!string.IsNullOrEmpty(_id)) referenceElement.SetAttribute("Id", _id); - if (_uri != null) + if (_uri is not null) referenceElement.SetAttribute("URI", _uri); if (!string.IsNullOrEmpty(_type)) @@ -191,9 +191,9 @@ internal XmlElement GetXml(XmlDocument document) digestMethodElement.SetAttribute("Algorithm", _digestMethod); referenceElement.AppendChild(digestMethodElement); - if (DigestValue == null) + if (DigestValue is null) { - if (_hashAlgorithm.Hash == null) + if (_hashAlgorithm.Hash is null) throw new CryptographicException(SR.Cryptography_Xml_DigestValueRequired); DigestValue = _hashAlgorithm.Hash; } @@ -207,7 +207,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); _id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); @@ -223,7 +223,7 @@ public void LoadXml(XmlElement value) bool hasTransforms = false; TransformChain = new TransformChain(); XmlNodeList transformsNodes = value.SelectNodes("ds:Transforms", nsm); - if (transformsNodes != null && transformsNodes.Count != 0) + if (transformsNodes is not null && transformsNodes.Count != 0) { if (transformsNodes.Count > 1) { @@ -236,7 +236,7 @@ public void LoadXml(XmlElement value) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms"); } XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm); - if (transformNodes != null) + if (transformNodes is not null) { if (transformNodes.Count != transformsElement.SelectNodes("*").Count) { @@ -250,12 +250,12 @@ public void LoadXml(XmlElement value) { XmlElement transformElement = transformNode as XmlElement; string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); - if (algorithm == null || !Utils.VerifyAttributes(transformElement, "Algorithm")) + if (algorithm is null || !Utils.VerifyAttributes(transformElement, "Algorithm")) { throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } Transform transform = CryptoHelpers.CreateFromName(algorithm); - if (transform == null) + if (transform is null) { throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } @@ -269,7 +269,7 @@ public void LoadXml(XmlElement value) // Signature-->SignedInfo-->Reference-->Transforms-->Transform XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm); XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm); - if (signatureList != null) + if (signatureList is not null) { int position = 0; foreach (XmlNode node in signatureList) @@ -289,17 +289,17 @@ public void LoadXml(XmlElement value) // DigestMethod XmlNodeList digestMethodNodes = value.SelectNodes("ds:DigestMethod", nsm); - if (digestMethodNodes == null || digestMethodNodes.Count == 0 || digestMethodNodes.Count > 1) + if (digestMethodNodes is null || digestMethodNodes.Count == 0 || digestMethodNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod"); XmlElement digestMethodElement = digestMethodNodes[0] as XmlElement; _digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); - if (_digestMethod == null || !Utils.VerifyAttributes(digestMethodElement, "Algorithm")) + if (_digestMethod is null || !Utils.VerifyAttributes(digestMethodElement, "Algorithm")) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod"); // DigestValue XmlNodeList digestValueNodes = value.SelectNodes("ds:DigestValue", nsm); - if (digestValueNodes == null || digestValueNodes.Count == 0 || digestValueNodes.Count > 1) + if (digestValueNodes is null || digestValueNodes.Count == 0 || digestValueNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue"); XmlElement digestValueElement = digestValueNodes[0] as XmlElement; _digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText)); @@ -316,7 +316,7 @@ public void LoadXml(XmlElement value) public void AddTransform(Transform transform) { - if (transform == null) + if (transform is null) throw new ArgumentNullException(nameof(transform)); transform.Reference = this; @@ -335,11 +335,11 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm _hashAlgorithm = CryptoHelpers.CreateFromName(_digestMethod); - if (_hashAlgorithm == null) + if (_hashAlgorithm is null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); // Let's go get the target. - string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); + string baseUri = (document is null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebResponse response = null; Stream inputStream = null; @@ -359,7 +359,7 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re // Second-easiest case -- dereference the URI & pump through the TransformChain // handle the special cases where the URI is null (meaning whole doc) // or the URI is just a fragment (meaning a reference to an embedded Object) - if (_uri == null) + if (_uri is null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); @@ -371,7 +371,7 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re { // This is the self-referential case. First, check that we have a document context. // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process - if (document == null) + if (document is null) throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); // Normalize the containing document @@ -388,7 +388,7 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re if (idref == "xpointer(/)") { // This is a self referencial case - if (document == null) + if (document is null) throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); // We should not discard comments here!!! @@ -398,22 +398,22 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re } XmlElement elem = SignedXml.GetIdElement(document, idref); - if (elem != null) + if (elem is not null) _namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); - if (elem == null) + if (elem is null) { // Go throw the referenced items passed in - if (refList != null) + if (refList is not null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; - if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) + if ((tempElem is not null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; - if (_signedXml._context != null) + if (_signedXml._context is not null) _namespaces = Utils.GetPropagatedAttributes(_signedXml._context); break; } @@ -421,7 +421,7 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re } } - if (elem == null) + if (elem is null) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); @@ -461,11 +461,11 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re } finally { - if (hashInputStream != null) + if (hashInputStream is not null) hashInputStream.Close(); - if (response != null) + if (response is not null) response.Close(); - if (inputStream != null) + if (inputStream is not null) inputStream.Close(); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs index 263c789ae27551..bac2932a374f2d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs @@ -26,7 +26,7 @@ public int Count public int Add(object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is DataReference) && !(value is KeyReference)) @@ -52,7 +52,7 @@ public int IndexOf(object value) public void Insert(int index, object value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is DataReference) && !(value is KeyReference)) @@ -95,7 +95,7 @@ object IList.this[int index] get { return _references[index]; } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (!(value is DataReference) && !(value is KeyReference)) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs index f60c078778ccf3..8734b57c5a0b2c 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs @@ -49,7 +49,7 @@ public SignedInfo SignedInfo set { _signedInfo = value; - if (SignedXml != null && _signedInfo != null) + if (SignedXml is not null && _signedInfo is not null) _signedInfo.SignedXml = SignedXml; } } @@ -64,7 +64,7 @@ public KeyInfo KeyInfo { get { - if (_keyInfo == null) + if (_keyInfo is null) _keyInfo = new KeyInfo(); return _keyInfo; } @@ -101,13 +101,13 @@ internal XmlElement GetXml(XmlDocument document) signatureElement.SetAttribute("Id", _id); // Add the SignedInfo - if (_signedInfo == null) + if (_signedInfo is null) throw new CryptographicException(SR.Cryptography_Xml_SignedInfoRequired); signatureElement.AppendChild(_signedInfo.GetXml(document)); // Add the SignatureValue - if (_signatureValue == null) + if (_signatureValue is null) throw new CryptographicException(SR.Cryptography_Xml_SignatureValueRequired); XmlElement signatureValueElement = document.CreateElement("SignatureValue", SignedXml.XmlDsigNamespaceUrl); @@ -124,7 +124,7 @@ internal XmlElement GetXml(XmlDocument document) foreach (object obj in _embeddedObjects) { DataObject dataObj = obj as DataObject; - if (dataObj != null) + if (dataObj is not null) { signatureElement.AppendChild(dataObj.GetXml(document)); } @@ -136,7 +136,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { // Make sure we don't get passed null - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // Signature @@ -155,7 +155,7 @@ public void LoadXml(XmlElement value) // SignedInfo XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm); - if (signedInfoNodes == null || signedInfoNodes.Count == 0 || signedInfoNodes.Count > 1) + if (signedInfoNodes is null || signedInfoNodes.Count == 0 || signedInfoNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement; expectedChildNodes += signedInfoNodes.Count; @@ -165,7 +165,7 @@ public void LoadXml(XmlElement value) // SignatureValue XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm); - if (signatureValueNodes == null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1) + if (signatureValueNodes is null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement; expectedChildNodes += signatureValueNodes.Count; @@ -177,7 +177,7 @@ public void LoadXml(XmlElement value) // KeyInfo - optional single element XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); _keyInfo = new KeyInfo(); - if (keyInfoNodes != null) + if (keyInfoNodes is not null) { if (keyInfoNodes.Count > 1) { @@ -186,7 +186,7 @@ public void LoadXml(XmlElement value) foreach (XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; - if (keyInfoElement != null) + if (keyInfoElement is not null) _keyInfo.LoadXml(keyInfoElement); } expectedChildNodes += keyInfoNodes.Count; @@ -195,12 +195,12 @@ public void LoadXml(XmlElement value) // Object - zero or more elements allowed XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); _embeddedObjects.Clear(); - if (objectNodes != null) + if (objectNodes is not null) { foreach (XmlNode node in objectNodes) { XmlElement objectElement = node as XmlElement; - if (objectElement != null) + if (objectElement is not null) { DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); @@ -212,7 +212,7 @@ public void LoadXml(XmlElement value) // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); - if (nodeList != null) + if (nodeList is not null) { foreach (XmlNode node in nodeList) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs index fa61cdc33f864e..06ed89785b759e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs @@ -77,7 +77,7 @@ public string CanonicalizationMethod get { // Default the canonicalization method to C14N - if (_canonicalizationMethod == null) + if (_canonicalizationMethod is null) return SignedXml.XmlDsigC14NTransformUrl; return _canonicalizationMethod; } @@ -92,10 +92,10 @@ public Transform CanonicalizationMethodObject { get { - if (_canonicalizationMethodTransform == null) + if (_canonicalizationMethodTransform is null) { _canonicalizationMethodTransform = CryptoHelpers.CreateFromName(CanonicalizationMethod); - if (_canonicalizationMethodTransform == null) + if (_canonicalizationMethodTransform is null) throw new CryptographicException(SR.Format(SR.Cryptography_Xml_CreateTransformFailed, CanonicalizationMethod)); _canonicalizationMethodTransform.SignedXml = SignedXml; _canonicalizationMethodTransform.Reference = null; @@ -133,7 +133,7 @@ internal bool CacheValid { get { - if (_cachedXml == null) return false; + if (_cachedXml is null) return false; // now check all the references foreach (Reference reference in References) { @@ -174,7 +174,7 @@ internal XmlElement GetXml(XmlDocument document) XmlElement signatureMethodElement = document.CreateElement("SignatureMethod", SignedXml.XmlDsigNamespaceUrl); signatureMethodElement.SetAttribute("Algorithm", _signatureMethod); // Add HMACOutputLength tag if we have one - if (_signatureLength != null) + if (_signatureLength is not null) { XmlElement hmacLengthElement = document.CreateElement(null, "HMACOutputLength", SignedXml.XmlDsigNamespaceUrl); XmlText outputLength = document.CreateTextNode(_signatureLength); @@ -199,7 +199,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); // SignedInfo @@ -218,12 +218,12 @@ public void LoadXml(XmlElement value) // CanonicalizationMethod -- must be present XmlNodeList canonicalizationMethodNodes = signedInfoElement.SelectNodes("ds:CanonicalizationMethod", nsm); - if (canonicalizationMethodNodes == null || canonicalizationMethodNodes.Count == 0 || canonicalizationMethodNodes.Count > 1) + if (canonicalizationMethodNodes is null || canonicalizationMethodNodes.Count == 0 || canonicalizationMethodNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/CanonicalizationMethod"); XmlElement canonicalizationMethodElement = canonicalizationMethodNodes.Item(0) as XmlElement; expectedChildNodes += canonicalizationMethodNodes.Count; _canonicalizationMethod = Utils.GetAttribute(canonicalizationMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); - if (_canonicalizationMethod == null || !Utils.VerifyAttributes(canonicalizationMethodElement, "Algorithm")) + if (_canonicalizationMethod is null || !Utils.VerifyAttributes(canonicalizationMethodElement, "Algorithm")) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/CanonicalizationMethod"); _canonicalizationMethodTransform = null; if (canonicalizationMethodElement.ChildNodes.Count > 0) @@ -231,17 +231,17 @@ public void LoadXml(XmlElement value) // SignatureMethod -- must be present XmlNodeList signatureMethodNodes = signedInfoElement.SelectNodes("ds:SignatureMethod", nsm); - if (signatureMethodNodes == null || signatureMethodNodes.Count == 0 || signatureMethodNodes.Count > 1) + if (signatureMethodNodes is null || signatureMethodNodes.Count == 0 || signatureMethodNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/SignatureMethod"); XmlElement signatureMethodElement = signatureMethodNodes.Item(0) as XmlElement; expectedChildNodes += signatureMethodNodes.Count; _signatureMethod = Utils.GetAttribute(signatureMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); - if (_signatureMethod == null || !Utils.VerifyAttributes(signatureMethodElement, "Algorithm")) + if (_signatureMethod is null || !Utils.VerifyAttributes(signatureMethodElement, "Algorithm")) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/SignatureMethod"); // Now get the output length if we are using a MAC algorithm XmlElement signatureLengthElement = signatureMethodElement.SelectSingleNode("ds:HMACOutputLength", nsm) as XmlElement; - if (signatureLengthElement != null) + if (signatureLengthElement is not null) _signatureLength = signatureLengthElement.InnerXml; // flush out any reference that was there @@ -249,7 +249,7 @@ public void LoadXml(XmlElement value) // Reference - 0 or more XmlNodeList referenceNodes = signedInfoElement.SelectNodes("ds:Reference", nsm); - if (referenceNodes != null) + if (referenceNodes is not null) { if (referenceNodes.Count > Utils.MaxReferencesPerSignedInfo) { @@ -276,7 +276,7 @@ public void LoadXml(XmlElement value) public void AddReference(Reference reference) { - if (reference == null) + if (reference is null) throw new ArgumentNullException(nameof(reference)); reference.SignedXml = SignedXml; 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 51950077749823..1060fce347a41a 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 @@ -92,21 +92,21 @@ public SignedXml() public SignedXml(XmlDocument document) { - if (document == null) + if (document is null) throw new ArgumentNullException(nameof(document)); Initialize(document.DocumentElement); } public SignedXml(XmlElement elem) { - if (elem == null) + if (elem is null) throw new ArgumentNullException(nameof(elem)); Initialize(elem); } private void Initialize(XmlElement element) { - _containingDocument = (element == null ? null : element.OwnerDocument); + _containingDocument = (element is null ? null : element.OwnerDocument); _context = element; m_signature = new Signature(); m_signature.SignedXml = this; @@ -164,7 +164,7 @@ public EncryptedXml EncryptedXml { get { - if (_exml == null) + if (_exml is null) _exml = new EncryptedXml(_containingDocument); // default processing rules return _exml; } @@ -205,7 +205,7 @@ public KeyInfo KeyInfo public XmlElement GetXml() { // If we have a document context, then return a signature element in this context - if (_containingDocument != null) + if (_containingDocument is not null) return m_signature.GetXml(_containingDocument); else return m_signature.GetXml(); @@ -213,12 +213,12 @@ public XmlElement GetXml() public void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); m_signature.LoadXml(value); - if (_context == null) + if (_context is null) { _context = value; } @@ -262,12 +262,12 @@ public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) do { key = GetPublicKey(); - if (key != null) + if (key is not null) { bRet = CheckSignature(key); SignedXmlDebugLog.LogVerificationResult(this, key, bRet); } - } while (key != null && bRet == false); + } while (key is not null && bRet == false); signingKey = key; return bRet; @@ -379,11 +379,11 @@ public void ComputeSignature() // Load the key AsymmetricAlgorithm key = SigningKey; - if (key == null) + if (key is null) throw new CryptographicException(SR.Cryptography_Xml_LoadKeyFailed); // Check the signature algorithm associated with the key so that we can accordingly set the signature method - if (SignedInfo.SignatureMethod == null) + if (SignedInfo.SignatureMethod is null) { if (key is DSA) { @@ -392,7 +392,7 @@ public void ComputeSignature() else if (key is RSA) { // Default to RSA-SHA256 - if (SignedInfo.SignatureMethod == null) + if (SignedInfo.SignatureMethod is null) SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; } else @@ -403,10 +403,10 @@ public void ComputeSignature() // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignedInfo.SignatureMethod); - if (signatureDescription == null) + if (signatureDescription is null) throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); HashAlgorithm hashAlg = signatureDescription.CreateDigest(); - if (hashAlg == null) + if (hashAlg is null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); // Updates the HashAlgorithm's state for signing with the signature formatter below. @@ -421,15 +421,15 @@ public void ComputeSignature() public void ComputeSignature(KeyedHashAlgorithm macAlg) { - if (macAlg == null) + if (macAlg is null) throw new ArgumentNullException(nameof(macAlg)); HMAC hash = macAlg as HMAC; - if (hash == null) + if (hash is null) throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); int signatureLength; - if (m_signature.SignedInfo.SignatureLength == null) + if (m_signature.SignedInfo.SignatureLength is null) signatureLength = hash.HashSize; else signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); @@ -463,39 +463,39 @@ public void ComputeSignature(KeyedHashAlgorithm macAlg) protected virtual AsymmetricAlgorithm GetPublicKey() { - if (KeyInfo == null) + if (KeyInfo is null) throw new CryptographicException(SR.Cryptography_Xml_KeyInfoRequired); - if (_x509Enum != null) + if (_x509Enum is not null) { AsymmetricAlgorithm key = GetNextCertificatePublicKey(); - if (key != null) + if (key is not null) return key; } - if (_keyInfoEnum == null) + if (_keyInfoEnum is null) _keyInfoEnum = KeyInfo.GetEnumerator(); // In our implementation, we move to the next KeyInfo clause which is an RSAKeyValue, DSAKeyValue or KeyInfoX509Data while (_keyInfoEnum.MoveNext()) { RSAKeyValue rsaKeyValue = _keyInfoEnum.Current as RSAKeyValue; - if (rsaKeyValue != null) + if (rsaKeyValue is not null) return rsaKeyValue.Key; DSAKeyValue dsaKeyValue = _keyInfoEnum.Current as DSAKeyValue; - if (dsaKeyValue != null) + if (dsaKeyValue is not null) return dsaKeyValue.Key; KeyInfoX509Data x509Data = _keyInfoEnum.Current as KeyInfoX509Data; - if (x509Data != null) + if (x509Data is not null) { _x509Collection = Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification); if (_x509Collection.Count > 0) { _x509Enum = _x509Collection.GetEnumerator(); AsymmetricAlgorithm key = GetNextCertificatePublicKey(); - if (key != null) + if (key is not null) return key; } } @@ -507,12 +507,12 @@ protected virtual AsymmetricAlgorithm GetPublicKey() private X509Certificate2Collection BuildBagOfCerts() { X509Certificate2Collection collection = new X509Certificate2Collection(); - if (KeyInfo != null) + if (KeyInfo is not null) { foreach (KeyInfoClause clause in KeyInfo) { KeyInfoX509Data x509Data = clause as KeyInfoX509Data; - if (x509Data != null) + if (x509Data is not null) collection.AddRange(Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification)); } } @@ -525,7 +525,7 @@ private AsymmetricAlgorithm GetNextCertificatePublicKey() while (_x509Enum.MoveNext()) { X509Certificate2 certificate = (X509Certificate2)_x509Enum.Current; - if (certificate != null) + if (certificate is not null) return Utils.GetAnyPublicKey(certificate); } @@ -539,7 +539,7 @@ public virtual XmlElement GetIdElement(XmlDocument document, string idValue) internal static XmlElement DefaultGetIdElement(XmlDocument document, string idValue) { - if (document == null) + if (document is null) return null; try @@ -558,7 +558,7 @@ internal static XmlElement DefaultGetIdElement(XmlDocument document, string idVa // Get the element with idValue XmlElement elem = document.GetElementById(idValue); - if (elem != null) + if (elem is not null) { // Have to check for duplicate ID values from the DTD. @@ -568,16 +568,16 @@ internal static XmlElement DefaultGetIdElement(XmlDocument document, string idVa // If it's null here we want to know about it, because it means that // GetElementById failed to work across the cloning, and our uniqueness // test is invalid. - System.Diagnostics.Debug.Assert(cloneElem != null); + System.Diagnostics.Debug.Assert(cloneElem is not null); // Guard against null anyways - if (cloneElem != null) + if (cloneElem is not null) { cloneElem.Attributes.RemoveAll(); XmlElement cloneElem2 = docClone.GetElementById(idValue); - if (cloneElem2 != null) + if (cloneElem2 is not null) { throw new CryptographicException( SR.Cryptography_Xml_InvalidReference); @@ -588,10 +588,10 @@ internal static XmlElement DefaultGetIdElement(XmlDocument document, string idVa } elem = GetSingleReferenceTarget(document, "Id", idValue); - if (elem != null) + if (elem is not null) return elem; elem = GetSingleReferenceTarget(document, "id", idValue); - if (elem != null) + if (elem is not null) return elem; elem = GetSingleReferenceTarget(document, "ID", idValue); @@ -629,14 +629,14 @@ private static bool DefaultSignatureFormatValidator(SignedXml signedXml) private bool DoesSignatureUseTruncatedHmac() { // If we're not using the SignatureLength property, then we're not truncating the signature length - if (SignedInfo.SignatureLength == null) + if (SignedInfo.SignatureLength is null) { return false; } // See if we're signed witn an HMAC algorithm HMAC hmac = CryptoHelpers.CreateFromName(SignatureMethod); - if (hmac == null) + if (hmac is null) { // We aren't signed with an HMAC algorithm, so we cannot have a truncated HMAC return false; @@ -724,7 +724,7 @@ private static IList KnownCanonicalizationMethods { get { - if (s_knownCanonicalizationMethods == null) + if (s_knownCanonicalizationMethods is null) { // Start with the list that the machine admin added, if any List safeAlgorithms = new List(); @@ -746,7 +746,7 @@ private static IList DefaultSafeTransformMethods { get { - if (s_defaultSafeTransformMethods == null) + if (s_defaultSafeTransformMethods is null) { List safeAlgorithms = new List(); @@ -775,12 +775,12 @@ private byte[] GetC14NDigest(HashAlgorithm hash) bool isKeyedHashAlgorithm = hash is KeyedHashAlgorithm; if (isKeyedHashAlgorithm || !_bCacheValid || !SignedInfo.CacheValid) { - string baseUri = (_containingDocument == null ? null : _containingDocument.BaseURI); + string baseUri = (_containingDocument is null ? null : _containingDocument.BaseURI); XmlResolver resolver = (_bResolverSet ? _xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument doc = Utils.PreProcessElementInput(SignedInfo.GetXml(), resolver, baseUri); // Add non default namespaces in scope - CanonicalXmlNodeList namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); + CanonicalXmlNodeList namespaces = (_context is null ? null : Utils.GetPropagatedAttributes(_context)); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); Utils.AddNamespaces(doc.DocumentElement, namespaces); @@ -803,7 +803,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 (reference.Uri is null || reference.Uri.Length == 0 || (reference.Uri.Length > 0 && reference.Uri[0] != '#')) { _refLevelCache[index] = 0; return 0; @@ -892,14 +892,14 @@ private void BuildDigestedReferences() foreach (Reference reference in sortedReferences) { // If no DigestMethod has yet been set, default it to sha1 - if (reference.DigestMethod == null) + if (reference.DigestMethod is null) reference.DigestMethod = Reference.DefaultDigestMethod; SignedXmlDebugLog.LogSigningReference(this, reference); reference.UpdateHashValue(_containingDocument, nodeList); // If this reference has an Id attribute, add it - if (reference.Id != null) + if (reference.Id is not null) nodeList.Add(reference.GetXml()); } } @@ -947,8 +947,8 @@ private bool CheckDigestedReferences() [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private static bool CryptographicEquals(byte[] a, byte[] b) { - System.Diagnostics.Debug.Assert(a != null); - System.Diagnostics.Debug.Assert(b != null); + System.Diagnostics.Debug.Assert(a is not null); + System.Diagnostics.Debug.Assert(b is not null); int result = 0; @@ -978,7 +978,7 @@ private static bool CryptographicEquals(byte[] a, byte[] b) // the signature format is acceptable, false means that the format is not valid. private bool CheckSignatureFormat() { - if (_signatureFormatValidator == null) + if (_signatureFormatValidator is null) { // No format validator means that we default to accepting the signature. (This is // effectively compatibility mode with v3.5). @@ -994,13 +994,13 @@ private bool CheckSignatureFormat() private bool CheckSignedInfo(AsymmetricAlgorithm key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignatureMethod); - if (signatureDescription == null) + if (signatureDescription is null) throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); // Let's see if the key corresponds with the SignatureMethod @@ -1009,7 +1009,7 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key) return false; HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); - if (hashAlgorithm == null) + if (hashAlgorithm is null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); byte[] hashval = GetC14NDigest(hashAlgorithm); @@ -1026,13 +1026,13 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key) private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) { - if (macAlg == null) + if (macAlg is null) throw new ArgumentNullException(nameof(macAlg)); SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); int signatureLength; - if (m_signature.SignedInfo.SignatureLength == null) + if (m_signature.SignedInfo.SignatureLength is null) signatureLength = macAlg.HashSize; else signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); @@ -1042,7 +1042,7 @@ private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); if (signatureLength % 8 != 0) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); - if (m_signature.SignatureValue == null) + if (m_signature.SignatureValue is null) throw new CryptographicException(SR.Cryptography_Xml_SignatureValueRequired); if (m_signature.SignatureValue.Length != signatureLength / 8) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); @@ -1074,7 +1074,7 @@ private static XmlElement GetSingleReferenceTarget(XmlDocument document, string XmlNodeList nodeList = document.SelectNodes(xPath); - if (nodeList == null || nodeList.Count == 0) + if (nodeList is null || nodeList.Count == 0) { return null; } @@ -1107,12 +1107,12 @@ private static bool IsKeyTheCorrectAlgorithm(AsymmetricAlgorithm key, Type expec // So, in the absence of a better approach, walk up the parent hierarchy until we find the ancestor that's a direct subclass of // AsymmetricAlgorithm and treat that as the algorithm identifier. // - while (expectedType != null && expectedType.BaseType != typeof(AsymmetricAlgorithm)) + while (expectedType is not null && expectedType.BaseType != typeof(AsymmetricAlgorithm)) { expectedType = expectedType.BaseType; } - if (expectedType == null) + if (expectedType is null) return false; // SignatureDescription specified something that isn't even a subclass of AsymmetricAlgorithm. For compatibility with 4.6, return false rather throw. if (actualType.IsSubclassOf(expectedType)) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs index 509934612ebbef..fd80e9ad8b966b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs @@ -193,7 +193,7 @@ private static bool VerboseLoggingEnabled /// private static string FormatBytes(byte[] bytes) { - if (bytes == null) + if (bytes is null) return NullString; return HexConverter.ToString(bytes, HexConverter.Casing.Lower); @@ -204,7 +204,7 @@ private static string FormatBytes(byte[] bytes) /// private static string GetKeyName(object key) { - Debug.Assert(key != null, "key != null"); + Debug.Assert(key is not null, "key is not null"); ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm; X509Certificate certificate = key as X509Certificate; @@ -220,15 +220,15 @@ private static string GetKeyName(object key) // string keyName = null; - if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null) + if (cspKey is not null && cspKey.CspKeyContainerInfo.KeyContainerName is not null) { keyName = "\"" + cspKey.CspKeyContainerInfo.KeyContainerName + "\""; } - else if (certificate2 != null) + else if (certificate2 is not null) { keyName = "\"" + certificate2.GetNameInfo(X509NameType.SimpleName, false) + "\""; } - else if (certificate != null) + else if (certificate is not null) { keyName = "\"" + certificate.Subject + "\""; } @@ -245,7 +245,7 @@ private static string GetKeyName(object key) /// private static string GetObjectId(object o) { - Debug.Assert(o != null, "o != null"); + Debug.Assert(o is not null, "o is not null"); return string.Format(CultureInfo.InvariantCulture, "{0}#{1}", o.GetType().Name, @@ -257,7 +257,7 @@ private static string GetObjectId(object o) /// private static string GetOidName(Oid oid) { - Debug.Assert(oid != null, "oid != null"); + Debug.Assert(oid is not null, "oid is not null"); string friendlyName = oid.FriendlyName; if (string.IsNullOrEmpty(friendlyName)) @@ -273,8 +273,8 @@ private static string GetOidName(Oid oid) /// transform canonicalizing the input internal static void LogBeginCanonicalization(SignedXml signedXml, Transform canonicalizationTransform) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(canonicalizationTransform is not null, "canonicalizationTransform is not null"); if (InformationLoggingEnabled) { @@ -308,8 +308,8 @@ internal static void LogBeginCanonicalization(SignedXml signedXml, Transform can /// Callback delegate which is being used for format verification internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func formatValidator) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(formatValidator != null, "formatValidator != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(formatValidator is not null, "formatValidator is not null"); if (InformationLoggingEnabled) { @@ -331,14 +331,14 @@ internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, FuncSignedInfo object being verified internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(signedInfo != null, " signedInfo != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(signedInfo is not null, " signedInfo is not null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignedInfo, - signedInfo.Id != null ? signedInfo.Id : NullString); + signedInfo.Id is not null ? signedInfo.Id : NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } } @@ -350,7 +350,7 @@ internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo sig /// Context of the signature internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElement context) { - Debug.Assert(signedXml != null, "signedXml != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); if (InformationLoggingEnabled) { @@ -364,7 +364,7 @@ internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElemen { string contextData = SR.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, - context != null ? context.OuterXml : NullString); + context is not null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, @@ -380,7 +380,7 @@ internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElemen /// Context of the verification internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context) { - Debug.Assert(signedXml != null, "signedXml != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); if (InformationLoggingEnabled) { @@ -394,7 +394,7 @@ internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlEleme { string contextData = SR.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, - context != null ? context.OuterXml : NullString); + context is not null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, @@ -410,8 +410,8 @@ internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlEleme /// transform canonicalizing the input internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canonicalizationTransform) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(canonicalizationTransform is not null, "canonicalizationTransform is not null"); if (VerboseLoggingEnabled) { @@ -435,7 +435,7 @@ internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canon /// result of the signature format verification internal static void LogFormatValidationResult(SignedXml signedXml, bool result) { - Debug.Assert(signedXml != null, "signedXml != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); if (InformationLoggingEnabled) { @@ -454,8 +454,8 @@ internal static void LogFormatValidationResult(SignedXml signedXml, bool result) /// List of valid canonicalization algorithms internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable validAlgorithms) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(validAlgorithms != null, "validAlgorithms != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(validAlgorithms is not null, "validAlgorithms is not null"); if (InformationLoggingEnabled) { @@ -493,9 +493,9 @@ internal static void LogUnsafeTransformMethod( IEnumerable validC14nAlgorithms, IEnumerable validTransformAlgorithms) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(validC14nAlgorithms != null, "validC14nAlgorithms != null"); - Debug.Assert(validTransformAlgorithms != null, "validTransformAlgorithms != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(validC14nAlgorithms is not null, "validC14nAlgorithms is not null"); + Debug.Assert(validTransformAlgorithms is not null, "validTransformAlgorithms is not null"); if (InformationLoggingEnabled) { @@ -536,11 +536,11 @@ internal static void LogUnsafeTransformMethod( /// namespaces being propagated internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces) { - Debug.Assert(signedXml != null, "signedXml != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); if (InformationLoggingEnabled) { - if (namespaces != null) + if (namespaces is not null) { foreach (XmlAttribute propagatedNamespace in namespaces) { @@ -626,10 +626,10 @@ internal static void LogSigning(SignedXml signedXml, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(signatureDescription != null, "signatureDescription != null"); - Debug.Assert(hash != null, "hash != null"); - Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(signatureDescription is not null, "signatureDescription is not null"); + Debug.Assert(hash is not null, "hash is not null"); + Debug.Assert(asymmetricSignatureFormatter is not null, "asymmetricSignatureFormatter is not null"); if (InformationLoggingEnabled) { @@ -654,8 +654,8 @@ internal static void LogSigning(SignedXml signedXml, /// key the signature is created with internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(key != null, "key != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(key is not null, "key is not null"); if (InformationLoggingEnabled) { @@ -677,13 +677,13 @@ internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) /// Reference being hashed internal static void LogSigningReference(SignedXml signedXml, Reference reference) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(reference != null, "reference != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(reference is not null, "reference is not null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); - string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; + string hashAlgorithmName = hashAlgorithm is null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningReference, GetObjectId(reference), @@ -728,8 +728,8 @@ internal static void LogVerificationFailure(SignedXml signedXml, string failureL /// true if the signature verified, false otherwise internal static void LogVerificationResult(SignedXml signedXml, object key, bool verified) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(key != null, "key != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(key is not null, "key is not null"); if (InformationLoggingEnabled) { @@ -754,8 +754,8 @@ internal static void LogVerificationResult(SignedXml signedXml, object key, bool /// key usages being examined internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate certificate, X509KeyUsageExtension keyUsages) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(certificate != null, "certificate != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(certificate is not null, "certificate is not null"); if (InformationLoggingEnabled) { @@ -779,8 +779,8 @@ internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate cert /// reference being verified internal static void LogVerifyReference(SignedXml signedXml, Reference reference) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(reference != null, "reference != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(reference is not null, "reference is not null"); if (InformationLoggingEnabled) { @@ -810,15 +810,15 @@ internal static void LogVerifyReferenceHash(SignedXml signedXml, byte[] actualHash, byte[] expectedHash) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(reference != null, "reference != null"); - Debug.Assert(actualHash != null, "actualHash != null"); - Debug.Assert(expectedHash != null, "expectedHash != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(reference is not null, "reference is not null"); + Debug.Assert(actualHash is not null, "actualHash is not null"); + Debug.Assert(expectedHash is not null, "expectedHash is not null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); - string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; + string hashAlgorithmName = hashAlgorithm is null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_ReferenceHash, GetObjectId(reference), @@ -853,10 +853,10 @@ internal static void LogVerifySignedInfo(SignedXml signedXml, byte[] actualHashValue, byte[] signatureValue) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(signatureDescription != null, "signatureDescription != null"); - Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); - Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(signatureDescription is not null, "signatureDescription is not null"); + Debug.Assert(hashAlgorithm is not null, "hashAlgorithm is not null"); + Debug.Assert(asymmetricSignatureDeformatter is not null, "asymmetricSignatureDeformatter is not null"); if (InformationLoggingEnabled) { @@ -899,8 +899,8 @@ internal static void LogVerifySignedInfo(SignedXml signedXml, byte[] actualHashValue, byte[] signatureValue) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(mac != null, "mac != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(mac is not null, "mac is not null"); if (InformationLoggingEnabled) { @@ -935,9 +935,9 @@ internal static void LogVerifySignedInfo(SignedXml signedXml, /// certificate having the chain built for it internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(certificate != null, "certificate != null"); - Debug.Assert(chain != null, "chain != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(certificate is not null, "certificate is not null"); + Debug.Assert(chain is not null, "chain is not null"); if (InformationLoggingEnabled) { @@ -1026,13 +1026,13 @@ internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X5 internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, Reference reference) { - Debug.Assert(signedXml != null, "signedXml != null"); - Debug.Assert(reference != null, "reference != null"); + Debug.Assert(signedXml is not null, "signedXml is not null"); + Debug.Assert(reference is not null, "reference is not null"); if (InformationLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); - string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; + string hashAlgorithmName = hashAlgorithm is null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SignedXmlRecursionLimit, GetObjectId(reference), @@ -1055,7 +1055,7 @@ internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, /// type of event being traced private static void WriteLine(object source, TraceEventType eventType, SignedXmlDebugEvent eventId, string data) { - Debug.Assert(source != null, "source != null"); + Debug.Assert(source is not null, "source is not null"); Debug.Assert(!string.IsNullOrEmpty(data), "!string.IsNullOrEmpty(data)"); Debug.Assert(InformationLoggingEnabled, "InformationLoggingEnabled"); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs index 45a05d6d062b4f..235501fba7157a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs @@ -96,7 +96,7 @@ public abstract Type[] OutputTypes internal bool AcceptsType(Type inputType) { - if (InputTypes != null) + if (InputTypes is not null) { for (int i = 0; i < InputTypes.Length; i++) { @@ -129,7 +129,7 @@ internal XmlElement GetXml(XmlDocument document, string name) if (!string.IsNullOrEmpty(Algorithm)) transformElement.SetAttribute("Algorithm", Algorithm); XmlNodeList children = GetInnerXml(); - if (children != null) + if (children is not null) { foreach (XmlNode node in children) { @@ -158,12 +158,12 @@ public XmlElement Context { get { - if (_context != null) + if (_context is not null) return _context; Reference reference = Reference; - SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); - if (signedXml == null) + SignedXml signedXml = (reference is null ? SignedXml : reference.SignedXml); + if (signedXml is null) return null; return signedXml._context; @@ -178,14 +178,14 @@ public Hashtable PropagatedNamespaces { get { - if (_propagatedNamespaces != null) + if (_propagatedNamespaces is not null) return _propagatedNamespaces; Reference reference = Reference; - SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); + SignedXml signedXml = (reference is null ? SignedXml : reference.SignedXml); // If the reference is not a Uri reference with a DataObject target, return an empty hashtable. - if (reference != null && + if (reference is not null && ((reference.ReferenceTargetType != ReferenceTargetType.UriReference) || (string.IsNullOrEmpty(reference.Uri) || reference.Uri[0] != '#'))) { @@ -194,13 +194,13 @@ public Hashtable PropagatedNamespaces } CanonicalXmlNodeList namespaces = null; - if (reference != null) + if (reference is not null) namespaces = reference._namespaces; - else if (signedXml?._context != null) + else if (signedXml?._context is not null) namespaces = Utils.GetPropagatedAttributes(signedXml._context); // if no namespaces have been propagated, return an empty hashtable. - if (namespaces == null) + if (namespaces is null) { _propagatedNamespaces = new Hashtable(0); return _propagatedNamespaces; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs index b9bdf2401f8373..69f83c005306a0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs @@ -32,7 +32,7 @@ public TransformChain() public void Add(Transform transform) { - if (transform != null) + if (transform is not null) _transforms.Add(transform); } @@ -63,7 +63,7 @@ internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlRe object currentInput = inputObject; foreach (Transform transform in _transforms) { - if (currentInput == null || transform.AcceptsType(currentInput.GetType())) + if (currentInput is null || transform.AcceptsType(currentInput.GetType())) { //in this case, no translation necessary, pump it through transform.Resolver = resolver; @@ -165,11 +165,11 @@ internal XmlElement GetXml(XmlDocument document, string ns) XmlElement transformsElement = document.CreateElement("Transforms", ns); foreach (Transform transform in _transforms) { - if (transform != null) + if (transform is not null) { // Construct the individual transform element XmlElement transformElement = transform.GetXml(document); - if (transformElement != null) + if (transformElement is not null) transformsElement.AppendChild(transformElement); } } @@ -178,7 +178,7 @@ internal XmlElement GetXml(XmlDocument document, string ns) internal void LoadXml(XmlElement value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); @@ -194,7 +194,7 @@ internal void LoadXml(XmlElement value) XmlElement transformElement = (XmlElement)transformNodes.Item(i); string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); Transform transform = CryptoHelpers.CreateFromName(algorithm); - if (transform == null) + if (transform is null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); // let the transform read the children of the transformElement for data transform.LoadInnerXml(transformElement.ChildNodes); 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 123afc5d210567..ee14dd50b9aa0e 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 @@ -35,7 +35,7 @@ private static bool HasNamespace(XmlElement element, string prefix, string value // A helper function that determines if a namespace node is a committed attribute internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value) { - if (element == null) + if (element is null) throw new ArgumentNullException(nameof(element)); string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns"); @@ -45,14 +45,14 @@ internal static bool IsCommittedNamespace(XmlElement element, string prefix, str internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value) { - if (element == null) + if (element is null) throw new ArgumentNullException(nameof(element)); XmlNode ancestorNode = ((XmlNode)element).ParentNode; - while (ancestorNode != null) + while (ancestorNode is not null) { XmlElement ancestorElement = ancestorNode as XmlElement; - if (ancestorElement != null) + if (ancestorElement is not null) if (HasNamespace(ancestorElement, prefix, value)) return true; ancestorNode = ancestorNode.ParentNode; } @@ -63,7 +63,7 @@ internal static bool IsRedundantNamespace(XmlElement element, string prefix, str internal static string GetAttribute(XmlElement element, string localName, string namespaceURI) { string s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null); - if (s == null && element.HasAttribute(localName, namespaceURI)) + if (s is null && element.HasAttribute(localName, namespaceURI)) s = element.GetAttribute(localName, namespaceURI); return s; } @@ -75,7 +75,7 @@ internal static bool HasAttribute(XmlElement element, string localName, string n internal static bool VerifyAttributes(XmlElement element, string expectedAttrName) { - return VerifyAttributes(element, expectedAttrName == null ? null : new string[] { expectedAttrName }); + return VerifyAttributes(element, expectedAttrName is null ? null : new string[] { expectedAttrName }); } internal static bool VerifyAttributes(XmlElement element, string[] expectedAttrNames) @@ -85,7 +85,7 @@ internal static bool VerifyAttributes(XmlElement element, string[] expectedAttrN // There are a few Xml Special Attributes that are always allowed on any node. Make sure we allow those here. bool attrIsAllowed = attr.Name == "xmlns" || attr.Name.StartsWith("xmlns:") || attr.Name == "xml:space" || attr.Name == "xml:lang" || attr.Name == "xml:base"; int expectedInd = 0; - while (!attrIsAllowed && expectedAttrNames != null && expectedInd < expectedAttrNames.Length) + while (!attrIsAllowed && expectedAttrNames is not null && expectedInd < expectedAttrNames.Length) { attrIsAllowed = attr.Name == expectedAttrNames[expectedInd]; expectedInd++; @@ -132,7 +132,7 @@ internal static bool HasNamespacePrefix(XmlAttribute a, string nsPrefix) internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute nearestAncestorWithSamePrefix) { - if (nearestAncestorWithSamePrefix == null) + if (nearestAncestorWithSamePrefix is null) return !IsEmptyDefaultNamespaceNode(a); else return !nearestAncestorWithSamePrefix.Value.Equals(a.Value); @@ -200,7 +200,7 @@ internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlReso internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri) { - if (document == null) + if (document is null) throw new ArgumentNullException(nameof(document)); MyXmlDocument doc = new MyXmlDocument(); @@ -222,7 +222,7 @@ internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlRes internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri) { - if (elem == null) + if (elem is null) throw new ArgumentNullException(nameof(elem)); MyXmlDocument doc = new MyXmlDocument(); @@ -244,7 +244,7 @@ internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver internal static XmlDocument DiscardComments(XmlDocument document) { XmlNodeList nodeList = document.SelectNodes("//comment()"); - if (nodeList != null) + if (nodeList is not null) { foreach (XmlNode node1 in nodeList) { @@ -269,7 +269,7 @@ internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComment XmlNode rootNode = (XmlNode)elementList[index]; // Add the children nodes XmlNodeList childNodes = rootNode.ChildNodes; - if (childNodes != null) + if (childNodes is not null) { foreach (XmlNode node1 in childNodes) { @@ -281,7 +281,7 @@ internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComment } // Add the attribute nodes XmlAttributeCollection attribNodes = rootNode.Attributes; - if (attribNodes != null) + if (attribNodes is not null) { foreach (XmlNode attribNode in rootNode.Attributes) { @@ -363,7 +363,7 @@ internal static void RemoveAllChildren(XmlElement inputElement) XmlNode child = inputElement.FirstChild; XmlNode sibling = null; - while (child != null) + while (child is not null) { sibling = child.NextSibling; inputElement.RemoveChild(child); @@ -379,7 +379,7 @@ internal static long Pump(Stream input, Stream output) { // Use MemoryStream's WriteTo(Stream) method if possible MemoryStream inputMS = input as MemoryStream; - if (inputMS != null && inputMS.Position == 0) + if (inputMS is not null && inputMS.Position == 0) { inputMS.WriteTo(output); return inputMS.Length; @@ -402,7 +402,7 @@ internal static long Pump(Stream input, Stream output) internal static Hashtable TokenizePrefixListString(string s) { Hashtable set = new Hashtable(); - if (s != null) + if (s is not null) { string[] prefixes = s.Split(null); foreach (string prefix in prefixes) @@ -461,7 +461,7 @@ internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList) { foreach (XmlNode node in nodeList) { - if (node.OwnerDocument != null) + if (node.OwnerDocument is not null) return node.OwnerDocument; } return null; @@ -469,7 +469,7 @@ internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList) internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) { - if (namespaces != null) + if (namespaces is not null) { foreach (XmlNode attrib in namespaces) { @@ -485,7 +485,7 @@ internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespa internal static void AddNamespaces(XmlElement elem, Hashtable namespaces) { - if (namespaces != null) + if (namespaces is not null) { foreach (string key in namespaces.Keys) { @@ -500,17 +500,17 @@ internal static void AddNamespaces(XmlElement elem, Hashtable namespaces) // This method gets the attributes that should be propagated internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { - if (elem == null) + if (elem is null) return null; CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); XmlNode ancestorNode = elem; bool bDefNamespaceToAdd = true; - while (ancestorNode != null) + while (ancestorNode is not null) { XmlElement ancestorElement = ancestorNode as XmlElement; - if (ancestorElement == null) + if (ancestorElement is null) { ancestorNode = ancestorNode.ParentNode; continue; @@ -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 (issuerName is null || issuerName.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(issuerName)); - if (serialNumber == null || serialNumber.Length == 0) + if (serialNumber is null || serialNumber.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(serialNumber)); return new X509IssuerSerial() @@ -637,7 +637,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn { X509Certificate2Collection collection = new X509Certificate2Collection(); ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null); - if (keyInfoX509Data.Certificates != null) + if (keyInfoX509Data.Certificates is not null) { foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) { @@ -653,8 +653,8 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn } } - if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null && - keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null) + if (keyInfoX509Data.SubjectNames is null && keyInfoX509Data.IssuerSerials is null && + keyInfoX509Data.SubjectKeyIds is null && decryptionIssuerSerials is null) return collection; // Open LocalMachine and CurrentUser "Other People"/"My" stores. @@ -666,7 +666,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn for (int index = 0; index < stores.Length; index++) { - if (stores[index] != null) + if (stores[index] is not null) { X509Certificate2Collection filters = null; // We don't care if we can't open the store. @@ -675,14 +675,14 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); filters = stores[index].Certificates; stores[index].Close(); - if (keyInfoX509Data.SubjectNames != null) + if (keyInfoX509Data.SubjectNames is not null) { foreach (string subjectName in keyInfoX509Data.SubjectNames) { filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false); } } - if (keyInfoX509Data.IssuerSerials != null) + if (keyInfoX509Data.IssuerSerials is not null) { foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials) { @@ -690,7 +690,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } - if (keyInfoX509Data.SubjectKeyIds != null) + if (keyInfoX509Data.SubjectKeyIds is not null) { foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds) { @@ -698,7 +698,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false); } } - if (decryptionIssuerSerials != null) + if (decryptionIssuerSerials is not null) { foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials) { @@ -712,7 +712,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn // Opening LocalMachine stores (other than Root or CertificateAuthority) on Linux catch (PlatformNotSupportedException) { } - if (filters != null) + if (filters is not null) collection.AddRange(filters); } } 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 9c7f1ff3682cbb..c5456fa4a16084 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 @@ -30,7 +30,7 @@ private ArrayList ExceptUris { get { - if (_arrayListUri == null) + if (_arrayListUri is null) _arrayListUri = new ArrayList(); return _arrayListUri; } @@ -38,7 +38,7 @@ private ArrayList ExceptUris protected virtual bool IsTargetElement(XmlElement inputElement, string idValue) { - if (inputElement == null) + if (inputElement is null) return false; if (inputElement.GetAttribute("Id") == idValue || inputElement.GetAttribute("id") == idValue || inputElement.GetAttribute("ID") == idValue) @@ -51,12 +51,12 @@ public EncryptedXml EncryptedXml { get { - if (_exml != null) + if (_exml is not null) return _exml; Reference reference = Reference; - SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); - if (signedXml == null || signedXml.EncryptedXml == null) + SignedXml signedXml = (reference is null ? SignedXml : reference.SignedXml); + if (signedXml is null || signedXml.EncryptedXml is null) _exml = new EncryptedXml(_containingDocument); // default processing rules else _exml = signedXml.EncryptedXml; @@ -78,26 +78,26 @@ public override Type[] OutputTypes public void AddExceptUri(string uri) { - if (uri == null) + if (uri is null) throw new ArgumentNullException(nameof(uri)); ExceptUris.Add(uri); } public override void LoadInnerXml(XmlNodeList nodeList) { - if (nodeList == null) + if (nodeList is null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); ExceptUris.Clear(); foreach (XmlNode node in nodeList) { XmlElement elem = node as XmlElement; - if (elem != null) + if (elem is not null) { if (elem.LocalName == "Except" && elem.NamespaceURI == XmlDecryptionTransformNamespaceUrl) { // the Uri is required string uri = Utils.GetAttribute(elem, "URI", XmlDecryptionTransformNamespaceUrl); - if (uri == null || uri.Length == 0 || uri[0] != '#') + if (uri is null || uri.Length == 0 || uri[0] != '#') throw new CryptographicException(SR.Cryptography_Xml_UriRequired); if (!Utils.VerifyAttributes(elem, "URI")) { @@ -159,7 +159,7 @@ private void LoadStreamInput(Stream stream) private void LoadXmlDocumentInput(XmlDocument document) { - if (document == null) + if (document is null) throw new ArgumentNullException(nameof(document)); _containingDocument = document; _nsm = new XmlNamespaceManager(document.NameTable); @@ -203,7 +203,7 @@ private bool ProcessEncryptedDataItem(XmlElement encryptedDataElement) EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); SymmetricAlgorithm symAlg = EncryptedXml.GetDecryptionKey(ed, null); - if (symAlg == null) + if (symAlg is null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); byte[] decrypted = EncryptedXml.DecryptData(ed, symAlg); @@ -213,7 +213,7 @@ private bool ProcessEncryptedDataItem(XmlElement encryptedDataElement) private void ProcessElementRecursively(XmlNodeList encryptedDatas) { - if (encryptedDatas == null || encryptedDatas.Count == 0) + if (encryptedDatas is null || encryptedDatas.Count == 0) return; Queue encryptedDatasQueue = new Queue(); foreach (XmlNode value in encryptedDatas) @@ -221,10 +221,10 @@ private void ProcessElementRecursively(XmlNodeList encryptedDatas) encryptedDatasQueue.Enqueue(value); } XmlNode node = encryptedDatasQueue.Dequeue() as XmlNode; - while (node != null) + while (node is not null) { XmlElement encryptedDataElement = node as XmlElement; - if (encryptedDataElement != null && encryptedDataElement.LocalName == "EncryptedData" && + if (encryptedDataElement is not null && encryptedDataElement.LocalName == "EncryptedData" && encryptedDataElement.NamespaceURI == EncryptedXml.XmlEncNamespaceUrl) { XmlNode sibling = encryptedDataElement.NextSibling; @@ -233,9 +233,9 @@ private void ProcessElementRecursively(XmlNodeList encryptedDatas) { // find the new decrypted element. XmlNode child = parent.FirstChild; - while (child != null && child.NextSibling != sibling) + while (child is not null && child.NextSibling != sibling) child = child.NextSibling; - if (child != null) + if (child is not null) { XmlNodeList nodes = child.SelectNodes("//enc:EncryptedData", _nsm); if (nodes.Count > 0) @@ -257,7 +257,7 @@ private void ProcessElementRecursively(XmlNodeList encryptedDatas) public override object GetOutput() { // decrypt the encrypted sections - if (_encryptedDataList != null) + if (_encryptedDataList is not null) ProcessElementRecursively(_encryptedDataList); // propagate namespaces Utils.AddNamespaces(_containingDocument.DocumentElement, PropagatedNamespaces); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs index 812d84800cdf0d..e3ad927af5bd63 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs @@ -59,7 +59,7 @@ public override void LoadInput(object obj) private void LoadStreamInput(Stream inputStream) { - if (inputStream == null) throw new ArgumentException("obj"); + if (inputStream is null) throw new ArgumentException("obj"); MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[1024]; int bytesRead; @@ -94,7 +94,7 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) foreach (XmlNode node in nodeList) { XmlNode result = node.SelectSingleNode("self::text()"); - if (result != null) + if (result is not null) sb.Append(result.OuterXml); } UTF8Encoding utf8 = new UTF8Encoding(false); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs index b27276b370cf97..6487fdc44073b6 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs @@ -36,7 +36,7 @@ public override Type[] OutputTypes public override void LoadInnerXml(XmlNodeList nodeList) { - if (nodeList != null && nodeList.Count > 0) + if (nodeList is not null && nodeList.Count > 0) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs index d4be6ffa73f0f6..9d395b82108548 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs @@ -46,7 +46,7 @@ public override Type[] OutputTypes // An enveloped signature has no inner XML elements public override void LoadInnerXml(XmlNodeList nodeList) { - if (nodeList != null && nodeList.Count > 0) + if (nodeList is not null && nodeList.Count > 0) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } @@ -83,7 +83,7 @@ private void LoadStreamInput(Stream stream) XmlReader xmlReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI); doc.Load(xmlReader); _containingDocument = doc; - if (_containingDocument == null) + if (_containingDocument is null) throw new CryptographicException(SR.Cryptography_Xml_EnvelopedSignatureRequiresContext); _nsm = new XmlNamespaceManager(_containingDocument.NameTable); _nsm.AddNamespace("dsig", SignedXml.XmlDsigNamespaceUrl); @@ -92,10 +92,10 @@ private void LoadStreamInput(Stream stream) private void LoadXmlNodeListInput(XmlNodeList nodeList) { // Empty node list is not acceptable - if (nodeList == null) + if (nodeList is null) throw new ArgumentNullException(nameof(nodeList)); _containingDocument = Utils.GetOwnerDocument(nodeList); - if (_containingDocument == null) + if (_containingDocument is null) throw new CryptographicException(SR.Cryptography_Xml_EnvelopedSignatureRequiresContext); _nsm = new XmlNamespaceManager(_containingDocument.NameTable); @@ -105,7 +105,7 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) private void LoadXmlDocumentInput(XmlDocument doc) { - if (doc == null) + if (doc is null) throw new ArgumentNullException(nameof(doc)); _containingDocument = doc; _nsm = new XmlNamespaceManager(_containingDocument.NameTable); @@ -114,21 +114,21 @@ private void LoadXmlDocumentInput(XmlDocument doc) public override object GetOutput() { - if (_containingDocument == null) + if (_containingDocument is null) throw new CryptographicException(SR.Cryptography_Xml_EnvelopedSignatureRequiresContext); // If we have received an XmlNodeList as input - if (_inputNodeList != null) + if (_inputNodeList is not null) { // If the position has not been set, then we don't want to remove any signature tags if (_signaturePosition == 0) return _inputNodeList; XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); - if (signatureList == null) return _inputNodeList; + if (signatureList is null) return _inputNodeList; CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); foreach (XmlNode node in _inputNodeList) { - if (node == null) continue; + if (node is null) continue; // keep namespaces if (Utils.IsXmlNamespaceNode(node) || Utils.IsNamespaceNode(node)) { @@ -147,7 +147,7 @@ public override object GetOutput() position++; if (node1 == result) break; } - if (result == null || position != _signaturePosition) + if (result is null || position != _signaturePosition) { resultNodeList.Add(node); } @@ -161,7 +161,7 @@ public override object GetOutput() else { XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); - if (signatureList == null) return _containingDocument; + if (signatureList is null) return _containingDocument; if (signatureList.Count < _signaturePosition || _signaturePosition <= 0) return _containingDocument; // Remove the signature node with all its children nodes @@ -174,7 +174,7 @@ public override object GetOutput(Type type) { if (type == typeof(XmlNodeList) || type.IsSubclassOf(typeof(XmlNodeList))) { - if (_inputNodeList == null) + if (_inputNodeList is null) { _inputNodeList = Utils.AllDescendantNodes(_containingDocument, true); } @@ -182,7 +182,7 @@ public override object GetOutput(Type type) } else if (type == typeof(XmlDocument) || type.IsSubclassOf(typeof(XmlDocument))) { - if (_inputNodeList != null) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); + if (_inputNodeList is not null) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); return (XmlDocument)GetOutput(); } else diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs index dba65b391cecb8..deeef8b6c6ad78 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs @@ -45,12 +45,12 @@ public override Type[] OutputTypes public override void LoadInnerXml(XmlNodeList nodeList) { - if (nodeList != null) + if (nodeList is not null) { foreach (XmlNode n in nodeList) { XmlElement e = n as XmlElement; - if (e != null) + if (e is not null) { if (e.LocalName.Equals("InclusiveNamespaces") && e.NamespaceURI.Equals(SignedXml.XmlDsigExcC14NTransformUrl) && @@ -93,7 +93,7 @@ public override void LoadInput(object obj) protected override XmlNodeList GetInnerXml() { - if (InclusiveNamespacesPrefixList == null) + if (InclusiveNamespacesPrefixList is null) return null; XmlDocument document = new XmlDocument(); XmlElement element = document.CreateElement("Transform", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs index c6c0eb64601a1a..7ee49aa3156d66 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs @@ -35,7 +35,7 @@ public override Type[] OutputTypes public override void LoadInnerXml(XmlNodeList nodeList) { // XPath transform is specified by text child of first XPath child - if (nodeList == null) + if (nodeList is null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); foreach (XmlNode node in nodeList) @@ -43,7 +43,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) string prefix = null; string namespaceURI = null; XmlElement elem = node as XmlElement; - if (elem != null) + if (elem is not null) { if (elem.LocalName == "XPath") { @@ -62,7 +62,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) { prefix = attrib.LocalName; namespaceURI = attrib.Value; - if (prefix == null) + if (prefix is null) { prefix = elem.Prefix; namespaceURI = elem.NamespaceURI; @@ -79,7 +79,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) } } - if (_xpathexpr == null) + if (_xpathexpr is null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } @@ -88,7 +88,7 @@ protected override XmlNodeList GetInnerXml() XmlDocument document = new XmlDocument(); XmlElement element = document.CreateElement(null, "XPath", SignedXml.XmlDsigNamespaceUrl); - if (_nsm != null) + if (_nsm is not null) { // Add each of the namespaces as attributes of the element foreach (string prefix in _nsm) @@ -103,7 +103,7 @@ protected override XmlNodeList GetInnerXml() // Other namespaces default: // Ignore the default namespace - if (prefix != null && prefix.Length > 0) + if (prefix is not null && prefix.Length > 0) element.SetAttribute("xmlns:" + prefix, _nsm.LookupNamespace(prefix)); break; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs index 4dfc3bc1a63b95..9399fe23913870 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs @@ -46,7 +46,7 @@ public override Type[] OutputTypes public override void LoadInnerXml(XmlNodeList nodeList) { - if (nodeList == null) + if (nodeList is null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); // check that the XSLT element is well formed XmlElement firstDataElement = null; @@ -66,7 +66,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) // Only allow whitespace count++; } - if (count != 1 || firstDataElement == null) + if (count != 1 || firstDataElement is null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); _xslNodes = nodeList; _xslFragment = firstDataElement.OuterXml.Trim(null); @@ -79,7 +79,7 @@ protected override XmlNodeList GetInnerXml() public override void LoadInput(object obj) { - if (_inputStream != null) + if (_inputStream is not null) _inputStream.Close(); _inputStream = new MemoryStream(); if (obj is Stream) @@ -90,7 +90,7 @@ public override void LoadInput(object obj) { CanonicalXml xmlDoc = new CanonicalXml((XmlNodeList)obj, null, _includeComments); byte[] buffer = xmlDoc.GetBytes(); - if (buffer == null) return; + if (buffer is null) return; _inputStream.Write(buffer, 0, buffer.Length); _inputStream.Flush(); _inputStream.Position = 0; @@ -99,7 +99,7 @@ public override void LoadInput(object obj) { CanonicalXml xmlDoc = new CanonicalXml((XmlDocument)obj, null, _includeComments); byte[] buffer = xmlDoc.GetBytes(); - if (buffer == null) return; + if (buffer is null) return; _inputStream.Write(buffer, 0, buffer.Length); _inputStream.Flush(); _inputStream.Position = 0; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs index 3edd81816ae3f1..6cdf0dc8b7cf1b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs @@ -51,9 +51,9 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto encryptionMethod = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/enc:EncryptionMethod", _namespaceManager) as XmlElement; keyInfo = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/dsig:KeyInfo", _namespaceManager) as XmlElement; cipherData = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/enc:CipherData", _namespaceManager) as XmlElement; - if ((encryptionMethod != null) && - (keyInfo != null) && - (cipherData != null)) + if ((encryptionMethod is not null) && + (keyInfo is not null) && + (cipherData is not null)) { encryptionMethodObj = new EncryptionMethod(); keyInfoObj = new KeyInfo(); @@ -73,7 +73,7 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto decryptedContent = _relDecryptor.Decrypt(encryptionMethodObj, keyInfoObj, toDecrypt); - if ((decryptedContent == null) || (decryptedContent.Length == 0)) + if ((decryptedContent is null) || (decryptedContent.Length == 0)) throw new CryptographicException(SR.Cryptography_Xml_XrmlUnableToDecryptGrant); streamReader = new StreamReader(decryptedContent); @@ -83,13 +83,13 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto } finally { - if (toDecrypt != null) + if (toDecrypt is not null) toDecrypt.Close(); - if (decryptedContent != null) + if (decryptedContent is not null) decryptedContent.Close(); - if (streamReader != null) + if (streamReader is not null) streamReader.Close(); } @@ -126,14 +126,14 @@ public override object GetOutput(Type type) // License transform has no inner XML elements public override void LoadInnerXml(XmlNodeList nodeList) { - if (nodeList != null && nodeList.Count > 0) + if (nodeList is not null && nodeList.Count > 0) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } public override void LoadInput(object obj) { // Check if the Context property is set before this transform is invoked. - if (Context == null) + if (Context is null) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingContext); _license = new XmlDocument(); @@ -149,16 +149,16 @@ public override void LoadInput(object obj) // Get the nearest issuer node currentIssuerContext = Context.SelectSingleNode("ancestor-or-self::r:issuer[1]", _namespaceManager) as XmlElement; - if (currentIssuerContext == null) + if (currentIssuerContext is null) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingIssuer); signatureNode = currentIssuerContext.SelectSingleNode("descendant-or-self::dsig:Signature[1]", _namespaceManager) as XmlElement; - if (signatureNode != null) + if (signatureNode is not null) signatureNode.ParentNode.RemoveChild(signatureNode); // Get the nearest license node currentLicenseContext = currentIssuerContext.SelectSingleNode("ancestor-or-self::r:license[1]", _namespaceManager) as XmlElement; - if (currentLicenseContext == null) + if (currentLicenseContext is null) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingLicence); XmlNodeList issuerList = currentLicenseContext.SelectNodes("descendant-or-self::r:license[1]/r:issuer", _namespaceManager); @@ -178,7 +178,7 @@ public override void LoadInput(object obj) if (encryptedGrantList.Count > 0) { - if (_relDecryptor == null) + if (_relDecryptor is null) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingIRelDecryptor); DecryptEncryptedGrants(encryptedGrantList, _relDecryptor); diff --git a/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs b/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs index a6f292515de78d..7e98dd0b72bbde 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs @@ -57,7 +57,7 @@ protected HostProtectionException(SerializationInfo info, StreamingContext conte private void AppendResourceString(string resourceString, object attr, StringBuilder sb) { - if (attr == null) + if (attr is null) return; sb.Append(Environment.NewLine); diff --git a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/IDRole.cs b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/IDRole.cs index cc4863a5b0da8e..16a104b20fdd1c 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/IDRole.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/IDRole.cs @@ -19,7 +19,7 @@ internal IDRole(bool authenticated, string id, string role) internal IDRole(SecurityElement e) { string elAuth = e.Attribute("Authenticated"); - Authenticated = elAuth == null ? false : string.Equals(elAuth, "true", StringComparison.OrdinalIgnoreCase); + Authenticated = elAuth is null ? false : string.Equals(elAuth, "true", StringComparison.OrdinalIgnoreCase); ID = e.Attribute("ID"); Role = e.Attribute("Role"); } @@ -32,11 +32,11 @@ internal SecurityElement ToXml() { root.AddAttribute("Authenticated", "true"); } - if (ID != null) + if (ID is not null) { root.AddAttribute("ID", SecurityElement.Escape(ID)); } - if (Role != null) + if (Role is not null) { root.AddAttribute("Role", SecurityElement.Escape(Role)); } @@ -49,8 +49,8 @@ public override int GetHashCode() unchecked { return ((Authenticated ? 0 : 101) + - (ID == null ? 0 : ID.GetHashCode()) + - (Role == null ? 0 : Role.GetHashCode())); + (ID is null ? 0 : ID.GetHashCode()) + + (Role is null ? 0 : Role.GetHashCode())); } } } diff --git a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs index c1379d1c431ff1..23edb8fceb8a81 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs @@ -50,7 +50,7 @@ private bool IsEmpty() { foreach (IDRole idRole in _idArray) { - if (idRole.ID == null || idRole.ID.Length != 0 || idRole.Role == null || idRole.Role.Length != 0 || idRole.Authenticated) + if (idRole.ID is null || idRole.ID.Length != 0 || idRole.Role is null || idRole.Role.Length != 0 || idRole.Authenticated) return false; } return true; @@ -59,14 +59,14 @@ private bool IsEmpty() private bool VerifyType(IPermission perm) { // if perm is null, then obviously not of the same type - return (perm != null) && (perm.GetType() == GetType()); + return (perm is not null) && (perm.GetType() == GetType()); } public bool IsUnrestricted() { foreach (IDRole idRole in _idArray) { - if (idRole.ID != null || idRole.Role != null || !idRole.Authenticated) + if (idRole.ID is not null || idRole.Role is not null || !idRole.Authenticated) return false; } return true; @@ -74,7 +74,7 @@ public bool IsUnrestricted() public bool IsSubsetOf(IPermission target) { - if (target == null) + if (target is null) { return IsEmpty(); } @@ -100,8 +100,8 @@ public bool IsSubsetOf(IPermission target) foreach (IDRole operandIdRole in operand._idArray) { if ((operandIdRole.Authenticated == idRole.Authenticated) && - (operandIdRole.ID == null || (idRole.ID != null && idRole.ID.Equals(operandIdRole.ID))) && - (operandIdRole.Role == null || (idRole.Role != null && idRole.Role.Equals(operandIdRole.Role)))) + (operandIdRole.ID is null || (idRole.ID is not null && idRole.ID.Equals(operandIdRole.ID))) && + (operandIdRole.Role is null || (idRole.Role is not null && idRole.Role.Equals(operandIdRole.Role)))) { foundMatch = true; break; @@ -117,7 +117,7 @@ public bool IsSubsetOf(IPermission target) public IPermission Intersect(IPermission target) { - if (target == null) + if (target is null) { return null; } @@ -149,19 +149,19 @@ public IPermission Intersect(IPermission target) bool newAuthenticated = operandIdRole.Authenticated; bool addToNewIDRoles = false; - if (operandIdRole.ID == null || idRole.ID == null || idRole.ID.Equals(operandIdRole.ID)) + if (operandIdRole.ID is null || idRole.ID is null || idRole.ID.Equals(operandIdRole.ID)) { - newID = operandIdRole.ID == null ? idRole.ID : operandIdRole.ID; + newID = operandIdRole.ID is null ? idRole.ID : operandIdRole.ID; addToNewIDRoles = true; } - if (operandIdRole.Role == null || idRole.Role == null || idRole.Role.Equals(operandIdRole.Role)) + if (operandIdRole.Role is null || idRole.Role is null || idRole.Role.Equals(operandIdRole.Role)) { - newRole = operandIdRole.Role == null ? idRole.Role : operandIdRole.Role; + newRole = operandIdRole.Role is null ? idRole.Role : operandIdRole.Role; addToNewIDRoles = true; } if (addToNewIDRoles) { - if (idroles == null) + if (idroles is null) idroles = new List(); idroles.Add(new IDRole(newAuthenticated, newID, newRole)); } @@ -169,12 +169,12 @@ public IPermission Intersect(IPermission target) } } - return (idroles == null) ? null : new PrincipalPermission(idroles.ToArray()); + return (idroles is null) ? null : new PrincipalPermission(idroles.ToArray()); } public IPermission Union(IPermission other) { - if (other == null) + if (other is null) { return Copy(); } @@ -200,11 +200,11 @@ public IPermission Union(IPermission other) public override bool Equals(object obj) { IPermission perm = obj as IPermission; - if (obj != null && perm == null) + if (obj is not null && perm is null) return false; if (!IsSubsetOf(perm)) return false; - if (perm != null && !perm.IsSubsetOf(this)) + if (perm is not null && !perm.IsSubsetOf(this)) return false; return true; } @@ -225,9 +225,9 @@ public IPermission Copy() public void Demand() { IPrincipal principal = Thread.CurrentPrincipal; - if (principal == null) + if (principal is null) throw new SecurityException(SR.Security_PrincipalPermission); - if (_idArray == null) + if (_idArray is null) return; // A demand passes when the grant satisfies all entries. @@ -239,9 +239,9 @@ public void Demand() return; } else if (principal.Identity.IsAuthenticated && - (idRole.ID == null || string.Equals(principal.Identity.Name, idRole.ID, StringComparison.OrdinalIgnoreCase))) + (idRole.ID is null || string.Equals(principal.Identity.Name, idRole.ID, StringComparison.OrdinalIgnoreCase))) { - if (idRole.Role == null || principal.IsInRole(idRole.Role)) + if (idRole.Role is null || principal.IsInRole(idRole.Role)) return; } } @@ -257,7 +257,7 @@ public SecurityElement ToXml() root.AddAttribute("class", typename + ", " + GetType().Module.Assembly.FullName.Replace('\"', '\'')); root.AddAttribute("version", "1"); - if (_idArray != null) + if (_idArray is not null) { foreach (IDRole idRole in _idArray) { @@ -270,18 +270,18 @@ public SecurityElement ToXml() public void FromXml(SecurityElement elem) { - if (elem == null) + if (elem is null) throw new ArgumentNullException(nameof(elem)); - if (elem.Tag == null || !elem.Tag.Equals("Permission") && !elem.Tag.Equals("IPermission")) + if (elem.Tag is null || !elem.Tag.Equals("Permission") && !elem.Tag.Equals("IPermission")) throw new ArgumentException(SR.Argument_NotAPermissionElement); string version = elem.Attribute("version"); - if (version == null || (version != null && !version.Equals("1"))) + if (version is null || (version is not null && !version.Equals("1"))) throw new ArgumentException(SR.Argument_InvalidXMLBadVersion); - if (elem.Children != null && elem.Children.Count != 0) + if (elem.Children is not null && elem.Children.Count != 0) { int numChildren = elem.Children.Count; int count = 0; diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs index 131ff6dbf8319c..72a4bf7f0954be 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs @@ -68,7 +68,7 @@ bool ICollection.IsReadOnly public void Add(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -78,7 +78,7 @@ public void Add(IdentityReference identity) public bool Remove(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -98,7 +98,7 @@ public void Clear() public bool Contains(IdentityReference identity) { - if (identity == null) + if (identity is null) { throw new ArgumentNullException(nameof(identity)); } @@ -156,7 +156,7 @@ public IdentityReferenceCollection Translate(Type targetType) public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) { - if (targetType == null) + if (targetType is null) { throw new ArgumentNullException(nameof(targetType)); } @@ -308,7 +308,7 @@ public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) Result = new IdentityReferenceCollection(); - if (TargetSids != null) + if (TargetSids is not null) { foreach (IdentityReference id in TargetSids) { @@ -319,7 +319,7 @@ public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) } } - if (TargetNTAccounts != null) + if (TargetNTAccounts is not null) { foreach (IdentityReference id in TargetNTAccounts) { diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs index 5cfa7887b40736..59dbc26cedb2f8 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs @@ -45,7 +45,7 @@ public IdentityReferenceCollection UnmappedIdentities { get { - if (_unmappedIdentities == null) + if (_unmappedIdentities is null) { _unmappedIdentities = new IdentityReferenceCollection(); } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityReference.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityReference.cs index e1b73c428cf9aa..e70ed95ff8dcdb 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityReference.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityReference.cs @@ -31,7 +31,7 @@ internal IdentityReference() { return true; } - else if (l == null || r == null) + else if (l is null || r is null) { return false; } 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 88d64de715cc6a..c2d0664a90bdca 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 @@ -32,7 +32,7 @@ public sealed class NTAccount : IdentityReference public NTAccount(string domainName, string accountName) { - if (accountName == null) + if (accountName is null) { throw new ArgumentNullException(nameof(accountName)); } @@ -47,12 +47,12 @@ public NTAccount(string domainName, string accountName) throw new ArgumentException(SR.IdentityReference_AccountNameTooLong, nameof(accountName)); } - if (domainName != null && domainName.Length > MaximumDomainNameLength) + if (domainName is not null && domainName.Length > MaximumDomainNameLength) { throw new ArgumentException(SR.IdentityReference_DomainNameTooLong, nameof(domainName)); } - if (domainName == null || domainName.Length == 0) + if (domainName is null || domainName.Length == 0) { _name = accountName; } @@ -64,7 +64,7 @@ public NTAccount(string domainName, string accountName) public NTAccount(string name) { - if (name == null) + if (name is null) { throw new ArgumentNullException(nameof(name)); } @@ -111,7 +111,7 @@ public override bool IsValidTargetType(Type targetType) public override IdentityReference Translate(Type targetType) { - if (targetType == null) + if (targetType is null) { throw new ArgumentNullException(nameof(targetType)); } @@ -175,7 +175,7 @@ internal static IdentityReferenceCollection Translate(IdentityReferenceCollectio internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, out bool someFailed) { - if (sourceAccounts == null) + if (sourceAccounts is null) { throw new ArgumentNullException(nameof(sourceAccounts)); } @@ -201,7 +201,7 @@ internal static IdentityReferenceCollection Translate(IdentityReferenceCollectio { return true; } - else if (l == null || r == null) + else if (l is null || r is null) { return false; } @@ -223,7 +223,7 @@ internal static IdentityReferenceCollection Translate(IdentityReferenceCollectio private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed) { - if (sourceAccounts == null) + if (sourceAccounts is null) { throw new ArgumentNullException(nameof(sourceAccounts)); } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs index 95e12eba0c3f71..30d98675b647b1 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs @@ -406,7 +406,7 @@ private void CreateFromBinaryForm(byte[] binaryForm, int offset) // Give us something to work with // - if (binaryForm == null) + if (binaryForm is null) { throw new ArgumentNullException(nameof(binaryForm)); } @@ -518,7 +518,7 @@ public SecurityIdentifier(string sddlForm) // Give us something to work with // - if (sddlForm == null) + if (sddlForm is null) { throw new ArgumentNullException(nameof(sddlForm)); } @@ -603,7 +603,7 @@ public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier? domainSi int error; if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid)) { - if (domainSid == null) + if (domainSid is null) { throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType)); } @@ -741,7 +741,7 @@ public override int GetHashCode() public override string ToString() { - if (_sddlForm == null) + if (_sddlForm is null) { // // Typecasting of _IdentifierAuthority to a ulong below is important, since @@ -844,7 +844,7 @@ public bool IsAccountSid() _accountDomainSidInitialized = true; } - if (_accountDomainSid == null) + if (_accountDomainSid is null) { return false; } @@ -855,7 +855,7 @@ public bool IsAccountSid() public override IdentityReference Translate(Type targetType) { - if (targetType == null) + if (targetType is null) { throw new ArgumentNullException(nameof(targetType)); } @@ -893,7 +893,7 @@ public override IdentityReference Translate(Type targetType) { return true; } - else if (l == null || r == null) + else if (l is null || r is null) { return false; } @@ -914,7 +914,7 @@ public override IdentityReference Translate(Type targetType) public int CompareTo(SecurityIdentifier? sid) { - if (sid == null) + if (sid is null) { throw new ArgumentNullException(nameof(sid)); } @@ -993,7 +993,7 @@ public bool IsEqualDomainSid(SecurityIdentifier sid) private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed) { - if (sourceSids == null) + if (sourceSids is null) { throw new ArgumentNullException(nameof(sourceSids)); } @@ -1172,7 +1172,7 @@ internal static IdentityReferenceCollection Translate(IdentityReferenceCollectio internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed) { - if (sourceSids == null) + if (sourceSids is null) { throw new ArgumentNullException(nameof(sourceSids)); } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs index a4302d97b6a732..a1975557b1c356 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs @@ -189,7 +189,7 @@ out byte[]? resultSid internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2) { - if (sid1 == null || sid2 == null) + if (sid1 is null || sid2 is null) { return false; } @@ -211,7 +211,7 @@ internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifie internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains) { - Debug.Assert(referencedDomains != null, "referencedDomains != null"); + Debug.Assert(referencedDomains is not null, "referencedDomains is not null"); // We don't know the real size of the referenced domains yet, so we need to set an initial // size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of @@ -241,7 +241,7 @@ internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle refe } finally { - if (pRdl != null) + if (pRdl is not null) referencedDomains.ReleasePointer(); } } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index 4bff4c48735ca0..d2101f9155abfb 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -133,7 +133,7 @@ public WindowsIdentity(string sUserPrincipalName) sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); - if (sUserPrincipalName == null) + if (sUserPrincipalName is null) throw new ArgumentNullException(nameof(sUserPrincipalName)); byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); @@ -196,7 +196,7 @@ public WindowsIdentity(string sUserPrincipalName) if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); - if (profileBuffer != null) + if (profileBuffer is not null) profileBuffer.Dispose(); _safeTokenHandle = accessTokenHandle; @@ -357,7 +357,7 @@ public sealed override string? AuthenticationType if (_safeTokenHandle.IsInvalid) return string.Empty; - if (_authType == null) + if (_authType is null) { Interop.LUID authId = GetLogonAuthId(_safeTokenHandle); if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID) @@ -567,7 +567,7 @@ internal string GetName() if (_safeTokenHandle.IsInvalid) return string.Empty; - if (_name == null) + if (_name is null) { // revert thread impersonation for the duration of the call to get the name. RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate @@ -588,7 +588,7 @@ public SecurityIdentifier? Owner if (_safeTokenHandle.IsInvalid) return null; - if (_owner == null) + if (_owner is null) { using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner, nullOnInvalidParam: false)!) { @@ -608,7 +608,7 @@ public SecurityIdentifier? User if (_safeTokenHandle.IsInvalid) return null; - if (_user == null) + if (_user is null) { using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser, nullOnInvalidParam: false)!) { @@ -628,7 +628,7 @@ public IdentityReferenceCollection? Groups if (_safeTokenHandle.IsInvalid) return null; - if (_groups == null) + if (_groups is null) { IdentityReferenceCollection groups = new IdentityReferenceCollection(); using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups, nullOnInvalidParam: false)!) @@ -679,7 +679,7 @@ public virtual IntPtr Token public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { - if (action == null) + if (action is null) throw new ArgumentNullException(nameof(action)); RunImpersonatedInternal(safeAccessTokenHandle, action); @@ -688,7 +688,7 @@ public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, public static T RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Func func) { - if (func == null) + if (func is null) throw new ArgumentNullException(nameof(func)); T result = default!; @@ -719,7 +719,7 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed) + if (_safeTokenHandle is not null && !_safeTokenHandle.IsClosed) _safeTokenHandle.Dispose(); } _name = null; @@ -743,7 +743,7 @@ private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action token = DuplicateAccessToken(token); SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out bool isImpersonating, out int hr); - if (previousToken == null || previousToken.IsInvalid) + if (previousToken is null || previousToken.IsInvalid) throw new SecurityException(new Win32Exception(hr).Message); s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null; @@ -779,7 +779,7 @@ private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs instanceClaims, TokenInformatio safeAllocHandle = GetTokenInformation(_safeTokenHandle, tokenInformationClass, nullOnInvalidParam: true); - if (safeAllocHandle == null) + if (safeAllocHandle is null) { s_ignoreWindows8Properties = true; return; 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 69463bc747b6e2..16b303c183bd2c 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 @@ -46,7 +46,7 @@ public WindowsPrincipal(WindowsIdentity ntIdentity) public override bool IsInRole(string role) { - if (role == null || role.Length == 0) + if (role is null || role.Length == 0) return false; NTAccount ntAccount = new NTAccount(role); @@ -138,7 +138,7 @@ public virtual bool IsInRole(int rid) public virtual bool IsInRole(SecurityIdentifier sid) { - if (sid == null) + if (sid is null) throw new ArgumentNullException(nameof(sid)); // special case the anonymous identity. diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs index 7778341f0d29e9..94bfa0c1494fef 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs @@ -37,7 +37,7 @@ public Atom10FeedFormatter() : this(typeof(SyndicationFeed)) public Atom10FeedFormatter(Type feedTypeToCreate) : base() { - if (feedTypeToCreate == null) + if (feedTypeToCreate is null) { throw new ArgumentNullException(nameof(feedTypeToCreate)); } @@ -72,7 +72,7 @@ internal override TryParseDateTimeCallback GetDefaultDateTimeParser() public override bool CanRead(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -84,7 +84,7 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -94,7 +94,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -114,7 +114,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -380,7 +380,7 @@ internal bool TryParseItemElementFrom(XmlReader reader, SyndicationItem result) internal void WriteContentTo(XmlWriter writer, string elementName, SyndicationContent content) { - if (content != null) + if (content is not null) { content.WriteTo(writer, elementName, Atom10Constants.Atom10Namespace); } @@ -388,7 +388,7 @@ internal void WriteContentTo(XmlWriter writer, string elementName, SyndicationCo internal void WriteElement(XmlWriter writer, string elementName, string value) { - if (value != null) + if (value is not null) { writer.WriteElementString(elementName, Atom10Constants.Atom10Namespace, value); } @@ -462,7 +462,7 @@ internal void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseUri) { writer.WriteStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { writer.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } @@ -495,11 +495,11 @@ internal void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseUri) protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -511,11 +511,11 @@ protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed fee protected virtual IEnumerable ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -538,7 +538,7 @@ protected virtual void WriteItem(XmlWriter writer, SyndicationItem item, Uri fee protected virtual void WriteItems(XmlWriter writer, IEnumerable items, Uri feedBaseUri) { - if (items == null) + if (items is null) { return; } @@ -581,7 +581,7 @@ private static TextSyndicationContent ReadTextContentFromHelper(XmlReader reader if (preserveAttributeExtensions) { string value = reader.Value; - if (attrs == null) + if (attrs is null) { attrs = new Dictionary(); } @@ -592,7 +592,7 @@ private static TextSyndicationContent ReadTextContentFromHelper(XmlReader reader reader.MoveToElement(); string val = (kind == TextSyndicationContentKind.XHtml) ? reader.ReadInnerXml() : reader.ReadElementString(); TextSyndicationContent result = new TextSyndicationContent(val, kind); - if (attrs != null) + if (attrs is not null) { foreach (XmlQualifiedName attr in attrs.Keys) { @@ -790,7 +790,7 @@ private SyndicationFeed ReadFeedFrom(XmlReader reader, SyndicationFeed result, b } } - if (feedItems != null) + if (feedItems is not null) { result.Items = feedItems; } @@ -799,7 +799,7 @@ private SyndicationFeed ReadFeedFrom(XmlReader reader, SyndicationFeed result, b } finally { - if (extWriter != null) + if (extWriter is not null) { ((IDisposable)extWriter).Dispose(); } @@ -987,7 +987,7 @@ private void ReadLink(XmlReader reader, SyndicationLink link, Uri baseUri) link.MediaType = mediaType; link.RelationshipType = relationship; link.Title = title; - link.Uri = (val != null) ? UriFromString(val, UriKind.RelativeOrAbsolute, Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace, reader) : null; + link.Uri = (val is not null) ? UriFromString(val, UriKind.RelativeOrAbsolute, Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace, reader) : null; } private SyndicationLink ReadLinkFrom(XmlReader reader, SyndicationFeed feed) @@ -1102,7 +1102,7 @@ private void WriteCategoriesTo(XmlWriter writer, Collection private void WriteFeed(XmlWriter writer) { - if (Feed == null) + if (Feed is null) { throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed); } @@ -1118,7 +1118,7 @@ private void WriteFeedTo(XmlWriter writer, SyndicationFeed feed, bool isSourceFe { writer.WriteAttributeString("xml", "lang", XmlNs, feed.Language); } - if (feed.BaseUri != null) + if (feed.BaseUri is not null) { writer.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(feed.BaseUri)); } @@ -1141,7 +1141,7 @@ private void WriteFeedTo(XmlWriter writer, SyndicationFeed feed, bool isSourceFe WriteContentTo(writer, Atom10Constants.RightsTag, feed.Copyright); WriteFeedLastUpdatedTimeTo(writer, feed.LastUpdatedTime, isElementRequired); WriteCategoriesTo(writer, feed.Categories); - if (feed.ImageUrl != null) + if (feed.ImageUrl is not null) { WriteElement(writer, Atom10Constants.LogoTag, feed.ImageUrl.ToString()); } @@ -1165,7 +1165,7 @@ private void WriteFeedTo(XmlWriter writer, SyndicationFeed feed, bool isSourceFe private void WriteItemContents(XmlWriter dictWriter, SyndicationItem item, Uri feedBaseUri) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { dictWriter.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } @@ -1193,7 +1193,7 @@ private void WriteItemContents(XmlWriter dictWriter, SyndicationItem item, Uri f WriteCategoriesTo(dictWriter, item.Categories); WriteContentTo(dictWriter, Atom10Constants.ContentTag, item.Content); WriteContentTo(dictWriter, Atom10Constants.RightsTag, item.Copyright); - if (item.SourceFeed != null) + if (item.SourceFeed is not null) { dictWriter.WriteStartElement(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace); WriteFeedTo(dictWriter, item.SourceFeed, isSourceFeed: true); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs index 85494e557f1435..e3dd1d7e2d6d9e 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs @@ -21,7 +21,7 @@ public Atom10ItemFormatter() : this(typeof(SyndicationItem)) public Atom10ItemFormatter(Type itemTypeToCreate) : base() { - if (itemTypeToCreate == null) + if (itemTypeToCreate is null) { throw new ArgumentNullException(nameof(itemTypeToCreate)); } @@ -64,7 +64,7 @@ public bool PreserveElementExtensions public override bool CanRead(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -76,7 +76,7 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -86,7 +86,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -106,7 +106,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -126,7 +126,7 @@ private void ReadItem(XmlReader reader) private void WriteItem(XmlWriter writer) { - if (Item == null) + if (Item is null) { throw new InvalidOperationException(SR.ItemFormatterDoesNotHaveItem); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs index 65720a8c7be0bf..f9ee7436e11365 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs @@ -21,7 +21,7 @@ public AtomPub10CategoriesDocumentFormatter() : this(typeof(InlineCategoriesDocu public AtomPub10CategoriesDocumentFormatter(Type inlineDocumentType, Type referencedDocumentType) : base() { - if (inlineDocumentType == null) + if (inlineDocumentType is null) { throw new ArgumentNullException(nameof(inlineDocumentType)); } @@ -29,7 +29,7 @@ public AtomPub10CategoriesDocumentFormatter(Type inlineDocumentType, Type refere { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(inlineDocumentType), nameof(InlineCategoriesDocument)), nameof(inlineDocumentType)); } - if (referencedDocumentType == null) + if (referencedDocumentType is null) { throw new ArgumentNullException(nameof(referencedDocumentType)); } @@ -62,7 +62,7 @@ public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite) public override bool CanRead(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -74,7 +74,7 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -84,11 +84,11 @@ void IXmlSerializable.ReadXml(XmlReader reader) void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (Document == null) + if (Document is null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } @@ -98,7 +98,7 @@ void IXmlSerializable.WriteXml(XmlWriter writer) public override void ReadFrom(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -112,11 +112,11 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (Document == null) + if (Document is null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs index aec63b1949b0c9..4b748cbf09d75b 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs @@ -24,7 +24,7 @@ public AtomPub10ServiceDocumentFormatter() : this(typeof(ServiceDocument)) public AtomPub10ServiceDocumentFormatter(Type documentTypeToCreate) : base() { - if (documentTypeToCreate == null) + if (documentTypeToCreate is null) { throw new ArgumentNullException(nameof(documentTypeToCreate)); } @@ -47,7 +47,7 @@ public AtomPub10ServiceDocumentFormatter(ServiceDocument documentToWrite) : base public override bool CanRead(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -59,7 +59,7 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -69,11 +69,11 @@ void IXmlSerializable.ReadXml(XmlReader reader) void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (Document == null) + if (Document is null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } @@ -83,7 +83,7 @@ void IXmlSerializable.WriteXml(XmlWriter writer) public override void ReadFrom(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -99,11 +99,11 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (Document == null) + if (Document is null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } @@ -133,7 +133,7 @@ internal static CategoriesDocument ReadCategories(XmlReader reader, Uri baseUri, internal static void WriteCategoriesInnerXml(XmlWriter writer, CategoriesDocument categories, Uri baseUri, string version) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, categories.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { WriteXmlBase(writer, baseUriToWrite); } @@ -218,7 +218,7 @@ private static void ReadInlineCategories(XmlReader reader, InlineCategoriesDocum { SyndicationCategory category = CreateCategory(inlineCategories); Atom10FeedFormatter.ReadCategory(reader, category, version, preserveAttributeExtensions: true, preserveElementExtensions: true, maxExtensionSize); - if (category.Scheme == null) + if (category.Scheme is null) { category.Scheme = inlineCategories.Scheme; } @@ -331,7 +331,7 @@ private static void WriteInlineCategoriesContent(XmlWriter writer, InlineCategor private static void WriteReferencedCategoriesContent(XmlWriter writer, ReferencedCategoriesDocument categories, string version) { - if (categories.Link != null) + if (categories.Link is not null) { writer.WriteAttributeString(App10Constants.Href, FeedUtils.GetUriString(categories.Link)); } @@ -567,17 +567,17 @@ private void WriteCollection(XmlWriter writer, ResourceCollectionInfo collection { writer.WriteStartElement(App10Constants.Prefix, App10Constants.Collection, App10Constants.Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, collection.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { baseUri = collection.BaseUri; WriteXmlBase(writer, baseUriToWrite); } - if (collection.Link != null) + if (collection.Link is not null) { writer.WriteAttributeString(App10Constants.Href, FeedUtils.GetUriString(collection.Link)); } WriteAttributeExtensions(writer, collection, Version); - if (collection.Title != null) + if (collection.Title is not null) { collection.Title.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); } @@ -602,7 +602,7 @@ private void WriteDocument(XmlWriter writer) WriteXmlLang(writer, Document.Language); } Uri baseUri = Document.BaseUri; - if (baseUri != null) + if (baseUri is not null) { WriteXmlBase(writer, baseUri); } @@ -619,13 +619,13 @@ private void WriteWorkspace(XmlWriter writer, Workspace workspace, Uri baseUri) { writer.WriteStartElement(App10Constants.Prefix, App10Constants.Workspace, App10Constants.Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, workspace.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { baseUri = workspace.BaseUri; WriteXmlBase(writer, baseUriToWrite); } WriteAttributeExtensions(writer, workspace, Version); - if (workspace.Title != null) + if (workspace.Title is not null) { workspace.Title.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs index 318b0014f45f5b..0047a7c11c15c3 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs @@ -14,7 +14,7 @@ internal struct ExtensibleSyndicationObject : IExtensibleSyndicationObject private ExtensibleSyndicationObject(ExtensibleSyndicationObject source) { - if (source._attributeExtensions != null) + if (source._attributeExtensions is not null) { _attributeExtensions = new Dictionary(); foreach (XmlQualifiedName key in source._attributeExtensions.Keys) @@ -26,7 +26,7 @@ private ExtensibleSyndicationObject(ExtensibleSyndicationObject source) { _attributeExtensions = null; } - if (source._elementExtensions != null) + if (source._elementExtensions is not null) { _elementExtensions = new SyndicationElementExtensionCollection(source._elementExtensions); } @@ -65,7 +65,7 @@ private static XmlBuffer CreateXmlBuffer(XmlDictionaryReader unparsedExtensionsR internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) { - if (readerOverUnparsedExtensions == null) + if (readerOverUnparsedExtensions is null) { throw new ArgumentNullException(nameof(readerOverUnparsedExtensions)); } @@ -86,12 +86,12 @@ internal void LoadElementExtensions(XmlBuffer buffer) internal void WriteAttributeExtensions(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (_attributeExtensions != null) + if (_attributeExtensions is not null) { foreach (XmlQualifiedName qname in _attributeExtensions.Keys) { @@ -103,12 +103,12 @@ internal void WriteAttributeExtensions(XmlWriter writer) internal void WriteElementExtensions(XmlWriter writer, Func shouldSkipElement = null) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (_elementExtensions != null) + if (_elementExtensions is not null) { _elementExtensions.WriteTo(writer, shouldSkipElement); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs index 7b20e996ad68bd..917017f6e37467 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs @@ -12,7 +12,7 @@ internal static class FeedUtils public static string AddLineInfo(XmlReader reader, string error) { IXmlLineInfo lineInfo = reader as IXmlLineInfo; - if (lineInfo != null && lineInfo.HasLineInfo()) + if (lineInfo is not null && lineInfo.HasLineInfo()) { error = string.Format(CultureInfo.InvariantCulture, "{0} {1}", SR.Format(SR.ErrorInLine, lineInfo.LineNumber, lineInfo.LinePosition), SR.Format(error)); } @@ -21,7 +21,7 @@ public static string AddLineInfo(XmlReader reader, string error) internal static Collection CloneCategories(Collection categories) { - if (categories == null) + if (categories is null) { return null; } @@ -35,7 +35,7 @@ internal static Collection CloneCategories(Collection CloneLinks(Collection links) { - if (links == null) + if (links is null) { return null; } @@ -49,7 +49,7 @@ internal static Collection CloneLinks(Collection ClonePersons(Collection persons) { - if (persons == null) + if (persons is null) { return null; } @@ -63,7 +63,7 @@ internal static Collection ClonePersons(Collection categories) : t public InlineCategoriesDocument(IEnumerable categories, bool isFixed, string scheme) { - if (categories != null) + if (categories is not null) { _categories = new NullNotAllowedCollection(); foreach (SyndicationCategory category in categories) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs index b3d9fa52f98d0d..1f37c282a46825 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs @@ -13,7 +13,7 @@ public NullNotAllowedCollection() : base() protected override void InsertItem(int index, TCollectionItem item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -23,7 +23,7 @@ protected override void InsertItem(int index, TCollectionItem item) protected override void SetItem(int index, TCollectionItem item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs index d4bfc6e7f48e08..d133adce06402e 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs @@ -18,7 +18,7 @@ public ResourceCollectionInfo() { } - public ResourceCollectionInfo(string title, Uri link) : this((title == null) ? null : new TextSyndicationContent(title), link) + public ResourceCollectionInfo(string title, Uri link) : this((title is null) ? null : new TextSyndicationContent(title), link) { } @@ -36,7 +36,7 @@ public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerabl Title = title ?? throw new ArgumentNullException(nameof(title)); Link = link ?? throw new ArgumentNullException(nameof(link)); - if (categories != null) + if (categories is not null) { _categories = new NullNotAllowedCollection(); foreach (CategoriesDocument category in categories) @@ -45,7 +45,7 @@ public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerabl } } - if (accepts != null) + if (accepts is not null) { _accepts = new NullNotAllowedCollection(); foreach (string accept in accepts) @@ -117,7 +117,7 @@ internal void LoadElementExtensions(XmlBuffer buffer) private static IEnumerable CreateSingleEmptyAccept() { - if (s_singleEmptyAccept == null) + if (s_singleEmptyAccept is null) { s_singleEmptyAccept = new List(1) { string.Empty }.AsReadOnly(); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs index d6d8cb85dc9b04..2e72bce1b908e5 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs @@ -32,7 +32,7 @@ public Rss20FeedFormatter() : this(typeof(SyndicationFeed)) public Rss20FeedFormatter(Type feedTypeToCreate) : base() { - if (feedTypeToCreate == null) + if (feedTypeToCreate is null) { throw new ArgumentNullException(nameof(feedTypeToCreate)); } @@ -74,7 +74,7 @@ public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsA public override bool CanRead(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -86,7 +86,7 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -96,7 +96,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -116,7 +116,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -146,11 +146,11 @@ internal void WriteItemContents(XmlWriter writer, SyndicationItem item) protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -162,11 +162,11 @@ protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed fee protected virtual IEnumerable ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -189,7 +189,7 @@ protected virtual void WriteItem(XmlWriter writer, SyndicationItem item, Uri fee protected virtual void WriteItems(XmlWriter writer, IEnumerable items, Uri feedBaseUri) { - if (items == null) + if (items is null) { return; } @@ -375,7 +375,7 @@ private void ReadItemFrom(XmlReader reader, SyndicationItem result, Uri feedBase { bool isPermalink = true; string permalinkString = reader.GetAttribute(Rss20Constants.IsPermaLinkTag, Rss20Constants.Rss20Namespace); - if ((permalinkString != null) && (permalinkString.ToUpperInvariant() == "FALSE")) + if ((permalinkString is not null) && (permalinkString.ToUpperInvariant() == "FALSE")) { isPermalink = false; } @@ -469,14 +469,14 @@ private void ReadItemFrom(XmlReader reader, SyndicationItem result, Uri feedBase } reader.ReadEndElement(); // item - if (!readAlternateLink && fallbackAlternateLink != null) + if (!readAlternateLink && fallbackAlternateLink is not null) { result.Links.Add(SyndicationLink.CreateAlternateLink(UriFromString(fallbackAlternateLink, UriKind.RelativeOrAbsolute, fallbackAlternateLinkLocalName, fallbackAlternateLinkNamespace, reader))); readAlternateLink = true; } // if there's no content and no alternate link set the summary as the item content - if (result.Content == null && !readAlternateLink) + if (result.Content is null && !readAlternateLink) { result.Content = result.Summary; result.Summary = null; @@ -771,7 +771,7 @@ private void ReadXml(XmlReader reader, SyndicationFeed result) } } - if (feedItems != null) + if (feedItems is not null) { result.Items = feedItems; } @@ -802,7 +802,7 @@ private void WriteAlternateLink(XmlWriter writer, SyndicationLink link, Uri base { writer.WriteStartElement(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { writer.WriteAttributeString("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } @@ -813,7 +813,7 @@ private void WriteAlternateLink(XmlWriter writer, SyndicationLink link, Uri base private void WriteCategory(XmlWriter writer, SyndicationCategory category) { - if (category == null) + if (category is null) { return; } @@ -829,7 +829,7 @@ private void WriteCategory(XmlWriter writer, SyndicationCategory category) private void WriteFeed(XmlWriter writer) { - if (Feed == null) + if (Feed is null) { throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed); } @@ -840,12 +840,12 @@ private void WriteFeed(XmlWriter writer) } writer.WriteAttributeString(Rss20Constants.VersionTag, Rss20Constants.Version); writer.WriteStartElement(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace); - if (Feed.BaseUri != null) + if (Feed.BaseUri is not null) { writer.WriteAttributeString("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(Feed.BaseUri)); } WriteAttributeExtensions(writer, Feed, Version); - string title = Feed.Title != null ? Feed.Title.Text : string.Empty; + string title = Feed.Title is not null ? Feed.Title.Text : string.Empty; writer.WriteElementString(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, title); SyndicationLink alternateLink = null; @@ -859,22 +859,22 @@ private void WriteFeed(XmlWriter writer) } } - string description = Feed.Description != null ? Feed.Description.Text : string.Empty; + string description = Feed.Description is not null ? Feed.Description.Text : string.Empty; writer.WriteElementString(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, description); - if (Feed.Language != null) + if (Feed.Language is not null) { writer.WriteElementString(Rss20Constants.LanguageTag, Feed.Language); } - if (Feed.Copyright != null) + if (Feed.Copyright is not null) { writer.WriteElementString(Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace, Feed.Copyright.Text); } // if there's a single author with an email address, then serialize as the managingEditor // else serialize the authors as Atom extensions - if ((Feed.Authors.Count == 1) && (Feed.Authors[0].Email != null)) + if ((Feed.Authors.Count == 1) && (Feed.Authors[0].Email is not null)) { WritePerson(writer, Rss20Constants.ManagingEditorTag, Feed.Authors[0]); } @@ -911,23 +911,23 @@ private void WriteFeed(XmlWriter writer) } } - if (Feed.ImageUrl != null) + if (Feed.ImageUrl is not null) { writer.WriteStartElement(Rss20Constants.ImageTag); writer.WriteElementString(Rss20Constants.UrlTag, FeedUtils.GetUriString(Feed.ImageUrl)); writer.WriteElementString(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, title); - string imgAlternateLink = (alternateLink != null) ? FeedUtils.GetUriString(alternateLink.Uri) : string.Empty; + string imgAlternateLink = (alternateLink is not null) ? FeedUtils.GetUriString(alternateLink.Uri) : string.Empty; writer.WriteElementString(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace, imgAlternateLink); writer.WriteEndElement(); // image } // Optional spec items - if (Feed.InternalDocumentation?.Uri != null) + if (Feed.InternalDocumentation?.Uri is not null) { writer.WriteElementString(Rss20Constants.DocumentationTag, Feed.InternalDocumentation.Uri.ToString()); } - if (Feed.InternalTimeToLive != null) + if (Feed.InternalTimeToLive is not null) { writer.WriteElementString(Rss20Constants.TimeToLiveTag, ((int)Feed.InternalTimeToLive.Value.TotalMinutes).ToString()); } @@ -956,7 +956,7 @@ private void WriteFeed(XmlWriter writer) writer.WriteEndElement(); } - if (Feed.InternalTextInput != null) + if (Feed.InternalTextInput is not null) { writer.WriteStartElement(Rss20Constants.TextInputTag); @@ -993,7 +993,7 @@ private void WriteFeed(XmlWriter writer) private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedBaseUri) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { writer.WriteAttributeString("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } @@ -1005,7 +1005,7 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB { if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag) { - if (firstAlternateLink == null) + if (firstAlternateLink is null) { firstAlternateLink = item.Links[i]; } @@ -1030,7 +1030,7 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB writer.WriteString(guid); writer.WriteEndElement(); } - if (firstAlternateLink != null) + if (firstAlternateLink is not null) { WriteAlternateLink(writer, firstAlternateLink, (item.BaseUri ?? feedBaseUri)); } @@ -1053,7 +1053,7 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB } bool serializedTitle = false; - if (item.Title != null) + if (item.Title is not null) { writer.WriteElementString(Rss20Constants.TitleTag, item.Title.Text); serializedTitle = true; @@ -1061,22 +1061,22 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB bool serializedContentAsDescription = false; TextSyndicationContent summary = item.Summary; - if (summary == null) + if (summary is null) { summary = (item.Content as TextSyndicationContent); - serializedContentAsDescription = (summary != null); + serializedContentAsDescription = (summary is not null); } // the spec requires the wire to have a title or a description - if (!serializedTitle && summary == null) + if (!serializedTitle && summary is null) { summary = new TextSyndicationContent(string.Empty); } - if (summary != null) + if (summary is not null) { writer.WriteElementString(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, summary.Text); } - if (item.SourceFeed != null) + if (item.SourceFeed is not null) { writer.WriteStartElement(Rss20Constants.SourceTag, Rss20Constants.Rss20Namespace); WriteAttributeExtensions(writer, item.SourceFeed, Version); @@ -1089,11 +1089,11 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB break; } } - if (selfLink != null && !item.SourceFeed.AttributeExtensions.ContainsKey(s_rss20Url)) + if (selfLink is not null && !item.SourceFeed.AttributeExtensions.ContainsKey(s_rss20Url)) { writer.WriteAttributeString(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(selfLink.Uri)); } - string title = (item.SourceFeed.Title != null) ? item.SourceFeed.Title.Text : string.Empty; + string title = (item.SourceFeed.Title is not null) ? item.SourceFeed.Title.Text : string.Empty; writer.WriteString(title); writer.WriteEndElement(); } @@ -1110,7 +1110,7 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB { if (item.Links[i].RelationshipType == Rss20Constants.EnclosureTag) { - if (firstEnclosureLink == null) + if (firstEnclosureLink is null) { firstEnclosureLink = item.Links[i]; WriteMediaEnclosure(writer, item.Links[i], item.BaseUri); @@ -1167,7 +1167,7 @@ private void WriteMediaEnclosure(XmlWriter writer, SyndicationLink link, Uri bas { writer.WriteStartElement(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); - if (baseUriToWrite != null) + if (baseUriToWrite is not null) { writer.WriteAttributeString("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } @@ -1176,7 +1176,7 @@ private void WriteMediaEnclosure(XmlWriter writer, SyndicationLink link, Uri bas { writer.WriteAttributeString(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(link.Uri)); } - if (link.MediaType != null && !link.AttributeExtensions.ContainsKey(s_rss20Type)) + if (link.MediaType is not null && !link.AttributeExtensions.ContainsKey(s_rss20Type)) { writer.WriteAttributeString(Rss20Constants.TypeTag, Rss20Constants.Rss20Namespace, link.MediaType); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs index 015315700ad0ae..ebb819609a6c93 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs @@ -22,7 +22,7 @@ public Rss20ItemFormatter() : this(typeof(SyndicationItem)) public Rss20ItemFormatter(Type itemTypeToCreate) : base() { - if (itemTypeToCreate == null) + if (itemTypeToCreate is null) { throw new ArgumentNullException(nameof(itemTypeToCreate)); } @@ -87,7 +87,7 @@ public bool SerializeExtensionsAsAtom public override bool CanRead(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -99,7 +99,7 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -109,7 +109,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -129,7 +129,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -149,7 +149,7 @@ private void ReadItem(XmlReader reader) private void WriteItem(XmlWriter writer) { - if (Item == null) + if (Item is null) { throw new InvalidOperationException(SR.ItemFormatterDoesNotHaveItem); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs index 7e242790f21bb2..3697de99f5b268 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs @@ -18,7 +18,7 @@ public ServiceDocument() : this(null) public ServiceDocument(IEnumerable workspaces) { - if (workspaces != null) + if (workspaces is not null) { _workspaces = new NullNotAllowedCollection(); foreach (Workspace workspace in workspaces) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs index 495cd6f18f09e6..06b83f06c468e7 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs @@ -31,7 +31,7 @@ protected ServiceDocumentFormatter(ServiceDocument documentToWrite) internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, CategoriesDocument categories) { - Debug.Assert(categories != null); + Debug.Assert(categories is not null); SyndicationFeedFormatter.CloseBuffer(buffer, writer); categories.LoadElementExtensions(buffer); @@ -39,7 +39,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ResourceCollectionInfo collection) { - Debug.Assert(collection != null); + Debug.Assert(collection is not null); SyndicationFeedFormatter.CloseBuffer(buffer, writer); collection.LoadElementExtensions(buffer); @@ -47,7 +47,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, Workspace workspace) { - Debug.Assert(workspace != null); + Debug.Assert(workspace is not null); SyndicationFeedFormatter.CloseBuffer(buffer, writer); workspace.LoadElementExtensions(buffer); @@ -55,7 +55,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -66,7 +66,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories) { - if (inlineCategories == null) + if (inlineCategories is null) { throw new ArgumentNullException(nameof(inlineCategories)); } @@ -76,7 +76,7 @@ protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inl protected static ResourceCollectionInfo CreateCollection(Workspace workspace) { - if (workspace == null) + if (workspace is null) { throw new ArgumentNullException(nameof(workspace)); } @@ -96,7 +96,7 @@ protected static ReferencedCategoriesDocument CreateReferencedCategories(Resourc protected static Workspace CreateWorkspace(ServiceDocument document) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -106,7 +106,7 @@ protected static Workspace CreateWorkspace(ServiceDocument document) protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize) { - if (categories == null) + if (categories is null) { throw new ArgumentNullException(nameof(categories)); } @@ -116,7 +116,7 @@ protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -126,7 +126,7 @@ protected static void LoadElementExtensions(XmlReader reader, ResourceCollection protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize) { - if (workspace == null) + if (workspace is null) { throw new ArgumentNullException(nameof(workspace)); } @@ -136,7 +136,7 @@ protected static void LoadElementExtensions(XmlReader reader, Workspace workspac protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -146,7 +146,7 @@ protected static void LoadElementExtensions(XmlReader reader, ServiceDocument do protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -156,7 +156,7 @@ protected static bool TryParseAttribute(string name, string ns, string value, Se protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -166,7 +166,7 @@ protected static bool TryParseAttribute(string name, string ns, string value, Re protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version) { - if (categories == null) + if (categories is null) { throw new ArgumentNullException(nameof(categories)); } @@ -176,7 +176,7 @@ protected static bool TryParseAttribute(string name, string ns, string value, Ca protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version) { - if (workspace == null) + if (workspace is null) { throw new ArgumentNullException(nameof(workspace)); } @@ -186,7 +186,7 @@ protected static bool TryParseAttribute(string name, string ns, string value, Wo protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -196,7 +196,7 @@ protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo c protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -206,7 +206,7 @@ protected static bool TryParseElement(XmlReader reader, ServiceDocument document protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version) { - if (workspace == null) + if (workspace is null) { throw new ArgumentNullException(nameof(workspace)); } @@ -216,7 +216,7 @@ protected static bool TryParseElement(XmlReader reader, Workspace workspace, str protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version) { - if (categories == null) + if (categories is null) { throw new ArgumentNullException(nameof(categories)); } @@ -226,7 +226,7 @@ protected static bool TryParseElement(XmlReader reader, CategoriesDocument categ protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -236,7 +236,7 @@ protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version) { - if (workspace == null) + if (workspace is null) { throw new ArgumentNullException(nameof(workspace)); } @@ -246,7 +246,7 @@ protected static void WriteAttributeExtensions(XmlWriter writer, Workspace works protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -256,7 +256,7 @@ protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollect protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories, string version) { - if (categories == null) + if (categories is null) { throw new ArgumentNullException(nameof(categories)); } @@ -266,7 +266,7 @@ protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocum protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document, string version) { - if (document == null) + if (document is null) { throw new ArgumentNullException(nameof(document)); } @@ -276,7 +276,7 @@ protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument d protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace, string version) { - if (workspace == null) + if (workspace is null) { throw new ArgumentNullException(nameof(workspace)); } @@ -286,7 +286,7 @@ protected static void WriteElementExtensions(XmlWriter writer, Workspace workspa protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { - if (collection == null) + if (collection is null) { throw new ArgumentNullException(nameof(collection)); } @@ -296,7 +296,7 @@ protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectio protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories, string version) { - if (categories == null) + if (categories is null) { throw new ArgumentNullException(nameof(categories)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs index f3df2e2b9e497b..c34a502b75fb2b 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs @@ -28,7 +28,7 @@ public SyndicationCategory(string name, string scheme, string label) protected SyndicationCategory(SyndicationCategory source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs index 52e281bf79a704..56415f22c15614 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs @@ -69,7 +69,7 @@ public static XmlSyndicationContent CreateXmlContent(object xmlSerializerObject, public void WriteTo(XmlWriter writer, string outerElementName, string outerElementNamespace) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } @@ -80,7 +80,7 @@ public void WriteTo(XmlWriter writer, string outerElementName, string outerEleme writer.WriteStartElement(outerElementName, outerElementNamespace); writer.WriteAttributeString(Atom10Constants.TypeTag, string.Empty, Type); - if (_attributeExtensions != null) + if (_attributeExtensions is not null) { foreach (XmlQualifiedName key in _attributeExtensions.Keys) { @@ -98,12 +98,12 @@ public void WriteTo(XmlWriter writer, string outerElementName, string outerEleme internal void CopyAttributeExtensions(SyndicationContent source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (source._attributeExtensions != null) + if (source._attributeExtensions is not null) { foreach (XmlQualifiedName key in source._attributeExtensions.Keys) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs index 699b1d2c1b9463..d868684d9948eb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs @@ -21,7 +21,7 @@ public class SyndicationElementExtension public SyndicationElementExtension(XmlReader xmlReader) { - if (xmlReader == null) + if (xmlReader is null) { throw new ArgumentNullException(nameof(xmlReader)); } @@ -57,7 +57,7 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { - if (dataContractExtension == null) + if (dataContractExtension is null) { throw new ArgumentNullException(nameof(dataContractExtension)); } @@ -66,7 +66,7 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje throw new ArgumentException(SR.OuterNameOfElementExtensionEmpty, nameof(outerName)); } - if (dataContractSerializer == null) + if (dataContractSerializer is null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } @@ -78,12 +78,12 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje public SyndicationElementExtension(object xmlSerializerExtension, XmlSerializer serializer) { - if (xmlSerializerExtension == null) + if (xmlSerializerExtension is null) { throw new ArgumentNullException(nameof(xmlSerializerExtension)); } - if (serializer == null) + if (serializer is null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } @@ -103,7 +103,7 @@ public string OuterName { get { - if (_outerName == null) + if (_outerName is null) { EnsureOuterNameAndNs(); } @@ -116,7 +116,7 @@ public string OuterNamespace { get { - if (_outerName == null) + if (_outerName is null) { EnsureOuterNameAndNs(); } @@ -129,12 +129,12 @@ public string OuterNamespace public TExtension GetObject(XmlObjectSerializer serializer) { - if (serializer == null) + if (serializer is null) { throw new ArgumentNullException(nameof(serializer)); } - if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) + if (_extensionData is not null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; } @@ -146,12 +146,12 @@ public TExtension GetObject(XmlObjectSerializer serializer) public TExtension GetObject(XmlSerializer serializer) { - if (serializer == null) + if (serializer is null) { throw new ArgumentNullException(nameof(serializer)); } - if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) + if (_extensionData is not null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; } @@ -181,12 +181,12 @@ public XmlReader GetReader() public void WriteTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (_extensionDataWriter != null) + if (_extensionDataWriter is not null) { _extensionDataWriter.WriteTo(writer); } @@ -201,7 +201,7 @@ public void WriteTo(XmlWriter writer) private void EnsureBuffer() { - if (_buffer == null) + if (_buffer is null) { _buffer = new XmlBuffer(int.MaxValue); using (XmlDictionaryWriter writer = _buffer.OpenSection(XmlDictionaryReaderQuotas.Max)) @@ -218,7 +218,7 @@ private void EnsureBuffer() private void EnsureOuterNameAndNs() { - Debug.Assert(_extensionDataWriter != null, "outer name is null only for datacontract and xmlserializer cases"); + Debug.Assert(_extensionDataWriter is not null, "outer name is null only for datacontract and xmlserializer cases"); _extensionDataWriter.ComputeOuterNameAndNs(out _outerName, out _outerNamespace); } @@ -233,7 +233,7 @@ private class ExtensionDataWriter public ExtensionDataWriter(object extensionData, XmlObjectSerializer dataContractSerializer, string outerName, string outerNamespace) { - Debug.Assert(extensionData != null && dataContractSerializer != null, "null check"); + Debug.Assert(extensionData is not null && dataContractSerializer is not null, "null check"); _dataContractSerializer = dataContractSerializer; _extensionData = extensionData; _outerName = outerName; @@ -242,22 +242,22 @@ public ExtensionDataWriter(object extensionData, XmlObjectSerializer dataContrac public ExtensionDataWriter(object extensionData, XmlSerializer serializer) { - Debug.Assert(extensionData != null && serializer != null, "null check"); + Debug.Assert(extensionData is not null && serializer is not null, "null check"); _xmlSerializer = serializer; _extensionData = extensionData; } public void WriteTo(XmlWriter writer) { - if (_xmlSerializer != null) + if (_xmlSerializer is not null) { - Debug.Assert((_dataContractSerializer == null && _outerName == null && _outerNamespace == null), "Xml serializer cannot have outer name, ns"); + Debug.Assert((_dataContractSerializer is null && _outerName is null && _outerNamespace is null), "Xml serializer cannot have outer name, ns"); _xmlSerializer.Serialize(writer, _extensionData); } else { - Debug.Assert(_xmlSerializer == null, "Xml serializer cannot be configured"); - if (_outerName != null) + Debug.Assert(_xmlSerializer is null, "Xml serializer cannot be configured"); + if (_outerName is not null) { writer.WriteStartElement(_outerName, _outerNamespace); _dataContractSerializer.WriteObjectContent(writer, _extensionData); @@ -272,13 +272,13 @@ public void WriteTo(XmlWriter writer) internal void ComputeOuterNameAndNs(out string name, out string ns) { - Debug.Assert(_outerName == null, "All callers of this function should already check for a null outer name."); - if (_dataContractSerializer != null) + Debug.Assert(_outerName is null, "All callers of this function should already check for a null outer name."); + if (_dataContractSerializer is not null) { - Debug.Assert(_xmlSerializer == null, "only one of xmlserializer or datacontract serializer can be present"); + Debug.Assert(_xmlSerializer is null, "only one of xmlserializer or datacontract serializer can be present"); XsdDataContractExporter dcExporter = new XsdDataContractExporter(); XmlQualifiedName qName = dcExporter.GetRootElementName(_extensionData.GetType()); - if (qName != null) + if (qName is not null) { name = qName.Name; ns = qName.Namespace; @@ -291,10 +291,10 @@ internal void ComputeOuterNameAndNs(out string name, out string ns) } else { - Debug.Assert(_dataContractSerializer == null, "only one of xmlserializer or datacontract serializer can be present"); + Debug.Assert(_dataContractSerializer is null, "only one of xmlserializer or datacontract serializer can be present"); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(_extensionData.GetType()); - if (typeMapping != null && !string.IsNullOrEmpty(typeMapping.ElementName)) + if (typeMapping is not null && !string.IsNullOrEmpty(typeMapping.ElementName)) { name = typeMapping.ElementName; ns = typeMapping.Namespace; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs index 49cf23de699ef2..2f42a25abbd099 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs @@ -22,7 +22,7 @@ internal SyndicationElementExtensionCollection() : this((XmlBuffer)null) internal SyndicationElementExtensionCollection(XmlBuffer buffer) : base() { _buffer = buffer; - if (_buffer != null) + if (_buffer is not null) { PopulateElements(); } @@ -63,12 +63,12 @@ public void Add(object dataContractExtension, DataContractSerializer serializer) public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { - if (dataContractExtension == null) + if (dataContractExtension is null) { throw new ArgumentNullException(nameof(dataContractExtension)); } - if (dataContractSerializer == null) + if (dataContractSerializer is null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } @@ -77,12 +77,12 @@ public void Add(string outerName, string outerNamespace, object dataContractExte public void Add(object xmlSerializerExtension, XmlSerializer serializer) { - if (xmlSerializerExtension == null) + if (xmlSerializerExtension is null) { throw new ArgumentNullException(nameof(xmlSerializerExtension)); } - if (serializer == null) + if (serializer is null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } @@ -91,7 +91,7 @@ public void Add(object xmlSerializerExtension, XmlSerializer serializer) public void Add(XmlReader xmlReader) { - if (xmlReader == null) + if (xmlReader is null) { throw new ArgumentNullException(nameof(xmlReader)); } @@ -114,7 +114,7 @@ public Collection ReadElementExtensions(string extension public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { - if (serializer == null) + if (serializer is null) { throw new ArgumentNullException(nameof(serializer)); } @@ -124,7 +124,7 @@ public Collection ReadElementExtensions(string extension public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlSerializer serializer) { - if (serializer == null) + if (serializer is null) { throw new ArgumentNullException(nameof(serializer)); } @@ -134,14 +134,14 @@ public Collection ReadElementExtensions(string extension internal void WriteTo(XmlWriter writer, Func shouldSkipElement) { - if (_buffer != null) + if (_buffer is not null) { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); while (reader.IsStartElement()) { - if (shouldSkipElement != null && shouldSkipElement(reader.LocalName, reader.NamespaceURI)) + if (shouldSkipElement is not null && shouldSkipElement(reader.LocalName, reader.NamespaceURI)) { reader.Skip(); continue; @@ -170,7 +170,7 @@ protected override void ClearItems() protected override void InsertItem(int index, SyndicationElementExtension item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -193,7 +193,7 @@ protected override void RemoveItem(int index) protected override void SetItem(int index, SyndicationElementExtension item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -205,7 +205,7 @@ protected override void SetItem(int index, SyndicationElementExtension item) private XmlBuffer GetOrCreateBufferOverExtensions() { - if (_buffer != null) + if (_buffer is not null) { return _buffer; } @@ -248,9 +248,9 @@ private Collection ReadExtensions(string extensionName, throw new ArgumentException(SR.ExtensionNameNotSpecified); } - Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied"); + Debug.Assert((dcSerializer is null) != (xmlSerializer is null), "exactly one serializer should be supplied"); // normalize the null and empty namespace - if (extensionNamespace == null) + if (extensionNamespace is null) { extensionNamespace = string.Empty; } @@ -261,7 +261,7 @@ private Collection ReadExtensions(string extensionName, { continue; } - if (dcSerializer != null) + if (dcSerializer is not null) { results.Add(this[i].GetObject(dcSerializer)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs index 2ba333b92c9173..d984cb3aa990d8 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs @@ -50,15 +50,15 @@ public SyndicationFeed(string title, string description, Uri feedAlternateLink, public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime, IEnumerable items) { - if (title != null) + if (title is not null) { Title = new TextSyndicationContent(title); } - if (description != null) + if (description is not null) { Description = new TextSyndicationContent(description); } - if (feedAlternateLink != null) + if (feedAlternateLink is not null) { Links.Add(SyndicationLink.CreateAlternateLink(feedAlternateLink)); } @@ -69,7 +69,7 @@ public SyndicationFeed(string title, string description, Uri feedAlternateLink, protected SyndicationFeed(SyndicationFeed source, bool cloneItems) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -154,7 +154,7 @@ public DateTimeOffset LastUpdatedTime { get { - if (LastUpdatedTimeException != null) + if (LastUpdatedTimeException is not null) { throw LastUpdatedTimeException; } @@ -205,7 +205,7 @@ public Collection SkipHours { get { - if (InternalSkipHours == null) + if (InternalSkipHours is null) { var skipHours = new Collection(); TryReadSkipHoursFromExtension(ElementExtensions, skipHours); @@ -222,7 +222,7 @@ public Collection SkipDays { get { - if (InternalSkipDays == null) + if (InternalSkipDays is null) { var skipDays = new Collection(); TryReadSkipDaysFromExtension(ElementExtensions, skipDays); @@ -246,7 +246,7 @@ private SyndicationLink TryReadDocumentationFromExtension(SyndicationElementExte SyndicationElementExtension documentationElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.DocumentationTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); - if (documentationElement == null) + if (documentationElement is null) return null; using (XmlReader reader = documentationElement.GetReader()) @@ -261,7 +261,7 @@ private SyndicationLink TryReadDocumentationFromExtension(SyndicationElementExte SyndicationElementExtension timeToLiveElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.TimeToLiveTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); - if (timeToLiveElement == null) + if (timeToLiveElement is null) return null; using (XmlReader reader = timeToLiveElement.GetReader()) @@ -290,7 +290,7 @@ private void TryReadSkipHoursFromExtension(SyndicationElementExtensionCollection SyndicationElementExtension skipHoursElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.SkipHoursTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); - if (skipHoursElement == null) + if (skipHoursElement is null) return; using (XmlReader reader = skipHoursElement.GetReader()) @@ -324,7 +324,7 @@ private void TryReadSkipDaysFromExtension(SyndicationElementExtensionCollection SyndicationElementExtension skipDaysElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.SkipDaysTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); - if (skipDaysElement == null) + if (skipDaysElement is null) return; using (XmlReader reader = skipDaysElement.GetReader()) @@ -360,7 +360,7 @@ private SyndicationTextInput TryReadTextInputFromExtension(SyndicationElementExt SyndicationElementExtension textInputElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.TextInputTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); - if (textInputElement == null) + if (textInputElement is null) return null; var textInput = new SyndicationTextInput(); @@ -404,14 +404,14 @@ private SyndicationTextInput TryReadTextInputFromExtension(SyndicationElementExt private static bool IsValidTextInput(SyndicationTextInput textInput) { // All textInput items are required, we check if all items were instantiated. - return textInput.Description != null && textInput.Title != null && textInput.Name != null && textInput.Link != null; + return textInput.Description is not null && textInput.Title is not null && textInput.Name is not null && textInput.Link is not null; } public static SyndicationFeed Load(XmlReader reader) => Load(reader); public static TSyndicationFeed Load(XmlReader reader) where TSyndicationFeed : SyndicationFeed, new() { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -503,19 +503,19 @@ private bool ShouldSkipWritingElements(string localName, string ns) switch (localName) { case Rss20Constants.DocumentationTag: - return InternalDocumentation != null; + return InternalDocumentation is not null; case Rss20Constants.TimeToLiveTag: - return InternalTimeToLive != null; + return InternalTimeToLive is not null; case Rss20Constants.TextInputTag: - return InternalTextInput != null; + return InternalTextInput is not null; case Rss20Constants.SkipHoursTag: - return InternalSkipHours != null; + return InternalSkipHours is not null; case Rss20Constants.SkipDaysTag: - return InternalSkipDays != null; + return InternalSkipDays is not null; } } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs index f4dbc2eb004f0c..06e06a7d1dfed8 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs @@ -55,7 +55,7 @@ private bool NotImplementedDateTimeParser(XmlDateTimeData XmlDateTimeData, out D protected internal static SyndicationCategory CreateCategory(SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -65,7 +65,7 @@ protected internal static SyndicationCategory CreateCategory(SyndicationFeed fee protected internal static SyndicationCategory CreateCategory(SyndicationItem item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -75,7 +75,7 @@ protected internal static SyndicationCategory CreateCategory(SyndicationItem ite protected internal static SyndicationItem CreateItem(SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -85,7 +85,7 @@ protected internal static SyndicationItem CreateItem(SyndicationFeed feed) protected internal static SyndicationLink CreateLink(SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -95,7 +95,7 @@ protected internal static SyndicationLink CreateLink(SyndicationFeed feed) protected internal static SyndicationLink CreateLink(SyndicationItem item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -105,7 +105,7 @@ protected internal static SyndicationLink CreateLink(SyndicationItem item) protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -115,7 +115,7 @@ protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed) protected internal static SyndicationPerson CreatePerson(SyndicationItem item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -125,7 +125,7 @@ protected internal static SyndicationPerson CreatePerson(SyndicationItem item) protected internal static void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -135,7 +135,7 @@ protected internal static void LoadElementExtensions(XmlReader reader, Syndicati protected internal static void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -145,7 +145,7 @@ protected internal static void LoadElementExtensions(XmlReader reader, Syndicati protected internal static void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize) { - if (category == null) + if (category is null) { throw new ArgumentNullException(nameof(category)); } @@ -155,7 +155,7 @@ protected internal static void LoadElementExtensions(XmlReader reader, Syndicati protected internal static void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize) { - if (link == null) + if (link is null) { throw new ArgumentNullException(nameof(link)); } @@ -165,7 +165,7 @@ protected internal static void LoadElementExtensions(XmlReader reader, Syndicati protected internal static void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize) { - if (person == null) + if (person is null) { throw new ArgumentNullException(nameof(person)); } @@ -175,7 +175,7 @@ protected internal static void LoadElementExtensions(XmlReader reader, Syndicati protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -189,7 +189,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -203,7 +203,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version) { - if (category == null) + if (category is null) { throw new ArgumentNullException(nameof(category)); } @@ -217,7 +217,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version) { - if (link == null) + if (link is null) { throw new ArgumentNullException(nameof(link)); } @@ -231,7 +231,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version) { - if (person == null) + if (person is null) { throw new ArgumentNullException(nameof(person)); } @@ -250,7 +250,7 @@ protected internal static bool TryParseContent(XmlReader reader, SyndicationItem protected internal static bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -260,7 +260,7 @@ protected internal static bool TryParseElement(XmlReader reader, SyndicationFeed protected internal static bool TryParseElement(XmlReader reader, SyndicationItem item, string version) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -270,7 +270,7 @@ protected internal static bool TryParseElement(XmlReader reader, SyndicationItem protected internal static bool TryParseElement(XmlReader reader, SyndicationCategory category, string version) { - if (category == null) + if (category is null) { throw new ArgumentNullException(nameof(category)); } @@ -280,7 +280,7 @@ protected internal static bool TryParseElement(XmlReader reader, SyndicationCate protected internal static bool TryParseElement(XmlReader reader, SyndicationLink link, string version) { - if (link == null) + if (link is null) { throw new ArgumentNullException(nameof(link)); } @@ -290,7 +290,7 @@ protected internal static bool TryParseElement(XmlReader reader, SyndicationLink protected internal static bool TryParseElement(XmlReader reader, SyndicationPerson person, string version) { - if (person == null) + if (person is null) { throw new ArgumentNullException(nameof(person)); } @@ -300,7 +300,7 @@ protected internal static bool TryParseElement(XmlReader reader, SyndicationPers protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed, string version) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -310,7 +310,7 @@ protected internal static void WriteAttributeExtensions(XmlWriter writer, Syndic protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item, string version) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -320,7 +320,7 @@ protected internal static void WriteAttributeExtensions(XmlWriter writer, Syndic protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category, string version) { - if (category == null) + if (category is null) { throw new ArgumentNullException(nameof(category)); } @@ -330,7 +330,7 @@ protected internal static void WriteAttributeExtensions(XmlWriter writer, Syndic protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version) { - if (link == null) + if (link is null) { throw new ArgumentNullException(nameof(link)); } @@ -340,7 +340,7 @@ protected internal static void WriteAttributeExtensions(XmlWriter writer, Syndic protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person, string version) { - if (person == null) + if (person is null) { throw new ArgumentNullException(nameof(person)); } @@ -350,7 +350,7 @@ protected internal static void WriteAttributeExtensions(XmlWriter writer, Syndic protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed, string version) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -360,7 +360,7 @@ protected internal static void WriteElementExtensions(XmlWriter writer, Syndicat protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationItem item, string version) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -370,7 +370,7 @@ protected internal static void WriteElementExtensions(XmlWriter writer, Syndicat protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationCategory category, string version) { - if (category == null) + if (category is null) { throw new ArgumentNullException(nameof(category)); } @@ -380,7 +380,7 @@ protected internal static void WriteElementExtensions(XmlWriter writer, Syndicat protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationLink link, string version) { - if (link == null) + if (link is null) { throw new ArgumentNullException(nameof(link)); } @@ -390,7 +390,7 @@ protected internal static void WriteElementExtensions(XmlWriter writer, Syndicat protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationPerson person, string version) { - if (person == null) + if (person is null) { throw new ArgumentNullException(nameof(person)); } @@ -467,7 +467,7 @@ internal static bool DefaultUriParser(XmlUriData XmlUriData, out Uri uri) internal static void CloseBuffer(XmlBuffer buffer, XmlDictionaryWriter extWriter) { - if (buffer == null) + if (buffer is null) { return; } @@ -478,7 +478,7 @@ internal static void CloseBuffer(XmlBuffer buffer, XmlDictionaryWriter extWriter internal static void CreateBufferIfRequiredAndWriteNode(ref XmlBuffer buffer, ref XmlDictionaryWriter extWriter, XmlReader reader, int maxExtensionSize) { - if (buffer == null) + if (buffer is null) { buffer = new XmlBuffer(maxExtensionSize); extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); @@ -501,7 +501,7 @@ internal static SyndicationFeed CreateFeedInstance(Type feedType) internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed) { - if (feed == null) + if (feed is null) { throw new ArgumentNullException(nameof(feed)); } @@ -512,7 +512,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item) { - Debug.Assert(item != null); + Debug.Assert(item is not null); CloseBuffer(buffer, writer); item.LoadElementExtensions(buffer); @@ -520,7 +520,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category) { - Debug.Assert(category != null); + Debug.Assert(category is not null); CloseBuffer(buffer, writer); category.LoadElementExtensions(buffer); @@ -528,7 +528,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link) { - Debug.Assert(link != null); + Debug.Assert(link is not null); CloseBuffer(buffer, writer); link.LoadElementExtensions(buffer); @@ -536,7 +536,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person) { - Debug.Assert(person != null); + Debug.Assert(person is not null); CloseBuffer(buffer, writer); person.LoadElementExtensions(buffer); @@ -544,7 +544,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void MoveToStartElement(XmlReader reader) { - Debug.Assert(reader != null, "reader != null"); + Debug.Assert(reader is not null, "reader is not null"); if (!reader.IsStartElement()) { XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader.CreateDictionaryReader(reader)); @@ -555,7 +555,7 @@ internal static void MoveToStartElement(XmlReader reader) private static T GetNonNullValue(T value, string errorMsg) { - if (value == null) + if (value is null) { throw new InvalidOperationException(errorMsg); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs index 4370ec9d8df246..9d24e18e69462f 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs @@ -29,18 +29,18 @@ public SyndicationItem(string title, string content, Uri itemAlternateLink) } public SyndicationItem(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) - : this(title, (content != null) ? new TextSyndicationContent(content) : null, itemAlternateLink, id, lastUpdatedTime) + : this(title, (content is not null) ? new TextSyndicationContent(content) : null, itemAlternateLink, id, lastUpdatedTime) { } public SyndicationItem(string title, SyndicationContent content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) { - if (title != null) + if (title is not null) { Title = new TextSyndicationContent(title); } Content = content; - if (itemAlternateLink != null) + if (itemAlternateLink is not null) { Links.Add(SyndicationLink.CreateAlternateLink(itemAlternateLink)); } @@ -50,7 +50,7 @@ public SyndicationItem(string title, SyndicationContent content, Uri itemAlterna protected SyndicationItem(SyndicationItem source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -58,14 +58,14 @@ protected SyndicationItem(SyndicationItem source) _extensions = source._extensions.Clone(); _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); - Content = (source.Content != null) ? source.Content.Clone() : null; + Content = (source.Content is not null) ? source.Content.Clone() : null; _contributors = FeedUtils.ClonePersons(source._contributors); Copyright = FeedUtils.CloneTextContent(source.Copyright); Id = source.Id; _lastUpdatedTime = source._lastUpdatedTime; _links = FeedUtils.CloneLinks(source._links); _publishDate = source._publishDate; - if (source.SourceFeed != null) + if (source.SourceFeed is not null) { SourceFeed = source.SourceFeed.Clone(false); SourceFeed.Items = new Collection(); @@ -108,7 +108,7 @@ public DateTimeOffset LastUpdatedTime { get { - if (LastUpdatedTimeException != null) + if (LastUpdatedTimeException is not null) { throw LastUpdatedTimeException; } @@ -133,7 +133,7 @@ public DateTimeOffset PublishDate { get { - if (PublishDateException != null) + if (PublishDateException is not null) { throw PublishDateException; } @@ -157,7 +157,7 @@ public DateTimeOffset PublishDate public static TSyndicationItem Load(XmlReader reader) where TSyndicationItem : SyndicationItem, new() { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -181,7 +181,7 @@ public DateTimeOffset PublishDate public void AddPermalink(Uri permalink) { - if (permalink == null) + if (permalink is null) { throw new ArgumentNullException(nameof(permalink)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs index b9fc1f4ce7c513..522d6dbb6df6b8 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs @@ -37,7 +37,7 @@ public SyndicationLink() : this(null, null, null, null, 0) protected SyndicationLink(SyndicationLink source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } @@ -108,13 +108,13 @@ public static SyndicationLink CreateSelfLink(Uri uri, string mediaType) public Uri GetAbsoluteUri() { - if (Uri != null) + if (Uri is not null) { if (Uri.IsAbsoluteUri) { return Uri; } - else if (BaseUri != null) + else if (BaseUri is not null) { return new Uri(BaseUri, Uri); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs index 5239fd9d55a01f..cc76fb2bb6d95f 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs @@ -29,7 +29,7 @@ public SyndicationPerson(string email, string name, string uri) protected SyndicationPerson(SyndicationPerson source) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs index 0a07ce488bbc5e..24ea6f1f31f3cb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs @@ -28,7 +28,7 @@ public TextSyndicationContent(string text, TextSyndicationContentKind textKind) protected TextSyndicationContent(TextSyndicationContent source) : base(source) { - Debug.Assert(source != null, "The base constructor already checks if source is valid."); + Debug.Assert(source is not null, "The base constructor already checks if source is valid."); Text = source.Text; _textKind = source._textKind; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs index a8527be8e514ac..65d2b1eef91f01 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs @@ -19,7 +19,7 @@ public UrlSyndicationContent(Uri url, string mediaType) : base() protected UrlSyndicationContent(UrlSyndicationContent source) : base(source) { - Debug.Assert(source != null, "The base constructor already checks if source is valid."); + Debug.Assert(source is not null, "The base constructor already checks if source is valid."); Url = source.Url; _mediaType = source._mediaType; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs index c4611820d67915..6332f5c5e7af5d 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs @@ -16,14 +16,14 @@ public Workspace() { } - public Workspace(string title, IEnumerable collections) : this((title != null) ? new TextSyndicationContent(title) : null, collections) + public Workspace(string title, IEnumerable collections) : this((title is not null) ? new TextSyndicationContent(title) : null, collections) { } public Workspace(TextSyndicationContent title, IEnumerable collections) { Title = title; - if (collections != null) + if (collections is not null) { _collections = new NullNotAllowedCollection(); foreach (ResourceCollectionInfo collection in collections) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs index a4f5139a95dd48..df268af8751ff7 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs @@ -19,7 +19,7 @@ public class XmlSyndicationContent : SyndicationContent // Reader must be positioned at an element public XmlSyndicationContent(XmlReader reader) { - if (reader == null) + if (reader is null) { throw new ArgumentNullException(nameof(reader)); } @@ -73,7 +73,7 @@ public XmlSyndicationContent(string type, SyndicationElementExtension extension) protected XmlSyndicationContent(XmlSyndicationContent source) : base(source) { - Debug.Assert(source != null, "The base constructor already checks if source is valid."); + Debug.Assert(source is not null, "The base constructor already checks if source is valid."); _contentBuffer = source._contentBuffer; Extension = source.Extension; _type = source._type; @@ -95,17 +95,17 @@ public XmlDictionaryReader GetReaderAtContent() public TContent ReadContent(XmlObjectSerializer dataContractSerializer) { - if (dataContractSerializer == null) + if (dataContractSerializer is null) { dataContractSerializer = new DataContractSerializer(typeof(TContent)); } - if (Extension != null) + if (Extension is not null) { return Extension.GetObject(dataContractSerializer); } else { - Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null"); + Debug.Assert(_contentBuffer is not null, "contentBuffer cannot be null"); using (XmlDictionaryReader reader = _contentBuffer.GetReader(0)) { // skip past the content element @@ -117,17 +117,17 @@ public TContent ReadContent(XmlObjectSerializer dataContractSerializer public TContent ReadContent(XmlSerializer serializer) { - if (serializer == null) + if (serializer is null) { serializer = new XmlSerializer(typeof(TContent)); } - if (Extension != null) + if (Extension is not null) { return Extension.GetObject(serializer); } else { - Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null"); + Debug.Assert(_contentBuffer is not null, "contentBuffer cannot be null"); using (XmlDictionaryReader reader = _contentBuffer.GetReader(0)) { // skip past the content element @@ -140,18 +140,18 @@ public TContent ReadContent(XmlSerializer serializer) // does not write start element or type attribute, writes other attributes and rest of content protected override void WriteContentsTo(XmlWriter writer) { - if (writer == null) + if (writer is null) { throw new ArgumentNullException(nameof(writer)); } - if (Extension != null) + if (Extension is not null) { Extension.WriteTo(writer); } else { - Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null"); + Debug.Assert(_contentBuffer is not null, "contentBuffer cannot be null"); using (XmlDictionaryReader reader = _contentBuffer.GetReader(0)) { reader.MoveToStartElement(); @@ -169,7 +169,7 @@ protected override void WriteContentsTo(XmlWriter writer) private void EnsureContentBuffer() { - if (_contentBuffer == null) + if (_contentBuffer is null) { XmlBuffer tmp = new XmlBuffer(int.MaxValue); using (XmlDictionaryWriter writer = tmp.OpenSection(XmlDictionaryReaderQuotas.Max)) diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs index f4ef7e7467f4a5..07403eac4e46a7 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs @@ -241,7 +241,7 @@ public virtual EventLog EventLog { get { - if (_eventLog == null) + if (_eventLog is null) { _eventLog = new EventLog("Application"); _eventLog.Source = ServiceName; @@ -285,7 +285,7 @@ public string ServiceName internal static bool ValidServiceName(string serviceName) { - if (serviceName == null) + if (serviceName is null) return false; // not too long and check for empty name as well. @@ -591,7 +591,7 @@ protected virtual void OnCustomCommand(int command) /// public static unsafe void Run(ServiceBase[] services) { - if (services == null || services.Length == 0) + if (services is null || services.Length == 0) throw new ArgumentException(SR.NoServices); IntPtr entriesPointer = Marshal.AllocHGlobal(checked((services.Length + 1) * sizeof(SERVICE_TABLE_ENTRY))); @@ -619,7 +619,7 @@ public static unsafe void Run(ServiceBase[] services) foreach (ServiceBase service in services) { - if (service._startFailedException != null) + if (service._startFailedException is not null) { // Propagate exceptions throw during OnStart. // Note that this same exception is also thrown from ServiceMainCallback @@ -666,7 +666,7 @@ public static unsafe void Run(ServiceBase[] services) /// public static void Run(ServiceBase service) { - if (service == null) + if (service is null) throw new ArgumentException(SR.NoServices); Run(new ServiceBase[] { service }); @@ -930,7 +930,7 @@ public unsafe void ServiceMainCallback(int argCount, IntPtr argPointer) ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServiceQueuedMainCallback!), args); _startCompletedSignal.WaitOne(); - if (_startFailedException != null) + if (_startFailedException is not null) { // Inform SCM that the service could not be started successfully. // (Unless the service has already provided another failure exit code) 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 fdb4d99d19df88..a51c507fbe5f85 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -139,7 +139,7 @@ public string DisplayName } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (string.Equals(value, _displayName, StringComparison.OrdinalIgnoreCase)) @@ -161,7 +161,7 @@ public ServiceController[] DependentServices { get { - if (_dependentServices == null) + if (_dependentServices is null) { using (var serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_ENUMERATE_DEPENDENTS)) { @@ -248,7 +248,7 @@ public string ServiceName } set { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (string.Equals(value, _name, StringComparison.OrdinalIgnoreCase)) @@ -272,7 +272,7 @@ public unsafe ServiceController[] ServicesDependedOn { get { - if (_servicesDependedOn != null) + if (_servicesDependedOn is not null) return _servicesDependedOn; using (var serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_QUERY_CONFIG)) @@ -302,7 +302,7 @@ public unsafe ServiceController[] ServicesDependedOn Dictionary? dependencyHash = null; char* dependencyChar = config.lpDependencies; - if (dependencyChar != null) + if (dependencyChar is not null) { // lpDependencies points to the start of multiple null-terminated strings. The list is // double-null terminated. @@ -335,7 +335,7 @@ public unsafe ServiceController[] ServicesDependedOn } } - if (dependencyHash != null) + if (dependencyHash is not null) { _servicesDependedOn = new ServiceController[dependencyHash.Count]; dependencyHash.Values.CopyTo(_servicesDependedOn, 0); @@ -438,7 +438,7 @@ private static bool CheckMachineName(string value) /// public void Close() { - if (_serviceManagerHandle != null) + if (_serviceManagerHandle is not null) { _serviceManagerHandle.Dispose(); _serviceManagerHandle = null; @@ -496,7 +496,7 @@ private unsafe void GenerateNames() // Try it as a display name string? result = GetServiceKeyName(_serviceManagerHandle, userGivenName); - if (result != null) + if (result is not null) { // Now we have both _name = result; @@ -508,7 +508,7 @@ private unsafe void GenerateNames() // Try it as a service name result = GetServiceDisplayName(_serviceManagerHandle, userGivenName); - if (result == null) + if (result is null) { throw new InvalidOperationException(SR.Format(SR.NoService, userGivenName, _machineName), new Win32Exception(Interop.Errors.ERROR_SERVICE_DOES_NOT_EXIST)); } @@ -522,7 +522,7 @@ private unsafe void GenerateNames() // We must have _name string? result = GetServiceDisplayName(_serviceManagerHandle, _name); - if (result == null) + if (result is null) { throw new InvalidOperationException(SR.Format(SR.NoService, _name, _machineName), new Win32Exception(Interop.Errors.ERROR_SERVICE_DOES_NOT_EXIST)); } @@ -625,7 +625,7 @@ private void GetDataBaseHandleWithConnectAccess() } // get a handle to SCM with connect access and store it in serviceManagerHandle field. - if (_serviceManagerHandle == null) + if (_serviceManagerHandle is null) { _serviceManagerHandle = GetDataBaseHandleWithAccess(_machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_CONNECT); } @@ -809,7 +809,7 @@ public void Start() /// Starts a service in the machine specified. public void Start(string[] args) { - if (args == null) + if (args is null) throw new ArgumentNullException(nameof(args)); using (SafeServiceHandle serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_START)) @@ -820,7 +820,7 @@ public void Start(string[] args) { for (i = 0; i < args.Length; i++) { - if (args[i] == null) + if (args[i] is null) throw new ArgumentNullException($"{nameof(args)}[{i}]", SR.ArgsCantBeNull); argPtrs[i] = Marshal.StringToHGlobalUni(args[i]); diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/SessionChangeDescription.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/SessionChangeDescription.cs index e7d83b4fe8f19e..4e8bcf5b1a9240 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/SessionChangeDescription.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/SessionChangeDescription.cs @@ -32,7 +32,7 @@ public int SessionId public override bool Equals(object? obj) { - if (obj == null || !(obj is SessionChangeDescription)) + if (obj is null || !(obj is SessionChangeDescription)) { return false; } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/Data/Tools/EncodingDataGenerator.cs b/src/libraries/System.Text.Encoding.CodePages/src/Data/Tools/EncodingDataGenerator.cs index 4bce132659d533..fe391978552c41 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/Data/Tools/EncodingDataGenerator.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/Data/Tools/EncodingDataGenerator.cs @@ -20,7 +20,7 @@ private static void Main(string[] args) try { EncodingDataGenerator edg = new EncodingDataGenerator(); - if (!edg.ParseParams(args) || edg.IanaMappings == null || edg.PreferredIANANames == null || edg.OutputDataTable == null) + if (!edg.ParseParams(args) || edg.IanaMappings is null || edg.PreferredIANANames is null || edg.OutputDataTable is null) { edg.Usage(); return; @@ -277,7 +277,7 @@ private IEnumerable> DelimitedFileRows(string path, int lineNumber = 1; string line; - for (; (line = input.ReadLine()) != null; ++lineNumber) + for (; (line = input.ReadLine()) is not null; ++lineNumber) { if (line.StartsWith(CommentIndicator) || string.IsNullOrWhiteSpace(line)) { diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs index 46c8a593d1048b..b84c81e5d0c633 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs @@ -152,14 +152,14 @@ internal unsafe struct CodePageHeader internal static Stream GetEncodingDataStream(string tableName) { - Debug.Assert(tableName != null, "table name can not be null"); + Debug.Assert(tableName is not null, "table name can not be null"); // NOTE: We must reflect on a public type that is exposed in the contract here // (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to // the right assembly. Stream? stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName); - if (stream == null) + if (stream is null) { // We can not continue if we can't get the resource. throw new InvalidOperationException(); @@ -188,7 +188,7 @@ private unsafe void LoadCodePageTables() // Look up the code page pointer private unsafe bool FindCodePage(int codePage) { - Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader"); + Debug.Assert(m_codePageHeader is not null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader"); // Loop through all of the m_pCodePageIndex[] items to find our code page byte[] codePageIndex = new byte[sizeof(CodePageIndex)]; @@ -289,10 +289,10 @@ internal static unsafe int GetCodePageByteSize(int codePage) // Allocate memory to load our code page protected unsafe byte* GetNativeMemory(int iSize) { - if (safeNativeMemoryHandle == null) + if (safeNativeMemoryHandle is null) { byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize); - Debug.Assert(pNativeMemory != null); + Debug.Assert(pNativeMemory is not null); safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory); } @@ -305,9 +305,9 @@ internal static unsafe int GetCodePageByteSize(int codePage) internal char[] GetBestFitUnicodeToBytesData() { // Read in our best fit table if necessary - if (arrayUnicodeBestFit == null) ReadBestFitTable(); + if (arrayUnicodeBestFit is null) ReadBestFitTable(); - Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit"); + Debug.Assert(arrayUnicodeBestFit is not null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit"); // Normally we don't have any best fit data. return arrayUnicodeBestFit!; @@ -316,9 +316,9 @@ internal char[] GetBestFitUnicodeToBytesData() internal char[] GetBestFitBytesToUnicodeData() { // Read in our best fit table if necessary - if (arrayBytesBestFit == null) ReadBestFitTable(); + if (arrayBytesBestFit is null) ReadBestFitTable(); - Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit"); + Debug.Assert(arrayBytesBestFit is not null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit"); // Normally we don't have any best fit data. return arrayBytesBestFit!; @@ -330,7 +330,7 @@ internal char[] GetBestFitBytesToUnicodeData() // the memory section pointer will get finalized one more time. internal unsafe void CheckMemorySection() { - if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) + if (safeNativeMemoryHandle is not null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) { LoadManagedCodePage(); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.netcoreapp.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.netcoreapp.cs index a0b19e2966d3dc..2134a629ce51ca 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.netcoreapp.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.netcoreapp.cs @@ -44,7 +44,7 @@ internal static unsafe EncodingInfo [] GetEncodings(CodePagesEncodingProvider pr string? resourceName = EncodingNLS.GetLocalizedEncodingNameResource(codePageIndex.CodePage); string? displayName = null; - if (resourceName != null && resourceName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) + if (resourceName is not null && resourceName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) { displayName = SR.GetResourceString(resourceName); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/CodePagesEncodingProvider.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/CodePagesEncodingProvider.cs index bb9f9dbf2955f6..028762a8ab7e0c 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/CodePagesEncodingProvider.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/CodePagesEncodingProvider.cs @@ -55,7 +55,7 @@ public static EncodingProvider Instance else { result = GetEncodingRare(codepage); - if (result == null) + if (result is null) return null; } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs index 00a03b3e999752..a056aefa4e1dec 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs @@ -216,7 +216,7 @@ private static object InternalSyncObject { get { - if (s_InternalSyncObject == null) + if (s_InternalSyncObject is null) { object o = new object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); @@ -232,7 +232,7 @@ protected unsafe override void ReadBestFitTable() lock (InternalSyncObject) { // If we got a best fit array already then don't do this - if (arrayUnicodeBestFit == null) + if (arrayUnicodeBestFit is null) { // // Read in Best Fit table. @@ -508,16 +508,16 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); - Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); + Debug.Assert(chars is not null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); + Debug.Assert(EncoderFallback is not null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); // Get any left over characters char charLeftOver = (char)0; - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder.charLeftOver; @@ -539,7 +539,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco if (charLeftOver > 0) { Debug.Assert(char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); - Debug.Assert(encoder != null, + Debug.Assert(encoder is not null, "[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -555,7 +555,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco // We have to use fallback method. char ch; - while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || + while ((ch = (fallbackBuffer is null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback @@ -572,10 +572,10 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco // Check for fallback, this'll catch surrogate pairs too. if (sTemp == 0 && ch != (char)0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { // Initialize the buffer - if (encoder == null) + if (encoder is null) fallbackBuffer = EncoderFallback!.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -603,13 +603,13 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); + Debug.Assert(bytes is not null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); - Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); + Debug.Assert(chars is not null, "[DBCSCodePageEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(EncoderFallback is not null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); @@ -626,7 +626,7 @@ public override unsafe int GetBytes(char* chars, int charCount, // Get any left over characters char charLeftOver = (char)0; - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), @@ -644,7 +644,7 @@ public override unsafe int GetBytes(char* chars, int charCount, // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Debug.Assert(encoder != null, + Debug.Assert(encoder is not null, "[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -657,7 +657,7 @@ public override unsafe int GetBytes(char* chars, int charCount, // Go ahead and do it, including the fallback. char ch; - while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || + while ((ch = (fallbackBuffer is null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback @@ -674,10 +674,10 @@ public override unsafe int GetBytes(char* chars, int charCount, // Check for fallback, this'll catch surrogate pairs too. if (sTemp == 0 && ch != (char)0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { // Initialize the buffer - Debug.Assert(encoder == null, + Debug.Assert(encoder is null, "[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder."); fallbackBuffer = EncoderFallback!.CreateFallbackBuffer(); fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); @@ -698,7 +698,7 @@ public override unsafe int GetBytes(char* chars, int charCount, if (bytes + 1 >= byteEnd) { // didn't use this char, we'll throw or use buffer - if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) + if (fallbackBuffer is null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)"); @@ -717,7 +717,7 @@ public override unsafe int GetBytes(char* chars, int charCount, else if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer - if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) + if (fallbackBuffer is null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)"); @@ -734,10 +734,10 @@ public override unsafe int GetBytes(char* chars, int charCount, } // encoder stuff if we have one - if (encoder != null) + if (encoder is not null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases - if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder) + if (fallbackBuffer is not null && !fallbackHelper.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; @@ -752,7 +752,7 @@ public override unsafe int GetBytes(char* chars, int charCount, public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { // Just assert, we're called internally so these should be safe, checked already - Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); + Debug.Assert(bytes is not null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); @@ -769,14 +769,14 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? base // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Debug.Assert(decoder == null || + Debug.Assert(decoder is null || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start"); DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // If we have a left over byte, use it - if (decoder != null && decoder.bLeftOver > 0) + if (decoder is not null && decoder.bLeftOver > 0) { // We have a left over byte? if (count == 0) @@ -789,7 +789,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? base } - Debug.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer is null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); @@ -814,7 +814,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? base charCount--; // We'll need a fallback - Debug.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer is null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); @@ -851,7 +851,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? base else { // No input left - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // have to flush anyway, set to unknown so we use fallback charCount++; // reallocate deallocated lead byte @@ -869,9 +869,9 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? base // Unknown and known chars already allocated, but fallbacks aren't if (c == UNKNOWN_CHAR_FLAG && iBytes != 0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -889,7 +889,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? base } // Shouldn't have anything in fallback buffer for GetChars - Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder is null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end"); @@ -901,9 +901,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); + Debug.Assert(bytes is not null, "[DBCSCodePageEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); - Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); + Debug.Assert(chars is not null, "[DBCSCodePageEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); @@ -922,14 +922,14 @@ public override unsafe int GetChars(byte* bytes, int byteCount, DecoderFallbackBuffer? fallbackBuffer = null; // Shouldn't have anything in fallback buffer for GetChars - Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder is null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // If we have a left over byte, use it - if (decoder != null && decoder.bLeftOver > 0) + if (decoder is not null && decoder.bLeftOver > 0) { // We have a left over byte? if (byteCount == 0) @@ -943,7 +943,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, // Well, we're flushing, so use '?' or fallback // fallback leftover byte - Debug.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer is null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); @@ -969,7 +969,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0) { - Debug.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer is null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); @@ -1012,7 +1012,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, else { // No input left - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // have to flush anyway, set to unknown so we use fallback c = UNKNOWN_CHAR_FLAG; @@ -1030,9 +1030,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, // See if it was unknown if (c == UNKNOWN_CHAR_FLAG && iBytes != 0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -1079,7 +1079,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, } // We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder - if (decoder != null) + if (decoder is not null) { // Clear it in case of MustFlush if (bUsedDecoder == false) @@ -1092,7 +1092,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, } // Shouldn't have anything in fallback buffer for GetChars - Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder is null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end"); @@ -1156,7 +1156,7 @@ public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) public override void Reset() { bLeftOver = 0; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs index 11e3c63e2f5c86..0db18c3b2e164c 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs @@ -51,7 +51,7 @@ private static object InternalSyncObject { get { - if (s_InternalSyncObject == null) + if (s_InternalSyncObject is null) { object o = new object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); @@ -65,13 +65,13 @@ public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallb { _oFallback = fallback; - if (_oFallback.arrayBestFit == null) + if (_oFallback.arrayBestFit is null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. - if (_oFallback.arrayBestFit == null) + if (_oFallback.arrayBestFit is null) _oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); } } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderFallbackBufferHelper.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderFallbackBufferHelper.cs index 0851a4acd7ef23..15d9e1127b4e49 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderFallbackBufferHelper.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderFallbackBufferHelper.cs @@ -22,7 +22,7 @@ public DecoderFallbackBufferHelper(DecoderFallbackBuffer? fallbackBuffer) internal unsafe void InternalReset() { - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(_fallbackBuffer is not null); byteStart = null; _fallbackBuffer!.Reset(); } @@ -43,8 +43,8 @@ internal void InternalInitialize(byte* _byteStart, char* _charEnd) // Don't touch ref chars unless we succeed internal bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { - Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(byteStart is not null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(_fallbackBuffer is not null); // See if there's a fallback character and we have an output buffer then copy our string. if (_fallbackBuffer!.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) @@ -99,8 +99,8 @@ internal bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) // array, and we might need the index, hence the byte* internal unsafe int InternalFallback(byte[] bytes, byte* pBytes) { - Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(byteStart is not null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(_fallbackBuffer is not null); // See if there's a fallback character and we have an output buffer then copy our string. if (_fallbackBuffer!.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs index 85926ad3a24206..d98ad4a276ebdc 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs @@ -50,7 +50,7 @@ internal bool InternalHasFallbackBuffer { get { - return m_fallbackBuffer != null; + return m_fallbackBuffer is not null; } } @@ -58,9 +58,9 @@ internal bool InternalHasFallbackBuffer { get { - if (m_fallbackBuffer == null) + if (m_fallbackBuffer is null) { - if (m_fallback != null) + if (m_fallback is not null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); @@ -72,7 +72,7 @@ internal bool InternalHasFallbackBuffer public override void Reset() { - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } @@ -84,7 +84,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -105,7 +105,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) @@ -129,8 +129,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -160,8 +160,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException((chars is null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -181,8 +181,8 @@ public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters - if (bytes == null || chars == null) - throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException((bytes is null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -220,8 +220,8 @@ public override unsafe void Convert(byte* bytes, int byteCount, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException(chars is null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -237,7 +237,7 @@ public override unsafe void Convert(byte* bytes, int byteCount, // It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !HasState) && - (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); + (m_fallbackBuffer is null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs index 3ae2e081079a6d..e53adff0b1bbeb 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs @@ -51,7 +51,7 @@ private static object InternalSyncObject { get { - if (s_InternalSyncObject == null) + if (s_InternalSyncObject is null) { object o = new object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); @@ -65,13 +65,13 @@ public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallb { _oFallback = fallback; - if (_oFallback.arrayBestFit == null) + if (_oFallback.arrayBestFit is null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. - if (_oFallback.arrayBestFit == null) + if (_oFallback.arrayBestFit is null) _oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs index 30a8329f34266b..8de8b026adf15d 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs @@ -31,7 +31,7 @@ public unsafe EncoderFallbackBufferHelper(EncoderFallbackBuffer? fallbackBuffer) // For example, what if someone fails a conversion and wants to reset one of our fallback buffers? internal unsafe void InternalReset() { - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(_fallbackBuffer is not null); charStart = null; bFallingBack = false; iRecursionCount = 0; @@ -53,7 +53,7 @@ internal unsafe void InternalInitialize(char* _charStart, char* _charEnd, Encode internal char InternalGetNextChar() { - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(_fallbackBuffer is not null); char ch = _fallbackBuffer!.GetNextChar(); bFallingBack = (ch != 0); if (ch == 0) iRecursionCount = 0; @@ -71,8 +71,8 @@ internal char InternalGetNextChar() internal unsafe bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart or fallback buffer - Debug.Assert(charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(charStart is not null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); + Debug.Assert(_fallbackBuffer is not null); // Get our index, remember chars was preincremented to point at next char, so have to decrement int index = (int)(chars - charStart) - 1; @@ -85,7 +85,7 @@ internal unsafe bool InternalFallback(char ch, ref char* chars) { // Nothing left in input buffer // No input, return 0 if mustflush is false - if (encoder != null && !encoder.MustFlush) + if (encoder is not null && !encoder.MustFlush) { // Done, nothing to fallback if (setEncoder) diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs index e204d344f9676d..f4fd2322cadf91 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs @@ -52,7 +52,7 @@ internal bool InternalHasFallbackBuffer { get { - return m_fallbackBuffer != null; + return m_fallbackBuffer is not null; } } @@ -60,9 +60,9 @@ internal bool InternalHasFallbackBuffer { get { - if (m_fallbackBuffer == null) + if (m_fallbackBuffer is null) { - if (m_fallback != null) + if (m_fallback is not null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); @@ -75,14 +75,14 @@ internal bool InternalHasFallbackBuffer public override void Reset() { charLeftOver = (char)0; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -107,7 +107,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count, bool public override unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) @@ -122,8 +122,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException((chars is null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -151,8 +151,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException((chars is null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -169,8 +169,8 @@ public override unsafe void Convert(char[] chars, int charIndex, int charCount, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException((chars is null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -208,8 +208,8 @@ public override unsafe void Convert(char* chars, int charCount, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -225,7 +225,7 @@ public override unsafe void Convert(char* chars, int charCount, // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (charsUsed == charCount) && (!flush || !HasState) && - (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); + (m_fallbackBuffer is null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingByteBuffer.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingByteBuffer.cs index a2a20b2984f3c4..9c165ae0fe3bf9 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingByteBuffer.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingByteBuffer.cs @@ -32,7 +32,7 @@ internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, EncoderNLS? inEncoder _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; - if (_encoder == null) + if (_encoder is null) fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); else { @@ -42,13 +42,13 @@ internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, EncoderNLS? inEncoder throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); } fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer); - fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); + fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes is not null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); - if (_bytes != null) + if (_bytes is not null) { if (_bytes >= _byteEnd - moreBytesExpected) { diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingCharBuffer.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingCharBuffer.cs index 38648d08db5331..8cacc67199efba 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingCharBuffer.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingCharBuffer.cs @@ -32,7 +32,7 @@ internal unsafe EncodingCharBuffer(EncodingNLS enc, DecoderNLS? decoder, char* c _bytes = byteStart; _byteEnd = byteStart + byteCount; - if (_decoder == null) + if (_decoder is null) _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); else _fallbackBuffer = _decoder.FallbackBuffer; @@ -47,7 +47,7 @@ internal unsafe EncodingCharBuffer(EncodingNLS enc, DecoderNLS? decoder, char* c internal unsafe bool AddChar(char ch, int numBytes) { - if (_chars != null) + if (_chars is not null) { if (_chars >= _charEnd) { @@ -149,7 +149,7 @@ internal unsafe bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) internal unsafe bool Fallback(byte[] byteBuffer) { // Do the fallback and add the data. - if (_chars != null) + if (_chars is not null) { char* pTemp = _chars; if (_fallbackBufferHelper.InternalFallback(byteBuffer, _bytes, ref _chars) == false) diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs index c2681e3a4d2e68..e862d1498f5a8b 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs @@ -48,7 +48,7 @@ protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -72,7 +72,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) public override unsafe int GetByteCount(string s) { // Validate input - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -84,7 +84,7 @@ public override unsafe int GetByteCount(string s) public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) @@ -101,8 +101,8 @@ public override unsafe int GetByteCount(char* chars, int count) public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s == null || bytes == null) - throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); + if (s is null || bytes is null) + throw new ArgumentNullException((s is null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -141,8 +141,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters - if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); + if (chars is null || bytes is null) + throw new ArgumentNullException((chars is null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -176,8 +176,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -194,7 +194,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -217,7 +217,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) @@ -233,8 +233,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -268,8 +268,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); + if (bytes is null || chars is null) + throw new ArgumentNullException(bytes is null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -286,7 +286,7 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters - if (bytes == null) + if (bytes is null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) @@ -314,9 +314,9 @@ public override Encoder GetEncoder() internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) { - if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded) + if (encoder is null || encoder.m_throwOnOverflow || nothingEncoded) { - if (encoder != null && encoder.InternalHasFallbackBuffer) + if (encoder is not null && encoder.InternalHasFallbackBuffer) encoder.FallbackBuffer.Reset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented an encoder fallback with a broken GetMaxCharCount @@ -329,9 +329,9 @@ internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) internal void ThrowCharsOverflow(DecoderNLS? decoder, bool nothingDecoded) { - if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded) + if (decoder is null || decoder.m_throwOnOverflow || nothingDecoded) { - if (decoder != null && decoder.InternalHasFallbackBuffer) + if (decoder is not null && decoder.InternalHasFallbackBuffer) decoder.FallbackBuffer.Reset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken @@ -363,10 +363,10 @@ public override string EncodingName { get { - if (_encodingName == null) + if (_encodingName is null) { _encodingName = GetLocalizedEncodingNameResource(CodePage); - if (_encodingName == null) + if (_encodingName is null) { throw new NotSupportedException( SR.Format(SR.MissingEncodingNameResource, WebName, CodePage)); @@ -380,7 +380,7 @@ public override string EncodingName // in this case. This currently returns the English name of the encoding from a // static data table. _encodingName = EncodingTable.GetEnglishNameFromCodePage(CodePage); - if (_encodingName == null) + if (_encodingName is null) { throw new NotSupportedException( SR.Format(SR.MissingEncodingNameResource, WebName, CodePage)); @@ -543,10 +543,10 @@ public override string WebName { get { - if (_webName == null) + if (_webName is null) { _webName = EncodingTable.GetWebNameFromCodePage(CodePage); - if (_webName == null) + if (_webName is null) { throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingTable.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingTable.cs index a248a9fc7e733f..953950b1386295 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingTable.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingTable.cs @@ -17,7 +17,7 @@ internal static partial class EncodingTable internal static int GetCodePageFromName(string name) { - if (name == null) + if (name is null) return 0; int codePage; diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs index 2f4042f334c561..17429c99ffe1e1 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs @@ -213,17 +213,17 @@ public override unsafe int GetBytes(char* chars, int charCount, { // Just need to ASSERT, this is called by something else internal that checked parameters already // We'll allow null bytes as a count - // Debug.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null"); + // Debug.Assert(bytes is not null, "[GB18030Encoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative"); - Debug.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null"); + Debug.Assert(chars is not null, "[GB18030Encoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Debug.Assert(EncoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(EncoderFallback is not null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; - if (encoder != null) + if (encoder is not null) charLeftOver = encoder.charLeftOver; // prepare our helpers @@ -336,7 +336,7 @@ public override unsafe int GetBytes(char* chars, int charCount, } // Do we need to flush our charLeftOver? - if ((encoder == null || encoder.MustFlush) && (charLeftOver > 0)) + if ((encoder is null || encoder.MustFlush) && (charLeftOver > 0)) { // Fall it back buffer.Fallback(charLeftOver); @@ -345,11 +345,11 @@ public override unsafe int GetBytes(char* chars, int charCount, } // Fallback stuck it in encoder if necessary, but we have to clear MustFlash cases - // (Check bytes != null, don't clear it if we're just counting) - if (encoder != null) + // (Check bytes is not null, don't clear it if we're just counting) + if (encoder is not null) { // Remember our charLeftOver - if (bytes != null) + if (bytes is not null) encoder.charLeftOver = charLeftOver; encoder.m_charsUsed = buffer.CharsUsed; @@ -399,9 +399,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, { // Just need to ASSERT, this is called by something else internal that checked parameters already // We'll allow null chars as a count - Debug.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null"); + Debug.Assert(bytes is not null, "[GB18030Encoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative"); - // Debug.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null"); + // Debug.Assert(chars is not null, "[GB18030Encoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative"); // Fix our decoder @@ -417,7 +417,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, short byte4 = -1; // See if there was anything to get out of the decoder - if (decoder != null && decoder.bLeftOver1 != -1) + if (decoder is not null && decoder.bLeftOver1 != -1) { // Need temp bytes because we can't muss up decoder byte1 = decoder.bLeftOver1; @@ -463,7 +463,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, if (!decoder.MustFlush) { // Don't stick stuff in decoder when counting - if (chars != null) + if (chars is not null) { // Don't have to flush, won't have any chars // Decoder is correct, just return @@ -659,10 +659,10 @@ public override unsafe int GetChars(byte* bytes, int byteCount, { // No room for 4 bytes, have 2 already, may be one more // Lead byte but no place to stick it - if (decoder != null && !decoder.MustFlush) + if (decoder is not null && !decoder.MustFlush) { // (make sure not to set decoder if counting, so check chars) - if (chars != null) + if (chars is not null) { // We'll be able to stick the remainder in the decoder byte1 = ch; @@ -695,11 +695,11 @@ public override unsafe int GetChars(byte* bytes, int byteCount, { // Lead byte but don't know about trail byte // (make sure not to set decoder if counting, so check bytes) - if (decoder != null && !decoder.MustFlush) + if (decoder is not null && !decoder.MustFlush) { // We'll be able to stick it in the decoder // (don't actually do it when counting though) - if (chars != null) + if (chars is not null) { byte1 = ch; byte2 = -1; @@ -723,9 +723,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, // Need to flush the decoder if necessary // (make sure not to set decoder if counting, so check bytes) - if (decoder != null) + if (decoder is not null) { - if (chars != null) + if (chars is not null) { decoder.bLeftOver1 = byte1; decoder.bLeftOver2 = byte2; @@ -801,7 +801,7 @@ public override void Reset() bLeftOver2 = -1; bLeftOver3 = -1; bLeftOver4 = -1; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs index 4c8d55e77f0e7a..8591dcc6f3e6ef 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs @@ -126,8 +126,8 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? base public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? baseEncoder) { // Allow null bytes for counting - Debug.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null"); - // Debug.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null"); + Debug.Assert(chars is not null, "[ISCIIEncoding.GetBytes]chars!=null"); + // Debug.Assert(bytes is not null, "[ISCIIEncoding.GetBytes]bytes!=null"); Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetBytes]charCount >=0"); Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetBytes]byteCount >=0"); @@ -141,7 +141,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int bool bLastVirama = false; // Use encoder info if available - if (encoder != null) + if (encoder is not null) { // Remember our old state currentCodePage = encoder.currentCodePage; @@ -261,7 +261,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int } // May need to switch back to our default code page - if (currentCodePage != _defaultCodePage && (encoder == null || encoder.MustFlush)) + if (currentCodePage != _defaultCodePage && (encoder is null || encoder.MustFlush)) { // It changed, spit out the ATR if (buffer.AddByte(ControlATR, (byte)(_defaultCodePage | ControlCodePageStart))) @@ -277,7 +277,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int // Note that we don't care about flush because Virama and code page // changes are legal at the end. // Don't set encoder if we're just counting - if (encoder != null && bytes != null) + if (encoder is not null && bytes is not null) { // Clear Encoder if necessary. if (!buffer.fallbackBufferHelper.bUsedEncoder) @@ -315,9 +315,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, { // Just need to ASSERT, this is called by something else internal that checked parameters already // Allow null chars for counting - Debug.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null"); + Debug.Assert(bytes is not null, "[ISCIIEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative"); - // Debug.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null"); + // Debug.Assert(chars is not null, "[ISCIIEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative"); // Need the ISCII Decoder @@ -334,7 +334,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char cLastCharForNoNextNukta = '\0'; // See if there's anything in our decoder - if (decoder != null) + if (decoder is not null) { currentCodePage = decoder.currentCodePage; bLastATR = decoder.bLastATR; @@ -604,7 +604,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, // If we don't have a decoder, or if we had to flush, then we need to get rid // of last ATR, LastNoNextNukta and LastDevenagariExt. - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // If these fail (because of Convert with insufficient buffer), then they'll turn off MustFlush as well. if (bLastATR) @@ -642,7 +642,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, // Remember any left over stuff // (only remember if we aren't counting) - if (decoder != null && chars != null) + if (decoder is not null && chars is not null) { // If not flushing or have state (from convert) then need to remember state if (!decoder.MustFlush || @@ -714,7 +714,7 @@ public override void Reset() { bLastVirama = false; charLeftOver = (char)0; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } @@ -754,7 +754,7 @@ public override void Reset() bLastDevenagariStressAbbr = false; cLastCharForNextNukta = '\0'; cLastCharForNoNextNukta = '\0'; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs index cc97ee3c3dab7c..8f223e89843c44 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs @@ -224,7 +224,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? base { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative"); - Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null"); + Debug.Assert(chars is not null, "[ISO2022Encoding.GetByteCount]chars is null"); // Just call GetBytes with null byte* to get count return GetBytes(chars, count, null, 0, baseEncoder); @@ -234,12 +234,12 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? baseEncoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null"); + Debug.Assert(chars is not null, "[ISO2022Encoding.GetBytes]chars is null"); Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative"); Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Debug.Assert(EncoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(EncoderFallback is not null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"); // Fix our encoder ISO2022Encoder? encoder = (ISO2022Encoder?)baseEncoder; @@ -274,7 +274,7 @@ public override unsafe int GetBytes(char* chars, int charCount, public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { // Just assert, we're called internally so these should be safe, checked already - Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null"); + Debug.Assert(bytes is not null, "[ISO2022Encoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative"); // Just call getChars with null char* to get count @@ -285,7 +285,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null"); + Debug.Assert(bytes is not null, "[ISO2022Encoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative"); Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative"); @@ -363,7 +363,7 @@ private unsafe int GetBytesCP5022xJP(char* chars, int charCount, ISO2022Modes shiftInMode = ISO2022Modes.ModeASCII; // Mode that shift in will go back to (only used by CP 50222) // Check our encoder - if (encoder != null) + if (encoder is not null) { char charLeftOver = encoder.charLeftOver; @@ -522,7 +522,7 @@ private unsafe int GetBytesCP5022xJP(char* chars, int charCount, // Switch back to ASCII if MustFlush or no encoder if (currentMode != ISO2022Modes.ModeASCII && - (encoder == null || encoder.MustFlush)) + (encoder is null || encoder.MustFlush)) { // If we're CP 50222 we may have to shift in from Katakana mode first if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana) @@ -552,7 +552,7 @@ private unsafe int GetBytesCP5022xJP(char* chars, int charCount, } // Remember our encoder state - if (bytes != null && encoder != null) + if (bytes is not null && encoder is not null) { // This is ASCII if we had to flush encoder.currentMode = currentMode; @@ -604,7 +604,7 @@ private unsafe int GetBytesCP50225KR(char* chars, int charCount, ISO2022Modes shiftOutMode = ISO2022Modes.ModeASCII; // ModeKR if already stamped lead bytes // Check our encoder - if (encoder != null) + if (encoder is not null) { // May have leftover stuff char charLeftOver = encoder.charLeftOver; @@ -686,7 +686,7 @@ private unsafe int GetBytesCP50225KR(char* chars, int charCount, // Switch back to ASCII if MustFlush or no encoder if (currentMode != ISO2022Modes.ModeASCII && - (encoder == null || encoder.MustFlush)) + (encoder is null || encoder.MustFlush)) { // Get back to ASCII to be safe. Only do it if it success. if (buffer.AddByte(SHIFT_IN)) @@ -698,7 +698,7 @@ private unsafe int GetBytesCP50225KR(char* chars, int charCount, } // Remember our encoder state - if (bytes != null && encoder != null) + if (bytes is not null && encoder is not null) { // If we didn't use the encoder, then there's no chars left over if (!buffer.fallbackBufferHelper.bUsedEncoder) @@ -752,7 +752,7 @@ private unsafe int GetBytesCP52936(char* chars, int charCount, ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Check our encoder - if (encoder != null) + if (encoder is not null) { char charLeftOver = encoder.charLeftOver; currentMode = encoder.currentMode; @@ -845,7 +845,7 @@ private unsafe int GetBytesCP52936(char* chars, int charCount, // Add ASCII shift out if we're at end of decoder if (currentMode != ISO2022Modes.ModeASCII && - (encoder == null || encoder.MustFlush)) + (encoder is null || encoder.MustFlush)) { // Need to add the ASCII mode marker // Only turn off other mode if this works @@ -858,7 +858,7 @@ private unsafe int GetBytesCP52936(char* chars, int charCount, } // Need to remember our mode - if (encoder != null && bytes != null) + if (encoder is not null && bytes is not null) { // This is ASCII if we had to flush encoder.currentMode = currentMode; @@ -887,7 +887,7 @@ private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, byte[] escapeBytes = new byte[4]; int escapeCount = 0; - if (decoder != null) + if (decoder is not null) { currentMode = decoder.currentMode; shiftInMode = decoder.shiftInOutMode; @@ -914,7 +914,7 @@ private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, // Stop if no more input if (!buffer.MoreData) { - if (decoder != null && !decoder.MustFlush) + if (decoder is not null && !decoder.MustFlush) break; } else @@ -1011,7 +1011,7 @@ private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, else { // Not enough input, use decoder if possible - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // No decoder, do fallback for this byte buffer.Fallback(ch); @@ -1019,7 +1019,7 @@ private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, } // Stick it in the decoder if we're not counting - if (chars != null) + if (chars is not null) { escapeBytes[0] = ch; escapeCount = 1; @@ -1077,7 +1077,7 @@ private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, } // Make sure our decoder state matches our mode, if not counting - if (chars != null && decoder != null) + if (chars is not null && decoder is not null) { // Remember it if we don't flush if (!decoder.MustFlush || escapeCount != 0) @@ -1212,7 +1212,7 @@ private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, byte[] escapeBytes = new byte[4]; int escapeCount = 0; - if (decoder != null) + if (decoder is not null) { currentMode = decoder.currentMode; @@ -1238,7 +1238,7 @@ private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, // Stop if no more input if (!buffer.MoreData) { - if (decoder != null && !decoder.MustFlush) + if (decoder is not null && !decoder.MustFlush) break; } else @@ -1333,7 +1333,7 @@ private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, else { // Not enough input, use decoder if possible - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // No decoder, do fallback for lonely 1st byte buffer.Fallback(ch); @@ -1341,7 +1341,7 @@ private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, } // Stick it in the decoder if we're not counting - if (chars != null) + if (chars is not null) { escapeBytes[0] = ch; escapeCount = 1; @@ -1376,7 +1376,7 @@ private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, } // Make sure our decoder state matches our mode, if not counting - if (chars != null && decoder != null) + if (chars is not null && decoder is not null) { // Remember it if we don't flush if (!decoder.MustFlush || escapeCount != 0) @@ -1441,7 +1441,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder? decoder) { Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetCharsCP52936]count >=0"); - Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null"); + Debug.Assert(bytes is not null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null"); // Get our info. EncodingCharBuffer buffer = new EncodingCharBuffer(this, decoder, chars, charCount, bytes, byteCount); @@ -1451,7 +1451,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, int byteLeftOver = -1; bool bUsedDecoder = false; - if (decoder != null) + if (decoder is not null) { currentMode = decoder.currentMode; // See if we have leftover decoder buffer to use @@ -1487,7 +1487,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, { // We don't have anything left, it'll be in decoder or a ? // don't fail if we are allowing overflows - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // We'll be a '?' buffer.Fallback(ch); @@ -1499,7 +1499,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, // Stick it in decoder decoder.ClearMustFlush(); - if (chars != null) + if (chars is not null) { decoder.bytesLeftOverCount = 1; decoder.bytesLeftOver[0] = (byte)'~'; @@ -1565,7 +1565,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, { // No bytes left // don't fail if we are allowing overflows - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { // Not enough bytes, fallback lead byte buffer.Fallback(ch); @@ -1577,7 +1577,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, decoder.ClearMustFlush(); // Stick it in decoder - if (chars != null) + if (chars is not null) { decoder.bytesLeftOverCount = 1; decoder.bytesLeftOver[0] = ch; @@ -1659,7 +1659,7 @@ private unsafe int GetCharsCP52936(byte* bytes, int byteCount, } // Need to remember our state, IF we're not counting - if (chars != null && decoder != null) + if (chars is not null && decoder is not null) { if (!bUsedDecoder) { @@ -1803,7 +1803,7 @@ public override void Reset() currentMode = ISO2022Modes.ModeASCII; shiftInOutMode = ISO2022Modes.ModeASCII; charLeftOver = (char)0; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } @@ -1838,7 +1838,7 @@ public override void Reset() bytesLeftOver = new byte[4]; currentMode = ISO2022Modes.ModeASCII; shiftInOutMode = ISO2022Modes.ModeASCII; - if (m_fallbackBuffer != null) + if (m_fallbackBuffer is not null) m_fallbackBuffer.Reset(); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs index 6bff617ddeab04..a5f9fde4623c7c 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs @@ -120,7 +120,7 @@ private static object InternalSyncObject { get { - if (s_InternalSyncObject == null) + if (s_InternalSyncObject is null) { object o = new object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); @@ -136,7 +136,7 @@ protected unsafe override void ReadBestFitTable() lock (InternalSyncObject) { // If we got a best fit array already, then don't do this - if (arrayUnicodeBestFit == null) + if (arrayUnicodeBestFit is null) { // // Read in Best Fit table. @@ -284,10 +284,10 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); - Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); + Debug.Assert(chars is not null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); + Debug.Assert(EncoderFallback is not null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); @@ -296,7 +296,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco // Get any left over characters char charLeftOver = (char)0; - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), @@ -314,7 +314,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco fallback = EncoderFallback as EncoderReplacementFallback; } - if ((fallback != null && fallback.MaxCharCount == 1)/* || bIsBestFit*/) + if ((fallback is not null && fallback.MaxCharCount == 1)/* || bIsBestFit*/) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. @@ -345,7 +345,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco { // Since leftover char was a surrogate, it'll have to be fallen back. // Get fallback - Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); + Debug.Assert(encoder is not null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder!.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, false); @@ -358,7 +358,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco // Go ahead and do it, including the fallback. char ch; - while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) + while ((ch = (fallbackBuffer is null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) @@ -374,10 +374,10 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { // Create & init fallback buffer - if (encoder == null) + if (encoder is null) fallbackBuffer = EncoderFallback!.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -398,7 +398,7 @@ public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? enco byteCount++; } - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end"); return (int)byteCount; @@ -408,13 +408,13 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); + Debug.Assert(bytes is not null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); - Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); + Debug.Assert(chars is not null, "[SBCSCodePageEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(EncoderFallback is not null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); @@ -423,7 +423,7 @@ public override unsafe int GetBytes(char* chars, int charCount, // Get any left over characters char charLeftOver = (char)0; - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), @@ -451,7 +451,7 @@ public override unsafe int GetBytes(char* chars, int charCount, char* charStart = chars; // See if we do the fast default or slightly slower fallback - if (fallback != null && fallback.MaxCharCount == 1) + if (fallback is not null && fallback.MaxCharCount == 1) { // Make sure our fallback character is valid first byte bReplacement = _mapUnicodeToBytes[fallback.DefaultString[0]]; @@ -506,7 +506,7 @@ public override unsafe int GetBytes(char* chars, int charCount, } // Clear encoder - if (encoder != null) + if (encoder is not null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); @@ -530,7 +530,7 @@ public override unsafe int GetBytes(char* chars, int charCount, { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); + Debug.Assert(encoder is not null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder!.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); @@ -550,7 +550,7 @@ public override unsafe int GetBytes(char* chars, int charCount, // Go ahead and do it, including the fallback. char ch; - while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || + while ((ch = (fallbackBuffer is null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback @@ -568,10 +568,10 @@ public override unsafe int GetBytes(char* chars, int charCount, if (bTemp == 0 && ch != (char)0) { // Get Fallback - if (fallbackBuffer == null) + if (fallbackBuffer is null) { // Create & init fallback buffer - if (encoder == null) + if (encoder is null) fallbackBuffer = EncoderFallback!.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; @@ -605,8 +605,8 @@ public override unsafe int GetBytes(char* chars, int charCount, if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer - Debug.Assert(fallbackBuffer == null || fallbackHelper.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); - if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) + Debug.Assert(fallbackBuffer is null || fallbackHelper.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); + if (fallbackBuffer is null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)"); chars--; // don't use last char @@ -621,10 +621,10 @@ public override unsafe int GetBytes(char* chars, int charCount, } // encoder stuff if we have one - if (encoder != null) + if (encoder is not null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases - if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder) + if (fallbackBuffer is not null && !fallbackHelper.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; @@ -633,7 +633,7 @@ public override unsafe int GetBytes(char* chars, int charCount, } // Expect Empty fallback buffer for SBCS - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } @@ -642,7 +642,7 @@ public override unsafe int GetBytes(char* chars, int charCount, public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? decoder) { // Just assert, we're called internally so these should be safe, checked already - Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); + Debug.Assert(bytes is not null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); @@ -653,7 +653,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? deco // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback? fallback = null; - if (decoder == null) + if (decoder is null) { fallback = DecoderFallback as DecoderReplacementFallback; bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback; @@ -667,7 +667,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? deco "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } - if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) + if (bUseBestFit || (fallback is not null && fallback.MaxCharCount == 1)) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. @@ -698,10 +698,10 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? deco if (c == UNKNOWN_CHAR) { // Must have a fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { // Need to adjust count so we get real start - if (decoder == null) + if (decoder is null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -719,7 +719,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? deco } // Fallback buffer must be empty - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end"); // Converted sequence is same length as input @@ -730,9 +730,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); + Debug.Assert(bytes is not null, "[SBCSCodePageEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); - Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); + Debug.Assert(chars is not null, "[SBCSCodePageEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); @@ -748,7 +748,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback? fallback = null; - if (decoder == null) + if (decoder is null) { fallback = DecoderFallback as DecoderReplacementFallback; bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback; @@ -762,11 +762,11 @@ public override unsafe int GetChars(byte* bytes, int byteCount, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } - if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) + if (bUseBestFit || (fallback is not null && fallback.MaxCharCount == 1)) { // Try it the fast way char replacementChar; - if (fallback == null) + if (fallback is null) replacementChar = '?'; // Best fit always has ? for fallback for SBCS else replacementChar = fallback.DefaultString[0]; @@ -787,7 +787,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char c; if (bUseBestFit) { - if (arrayBytesBestFit == null) + if (arrayBytesBestFit is null) { ReadBestFitTable(); } @@ -806,7 +806,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, } // bytes & chars used are the same - if (decoder != null) + if (decoder is not null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } @@ -829,9 +829,9 @@ public override unsafe int GetChars(byte* bytes, int byteCount, if (c == UNKNOWN_CHAR) { // Make sure we have a fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) + if (decoder is null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; @@ -873,11 +873,11 @@ public override unsafe int GetChars(byte* bytes, int byteCount, } // Might have had decoder fallback stuff. - if (decoder != null) + if (decoder is not null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end"); return (int)(chars - charStart); diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CaptureCollection.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CaptureCollection.cs index 87c41d39e31eea..a622035629384f 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CaptureCollection.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CaptureCollection.cs @@ -55,7 +55,7 @@ private Capture GetCapture(int i) if (_captures is null) { ForceInitialized(); - Debug.Assert(_captures != null); + Debug.Assert(_captures is not null); } return _captures[i]; @@ -184,7 +184,7 @@ private sealed class Enumerator : IEnumerator internal Enumerator(CaptureCollection collection) { - Debug.Assert(collection != null, "collection cannot be null."); + Debug.Assert(collection is not null, "collection cannot be null."); _collection = collection; _index = -1; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Group.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Group.cs index f4b2a7fb2e9804..c2d6115ea5db8e 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Group.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Group.cs @@ -41,7 +41,7 @@ internal Group(string text, int[] caps, int capcount, string name) /// public static Group Synchronized(Group inner) { - if (inner == null) + if (inner is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.inner); } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/GroupCollection.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/GroupCollection.cs index 592d4e054b45e2..c4a480dd1a6e4e 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/GroupCollection.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/GroupCollection.cs @@ -48,7 +48,7 @@ internal GroupCollection(Match match, Hashtable? caps) private Group GetGroup(int groupnum) { - if (_captureMap != null) + if (_captureMap is not null) { if (_captureMap.TryGetValue(groupnum, out int groupNumImpl)) { @@ -238,7 +238,7 @@ private sealed class Enumerator : IEnumerator, IEnumerator _regex != null && _regex.IsDebug; + internal bool IsDebug => _regex is not null && _regex.IsDebug; internal virtual void Dump() { @@ -379,7 +379,7 @@ internal MatchSparse(Regex regex, Hashtable caps, int capcount, string text, int [ExcludeFromCodeCoverage(Justification = "Debug only")] internal override void Dump() { - if (_caps != null) + if (_caps is not null) { foreach (object? entry in _caps) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/MatchCollection.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/MatchCollection.cs index 0f6414d1aeea8a..d1188ad0c06421 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/MatchCollection.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/MatchCollection.cs @@ -197,7 +197,7 @@ private sealed class Enumerator : IEnumerator internal Enumerator(MatchCollection collection) { - Debug.Assert(collection != null, "collection cannot be null."); + Debug.Assert(collection is not null, "collection cannot be null."); _collection = collection; _index = -1; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Cache.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Cache.cs index 5ba43c3a5ca06d..7ea0001777441e 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Cache.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Cache.cs @@ -147,7 +147,7 @@ private static bool TryGet(Key key, [NotNullWhen(true)] out Regex? regex) // by having a fast-path that stores the most recently used instance. Check // to see if that instance is the one we want; if it is, we're done. Node? lastAccessed = s_lastAccessed; - if (lastAccessed != null) + if (lastAccessed is not null) { if (lastAccessed.Key.Equals(key)) { @@ -269,8 +269,8 @@ private static void Add(Key key, Regex regex) public Key(string pattern, string culture, RegexOptions options, bool hasTimeout) { - Debug.Assert(pattern != null, "Pattern must be provided"); - Debug.Assert(culture != null, "Culture must be provided"); + Debug.Assert(pattern is not null, "Pattern must be provided"); + Debug.Assert(culture is not null, "Culture must be provided"); _pattern = pattern; _culture = culture; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs index ee40bac56dac3b..b4f7f88784a03d 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs @@ -337,7 +337,7 @@ public string GroupNameFromNumber(int i) } else { - return caps != null && !caps.TryGetValue(i, out i) ? string.Empty : + return caps is not null && !caps.TryGetValue(i, out i) ? string.Empty : (uint)i < (uint)capslist.Length ? capslist[i] : string.Empty; } @@ -353,7 +353,7 @@ public int GroupNumberFromName(string name) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name); } - if (capnames != null) + if (capnames is not null) { // Look up name if we have a hashtable of names. return capnames.TryGetValue(name, out int result) ? result : -1; @@ -422,7 +422,7 @@ internal void Run(string input, int startat, ref TState state, MatchCall [MethodImpl(MethodImplOptions.AggressiveInlining)] // factored out to be used by only two call sites private RegexRunner RentRunner() => Interlocked.Exchange(ref _runner, null) ?? // use a cached runner if there is one - (factory != null ? factory.CreateInstance() : // use the compiled RegexRunner factory if there is one + (factory is not null ? factory.CreateInstance() : // use the compiled RegexRunner factory if there is one new RegexInterpreter(_code!, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture)); /// Release the runner back to the cache. diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexAssemblyCompiler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexAssemblyCompiler.cs index ce7a8ce4e49ad8..b3ec19c0f8ceb1 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexAssemblyCompiler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexAssemblyCompiler.cs @@ -21,7 +21,7 @@ internal sealed class RegexAssemblyCompiler : RegexCompiler internal RegexAssemblyCompiler(AssemblyName an, CustomAttributeBuilder[]? attribs, string? resourceFile) : base(persistsAssembly: true) { - if (resourceFile != null) + if (resourceFile is not null) { // Unmanaged resources are not supported: _assembly.DefineUnmanagedResource(resourceFile); throw new PlatformNotSupportedException(); @@ -29,7 +29,7 @@ internal RegexAssemblyCompiler(AssemblyName an, CustomAttributeBuilder[]? attrib _assembly = AssemblyBuilder.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); // TODO https://github.com/dotnet/runtime/issues/30153: AssemblyBuilderAccess.Save _module = _assembly.DefineDynamicModule(an.Name + ".dll"); - if (attribs != null) + if (attribs is not null) { foreach (CustomAttributeBuilder attr in attribs) { @@ -142,17 +142,17 @@ private void GenerateRegexDefaultCtor(string pattern, RegexOptions options, Type Ldthis(); Ldc(code.CapSize); Stfld(RegexField(nameof(Regex.capsize))); - if (code.Caps != null) + if (code.Caps is not null) { // Caps = new Hashtable {{0, 0}, {1, 1}, ... }; GenerateCreateHashtable(RegexField(nameof(Regex.caps)), code.Caps); } - if (code.Tree.CapNames != null) + if (code.Tree.CapNames is not null) { // CapNames = new Hashtable {{"0", 0}, {"1", 1}, ...}; GenerateCreateHashtable(RegexField(nameof(Regex.capnames)), code.Tree.CapNames); } - if (code.Tree.CapsList != null) + if (code.Tree.CapsList is not null) { // capslist = new string[...]; // capslist[0] = "0"; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs index bf12098b1ec29a..179479bbec4560 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs @@ -191,12 +191,12 @@ public RegexBoyerMoore(string pattern, bool caseInsensitive, bool rightToLeft, C int i = ch >> 8; int j = ch & 0xFF; - if (NegativeUnicode == null) + if (NegativeUnicode is null) { NegativeUnicode = new int[256][]; } - if (NegativeUnicode[i] == null) + if (NegativeUnicode[i] is null) { int[] newarray = new int[256]; @@ -308,7 +308,7 @@ public int Scan(string text, int index, int beglimit, int endlimit) { if (chTest < 128) advance = NegativeASCII[chTest]; - else if (null != NegativeUnicode && (null != (unicodeLookup = NegativeUnicode[chTest >> 8]))) + else if (NegativeUnicode is not null && (null != (unicodeLookup = NegativeUnicode[chTest >> 8]))) advance = unicodeLookup[chTest & 0xFF]; else advance = defadv; @@ -338,7 +338,7 @@ public int Scan(string text, int index, int beglimit, int endlimit) advance = Positive[match]; if ((chTest & 0xFF80) == 0) test2 = (match - startmatch) + NegativeASCII[chTest]; - else if (null != NegativeUnicode && (null != (unicodeLookup = NegativeUnicode[chTest >> 8]))) + else if (NegativeUnicode is not null && (null != (unicodeLookup = NegativeUnicode[chTest >> 8]))) test2 = (match - startmatch) + unicodeLookup[chTest & 0xFF]; else { @@ -376,7 +376,7 @@ public string Dump(string indent) } sb.AppendLine(); - if (NegativeASCII != null) + if (NegativeASCII is not null) { sb.Append($"{indent}Negative table: "); for (int i = 0; i < NegativeASCII.Length; i++) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs index d4022f673e4ff7..3b367a8cec0a84 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs @@ -430,7 +430,7 @@ private RegexCharClass(bool negate, List? ranges, StringBuilder? ca _subtractor = subtraction; } - public bool CanMerge => !_negate && _subtractor == null; + public bool CanMerge => !_negate && _subtractor is null; public bool Negate { @@ -453,7 +453,7 @@ public void AddCharClass(RegexCharClass cc) EnsureRangeList().AddRange(cc._rangelist!); } - if (cc._categories != null) + if (cc._categories is not null) { EnsureCategories().Append(cc._categories); } @@ -491,7 +491,7 @@ private void AddSet(ReadOnlySpan set) public void AddSubtraction(RegexCharClass sub) { - Debug.Assert(_subtractor == null, "Can't add two subtractions to a char class. "); + Debug.Assert(_subtractor is null, "Can't add two subtractions to a char class. "); _subtractor = sub; } @@ -542,7 +542,7 @@ public void AddCategoryFromName(string categoryName, bool invert, bool caseInsen public void AddLowercase(CultureInfo culture) { List? rangeList = _rangelist; - if (rangeList != null) + if (rangeList is not null) { int count = rangeList.Count; for (int i = 0; i < count; i++) @@ -712,7 +712,7 @@ public static char SingletonChar(string set) } public static bool IsMergeable(string charClass) => - charClass != null && + charClass is not null && !IsNegated(charClass) && !IsSubtraction(charClass); @@ -1359,7 +1359,7 @@ private void ToStringClass(ref ValueStringBuilder vsb) // Append ranges List? rangelist = _rangelist; - if (rangelist != null) + if (rangelist is not null) { for (int i = 0; i < rangelist.Count; i++) { @@ -1395,7 +1395,7 @@ private void ToStringClass(ref ValueStringBuilder vsb) private void Canonicalize() { List? rangelist = _rangelist; - if (rangelist != null) + if (rangelist is not null) { // Find and eliminate overlapping or abutting ranges. if (rangelist.Count > 1) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs index dbfa9a5cdbdf56..0c4f7bff222e2d 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs @@ -407,14 +407,14 @@ public override string ToString() sb.AppendLine("Anchor: " + RegexPrefixAnalyzer.AnchorDescription(LeadingAnchor)); sb.AppendLine(""); - if (BoyerMoorePrefix != null) + if (BoyerMoorePrefix is not null) { sb.AppendLine("Boyer-Moore:"); sb.AppendLine(BoyerMoorePrefix.Dump(" ")); sb.AppendLine(); } - if (LeadingCharClasses != null) + if (LeadingCharClasses is not null) { sb.AppendLine("First Chars:"); for (int i = 0; i < LeadingCharClasses.Length; i++) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs index 4383e37e5880d4..7f1535760610b1 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs @@ -46,7 +46,7 @@ public string Name [MemberNotNull(nameof(_name))] set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(Name)); } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs index 7316eb8a1073c0..2cc37da2f171e0 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs @@ -203,10 +203,10 @@ public BacktrackNote(int flags, Label label, int codepos) /// private int AddBacktrackNote(int flags, Label l, int codepos) { - if (_notes == null || _notecount >= _notes.Length) + if (_notes is null || _notecount >= _notes.Length) { - var newnotes = new BacktrackNote[_notes == null ? 16 : _notes.Length * 2]; - if (_notes != null) + var newnotes = new BacktrackNote[_notes is null ? 16 : _notes.Length * 2]; + if (_notes is not null) { Array.Copy(_notes, newnotes, _notecount); } @@ -533,8 +533,8 @@ internal RentedLocalBuilder(Stack pool, LocalBuilder local) public void Dispose() { - Debug.Assert(_pool != null); - Debug.Assert(_local != null); + Debug.Assert(_pool is not null); + Debug.Assert(_local is not null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; @@ -798,14 +798,14 @@ private void Goto(int i) /// Sets the culture local to CultureInfo.CurrentCulture. private void InitLocalCultureInfo() { - Debug.Assert(_textInfoLocal != null); + Debug.Assert(_textInfoLocal is not null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfoLocal); } /// Whether ToLower operations should be performed with the invariant culture as opposed to the one in . - private bool UseToLowerInvariant => _textInfoLocal == null || (_options & RegexOptions.CultureInvariant) != 0; + private bool UseToLowerInvariant => _textInfoLocal is null || (_options & RegexOptions.CultureInvariant) != 0; /// Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c). private void CallToLower() @@ -997,7 +997,7 @@ private void GenerateBacktrackSection() /// protected void GenerateFindFirstChar() { - Debug.Assert(_code != null); + Debug.Assert(_code is not null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); @@ -1012,7 +1012,7 @@ protected void GenerateFindFirstChar() if (!_options.HasFlag(RegexOptions.CultureInvariant)) { bool needsCulture = _options.HasFlag(RegexOptions.IgnoreCase) || _boyerMoorePrefix?.CaseInsensitive == true; - if (!needsCulture && _leadingCharClasses != null) + if (!needsCulture && _leadingCharClasses is not null) { for (int i = 0; i < _leadingCharClasses.Length; i++) { @@ -1265,7 +1265,7 @@ protected void GenerateFindFirstChar() } } - if (_boyerMoorePrefix != null && _boyerMoorePrefix.NegativeUnicode == null) + if (_boyerMoorePrefix is not null && _boyerMoorePrefix.NegativeUnicode is null) { // Compiled Boyer-Moore string matching LocalBuilder limitLocal; @@ -1560,7 +1560,7 @@ protected void GenerateFindFirstChar() } else { - Debug.Assert(_leadingCharClasses != null && _leadingCharClasses.Length > 0); + Debug.Assert(_leadingCharClasses is not null && _leadingCharClasses.Length > 0); // If minRequiredLength > 0, we already output a more stringent check. In the rare case // where we were unable to get an accurate enough min required length to ensure it's larger @@ -1939,12 +1939,12 @@ static bool NodeSupportsNonBacktrackingImplementation(RegexNode node, int maxDep case RegexNode.Oneloop: case RegexNode.Notoneloop: case RegexNode.Setloop: - Debug.Assert(node.Next == null || node.Next.Type != RegexNode.Atomic, "Loop should have been transformed into an atomic type."); + Debug.Assert(node.Next is null || node.Next.Type != RegexNode.Atomic, "Loop should have been transformed into an atomic type."); goto case RegexNode.Onelazy; case RegexNode.Onelazy: case RegexNode.Notonelazy: case RegexNode.Setlazy: - supported = node.M == node.N || (node.Next != null && node.Next.Type == RegexNode.Atomic); + supported = node.M == node.N || (node.Next is not null && node.Next.Type == RegexNode.Atomic); break; // {Lazy}Loop repeaters are the same, except their child also needs to be supported. @@ -1952,7 +1952,7 @@ static bool NodeSupportsNonBacktrackingImplementation(RegexNode node, int maxDep case RegexNode.Loop: case RegexNode.Lazyloop: supported = - (node.M == node.N || (node.Next != null && node.Next.Type == RegexNode.Atomic)) && + (node.M == node.N || (node.Next is not null && node.Next.Type == RegexNode.Atomic)) && NodeSupportsNonBacktrackingImplementation(node.Child(0), maxDepth - 1); break; @@ -1971,7 +1971,7 @@ static bool NodeSupportsNonBacktrackingImplementation(RegexNode node, int maxDep // effectively atomic, as nothing will try to backtrack into it as it's the last thing). // Its children must all also be supported. case RegexNode.Alternate: - if (node.Next != null && + if (node.Next is not null && (node.IsAtomicByParent() || // atomic alternate (node.Next.Type == RegexNode.Capture && node.Next.Next is null))) // root alternate { @@ -1999,7 +1999,7 @@ static bool NodeSupportsNonBacktrackingImplementation(RegexNode node, int maxDep { // And we only support them in certain places in the tree. RegexNode? parent = node.Next; - while (parent != null) + while (parent is not null) { switch (parent.Type) { @@ -2028,7 +2028,7 @@ static bool NodeSupportsNonBacktrackingImplementation(RegexNode node, int maxDep if (supported) { parent = node; - while (parent != null && ((parent.Options & HasCapturesFlag) == 0)) + while (parent is not null && ((parent.Options & HasCapturesFlag) == 0)) { parent.Options |= HasCapturesFlag; parent = parent.Next; @@ -2066,7 +2066,7 @@ void LoadTextSpanLocal() // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { - if (local == null) + if (local is null) { Ldc(constant); } @@ -2205,7 +2205,7 @@ void EmitAtomicAlternate(RegexNode node) Stloc(runtextposLocal); LoadTextSpanLocal(); textSpanPos = startingTextSpanPos; - if (startingCrawlpos != null) + if (startingCrawlpos is not null) { EmitUncaptureUntil(startingCrawlpos); } @@ -2214,7 +2214,7 @@ void EmitAtomicAlternate(RegexNode node) // If the final branch fails, that's like any other failure, and we jump to // done (unless we have captures we need to unwind first, in which case we uncapture // them and then jump to done). - if (startingCrawlpos != null) + if (startingCrawlpos is not null) { Label uncapture = DefineLabel(); doneLabel = uncapture; @@ -2253,7 +2253,7 @@ void EmitCapture(RegexNode node) Debug.Assert(node.Type == RegexNode.Capture); Debug.Assert(node.N == -1, "Currently only support capnum, not uncapnum"); int capnum = node.M; - if (capnum != -1 && _code!.Caps != null) + if (capnum != -1 && _code!.Caps is not null) { capnum = (int)_code.Caps[capnum]!; } @@ -2282,7 +2282,7 @@ void EmitCapture(RegexNode node) // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCrawlpos) { - Debug.Assert(startingCrawlpos != null); + Debug.Assert(startingCrawlpos is not null); // while (Crawlpos() != startingCrawlpos) Uncapture(); Label condition = DefineLabel(); @@ -2393,7 +2393,7 @@ void EmitNode(RegexNode node) // An atomic lazy loop amounts to doing the minimum amount of work possible. // That means iterating as little as is required, which means a repeater // for the min, and if min is 0, doing nothing. - Debug.Assert(node.M == node.N || (node.Next != null && node.Next.Type == RegexNode.Atomic)); + Debug.Assert(node.M == node.N || (node.Next is not null && node.Next.Type == RegexNode.Atomic)); if (node.M > 0) { EmitNodeRepeater(node); @@ -3177,7 +3177,7 @@ void EmitAtomicSingleCharZeroOrOne(RegexNode node) void EmitAtomicNodeLoop(RegexNode node) { Debug.Assert(node.Type == RegexNode.Loop); - Debug.Assert(node.M == node.N || (node.Next != null && node.Next.Type == RegexNode.Atomic)); + Debug.Assert(node.M == node.N || (node.Next is not null && node.Next.Type == RegexNode.Atomic)); Debug.Assert(node.M < int.MaxValue); // If this is actually a repeater, emit that instead. @@ -3281,7 +3281,7 @@ void EmitAtomicNodeLoop(RegexNode node) /// Generates the code for "RegexRunner.Go". protected void GenerateGo() { - Debug.Assert(_code != null); + Debug.Assert(_code is not null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); @@ -5332,7 +5332,7 @@ private void EmitTimeoutCheck() return; } - Debug.Assert(_loopTimeoutCounterLocal != null); + Debug.Assert(_loopTimeoutCounterLocal is not null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounterLocal); diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs index 4cc3dc528605b9..0c30d0c1b66177 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs @@ -23,8 +23,8 @@ internal sealed class RegexInterpreter : RegexRunner public RegexInterpreter(RegexCode code, CultureInfo culture) { - Debug.Assert(code != null, "code must not be null."); - Debug.Assert(culture != null, "culture must not be null."); + Debug.Assert(code is not null, "code must not be null."); + Debug.Assert(culture is not null, "culture must not be null."); _code = code; _textInfo = culture.TextInfo; @@ -388,7 +388,7 @@ protected override bool FindFirstChar() } return - _code.BoyerMoorePrefix == null || // found a valid start or end anchor + _code.BoyerMoorePrefix is null || // found a valid start or end anchor _code.BoyerMoorePrefix.IsMatch(runtext!, runtextpos, runtextbeg, runtextend); } @@ -416,7 +416,7 @@ protected override bool FindFirstChar() } } - if (_code.BoyerMoorePrefix != null) + if (_code.BoyerMoorePrefix is not null) { runtextpos = _code.BoyerMoorePrefix.Scan(runtext!, runtextpos, runtextbeg, runtextend); diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs index bd55727af62a97..22792844b150ad 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs @@ -339,7 +339,7 @@ internal RegexNode FinalOptimize() case Setloop when node.N == int.MaxValue: case Setloopatomic when node.N == int.MaxValue: RegexNode? parent = node.Next; - if (parent != null && parent.Type == Concatenate) + if (parent is not null && parent.Type == Concatenate) { parent.InsertChild(1, new RegexNode(UpdateBumpalong, node.Options)); } @@ -430,7 +430,7 @@ private static void EliminateEndingBacktracking(RegexNode node, uint maxDepth) case Loop: { RegexNode? loopDescendent = FindLastExpressionInLoopForAutoAtomic(node, maxDepth - 1); - if (loopDescendent != null) + if (loopDescendent is not null) { node = loopDescendent; continue; // loop around to process node @@ -463,7 +463,7 @@ public bool IsAtomicByParent() } next = next.Next; - return next != null && next.Type == Atomic; + return next is not null && next.Type == Atomic; } /// @@ -1341,7 +1341,7 @@ static void ProcessNode(RegexNode node, RegexNode subsequent, uint maxDepth) if (node.Type == Loop) { RegexNode? loopDescendent = FindLastExpressionInLoopForAutoAtomic(node, maxDepth - 1); - if (loopDescendent != null) + if (loopDescendent is not null) { node = loopDescendent; continue; @@ -1720,7 +1720,7 @@ public void InsertChild(int index, RegexNode newChild) public void ReplaceChild(int index, RegexNode newChild) { - Debug.Assert(Children != null); + Debug.Assert(Children is not null); Debug.Assert(index < ChildCount()); newChild.Next = this; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs index fae6d582421b6e..bb5d7f321f3189 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs @@ -51,8 +51,8 @@ internal ref struct RegexParser private RegexParser(string pattern, RegexOptions options, CultureInfo culture, Hashtable caps, int capsize, Hashtable? capnames, Span optionSpan) { - Debug.Assert(pattern != null, "Pattern must be set"); - Debug.Assert(culture != null, "Culture must be set"); + Debug.Assert(pattern is not null, "Pattern must be set"); + Debug.Assert(culture is not null, "Culture must be set"); _pattern = pattern; _options = options; @@ -357,7 +357,7 @@ private RegexNode ScanRegex() PopGroup(); PopOptions(); - if (Unit() == null) + if (Unit() is null) { goto ContinueOuterScan; } @@ -395,7 +395,7 @@ private RegexNode ScanRegex() case '*': case '+': case '?': - if (Unit() == null) + if (Unit() is null) { throw wasPrevQuantifier ? MakeException(RegexParseError.NestedQuantifiersNotParenthesized, SR.Format(SR.NestedQuantifiersNotParenthesized, ch)) : @@ -419,7 +419,7 @@ private RegexNode ScanRegex() ch = RightCharMoveRight(); // Handle quantifiers - while (Unit() != null) + while (Unit() is not null) { int min; int max; @@ -1285,7 +1285,7 @@ private void ScanBlank() int pos = Textpos() - 1; while (newcapnum <= _captop) { - if (IsCaptureSlot(newcapnum) && (_caps == null || (int)_caps[newcapnum]! < pos)) + if (IsCaptureSlot(newcapnum) && (_caps is null || (int)_caps[newcapnum]! < pos)) { capnum = newcapnum; } @@ -1928,7 +1928,7 @@ private void NoteCaptureSlot(int i, int pos) /// Notes a used capture slot private void NoteCaptureName(string name, int pos) { - if (_capnames == null) + if (_capnames is null) { _capnames = new Hashtable(); _capnamelist = new List(); @@ -1944,7 +1944,7 @@ private void NoteCaptureName(string name, int pos) /// Assigns unused slot numbers to the capture names. private void AssignNameSlots() { - if (_capnames != null) + if (_capnames is not null) { for (int i = 0; i < _capnamelist!.Count; i++) { @@ -1981,13 +1981,13 @@ private void AssignNameSlots() // merge capsnumlist into capnamelist - if (_capnames != null || _capnumlist != null) + if (_capnames is not null || _capnumlist is not null) { List? oldcapnamelist; int next; int k = 0; - if (_capnames == null) + if (_capnames is null) { oldcapnamelist = null; _capnames = new Hashtable(); @@ -2003,7 +2003,7 @@ private void AssignNameSlots() for (int i = 0; i < _capcount; i++) { - int j = (_capnumlist == null) ? i : _capnumlist[i]; + int j = (_capnumlist is null) ? i : _capnumlist[i]; if (next == j) { @@ -2026,7 +2026,7 @@ private void AssignNameSlots() /// True if the capture slot was noted private bool IsCaptureSlot(int i) { - if (_caps != null) + if (_caps is not null) { return _caps.ContainsKey(i); } @@ -2035,7 +2035,7 @@ private bool IsCaptureSlot(int i) } /// Looks up the slot number for a given name - private bool IsCaptureName(string capname) => _capnames != null && _capnames.ContainsKey(capname); + private bool IsCaptureName(string capname) => _capnames is not null && _capnames.ContainsKey(capname); /// True if N option disabling '(' autocapture is on. private bool UseOptionN() => (_options & RegexOptions.ExplicitCapture) != 0; @@ -2174,7 +2174,7 @@ private void PopGroup() // The first () inside a Testgroup group goes directly to the group if (_group.Type == RegexNode.Testgroup && _group.ChildCount() == 0) { - if (_unit == null) + if (_unit is null) { throw MakeException(RegexParseError.AlternationHasMalformedCondition, SR.AlternationHasMalformedCondition); } @@ -2185,7 +2185,7 @@ private void PopGroup() } /// True if the group stack is empty. - private bool EmptyStack() => _stack == null; + private bool EmptyStack() => _stack is null; /// Start a new round for the parser state (in response to an open paren or string start) private void StartGroup(RegexNode openGroup) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs index 2f8d5d15efcebc..41f2b474827e5b 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs @@ -109,7 +109,7 @@ public static (string Prefix, bool CaseInsensitive) ComputeLeadingSubstring(Rege return (string.Empty, false); } - if (concatNode == null || nextChild >= concatNode.ChildCount()) + if (concatNode is null || nextChild >= concatNode.ChildCount()) { return (string.Empty, false); } @@ -126,7 +126,7 @@ public static (string CharClass, bool CaseInsensitive)[]? ComputeFirstCharClass( RegexFC? fc = s.RegexFCFromRegexTree(tree); s.Dispose(); - if (fc == null || fc._nullable) + if (fc is null || fc._nullable) { return null; } @@ -346,7 +346,7 @@ public static int FindLeadingAnchor(RegexTree tree) return 0; } - if (concatNode == null || nextChild >= concatNode.ChildCount()) + if (concatNode is null || nextChild >= concatNode.ChildCount()) { return 0; } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexReplacement.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexReplacement.cs index 44450feb069c6e..41a6a013076792 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexReplacement.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexReplacement.cs @@ -66,7 +66,7 @@ public RegexReplacement(string rep, RegexNode concat, Hashtable _caps) } int slot = child.M; - if (_caps != null && slot >= 0) + if (_caps is not null && slot >= 0) { slot = (int)_caps[slot]!; } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs index e3f48e3dded141..53750d1b36d567 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs @@ -204,7 +204,7 @@ protected internal RegexRunner() { } if (runtextpos == stoppos) { runtext = null; // drop reference to text to avoid keeping it alive in a cache - if (runmatch != null) runmatch.Text = null!; + if (runmatch is not null) runmatch.Text = null!; return Match.Empty; } @@ -357,7 +357,7 @@ internal void Scan(Regex regex, string text, int textstart, ref TState s if (runtextpos == stoppos) { runtext = null; // drop reference to text to avoid keeping it alive in a cache - if (runmatch != null) + if (runmatch is not null) { runmatch.Text = null!; } @@ -454,7 +454,7 @@ private void InitializeForGo() // If there is an alloc failure in the middle of the three allocations, // we may still return to reuse this instance, and we want to behave // as if the allocations didn't occur. - if (runcrawl != null) + if (runcrawl is not null) { runtrackpos = runtrack!.Length; runstackpos = runstack!.Length; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexWriter.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexWriter.cs index 2154947cfaa8d5..7e368a4ef5df1c 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexWriter.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexWriter.cs @@ -75,7 +75,7 @@ public RegexCode RegexCodeFromRegexTree(RegexTree tree) { // Construct sparse capnum mapping if some numbers are unused. int capsize; - if (tree.CapNumList == null || tree.CapTop == tree.CapNumList.Length) + if (tree.CapNumList is null || tree.CapTop == tree.CapNumList.Length) { capsize = tree.CapTop; _caps = null; @@ -149,7 +149,7 @@ public RegexCode RegexCodeFromRegexTree(RegexTree tree) // If we didn't find a single leading substring, or if we found one but we won't be able to use it for a Boyer-Moore // search, try to compute the characters set that might begin the string. if (boyerMoorePrefix is null || - (boyerMoorePrefix.NegativeUnicode != null && compiled)) // compilation won't use Boyer-Moore if it has a negative Unicode table + (boyerMoorePrefix.NegativeUnicode is not null && compiled)) // compilation won't use Boyer-Moore if it has a negative Unicode table { boyerMoorePrefix = null; @@ -254,7 +254,7 @@ private int StringCode(string str) /// private int MapCapnum(int capnum) => capnum == -1 ? -1 : - _caps != null ? (int)_caps[capnum]! : + _caps is not null ? (int)_caps[capnum]! : capnum; /// diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.cs index 9412cc28abfaf8..99cd80bec8be7c 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.cs @@ -116,7 +116,7 @@ public ValueTaskSourceStatus GetStatus(short token) return !IsCompleted ? ValueTaskSourceStatus.Pending : - _error == null ? ValueTaskSourceStatus.Succeeded : + _error is null ? ValueTaskSourceStatus.Succeeded : _error.SourceException is OperationCanceledException ? ValueTaskSourceStatus.Canceled : ValueTaskSourceStatus.Faulted; } @@ -210,27 +210,27 @@ public void OnCompleted(Action continuation, object? state, short token // after the CompareExchange, it'll find the state already stored. If someone misuses this // and schedules multiple continuations erroneously, we could end up using the wrong state. // Make a best-effort attempt to catch such misuse. - if (_continuationState != null) + if (_continuationState is not null) { ThrowMultipleContinuations(); } _continuationState = state; // Capture the execution context if necessary. - Debug.Assert(_executionContext == null); + Debug.Assert(_executionContext is null); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } // Capture the scheduling context if necessary. - Debug.Assert(_schedulingContext == null); + Debug.Assert(_schedulingContext is null); SynchronizationContext? sc = null; TaskScheduler? ts = null; if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { sc = SynchronizationContext.Current; - if (sc != null && sc.GetType() != typeof(SynchronizationContext)) + if (sc is not null && sc.GetType() != typeof(SynchronizationContext)) { _schedulingContext = sc; } @@ -251,7 +251,7 @@ public void OnCompleted(Action continuation, object? state, short token // inside the awaiter's OnCompleted method and we want to avoid possible stack dives, we must invoke // the continuation asynchronously rather than synchronously. Action? prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null); - if (prevContinuation != null) + if (prevContinuation is not null) { // If the set failed because there's already a delegate in _continuation, but that delegate is // something other than s_completedSentinel, something went wrong, which should only happen if @@ -266,11 +266,11 @@ public void OnCompleted(Action continuation, object? state, short token // Queue the continuation. We always queue here, even if !RunContinuationsAsynchronously, in order // to avoid stack diving; this path happens in the rare race when we're setting up to await and the // object is completed after the awaiter.IsCompleted but before the awaiter.OnCompleted. - if (_schedulingContext == null) + if (_schedulingContext is null) { QueueUserWorkItem(continuation, state); } - else if (sc != null) + else if (sc is not null) { sc.Post(static s => { @@ -280,7 +280,7 @@ public void OnCompleted(Action continuation, object? state, short token } else { - Debug.Assert(ts != null); + Debug.Assert(ts is not null); Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); } } @@ -372,12 +372,12 @@ private bool TryReserveCompletionIfCancelable() => /// Signals to a registered continuation that the operation has now completed. private void SignalCompletion() { - if (_continuation != null || Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null) != null) + if (_continuation is not null || Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null) is not null) { Debug.Assert(_continuation != s_completedSentinel, $"The continuation was the completion sentinel."); Debug.Assert(_continuation != s_availableSentinel, $"The continuation was the available sentinel."); - if (_schedulingContext == null) + if (_schedulingContext is null) { // There's no captured scheduling context. If we're forced to run continuations asynchronously, queue it. // Otherwise fall through to invoke it synchronously. @@ -404,7 +404,7 @@ private void SignalCompletion() // or if there's a current scheduler that's not the one we're targeting, queue it. // Otherwise fall through to invoke it synchronously. TaskScheduler ts = (TaskScheduler)_schedulingContext; - Debug.Assert(ts != null, "Expected a TaskScheduler"); + Debug.Assert(ts is not null, "Expected a TaskScheduler"); if (_runContinuationsAsynchronously || ts != TaskScheduler.Current) { Task.Factory.StartNew(static s => ((AsyncOperation)s!).SetCompletionAndInvokeContinuation(), this, @@ -420,7 +420,7 @@ private void SignalCompletion() private void SetCompletionAndInvokeContinuation() { - if (_executionContext == null) + if (_executionContext is null) { Action c = _continuation!; _continuation = s_completedSentinel; diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/BoundedChannel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/BoundedChannel.cs index cec397b78bc3f7..1f918a443a210a 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/BoundedChannel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/BoundedChannel.cs @@ -129,7 +129,7 @@ public override ValueTask ReadAsync(CancellationToken cancellationToken) // There weren't any items. If we're done writing so that there // will never be more items, fail. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return ChannelUtilities.GetInvalidCompletionValueTask(parent._doneWriting); } @@ -178,7 +178,7 @@ public override ValueTask WaitToReadAsync(CancellationToken cancellationTo } // There were no items available, so if we're done writing, a read will never be possible. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return parent._doneWriting != ChannelUtilities.s_doneWritingSentinel ? new ValueTask(Task.FromException(parent._doneWriting)) : @@ -223,7 +223,7 @@ private T DequeueItemAndPostProcess() // Dequeue an item. T item = parent._items.DequeueHead(); - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { // We're done writing, so if we're now empty, complete the channel. if (parent._items.IsEmpty) @@ -292,7 +292,7 @@ public override bool TryComplete(Exception? error) parent.AssertInvariants(); // If we've already marked the channel as completed, bail. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return false; } @@ -337,7 +337,7 @@ public override bool TryWrite(T item) parent.AssertInvariants(); // If we're done writing, nothing more to do. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return false; } @@ -362,13 +362,13 @@ public override bool TryWrite(T item) } } - if (blockedReader == null) + if (blockedReader is null) { // If there wasn't a blocked reader, then store the item. If no one's waiting // to be notified about a 0-to-1 transition, we're done. parent._items.EnqueueTail(item); waitingReadersTail = parent._waitingReadersTail; - if (waitingReadersTail == null) + if (waitingReadersTail is null) { return true; } @@ -413,9 +413,9 @@ public override bool TryWrite(T item) } // We either wrote the item already, or we're transferring it to the blocked reader we grabbed. - if (blockedReader != null) + if (blockedReader is not null) { - Debug.Assert(waitingReadersTail == null, "Shouldn't have any waiters to wake up"); + Debug.Assert(waitingReadersTail is null, "Shouldn't have any waiters to wake up"); // Transfer the written item to the blocked reader. bool success = blockedReader.TrySetResult(item); @@ -446,7 +446,7 @@ public override ValueTask WaitToWriteAsync(CancellationToken cancellationT parent.AssertInvariants(); // If we're done writing, no writes will ever succeed. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return parent._doneWriting != ChannelUtilities.s_doneWritingSentinel ? new ValueTask(Task.FromException(parent._doneWriting)) : @@ -497,7 +497,7 @@ public override ValueTask WriteAsync(T item, CancellationToken cancellationToken parent.AssertInvariants(); // If we're done writing, trying to write is an error. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(parent._doneWriting))); } @@ -522,13 +522,13 @@ public override ValueTask WriteAsync(T item, CancellationToken cancellationToken } } - if (blockedReader == null) + if (blockedReader is null) { // If there wasn't a blocked reader, then store the item. If no one's waiting // to be notified about a 0-to-1 transition, we're done. parent._items.EnqueueTail(item); waitingReadersTail = parent._waitingReadersTail; - if (waitingReadersTail == null) + if (waitingReadersTail is null) { return default; } @@ -589,7 +589,7 @@ public override ValueTask WriteAsync(T item, CancellationToken cancellationToken } // We either wrote the item already, or we're transfering it to the blocked reader we grabbed. - if (blockedReader != null) + if (blockedReader is not null) { // Transfer the written item to the blocked reader. bool success = blockedReader.TrySetResult(item); @@ -620,18 +620,18 @@ public override ValueTask WriteAsync(T item, CancellationToken cancellationToken [Conditional("DEBUG")] private void AssertInvariants() { - Debug.Assert(SyncObj != null, "The sync obj must not be null."); + Debug.Assert(SyncObj is not null, "The sync obj must not be null."); Debug.Assert(Monitor.IsEntered(SyncObj), "Invariants can only be validated while holding the lock."); if (!_items.IsEmpty) { Debug.Assert(_blockedReaders.IsEmpty, "There are items available, so there shouldn't be any blocked readers."); - Debug.Assert(_waitingReadersTail == null, "There are items available, so there shouldn't be any waiting readers."); + Debug.Assert(_waitingReadersTail is null, "There are items available, so there shouldn't be any waiting readers."); } if (_items.Count < _bufferedCapacity) { Debug.Assert(_blockedWriters.IsEmpty, "There's space available, so there shouldn't be any blocked writers."); - Debug.Assert(_waitingWritersTail == null, "There's space available, so there shouldn't be any waiting writers."); + Debug.Assert(_waitingWritersTail is null, "There's space available, so there shouldn't be any waiting writers."); } if (!_blockedReaders.IsEmpty) { @@ -645,7 +645,7 @@ private void AssertInvariants() } if (_completion.Task.IsCompleted) { - Debug.Assert(_doneWriting != null, "We can only complete if we're done writing."); + Debug.Assert(_doneWriting is not null, "We can only complete if we're done writing."); } } @@ -653,7 +653,7 @@ private void AssertInvariants() private int ItemsCountForDebugger => _items.Count; /// Report if the channel is closed or not. This should only be used by the debugger. - private bool ChannelIsClosedForDebugger => _doneWriting != null; + private bool ChannelIsClosedForDebugger => _doneWriting is not null; /// Gets an enumerator the debugger can use to show the contents of the channel. IEnumerator IDebugEnumerable.GetEnumerator() => _items.GetEnumerator(); diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs index f377993ec03df9..203d6ca9c81f1b 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs @@ -16,7 +16,7 @@ public static Channel CreateUnbounded() => /// Options that guide the behavior of the channel. /// The created channel. public static Channel CreateUnbounded(UnboundedChannelOptions options) => - options == null ? throw new ArgumentNullException(nameof(options)) : + options is null ? throw new ArgumentNullException(nameof(options)) : options.SingleReader ? new SingleConsumerUnboundedChannel(!options.AllowSynchronousContinuations) : (Channel)new UnboundedChannel(!options.AllowSynchronousContinuations); @@ -44,7 +44,7 @@ public static Channel CreateBounded(int capacity) /// The created channel. public static Channel CreateBounded(BoundedChannelOptions options) { - if (options == null) + if (options is null) { throw new ArgumentNullException(nameof(options)); } diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/ChannelUtilities.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/ChannelUtilities.cs index 82ea8816920f46..c5b5fc681c58b3 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/ChannelUtilities.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/ChannelUtilities.cs @@ -33,7 +33,7 @@ internal static void Complete(TaskCompletionSource tcs, Exception? e { tcs.TrySetCanceled(oce.CancellationToken); } - else if (error != null && error != s_doneWritingSentinel) + else if (error is not null && error != s_doneWritingSentinel) { tcs.TrySetException(error); } @@ -49,7 +49,7 @@ internal static void Complete(TaskCompletionSource tcs, Exception? e /// The failed task. internal static ValueTask GetInvalidCompletionValueTask(Exception error) { - Debug.Assert(error != null); + Debug.Assert(error is not null); Task t = error == s_doneWritingSentinel ? Task.FromException(CreateInvalidCompletionException()) : @@ -62,7 +62,7 @@ internal static ValueTask GetInvalidCompletionValueTask(Exception error) internal static void QueueWaiter(ref AsyncOperation? tail, AsyncOperation waiter) { AsyncOperation? c = tail; - if (c == null) + if (c is null) { waiter.Next = waiter; } @@ -77,7 +77,7 @@ internal static void QueueWaiter(ref AsyncOperation? tail, AsyncOperation< internal static void WakeUpWaiters(ref AsyncOperation? listTail, bool result, Exception? error = null) { AsyncOperation? tail = listTail; - if (tail != null) + if (tail is not null) { listTail = null; @@ -88,7 +88,7 @@ internal static void WakeUpWaiters(ref AsyncOperation? listTail, bool resu AsyncOperation next = c.Next!; c.Next = null; - bool completed = error != null ? c.TrySetException(error) : c.TrySetResult(result); + bool completed = error is not null ? c.TrySetException(error) : c.TrySetResult(result); Debug.Assert(completed || c.CancellationToken.CanBeCanceled); c = next; @@ -102,7 +102,7 @@ internal static void WakeUpWaiters(ref AsyncOperation? listTail, bool resu /// The error with which to complete each operations. internal static void FailOperations(Deque operations, Exception error) where T : AsyncOperation { - Debug.Assert(error != null); + Debug.Assert(error is not null); while (!operations.IsEmpty) { operations.DequeueHead().TrySetException(error); @@ -112,7 +112,7 @@ internal static void FailOperations(Deque operations, Exception er /// Creates and returns an exception object to indicate that a channel has been closed. internal static Exception CreateInvalidCompletionException(Exception? inner = null) => inner is OperationCanceledException ? inner : - inner != null && inner != s_doneWritingSentinel ? new ChannelClosedException(inner) : + inner is not null && inner != s_doneWritingSentinel ? new ChannelClosedException(inner) : new ChannelClosedException(); } } diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/SingleConsumerUnboundedChannel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/SingleConsumerUnboundedChannel.cs index 50398e841e7b7b..9fce8789a2cc3d 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/SingleConsumerUnboundedChannel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/SingleConsumerUnboundedChannel.cs @@ -89,7 +89,7 @@ public override ValueTask ReadAsync(CancellationToken cancellationToken) } // If no more items will be written, fail the read. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return ChannelUtilities.GetInvalidCompletionValueTask(parent._doneWriting); } @@ -123,7 +123,7 @@ public override bool TryRead([MaybeNullWhen(false)] out T item) SingleConsumerUnboundedChannel parent = _parent; if (parent._items.TryDequeue(out item)) { - if (parent._doneWriting != null && parent._items.IsEmpty) + if (parent._doneWriting is not null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } @@ -156,7 +156,7 @@ public override ValueTask WaitToReadAsync(CancellationToken cancellationTo } // There aren't any items; if we're done writing, there never will be more items. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return parent._doneWriting != ChannelUtilities.s_doneWritingSentinel ? new ValueTask(Task.FromException(parent._doneWriting)) : @@ -211,7 +211,7 @@ public override bool TryComplete(Exception? error) lock (parent.SyncObj) { // If we're already marked as complete, there's nothing more to do. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return false; } @@ -226,13 +226,13 @@ public override bool TryComplete(Exception? error) { completeTask = true; - if (parent._blockedReader != null) + if (parent._blockedReader is not null) { blockedReader = parent._blockedReader; parent._blockedReader = null; } - if (parent._waitingReader != null) + if (parent._waitingReader is not null) { waitingReader = parent._waitingReader; parent._waitingReader = null; @@ -246,10 +246,10 @@ public override bool TryComplete(Exception? error) ChannelUtilities.Complete(parent._completion, error); } - Debug.Assert(blockedReader == null || waitingReader == null, "There should only ever be at most one reader."); + Debug.Assert(blockedReader is null || waitingReader is null, "There should only ever be at most one reader."); // Complete a blocked reader if necessary - if (blockedReader != null) + if (blockedReader is not null) { error = ChannelUtilities.CreateInvalidCompletionException(error); blockedReader.TrySetException(error); @@ -257,9 +257,9 @@ public override bool TryComplete(Exception? error) // Complete a waiting reader if necessary. (We really shouldn't have both a blockedReader // and a waitingReader, but it's more expensive to prevent it than to just tolerate it.) - if (waitingReader != null) + if (waitingReader is not null) { - if (error != null) + if (error is not null) { waitingReader.TrySetException(error); } @@ -284,7 +284,7 @@ public override bool TryWrite(T item) lock (parent.SyncObj) { // If writing is completed, exit out without writing. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return false; } @@ -292,7 +292,7 @@ public override bool TryWrite(T item) // If there's a blocked reader, store it into a local for completion outside of the lock. // If there isn't a blocked reader, queue the item being written; then if there's a waiting blockedReader = parent._blockedReader; - if (blockedReader != null) + if (blockedReader is not null) { parent._blockedReader = null; } @@ -301,7 +301,7 @@ public override bool TryWrite(T item) parent._items.Enqueue(item); waitingReader = parent._waitingReader; - if (waitingReader == null) + if (waitingReader is null) { return true; } @@ -310,10 +310,10 @@ public override bool TryWrite(T item) } // If we get here, we grabbed a blocked or a waiting reader. - Debug.Assert((blockedReader != null) ^ (waitingReader != null), "Expected either a blocked or waiting reader, but not both"); + Debug.Assert((blockedReader is not null) ^ (waitingReader is not null), "Expected either a blocked or waiting reader, but not both"); // If we have a waiting reader, notify it that an item was written and exit. - if (waitingReader != null) + if (waitingReader is not null) { // If we get here, we grabbed a waiting reader. waitingReader.TrySetResult(item: true); @@ -324,7 +324,7 @@ public override bool TryWrite(T item) // In the case of a ReadAsync(CancellationToken), it's possible the reader could // have been completed due to cancellation by the time we get here. In that case, // we'll loop around to try again so as not to lose the item being written. - Debug.Assert(blockedReader != null); + Debug.Assert(blockedReader is not null); if (blockedReader.TrySetResult(item)) { return true; @@ -337,7 +337,7 @@ public override ValueTask WaitToWriteAsync(CancellationToken cancellationT Exception? doneWriting = _parent._doneWriting; return cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled(cancellationToken)) : - doneWriting == null ? new ValueTask(true) : + doneWriting is null ? new ValueTask(true) : doneWriting != ChannelUtilities.s_doneWritingSentinel ? new ValueTask(Task.FromException(doneWriting)) : default; } @@ -362,7 +362,7 @@ public override ValueTask WriteAsync(T item, CancellationToken cancellationToken private int ItemsCountForDebugger => _items.Count; /// Report if the channel is closed or not. This should only be used by the debugger. - private bool ChannelIsClosedForDebugger => _doneWriting != null; + private bool ChannelIsClosedForDebugger => _doneWriting is not null; /// Gets an enumerator the debugger can use to show the contents of the channel. IEnumerator IDebugEnumerable.GetEnumerator() => _items.GetEnumerator(); diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs index 612d6b50f8f368..77738a887ee495 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs @@ -85,7 +85,7 @@ public override ValueTask ReadAsync(CancellationToken cancellationToken) } // There are no items, so if we're done writing, fail. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return ChannelUtilities.GetInvalidCompletionValueTask(parent._doneWriting); } @@ -125,7 +125,7 @@ public override bool TryRead([MaybeNullWhen(false)] out T item) private void CompleteIfDone(UnboundedChannel parent) { - if (parent._doneWriting != null && parent._items.IsEmpty) + if (parent._doneWriting is not null && parent._items.IsEmpty) { // If we've now emptied the items queue and we're not getting any more, complete. ChannelUtilities.Complete(parent._completion, parent._doneWriting); @@ -157,7 +157,7 @@ public override ValueTask WaitToReadAsync(CancellationToken cancellationTo } // There are no items, so if we're done writing, there's never going to be data available. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return parent._doneWriting != ChannelUtilities.s_doneWritingSentinel ? new ValueTask(Task.FromException(parent._doneWriting)) : @@ -203,7 +203,7 @@ public override bool TryComplete(Exception? error) parent.AssertInvariants(); // If we've already marked the channel as completed, bail. - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return false; } @@ -244,7 +244,7 @@ public override bool TryWrite(T item) { // If writing has already been marked as done, fail the write. parent.AssertInvariants(); - if (parent._doneWriting != null) + if (parent._doneWriting is not null) { return false; } @@ -259,7 +259,7 @@ public override bool TryWrite(T item) { parent._items.Enqueue(item); waitingReadersTail = parent._waitingReadersTail; - if (waitingReadersTail == null) + if (waitingReadersTail is null) { return true; } @@ -272,7 +272,7 @@ public override bool TryWrite(T item) } } - if (blockedReader != null) + if (blockedReader is not null) { // Complete the reader. It's possible the reader was canceled, in which // case we loop around to try everything again. @@ -298,7 +298,7 @@ public override ValueTask WaitToWriteAsync(CancellationToken cancellationT Exception? doneWriting = _parent._doneWriting; return cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled(cancellationToken)) : - doneWriting == null ? new ValueTask(true) : // unbounded writing can always be done if we haven't completed + doneWriting is null ? new ValueTask(true) : // unbounded writing can always be done if we haven't completed doneWriting != ChannelUtilities.s_doneWritingSentinel ? new ValueTask(Task.FromException(doneWriting)) : default; } @@ -321,7 +321,7 @@ public override ValueTask WriteAsync(T item, CancellationToken cancellationToken [Conditional("DEBUG")] private void AssertInvariants() { - Debug.Assert(SyncObj != null, "The sync obj must not be null."); + Debug.Assert(SyncObj is not null, "The sync obj must not be null."); Debug.Assert(Monitor.IsEntered(SyncObj), "Invariants can only be validated while holding the lock."); if (!_items.IsEmpty) @@ -329,17 +329,17 @@ private void AssertInvariants() if (_runContinuationsAsynchronously) { Debug.Assert(_blockedReaders.IsEmpty, "There's data available, so there shouldn't be any blocked readers."); - Debug.Assert(_waitingReadersTail == null, "There's data available, so there shouldn't be any waiting readers."); + Debug.Assert(_waitingReadersTail is null, "There's data available, so there shouldn't be any waiting readers."); } Debug.Assert(!_completion.Task.IsCompleted, "We still have data available, so shouldn't be completed."); } - if ((!_blockedReaders.IsEmpty || _waitingReadersTail != null) && _runContinuationsAsynchronously) + if ((!_blockedReaders.IsEmpty || _waitingReadersTail is not null) && _runContinuationsAsynchronously) { Debug.Assert(_items.IsEmpty, "There are blocked/waiting readers, so there shouldn't be any data available."); } if (_completion.Task.IsCompleted) { - Debug.Assert(_doneWriting != null, "We're completed, so we must be done writing."); + Debug.Assert(_doneWriting is not null, "We're completed, so we must be done writing."); } } @@ -347,7 +347,7 @@ private void AssertInvariants() private int ItemsCountForDebugger => _items.Count; /// Report if the channel is closed or not. This should only be used by the debugger. - private bool ChannelIsClosedForDebugger => _doneWriting != null; + private bool ChannelIsClosedForDebugger => _doneWriting is not null; /// Gets an enumerator the debugger can use to show the contents of the channel. IEnumerator IDebugEnumerable.GetEnumerator() => _items.GetEnumerator(); diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs index 21cee18d3763d4..e6eb146e151e7f 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs @@ -189,11 +189,11 @@ public static void Invoke(params Action[] actions) /// public static void Invoke(ParallelOptions parallelOptions, params Action[] actions) { - if (actions == null) + if (actions is null) { throw new ArgumentNullException(nameof(actions)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -212,7 +212,7 @@ public static void Invoke(ParallelOptions parallelOptions, params Action[] actio for (int i = 0; i < actionsCopy.Length; i++) { actionsCopy[i] = actions[i]; - if (actionsCopy[i] == null) + if (actionsCopy[i] is null) { throw new ArgumentException(SR.Parallel_Invoke_ActionNull); } @@ -318,7 +318,7 @@ public static void Invoke(ParallelOptions parallelOptions, params Action[] actio } // If we have encountered any exceptions, then throw. - if ((exceptionQ != null) && (!exceptionQ.IsEmpty)) + if ((exceptionQ is not null) && (!exceptionQ.IsEmpty)) { ThrowSingleCancellationExceptionOrOtherException(exceptionQ, parallelOptions.CancellationToken, new AggregateException(exceptionQ)); @@ -383,7 +383,7 @@ public static void Invoke(ParallelOptions parallelOptions, params Action[] actio /// public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -412,7 +412,7 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action< /// public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -451,11 +451,11 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Actio /// public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -494,11 +494,11 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Paralle /// public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -550,7 +550,7 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Paral /// public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -580,7 +580,7 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action< /// public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -621,11 +621,11 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Actio /// public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -667,11 +667,11 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Paralle public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action body) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -725,15 +725,15 @@ public static ParallelLoopResult For( Func body, Action localFinally) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } @@ -787,15 +787,15 @@ public static ParallelLoopResult For( Func body, Action localFinally) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } @@ -860,19 +860,19 @@ public static ParallelLoopResult For( Func body, Action localFinally) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -937,19 +937,19 @@ public static ParallelLoopResult For( Func body, Action localFinally) { - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -1014,9 +1014,9 @@ private static ParallelLoopResult ForWorker( Func? bodyWithLocal, Func? localInit, Action? localFinally) { - Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, + Debug.Assert(((body is null ? 0 : 1) + (bodyWithState is null ? 0 : 1) + (bodyWithLocal is null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), + Debug.Assert(bodyWithLocal is not null || (localInit is null && localFinally is null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Instantiate our result. Specifics will be filled in later. @@ -1110,16 +1110,16 @@ private static ParallelLoopResult ForWorker( // If needed, it will contain a new instance of thread-local state by invoking the selector. ParallelLoopState32? state = null; - if (bodyWithState != null) + if (bodyWithState is not null) { - Debug.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags is not null); state = new ParallelLoopState32(sharedPStateFlags); } - else if (bodyWithLocal != null) + else if (bodyWithLocal is not null) { - Debug.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags is not null); state = new ParallelLoopState32(sharedPStateFlags); - if (localInit != null) + if (localInit is not null) { localValue = localInit(); bLocalValueInitialized = true; @@ -1132,7 +1132,7 @@ private static ParallelLoopResult ForWorker( // Now perform the loop itself. do { - if (body != null) + if (body is not null) { for (int j = nFromInclusiveLocal; j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.ParallelLoopStateNone // fast path check as SEL() doesn't inline @@ -1142,7 +1142,7 @@ private static ParallelLoopResult ForWorker( body(j); } } - else if (bodyWithState != null) + else if (bodyWithState is not null) { for (int j = nFromInclusiveLocal; j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.ParallelLoopStateNone // fast path check as SEL() doesn't inline @@ -1188,7 +1188,7 @@ private static ParallelLoopResult ForWorker( { // If a cleanup function was specified, call it. Otherwise, if the type is // IDisposable, we will invoke Dispose on behalf of the user. - if (localFinally != null && bLocalValueInitialized) + if (localFinally is not null && bLocalValueInitialized) { localFinally(localValue); } @@ -1212,7 +1212,7 @@ private static ParallelLoopResult ForWorker( // If we got through that with no exceptions, and we were canceled, then // throw our cancellation exception - if (oce != null) throw oce; + if (oce is not null) throw oce; } catch (AggregateException aggExp) { @@ -1275,9 +1275,9 @@ private static ParallelLoopResult ForWorker64( Func? bodyWithLocal, Func? localInit, Action? localFinally) { - Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, + Debug.Assert(((body is null ? 0 : 1) + (bodyWithState is null ? 0 : 1) + (bodyWithLocal is null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), + Debug.Assert(bodyWithLocal is not null || (localInit is null && localFinally is null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Instantiate our result. Specifics will be filled in later. @@ -1373,18 +1373,18 @@ private static ParallelLoopResult ForWorker64( // If needed, it will contain a new instance of thread-local state by invoking the selector. ParallelLoopState64? state = null; - if (bodyWithState != null) + if (bodyWithState is not null) { - Debug.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags is not null); state = new ParallelLoopState64(sharedPStateFlags); } - else if (bodyWithLocal != null) + else if (bodyWithLocal is not null) { - Debug.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags is not null); state = new ParallelLoopState64(sharedPStateFlags); // If a thread-local selector was supplied, invoke it. Otherwise, use the default. - if (localInit != null) + if (localInit is not null) { localValue = localInit(); bLocalValueInitialized = true; @@ -1397,7 +1397,7 @@ private static ParallelLoopResult ForWorker64( // Now perform the loop itself. do { - if (body != null) + if (body is not null) { for (long j = nFromInclusiveLocal; j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.ParallelLoopStateNone // fast path check as SEL() doesn't inline @@ -1407,7 +1407,7 @@ private static ParallelLoopResult ForWorker64( body(j); } } - else if (bodyWithState != null) + else if (bodyWithState is not null) { for (long j = nFromInclusiveLocal; j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.ParallelLoopStateNone // fast path check as SEL() doesn't inline @@ -1453,7 +1453,7 @@ private static ParallelLoopResult ForWorker64( { // If a cleanup function was specified, call it. Otherwise, if the type is // IDisposable, we will invoke Dispose on behalf of the user. - if (localFinally != null && bLocalValueInitialized) + if (localFinally is not null && bLocalValueInitialized) { localFinally(localValue); } @@ -1477,7 +1477,7 @@ private static ParallelLoopResult ForWorker64( // If we got through that with no exceptions, and we were canceled, then // throw our cancellation exception - if (oce != null) throw oce; + if (oce is not null) throw oce; } catch (AggregateException aggExp) { @@ -1535,11 +1535,11 @@ private static ParallelLoopResult ForWorker64( /// public static ParallelLoopResult ForEach(IEnumerable source, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -1580,15 +1580,15 @@ public static ParallelLoopResult ForEach(IEnumerable source, A /// public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -1620,11 +1620,11 @@ public static ParallelLoopResult ForEach(IEnumerable source, P /// public static ParallelLoopResult ForEach(IEnumerable source, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -1667,15 +1667,15 @@ public static ParallelLoopResult ForEach(IEnumerable source, A /// public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -1707,11 +1707,11 @@ public static ParallelLoopResult ForEach(IEnumerable source, P /// public static ParallelLoopResult ForEach(IEnumerable source, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -1754,15 +1754,15 @@ public static ParallelLoopResult ForEach(IEnumerable source, A /// public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -1815,19 +1815,19 @@ public static ParallelLoopResult ForEach(IEnumerable source, P public static ParallelLoopResult ForEach(IEnumerable source, Func localInit, Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } @@ -1892,23 +1892,23 @@ public static ParallelLoopResult ForEach(IEnumerable s ParallelOptions parallelOptions, Func localInit, Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -1961,19 +1961,19 @@ public static ParallelLoopResult ForEach(IEnumerable s public static ParallelLoopResult ForEach(IEnumerable source, Func localInit, Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } @@ -2037,23 +2037,23 @@ public static ParallelLoopResult ForEach(IEnumerable s public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Func localInit, Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -2095,10 +2095,10 @@ private static ParallelLoopResult ForEachWorker( Func? bodyWithEverything, Func? localInit, Action? localFinally) { - Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + - (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1, + Debug.Assert(((body is null ? 0 : 1) + (bodyWithState is null ? 0 : 1) + + (bodyWithStateAndIndex is null ? 0 : 1) + (bodyWithStateAndLocal is null ? 0 : 1) + (bodyWithEverything is null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), + Debug.Assert((bodyWithStateAndLocal is not null) || (bodyWithEverything is not null) || (localInit is null && localFinally is null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Before getting started, do a quick peek to see if we have been canceled already @@ -2153,28 +2153,28 @@ private static ParallelLoopResult ForEachWorker( Func? bodyWithEverything, Func? localInit, Action? localFinally) { - Debug.Assert(array != null); - Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null"); + Debug.Assert(array is not null); + Debug.Assert(parallelOptions is not null, "ForEachWorker(array): parallelOptions is null"); int from = array.GetLowerBound(0); int to = array.GetUpperBound(0) + 1; - if (body != null) + if (body is not null) { return ForWorker( from, to, parallelOptions, (i) => body(array[i]), null, null, null, null); } - else if (bodyWithState != null) + else if (bodyWithState is not null) { return ForWorker( from, to, parallelOptions, null, (i, state) => bodyWithState(array[i], state), null, null, null); } - else if (bodyWithStateAndIndex != null) + else if (bodyWithStateAndIndex is not null) { return ForWorker( from, to, parallelOptions, null, (i, state) => bodyWithStateAndIndex(array[i], state, i), null, null, null); } - else if (bodyWithStateAndLocal != null) + else if (bodyWithStateAndLocal is not null) { return ForWorker( from, to, parallelOptions, null, null, (i, state, local) => bodyWithStateAndLocal(array[i], state, local), localInit, localFinally); @@ -2212,25 +2212,25 @@ private static ParallelLoopResult ForEachWorker( Func? bodyWithEverything, Func? localInit, Action? localFinally) { - Debug.Assert(list != null); - Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null"); + Debug.Assert(list is not null); + Debug.Assert(parallelOptions is not null, "ForEachWorker(list): parallelOptions is null"); - if (body != null) + if (body is not null) { return ForWorker( 0, list.Count, parallelOptions, (i) => body(list[i]), null, null, null, null); } - else if (bodyWithState != null) + else if (bodyWithState is not null) { return ForWorker( 0, list.Count, parallelOptions, null, (i, state) => bodyWithState(list[i], state), null, null, null); } - else if (bodyWithStateAndIndex != null) + else if (bodyWithStateAndIndex is not null) { return ForWorker( 0, list.Count, parallelOptions, null, (i, state) => bodyWithStateAndIndex(list[i], state, i), null, null, null); } - else if (bodyWithStateAndLocal != null) + else if (bodyWithStateAndLocal is not null) { return ForWorker( 0, list.Count, parallelOptions, null, null, (i, state, local) => bodyWithStateAndLocal(list[i], state, local), localInit, localFinally); @@ -2289,11 +2289,11 @@ public static ParallelLoopResult ForEach( Partitioner source, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -2348,11 +2348,11 @@ public static ParallelLoopResult ForEach( Partitioner source, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -2410,11 +2410,11 @@ public static ParallelLoopResult ForEach( OrderablePartitioner source, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } @@ -2494,19 +2494,19 @@ public static ParallelLoopResult ForEach( Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } @@ -2584,19 +2584,19 @@ public static ParallelLoopResult ForEach( Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } @@ -2666,15 +2666,15 @@ public static ParallelLoopResult ForEach( ParallelOptions parallelOptions, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -2741,15 +2741,15 @@ public static ParallelLoopResult ForEach( ParallelOptions parallelOptions, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -2819,15 +2819,15 @@ public static ParallelLoopResult ForEach( ParallelOptions parallelOptions, Action body) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -2919,23 +2919,23 @@ public static ParallelLoopResult ForEach( Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -3025,23 +3025,23 @@ public static ParallelLoopResult ForEach( Func body, Action localFinally) { - if (source == null) + if (source is null) { throw new ArgumentNullException(nameof(source)); } - if (body == null) + if (body is null) { throw new ArgumentNullException(nameof(body)); } - if (localInit == null) + if (localInit is null) { throw new ArgumentNullException(nameof(localInit)); } - if (localFinally == null) + if (localFinally is null) { throw new ArgumentNullException(nameof(localFinally)); } - if (parallelOptions == null) + if (parallelOptions is null) { throw new ArgumentNullException(nameof(parallelOptions)); } @@ -3066,14 +3066,14 @@ private static ParallelLoopResult PartitionerForEachWorker( Func? localInit, Action? localFinally) { - Debug.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + - (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1, + Debug.Assert(((simpleBody is null ? 0 : 1) + (bodyWithState is null ? 0 : 1) + + (bodyWithStateAndIndex is null ? 0 : 1) + (bodyWithStateAndLocal is null ? 0 : 1) + (bodyWithEverything is null ? 0 : 1)) == 1, "PartitionForEach: expected exactly one body function to be supplied"); - Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), + Debug.Assert((bodyWithStateAndLocal is not null) || (bodyWithEverything is not null) || (localInit is null && localFinally is null), "PartitionForEach: thread local functions should only be supplied for loops w/ thread local bodies"); OrderablePartitioner? orderedSource = source as OrderablePartitioner; - Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null), + Debug.Assert((orderedSource is not null) || (bodyWithStateAndIndex is null && bodyWithEverything is null), "PartitionForEach: bodies with indices are only allowable for OrderablePartitioner"); if (!source.SupportsDynamicPartitions) @@ -3120,10 +3120,10 @@ private static ParallelLoopResult PartitionerForEachWorker( // Also, do some error checking. IEnumerable? partitionerSource = null; IEnumerable>? orderablePartitionerSource = null; - if (orderedSource != null) + if (orderedSource is not null) { orderablePartitionerSource = orderedSource.GetOrderableDynamicPartitions(); - if (orderablePartitionerSource == null) + if (orderablePartitionerSource is null) { throw new InvalidOperationException(SR.Parallel_ForEach_PartitionerReturnedNull); } @@ -3131,7 +3131,7 @@ private static ParallelLoopResult PartitionerForEachWorker( else { partitionerSource = source.GetDynamicPartitions(); - if (partitionerSource == null) + if (partitionerSource is null) { throw new InvalidOperationException(SR.Parallel_ForEach_PartitionerReturnedNull); } @@ -3162,15 +3162,15 @@ private static ParallelLoopResult PartitionerForEachWorker( // If needed, it will contain a new instance of thread-local state by invoking the selector. ParallelLoopState64? state = null; - if (bodyWithState != null || bodyWithStateAndIndex != null) + if (bodyWithState is not null || bodyWithStateAndIndex is not null) { state = new ParallelLoopState64(sharedPStateFlags); } - else if (bodyWithStateAndLocal != null || bodyWithEverything != null) + else if (bodyWithStateAndLocal is not null || bodyWithEverything is not null) { state = new ParallelLoopState64(sharedPStateFlags); // If a thread-local selector was supplied, invoke it. Otherwise, stick with the default. - if (localInit != null) + if (localInit is not null) { localValue = localInit(); bLocalValueInitialized = true; @@ -3180,18 +3180,18 @@ private static ParallelLoopResult PartitionerForEachWorker( // initialize a loop timer which will help us decide whether we should exit early int loopTimeout = ComputeTimeoutPoint(timeout); - if (orderedSource != null) // Use this path for OrderablePartitioner: + if (orderedSource is not null) // Use this path for OrderablePartitioner: { // first check if there's saved state from a previous replica that we might be replacing. // the only state to be passed down in such a transition is the enumerator IEnumerator>? myPartition = partitionState as IEnumerator>; - if (myPartition == null) + if (myPartition is null) { myPartition = orderablePartitionerSource!.GetEnumerator(); partitionState = myPartition; } - if (myPartition == null) + if (myPartition is null) throw new InvalidOperationException(SR.Parallel_ForEach_NullEnumerator); while (myPartition.MoveNext()) @@ -3201,15 +3201,15 @@ private static ParallelLoopResult PartitionerForEachWorker( TSource value = kvp.Value; // Update our iteration index - if (state != null) state.CurrentIteration = index; + if (state is not null) state.CurrentIteration = index; - if (simpleBody != null) + if (simpleBody is not null) simpleBody(value); - else if (bodyWithState != null) + else if (bodyWithState is not null) bodyWithState(value, state!); - else if (bodyWithStateAndIndex != null) + else if (bodyWithStateAndIndex is not null) bodyWithStateAndIndex(value, state!, index); - else if (bodyWithStateAndLocal != null) + else if (bodyWithStateAndLocal is not null) localValue = bodyWithStateAndLocal(value, state!, localValue); else localValue = bodyWithEverything!(value, state!, index, localValue); @@ -3231,28 +3231,28 @@ private static ParallelLoopResult PartitionerForEachWorker( // first check if there's saved state from a previous replica that we might be replacing. // the only state to be passed down in such a transition is the enumerator IEnumerator? myPartition = partitionState as IEnumerator; - if (myPartition == null) + if (myPartition is null) { myPartition = partitionerSource!.GetEnumerator(); partitionState = myPartition; } - if (myPartition == null) + if (myPartition is null) throw new InvalidOperationException(SR.Parallel_ForEach_NullEnumerator); // I'm not going to try to maintain this - if (state != null) + if (state is not null) state.CurrentIteration = 0; while (myPartition.MoveNext()) { TSource t = myPartition.Current; - if (simpleBody != null) + if (simpleBody is not null) simpleBody(t); - else if (bodyWithState != null) + else if (bodyWithState is not null) bodyWithState(t, state!); - else if (bodyWithStateAndLocal != null) + else if (bodyWithStateAndLocal is not null) localValue = bodyWithStateAndLocal(t, state!, localValue); else Debug.Fail("PartitionerForEach: illegal body type in Partitioner handler"); @@ -3282,7 +3282,7 @@ private static ParallelLoopResult PartitionerForEachWorker( } finally { - if (localFinally != null && bLocalValueInitialized) + if (localFinally is not null && bLocalValueInitialized) { localFinally(localValue); } @@ -3312,7 +3312,7 @@ private static ParallelLoopResult PartitionerForEachWorker( // If we got through that with no exceptions, and we were canceled, then // throw our cancellation exception - if (oce != null) throw oce; + if (oce is not null) throw oce; } catch (AggregateException aggExp) { @@ -3330,7 +3330,7 @@ private static ParallelLoopResult PartitionerForEachWorker( //dispose the partitioner source if it implements IDisposable IDisposable? d = null; - if (orderablePartitionerSource != null) + if (orderablePartitionerSource is not null) { d = orderablePartitionerSource as IDisposable; } @@ -3339,7 +3339,7 @@ private static ParallelLoopResult PartitionerForEachWorker( d = partitionerSource as IDisposable; } - if (d != null) + if (d is not null) { d.Dispose(); } @@ -3362,7 +3362,7 @@ private static ParallelLoopResult PartitionerForEachWorker( CancellationToken cancelToken) { // If collection is empty - no match: - if (exceptions == null || exceptions.Count == 0) + if (exceptions is null || exceptions.Count == 0) return null; // If token is not cancelled, it can not be part of an exception: @@ -3376,12 +3376,12 @@ private static ParallelLoopResult PartitionerForEachWorker( Debug.Assert(exObj is Exception); Exception ex = (Exception)exObj; - if (first == null) + if (first is null) first = ex; // If mismatch found, fail-fast: OperationCanceledException? ocEx = ex as OperationCanceledException; - if (ocEx == null || !cancelToken.Equals(ocEx.CancellationToken)) + if (ocEx is null || !cancelToken.Equals(ocEx.CancellationToken)) return null; } diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/ParallelRangeManager.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/ParallelRangeManager.cs index 386ac5132b3828..e8b24e826e9ab2 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/ParallelRangeManager.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/ParallelRangeManager.cs @@ -62,7 +62,7 @@ internal struct RangeWorker // whether to use 32-bits or 64-bits of current index in each range internal readonly bool _use32BitCurrentIndex; - internal bool IsInitialized { get { return _indexRanges != null; } } + internal bool IsInitialized { get { return _indexRanges is not null; } } /// /// Initializes a RangeWorker struct @@ -103,7 +103,7 @@ internal bool FindNewWork(out long nFromInclusiveLocal, out long nToExclusiveLoc if (currentRange._bRangeFinished == 0) { StrongBox? sharedCurrentIndexOffset = _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset; - if (sharedCurrentIndexOffset == null) + if (sharedCurrentIndexOffset is null) { Interlocked.CompareExchange(ref _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset, new StrongBox(0), null); sharedCurrentIndexOffset = _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset!; @@ -292,7 +292,7 @@ internal RangeManager(long nFromInclusive, long nToExclusive, long nStep, int nN /// internal RangeWorker RegisterNewWorker() { - Debug.Assert(_indexRanges != null && _indexRanges.Length != 0); + Debug.Assert(_indexRanges is not null && _indexRanges.Length != 0); int nInitialRange = (Interlocked.Increment(ref _nCurrentIndexRangeToAssign) - 1) % _indexRanges.Length; diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/TaskReplicator.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/TaskReplicator.cs index e7ee33ae0434a4..eb24ae544ef4e0 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/TaskReplicator.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/TaskReplicator.cs @@ -58,7 +58,7 @@ public void Wait() // in the case where all other threads are blocked for other reasons. // Task? pendingTask; - while ((pendingTask = _pendingTask) != null) + while ((pendingTask = _pendingTask) is not null) pendingTask.Wait(); } @@ -140,7 +140,7 @@ public static void Run(ReplicatableUserAction action, ParallelOp while (replicator._pendingReplicas.TryDequeue(out nextReplica)) nextReplica.Wait(); - if (replicator._exceptions != null) + if (replicator._exceptions is not null) throw new AggregateException(replicator._exceptions); } diff --git a/src/libraries/System.Threading/src/System/Threading/Barrier.cs b/src/libraries/System.Threading/src/System/Threading/Barrier.cs index 12024d6cb4a073..ae141624a2d2c7 100644 --- a/src/libraries/System.Threading/src/System/Threading/Barrier.cs +++ b/src/libraries/System.Threading/src/System/Threading/Barrier.cs @@ -55,7 +55,7 @@ public BarrierPostPhaseException(string? message) /// A string that describes the exception. /// The exception that is the cause of the current exception. public BarrierPostPhaseException(string? message, Exception? innerException) - : base(message == null ? SR.BarrierPostPhaseException : message, innerException) + : base(message is null ? SR.BarrierPostPhaseException : message, innerException) { } @@ -227,7 +227,7 @@ public Barrier(int participantCount, Action? postPhaseAction) _evenEvent = new ManualResetEventSlim(false); // Capture the context if the post phase action is not null - if (postPhaseAction != null) + if (postPhaseAction is not null) { _ownerThreadContext = ExecutionContext.Capture(); } @@ -741,7 +741,7 @@ public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellatio } } - if (_exception != null) + if (_exception is not null) throw new BarrierPostPhaseException(_exception); return true; @@ -755,16 +755,16 @@ public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellatio private void FinishPhase(bool observedSense) { // Execute the PHA in try/finally block to reset the variables back in case of it threw an exception - if (_postPhaseAction != null) + if (_postPhaseAction is not null) { try { // Capture the caller thread ID to check if the Add/RemoveParticipant(s) is called from the PHA _actionCallerID = Environment.CurrentManagedThreadId; - if (_ownerThreadContext != null) + if (_ownerThreadContext is not null) { ContextCallback? handler = s_invokePostPhaseAction; - if (handler == null) + if (handler is null) { s_invokePostPhaseAction = handler = InvokePostPhaseAction; } @@ -785,7 +785,7 @@ private void FinishPhase(bool observedSense) { _actionCallerID = 0; SetResetEvents(observedSense); - if (_exception != null) + if (_exception is not null) throw new BarrierPostPhaseException(_exception); } } diff --git a/src/libraries/System.Threading/src/System/Threading/CountdownEvent.cs b/src/libraries/System.Threading/src/System/Threading/CountdownEvent.cs index 7ef433c8c4094c..b3424ef0c93ffb 100644 --- a/src/libraries/System.Threading/src/System/Threading/CountdownEvent.cs +++ b/src/libraries/System.Threading/src/System/Threading/CountdownEvent.cs @@ -175,7 +175,7 @@ protected virtual void Dispose(bool disposing) public bool Signal() { ThrowIfDisposed(); - Debug.Assert(_event != null); + Debug.Assert(_event is not null); if (_currentCount <= 0) { @@ -221,7 +221,7 @@ public bool Signal(int signalCount) } ThrowIfDisposed(); - Debug.Assert(_event != null); + Debug.Assert(_event is not null); int observedCount; SpinWait spin = default; diff --git a/src/libraries/System.Threading/src/System/Threading/HostExecutionContextManager.cs b/src/libraries/System.Threading/src/System/Threading/HostExecutionContextManager.cs index 32cddc4d25ccfa..f6be262ad21546 100644 --- a/src/libraries/System.Threading/src/System/Threading/HostExecutionContextManager.cs +++ b/src/libraries/System.Threading/src/System/Threading/HostExecutionContextManager.cs @@ -21,7 +21,7 @@ public class HostExecutionContextManager public virtual object SetHostExecutionContext(HostExecutionContext hostExecutionContext) { - if (hostExecutionContext == null) + if (hostExecutionContext is null) { throw new InvalidOperationException(SR.HostExecutionContextManager_InvalidOperation_NotNewCaptureContext); } @@ -34,13 +34,13 @@ public virtual object SetHostExecutionContext(HostExecutionContext hostExecution public virtual void Revert(object previousState) { var switcher = previousState as HostExecutionContextSwitcher; - if (switcher == null) + if (switcher is null) { throw new InvalidOperationException( SR.HostExecutionContextManager_InvalidOperation_CannotOverrideSetWithoutRevert); } - if (t_currentContext != switcher._currentContext || switcher._asyncLocal == null || !switcher._asyncLocal.Value) + if (t_currentContext != switcher._currentContext || switcher._asyncLocal is null || !switcher._asyncLocal.Value) { throw new InvalidOperationException( SR.HostExecutionContextManager_InvalidOperation_CannotUseSwitcherOtherThread); diff --git a/src/libraries/System.Threading/src/System/Threading/ReaderWriterLock.cs b/src/libraries/System.Threading/src/System/Threading/ReaderWriterLock.cs index 90a8e5140efca4..cb38cda3834227 100644 --- a/src/libraries/System.Threading/src/System/Threading/ReaderWriterLock.cs +++ b/src/libraries/System.Threading/src/System/Threading/ReaderWriterLock.cs @@ -53,7 +53,7 @@ public bool IsReaderLockHeld get { ThreadLocalLockEntry? threadLocalLockEntry = ThreadLocalLockEntry.GetCurrent(_lockID); - if (threadLocalLockEntry != null) + if (threadLocalLockEntry is not null) { return threadLocalLockEntry._readerLevel > 0; } @@ -226,10 +226,10 @@ public void AcquireReaderLock(int millisecondsTimeout) if ((knownState & LockStates.ReaderSignaled) != 0 && (knownState & LockStates.WaitingReadersMask) == LockStates.WaitingReader) { - if (readerEvent == null) + if (readerEvent is null) { readerEvent = _readerEvent; - Debug.Assert(readerEvent != null); + Debug.Assert(readerEvent is not null); } // Ensure the event is signaled before resetting it, since the ReaderSignaled state is set @@ -386,10 +386,10 @@ public void AcquireWriterLock(int millisecondsTimeout) (knownState & LockStates.WriterSignaled) != 0 && (knownState & LockStates.WaitingWritersMask) == LockStates.WaitingWriter) { - if (writerEvent == null) + if (writerEvent is null) { writerEvent = _writerEvent; - Debug.Assert(writerEvent != null); + Debug.Assert(writerEvent is not null); } while (true) @@ -453,7 +453,7 @@ public void ReleaseReaderLock() } ThreadLocalLockEntry? threadLocalLockEntry = ThreadLocalLockEntry.GetCurrent(_lockID); - if (threadLocalLockEntry == null) + if (threadLocalLockEntry is null) { throw GetNotOwnerException(); } @@ -488,7 +488,7 @@ public void ReleaseReaderLock() if ((knownState & LockStates.WaitingWritersMask) != 0) { writerEvent = TryGetOrCreateWriterEvent(); - if (writerEvent == null) + if (writerEvent is null) { // Similar to below, wait for some time and try again Thread.Sleep(100); @@ -502,7 +502,7 @@ public void ReleaseReaderLock() else if ((knownState & LockStates.WaitingReadersMask) != 0) { readerEvent = TryGetOrCreateReaderEvent(); - if (readerEvent == null) + if (readerEvent is null) { // Wait for some time and try again. Since a WaitingReaders bit is set, the event would usually // already be created (if the waiting reader that called AcquireReaderLock is already waiting on the @@ -524,7 +524,7 @@ public void ReleaseReaderLock() } modifyState += LockStates.ReaderSignaled; } - else if (knownState == LockStates.Reader && (_readerEvent != null || _writerEvent != null)) + else if (knownState == LockStates.Reader && (_readerEvent is not null || _writerEvent is not null)) { cacheEvents = true; modifyState += LockStates.CachingEvents; @@ -543,14 +543,14 @@ public void ReleaseReaderLock() if ((knownState & LockStates.WaitingWritersMask) != 0) { Debug.Assert((_state & LockStates.WriterSignaled) != 0); - Debug.Assert(writerEvent != null); + Debug.Assert(writerEvent is not null); writerEvent.Set(); } // Check for waiting readers else if ((knownState & LockStates.WaitingReadersMask) != 0) { Debug.Assert((_state & LockStates.ReaderSignaled) != 0); - Debug.Assert(readerEvent != null); + Debug.Assert(readerEvent is not null); readerEvent.Set(); } // Check for the need to release events @@ -597,7 +597,7 @@ public void ReleaseWriterLock() if ((knownState & LockStates.WaitingReadersMask) != 0) { readerEvent = TryGetOrCreateReaderEvent(); - if (readerEvent == null) + if (readerEvent is null) { // Wait for some time and try again. Since a WaitingReaders bit is set, the event would usually // already be created (if the waiting reader that called AcquireReaderLock is already waiting on the @@ -622,7 +622,7 @@ public void ReleaseWriterLock() else if ((knownState & LockStates.WaitingWritersMask) != 0) { writerEvent = TryGetOrCreateWriterEvent(); - if (writerEvent == null) + if (writerEvent is null) { // Similar to above, wait for some time and try again Thread.Sleep(100); @@ -633,7 +633,7 @@ public void ReleaseWriterLock() } modifyState += LockStates.WriterSignaled; } - else if (knownState == LockStates.Writer && (_readerEvent != null || _writerEvent != null)) + else if (knownState == LockStates.Writer && (_readerEvent is not null || _writerEvent is not null)) { cacheEvents = true; modifyState += LockStates.CachingEvents; @@ -648,14 +648,14 @@ public void ReleaseWriterLock() if ((knownState & LockStates.WaitingReadersMask) != 0) { Debug.Assert((_state & LockStates.ReaderSignaled) != 0); - Debug.Assert(readerEvent != null); + Debug.Assert(readerEvent is not null); readerEvent.Set(); } // Check for waiting writers else if ((knownState & LockStates.WaitingWritersMask) != 0) { Debug.Assert((_state & LockStates.WriterSignaled) != 0); - Debug.Assert(writerEvent != null); + Debug.Assert(writerEvent is not null); writerEvent.Set(); } // Check for the need to release events @@ -689,7 +689,7 @@ public LockCookie UpgradeToWriterLock(int millisecondsTimeout) } ThreadLocalLockEntry? threadLocalLockEntry = ThreadLocalLockEntry.GetCurrent(_lockID); - if (threadLocalLockEntry == null) + if (threadLocalLockEntry is null) { lockCookie._flags = LockCookieFlags.Upgrade | LockCookieFlags.OwnedNone; } @@ -788,7 +788,7 @@ public void DowngradeFromWriterLock(ref LockCookie lockCookie) if ((knownState & LockStates.WaitingReadersMask) != 0) { readerEvent = TryGetOrCreateReaderEvent(); - if (readerEvent == null) + if (readerEvent is null) { // Wait for some time and try again. Since a WaitingReaders bit is set, the event would usually // already be created (if the waiting reader that called AcquireReaderLock is already waiting on the @@ -819,7 +819,7 @@ public void DowngradeFromWriterLock(ref LockCookie lockCookie) if ((knownState & LockStates.WaitingReadersMask) != 0) { Debug.Assert((_state & LockStates.ReaderSignaled) != 0); - Debug.Assert(readerEvent != null); + Debug.Assert(readerEvent is not null); readerEvent.Set(); } @@ -892,7 +892,7 @@ public LockCookie ReleaseLock() } ThreadLocalLockEntry? threadLocalLockEntry = ThreadLocalLockEntry.GetCurrent(_lockID); - if (threadLocalLockEntry == null) + if (threadLocalLockEntry is null) { lockCookie._flags = LockCookieFlags.Release | LockCookieFlags.OwnedNone; return lockCookie; @@ -920,7 +920,7 @@ public void RestoreLock(ref LockCookie lockCookie) throw GetInvalidLockCookieException(); } - if (_writerID == threadID || ThreadLocalLockEntry.GetCurrent(_lockID) != null) + if (_writerID == threadID || ThreadLocalLockEntry.GetCurrent(_lockID) is not null) { throw new SynchronizationLockException(SR.ReaderWriterLock_RestoreLockWithOwnedLocks); } @@ -994,7 +994,7 @@ private void RecoverLock(ref LockCookie lockCookie, LockCookieFlags flags) { AcquireReaderLock(Timeout.Infinite); ThreadLocalLockEntry? threadLocalLockEntry = ThreadLocalLockEntry.GetCurrent(_lockID); - Debug.Assert(threadLocalLockEntry != null); + Debug.Assert(threadLocalLockEntry is not null); threadLocalLockEntry._readerLevel = lockCookie._readerLevel; } } @@ -1019,14 +1019,14 @@ private static bool YieldProcessor() private ManualResetEventSlim GetOrCreateReaderEvent() { ManualResetEventSlim? currentEvent = _readerEvent; - if (currentEvent != null) + if (currentEvent is not null) { return currentEvent; } currentEvent = new ManualResetEventSlim(false, 0); ManualResetEventSlim? previousEvent = Interlocked.CompareExchange(ref _readerEvent, currentEvent, null); - if (previousEvent == null) + if (previousEvent is null) { return currentEvent; } @@ -1040,14 +1040,14 @@ private ManualResetEventSlim GetOrCreateReaderEvent() private AutoResetEvent GetOrCreateWriterEvent() { AutoResetEvent? currentEvent = _writerEvent; - if (currentEvent != null) + if (currentEvent is not null) { return currentEvent; } currentEvent = new AutoResetEvent(false); AutoResetEvent? previousEvent = Interlocked.CompareExchange(ref _writerEvent, currentEvent, null); - if (previousEvent == null) + if (previousEvent is null) { return currentEvent; } @@ -1229,10 +1229,10 @@ private ThreadLocalLockEntry(long lockID) private static void VerifyNoNonemptyEntryInListAfter(long lockID, ThreadLocalLockEntry afterEntry) { Debug.Assert(lockID != 0); - Debug.Assert(afterEntry != null); + Debug.Assert(afterEntry is not null); for (ThreadLocalLockEntry? currentEntry = afterEntry._next; - currentEntry != null; + currentEntry is not null; currentEntry = currentEntry._next) { Debug.Assert(currentEntry._lockID != lockID || currentEntry.IsFree); @@ -1244,7 +1244,7 @@ private static void VerifyNoNonemptyEntryInListAfter(long lockID, ThreadLocalLoc Debug.Assert(lockID != 0); ThreadLocalLockEntry? headEntry = t_lockEntryHead; - for (ThreadLocalLockEntry? currentEntry = headEntry; currentEntry != null; currentEntry = currentEntry._next) + for (ThreadLocalLockEntry? currentEntry = headEntry; currentEntry is not null; currentEntry = currentEntry._next) { if (currentEntry._lockID == lockID) { @@ -1263,7 +1263,7 @@ public static ThreadLocalLockEntry GetOrCreateCurrent(long lockID) Debug.Assert(lockID != 0); ThreadLocalLockEntry? headEntry = t_lockEntryHead; - if (headEntry != null) + if (headEntry is not null) { if (headEntry._lockID == lockID) { @@ -1286,13 +1286,13 @@ private static ThreadLocalLockEntry GetOrCreateCurrentSlow(long lockID, ThreadLo { Debug.Assert(lockID != 0); Debug.Assert(headEntry == t_lockEntryHead); - Debug.Assert(headEntry == null || headEntry._lockID != lockID); + Debug.Assert(headEntry is null || headEntry._lockID != lockID); ThreadLocalLockEntry? entry = null; ThreadLocalLockEntry? emptyEntryPrevious = null; ThreadLocalLockEntry? emptyEntry = null; - if (headEntry != null) + if (headEntry is not null) { if (headEntry.IsFree) { @@ -1300,7 +1300,7 @@ private static ThreadLocalLockEntry GetOrCreateCurrentSlow(long lockID, ThreadLo } for (ThreadLocalLockEntry? previousEntry = headEntry, currentEntry = headEntry._next; - currentEntry != null; + currentEntry is not null; previousEntry = currentEntry, currentEntry = currentEntry._next) { if (currentEntry._lockID == lockID) @@ -1313,7 +1313,7 @@ private static ThreadLocalLockEntry GetOrCreateCurrentSlow(long lockID, ThreadLo break; } - if (emptyEntry == null && currentEntry.IsFree) + if (emptyEntry is null && currentEntry.IsFree) { // Record the first empty entry in case there is no existing entry emptyEntryPrevious = previousEntry; @@ -1322,15 +1322,15 @@ private static ThreadLocalLockEntry GetOrCreateCurrentSlow(long lockID, ThreadLo } } - if (entry == null) + if (entry is null) { - if (emptyEntry != null) + if (emptyEntry is not null) { // Claim the first empty entry that was found emptyEntry._lockID = lockID; // Unlink the empty entry, preparing to move it to the head of the list - if (emptyEntryPrevious == null) + if (emptyEntryPrevious is null) { Debug.Assert(emptyEntry == headEntry); return emptyEntry; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs index d582c63a1e5be7..c43ea3615c0748 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs @@ -336,7 +336,7 @@ internal static void DistributedTransactionOutcome(InternalTransaction tx, Trans fo = tx._finalizedObject; } - if (null != fo) + if (fo is not null) { fo.Dispose(); } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs index d47da0914ef205..ecaee333833f63 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs @@ -22,7 +22,7 @@ public static class TransactionInterop { internal static DistributedTransaction ConvertToDistributedTransaction(Transaction transaction) { - if (null == transaction) + if (transaction is null) { throw new ArgumentNullException(nameof(transaction)); } @@ -62,12 +62,12 @@ internal static DistributedTransaction ConvertToDistributedTransaction(Transacti public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts) { - if (null == transaction) + if (transaction is null) { throw new ArgumentNullException(nameof(transaction)); } - if (null == whereabouts) + if (whereabouts is null) { throw new ArgumentNullException(nameof(whereabouts)); } @@ -95,7 +95,7 @@ public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts public static Transaction GetTransactionFromExportCookie(byte[] cookie) { - if (null == cookie) + if (cookie is null) { throw new ArgumentNullException(nameof(cookie)); } @@ -147,7 +147,7 @@ public static Transaction GetTransactionFromExportCookie(byte[] cookie) public static byte[] GetTransmitterPropagationToken(Transaction transaction) { - if (null == transaction) + if (transaction is null) { throw new ArgumentNullException(nameof(transaction)); } @@ -171,7 +171,7 @@ public static byte[] GetTransmitterPropagationToken(Transaction transaction) public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) { - if (null == propagationToken) + if (propagationToken is null) { throw new ArgumentNullException(nameof(propagationToken)); } @@ -194,7 +194,7 @@ public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] p // First check to see if there is a promoted LTM transaction with the same ID. If there is, just return that. Transaction? tx = TransactionManager.FindPromotedTransaction(txId); - if (null != tx) + if (tx is not null) { if (etwLog.IsEnabled()) { @@ -218,7 +218,7 @@ public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] p public static IDtcTransaction GetDtcTransaction(Transaction transaction) { - if (null == transaction) + if (transaction is null) { throw new ArgumentNullException(nameof(transaction)); } @@ -242,7 +242,7 @@ public static IDtcTransaction GetDtcTransaction(Transaction transaction) public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative) { - if (null == transactionNative) + if (transactionNative is null) { throw new ArgumentNullException(nameof(transactionNative)); } @@ -282,7 +282,7 @@ public static byte[] GetWhereabouts() internal static DistributedTransaction GetDistributedTransactionFromTransmitterPropagationToken(byte[] propagationToken) { - if (null == propagationToken) + if (propagationToken is null) { throw new ArgumentNullException(nameof(propagationToken)); } 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 4107e213ee455b..769e71a5520108 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -79,7 +79,7 @@ internal static void FireDistributedTransactionStarted(Transaction transaction) localStartedEventHandler = s_distributedTransactionStartedDelegate; } - if (null != localStartedEventHandler) + if (localStartedEventHandler is not null) { TransactionEventArgs args = new TransactionEventArgs(); args._transaction = transaction.InternalClone(); @@ -138,12 +138,12 @@ public static Enlistment Reenlist( throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } - if (null == recoveryInformation) + if (recoveryInformation is null) { throw new ArgumentNullException(nameof(recoveryInformation)); } - if (null == enlistmentNotification) + if (enlistmentNotification is null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } @@ -423,7 +423,7 @@ internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout) { Hashtable promotedTransactionTable = PromotedTransactionTable; WeakReference? weakRef = (WeakReference?)promotedTransactionTable[transactionIdentifier]; - if (null != weakRef) + if (weakRef is not null) { if (weakRef.Target is Transaction tx) { @@ -448,10 +448,10 @@ internal static Transaction FindOrCreatePromotedTransaction(Guid transactionIden lock (promotedTransactionTable) { WeakReference? weakRef = (WeakReference?)promotedTransactionTable[transactionIdentifier]; - if (null != weakRef) + if (weakRef is not null) { tx = weakRef.Target as Transaction; - if (null != tx) + if (tx is not null) { // If we found a transaction then dispose it dtx.Dispose(); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index 3a991ca09b4f4b..7db201dee0e24e 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -464,7 +464,7 @@ private void Initialize( TimeSpan scopeTimeout, bool interopModeSpecified) { - if (null == transactionToUse) + if (transactionToUse is null) { throw new ArgumentNullException(nameof(transactionToUse)); } @@ -571,15 +571,15 @@ public void Dispose() // Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None. else if (EnterpriseServicesInteropOption.None == actualCurrentScope._interopOption) { - if (((null != actualCurrentScope._expectedCurrent) && (!actualCurrentScope._expectedCurrent.Equals(current))) + if (((actualCurrentScope._expectedCurrent is not null) && (!actualCurrentScope._expectedCurrent.Equals(current))) || - ((null != current) && (null == actualCurrentScope._expectedCurrent)) + ((current is not null) && (actualCurrentScope._expectedCurrent is null)) ) { TransactionTraceIdentifier myId; TransactionTraceIdentifier currentId; - if (null == current) + if (current is null) { currentId = TransactionTraceIdentifier.Empty; } @@ -672,13 +672,13 @@ public void Dispose() if (EnterpriseServicesInteropOption.None == _interopOption) { if (((null != _expectedCurrent) && (!_expectedCurrent.Equals(current))) - || ((null != current) && (null == _expectedCurrent)) + || ((current is not null) && (null == _expectedCurrent)) ) { TransactionTraceIdentifier myId; TransactionTraceIdentifier currentId; - if (null == current) + if (current is null) { currentId = TransactionTraceIdentifier.Empty; } @@ -742,7 +742,7 @@ public void Dispose() // No try..catch here. Just let any exception thrown by InternalDispose go out. InternalDispose(); - if (null != exToThrow) + if (exToThrow is not null) { throw exToThrow; } @@ -810,7 +810,7 @@ private void InternalDispose() } else { - Debug.Assert(null != _dependentTransaction, "null != this.dependentTransaction"); + Debug.Assert(_dependentTransaction is not null, "this.dependentTransaction is not null"); _dependentTransaction.Complete(); } } @@ -867,7 +867,7 @@ public void Complete() private static void TimerCallback(object? state) { TransactionScope? scope = state as TransactionScope; - if (null == scope) + if (scope is null) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs index 3157fe62a86e0b..d1a67e53048989 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs @@ -1947,7 +1947,7 @@ internal override void CompleteAbortingClone(InternalTransaction tx) // If we have a phase1Volatile.VolatileDemux, we have a phase1 volatile enlistment // on the promoted transaction and it will take care of checking for incomplete aborting // dependent clones in its Prepare processing. - if (null != tx._phase1Volatiles.VolatileDemux) + if (tx._phase1Volatiles.VolatileDemux is not null) { tx._phase1Volatiles._dependentClones--; Debug.Assert(tx._phase1Volatiles._dependentClones >= 0); @@ -2005,7 +2005,7 @@ internal override void CreateAbortingClone(InternalTransaction tx) { // If we have a VolatileDemux in phase1Volatiles, then we have a phase1 volatile enlistment // on the promoted transaction, so we can depend on that to deal with our aborting dependent clones. - if (null != tx._phase1Volatiles.VolatileDemux) + if (tx._phase1Volatiles.VolatileDemux is not null) { tx._phase1Volatiles._dependentClones++; } @@ -3065,7 +3065,7 @@ internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exc protected override void PromotedTransactionOutcome(InternalTransaction tx) { - if ((null == tx._innerException) && (null != tx.PromotedTransaction)) + if ((tx._innerException is null) && (tx.PromotedTransaction is not null)) { tx._innerException = tx.PromotedTransaction.InnerException; } @@ -3248,7 +3248,7 @@ internal override void InDoubtFromEnlistment(InternalTransaction tx) protected override void PromotedTransactionOutcome(InternalTransaction tx) { - if ((null == tx._innerException) && (null != tx.PromotedTransaction)) + if ((tx._innerException is null) && (tx.PromotedTransaction is not null)) { tx._innerException = tx.PromotedTransaction.InnerException; } @@ -4153,7 +4153,7 @@ internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exc protected override void PromotedTransactionOutcome(InternalTransaction tx) { - if ((null == tx._innerException) && (null != tx.PromotedTransaction)) + if ((tx._innerException is null) && (tx.PromotedTransaction is not null)) { tx._innerException = tx.PromotedTransaction.InnerException; } @@ -4265,7 +4265,7 @@ internal override void ChangeStatePromotedPhase1(InternalTransaction tx) protected override void PromotedTransactionOutcome(InternalTransaction tx) { - if ((null == tx._innerException) && (null != tx.PromotedTransaction)) + if ((tx._innerException is null) && (tx.PromotedTransaction is not null)) { tx._innerException = tx.PromotedTransaction.InnerException; } diff --git a/src/libraries/System.Utf8String.Experimental/src/System/Utf8String.Portable.cs b/src/libraries/System.Utf8String.Experimental/src/System/Utf8String.Portable.cs index da0a4de8cc2d19..f7b6ffca213342 100644 --- a/src/libraries/System.Utf8String.Experimental/src/System/Utf8String.Portable.cs +++ b/src/libraries/System.Utf8String.Experimental/src/System/Utf8String.Portable.cs @@ -63,7 +63,7 @@ public Utf8String(char[] value, int startIndex, int length) [CLSCompliant(false)] public unsafe Utf8String(char* value) { - if (value == null) + if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/Mono/RuntimeHandles.cs b/src/mono/netcore/System.Private.CoreLib/src/Mono/RuntimeHandles.cs index 7e655adbbe66e9..ef45fbfd1738bf 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/Mono/RuntimeHandles.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/Mono/RuntimeHandles.cs @@ -25,7 +25,7 @@ internal RuntimeClassHandle(IntPtr ptr) public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((RuntimeClassHandle)obj).Value; @@ -40,7 +40,7 @@ public bool Equals(RuntimeClassHandle handle) public static bool operator ==(RuntimeClassHandle left, object? right) { - return right != null && right is RuntimeClassHandle rch && left.Equals(rch); + return right is not null && right is RuntimeClassHandle rch && left.Equals(rch); } public static bool operator !=(RuntimeClassHandle left, object? right) @@ -50,7 +50,7 @@ public bool Equals(RuntimeClassHandle handle) public static bool operator ==(object? left, RuntimeClassHandle right) { - return left != null && left is RuntimeClassHandle rch && rch.Equals(right); + return left is not null && left is RuntimeClassHandle rch && rch.Equals(right); } public static bool operator !=(object? left, RuntimeClassHandle right) @@ -117,7 +117,7 @@ private int GetConstraintsCount() { int i = 0; RuntimeStructs.MonoClass** p = value->constraints; - while (p != null && *p != null) + while (p is not null && *p is not null) { p++; i++; } @@ -138,7 +138,7 @@ internal RuntimeEventHandle(IntPtr v) public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((RuntimeEventHandle)obj).Value; @@ -178,7 +178,7 @@ internal RuntimePropertyHandle(IntPtr v) public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((RuntimePropertyHandle)obj).Value; diff --git a/src/mono/netcore/System.Private.CoreLib/src/Mono/SafeStringMarshal.cs b/src/mono/netcore/System.Private.CoreLib/src/Mono/SafeStringMarshal.cs index 76965c701b3981..cf7ce05f341b30 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/Mono/SafeStringMarshal.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/Mono/SafeStringMarshal.cs @@ -41,7 +41,7 @@ public IntPtr Value { get { - if (marshaled_string == IntPtr.Zero && str != null) + if (marshaled_string == IntPtr.Zero && str is not null) marshaled_string = StringToUtf8(str); return marshaled_string; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Array.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Array.Mono.cs index 00041067b23ffb..d44729f7d75ead 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Array.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Array.Mono.cs @@ -48,7 +48,7 @@ public int Rank public static unsafe void Clear(Array array, int index, int length) { - if (array == null) + if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lowerBound = array.GetLowerBound(0); @@ -76,10 +76,10 @@ public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array des public static void Copy(Array sourceArray, Array destinationArray, int length) { - if (sourceArray == null) + if (sourceArray is null) throw new ArgumentNullException(nameof(sourceArray)); - if (destinationArray == null) + if (destinationArray is null) throw new ArgumentNullException(nameof(destinationArray)); Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, @@ -93,10 +93,10 @@ public static void Copy(Array sourceArray, int sourceIndex, Array destinationArr private static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable) { - if (sourceArray == null) + if (sourceArray is null) throw new ArgumentNullException(nameof(sourceArray)); - if (destinationArray == null) + if (destinationArray is null) throw new ArgumentNullException(nameof(destinationArray)); if (length < 0) @@ -134,7 +134,7 @@ private static void Copy(Array sourceArray, int sourceIndex, Array destinationAr Type src_type = sourceArray.GetType().GetElementType()!; Type dst_type = destinationArray.GetType().GetElementType()!; - bool dst_type_vt = dst_type.IsValueType && Nullable.GetUnderlyingType(dst_type) == null; + bool dst_type_vt = dst_type.IsValueType && Nullable.GetUnderlyingType(dst_type) is null; bool src_is_enum = src_type.IsEnum; bool dst_is_enum = dst_type.IsEnum; @@ -169,7 +169,7 @@ private static void Copy(Array sourceArray, int sourceIndex, Array destinationAr if (!src_type.IsValueType && dst_is_enum) throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement); - if (dst_type_vt && (srcval == null || (src_type == typeof(object) && srcval.GetType() != dst_type))) + if (dst_type_vt && (srcval is null || (src_type == typeof(object) && srcval.GetType() != dst_type))) throw new InvalidCastException(); try @@ -260,7 +260,7 @@ public static unsafe Array CreateInstance(Type elementType, int length) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) + if (runtimeType is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); Array? array = null; @@ -279,7 +279,7 @@ public static unsafe Array CreateInstance(Type elementType, int length1, int len ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) + if (runtimeType is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); int* lengths = stackalloc int[] { length1, length2 }; @@ -301,7 +301,7 @@ public static unsafe Array CreateInstance(Type elementType, int length1, int len ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) + if (runtimeType is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); int* lengths = stackalloc int[] { length1, length2, length3 }; @@ -315,13 +315,13 @@ public static unsafe Array CreateInstance(Type elementType, params int[] lengths { if (elementType is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); - if (lengths == null) + if (lengths is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) + if (runtimeType is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); for (int i = 0; i < lengths.Length; i++) @@ -337,11 +337,11 @@ public static unsafe Array CreateInstance(Type elementType, params int[] lengths public static unsafe Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds) { - if (elementType == null) + if (elementType is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); - if (lengths == null) + if (lengths is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); - if (lowerBounds == null) + if (lowerBounds is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lowerBounds); if (lengths.Length != lowerBounds!.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds); @@ -353,7 +353,7 @@ public static unsafe Array CreateInstance(Type elementType, int[] lengths, int[] ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) + if (runtimeType is null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); Array? array = null; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs index 4f9ddf06470fbc..72ebe3f353e07d 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs @@ -9,14 +9,14 @@ public partial class Attribute { private static Attribute? GetAttr(ICustomAttributeProvider element, Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && !attributeType.IsInterface && attributeType != typeof(Attribute) && attributeType != typeof(CustomAttribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); object[] attrs = CustomAttribute.GetCustomAttributes(element, attributeType, inherit); - if (attrs == null || attrs.Length == 0) + if (attrs is null || attrs.Length == 0) return null; if (attrs.Length != 1) throw new AmbiguousMatchException(); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs index 94066bccfc5436..f3c06453be220f 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs @@ -15,7 +15,7 @@ public static Comparer Default get { Comparer? comparer = defaultComparer; - if (comparer == null) + if (comparer is null) { // Do not use static constructor. Generic static constructors are problematic for Mono AOT. Interlocked.CompareExchange(ref defaultComparer, CreateComparer(), null); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs index 0572362d3bb1b0..5e5c0734324f08 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs @@ -16,7 +16,7 @@ public static EqualityComparer Default get { EqualityComparer? comparer = defaultComparer; - if (comparer == null) + if (comparer is null) { // Do not use static constructor. Generic static constructors are problematic for Mono AOT. Interlocked.CompareExchange(ref defaultComparer, CreateComparer(), null); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs index b9589b49f9bd91..f1001b482a5406 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs @@ -145,7 +145,7 @@ public static Delegate CreateDelegate(Type type, object? firstArgument, MethodIn } Delegate? d = CreateDelegate_internal(type, firstArgument, method, throwOnBindFailure); - if (d != null) + if (d is not null) { d.original_method_info = method; d.data = delegate_data!; @@ -238,11 +238,11 @@ public static Delegate CreateDelegate(Type type, object? firstArgument, MethodIn if (ignoreCase) flags |= BindingFlags.IgnoreCase; - for (Type? targetType = target; targetType != null; targetType = targetType.BaseType) + for (Type? targetType = target; targetType is not null; targetType = targetType.BaseType) { MethodInfo? mi = targetType.GetMethod(method, flags, null, delargtypes, Array.Empty()); - if (mi != null && IsReturnTypeMatch(invoke.ReturnType!, mi.ReturnType!)) + if (mi is not null && IsReturnTypeMatch(invoke.ReturnType!, mi.ReturnType!)) { return mi; } @@ -257,7 +257,7 @@ private static bool IsMatchingCandidate(Type type, object? target, MethodInfo me { MethodInfo? invoke = type.GetMethod("Invoke"); - if (invoke == null || !IsReturnTypeMatch(invoke.ReturnType!, method.ReturnType!)) + if (invoke is null || !IsReturnTypeMatch(invoke.ReturnType!, method.ReturnType!)) { delegateData = null; return false; @@ -268,7 +268,7 @@ private static bool IsMatchingCandidate(Type type, object? target, MethodInfo me bool argLengthMatch; - if (target != null) + if (target is not null) { // delegate closed over target if (!method.IsStatic) @@ -311,7 +311,7 @@ private static bool IsMatchingCandidate(Type type, object? target, MethodInfo me bool argsMatch; delegateData = new DelegateData(); - if (target != null) + if (target is not null) { if (!method.IsStatic) { @@ -440,7 +440,7 @@ private static bool IsArgumentTypeMatchWithThis(Type delArgType, Type argType, b // replace all Type.Missing with default values defined on parameters of the delegate if any MethodInfo? invoke = GetType().GetMethod("Invoke"); - if (invoke != null && args != null) + if (invoke is not null && args is not null) { ParameterInfo[] delegateParameters = invoke.GetParameters(); for (int i = 0; i < args.Length; i++) @@ -498,16 +498,16 @@ public override bool Equals(object? obj) // Do not compare method_ptr, since it can point to a trampoline if (d._target == _target && d.Method == Method) { - if (d.data != null || data != null) + if (d.data is not null || data is not null) { /* Uncommon case */ - if (d.data != null && data != null) + if (d.data is not null && data is not null) return (d.data.target_type == data.target_type && d.data.method_name == data.method_name); else { - if (d.data != null) + if (d.data is not null) return d.data.target_type is null; - if (data != null) + if (data is not null) return data.target_type is null; return false; } @@ -522,12 +522,12 @@ public override int GetHashCode() { MethodInfo? m = Method; - return (m != null ? m.GetHashCode() : GetType().GetHashCode()) ^ RuntimeHelpers.GetHashCode(_target); + return (m is not null ? m.GetHashCode() : GetType().GetHashCode()) ^ RuntimeHelpers.GetHashCode(_target); } protected virtual MethodInfo GetMethodImpl() { - if (method_info != null) + if (method_info is not null) return method_info; if (method != IntPtr.Zero) @@ -546,14 +546,14 @@ private DelegateData CreateDelegateData() DelegateData delegate_data = new DelegateData(); if (method_info!.IsStatic) { - if (_target != null) + if (_target is not null) { delegate_data.curried_first_arg = true; } else { MethodInfo? invoke = GetType().GetMethod("Invoke"); - if (invoke != null && invoke.GetParametersCount() + 1 == method_info.GetParametersCount()) + if (invoke is not null && invoke.GetParametersCount() + 1 == method_info.GetParametersCount()) delegate_data.curried_first_arg = true; } } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs index e026e51adbe05a..0c492b397ea4a5 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs @@ -45,7 +45,7 @@ private void InitializeForCurrentThread(int skipFrames, bool needFileInfo) while (skipFrames >= 0) { sf = new StackFrame(skipFrames, needFileInfo); - if (sf.GetMethod() == null) + if (sf.GetMethod() is null) { break; } @@ -65,7 +65,7 @@ private void InitializeForException(Exception e, int skipFrames, bool needFileIn int foreignFrames; MonoStackFrame[]? foreignExceptions = e.foreignExceptionsFrames; - if (foreignExceptions != null) + if (foreignExceptions is not null) { foreignFrames = foreignExceptions.Length; _numOfFrames += foreignFrames; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs index 3e342b73b6c984..71dd77605ce184 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs @@ -27,7 +27,7 @@ private static EnumInfo GetEnumInfo(RuntimeType enumType, bool getNames = true) { EnumInfo? entry = enumType.Cache.EnumInfo; - if (entry == null || (getNames && entry.Names == null)) + if (entry is null || (getNames && entry.Names is null)) { if (!GetEnumValuesAndNames(enumType, out ulong[]? values, out string[]? names)) Array.Sort(values, names, Collections.Generic.Comparer.Default); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs index 1b75ae0abbc2ba..dde28abd3f63c0 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs @@ -16,9 +16,9 @@ public partial class Environment private static string? GetEnvironmentVariableCore(string variable) { - Debug.Assert(variable != null); + Debug.Assert(variable is not null); - if (s_environment == null) + if (s_environment is null) { return InternalGetEnvironmentVariable(variable); } @@ -41,13 +41,13 @@ private static string InternalGetEnvironmentVariable(string name) private static unsafe void SetEnvironmentVariableCore(string variable, string? value) { - Debug.Assert(variable != null); + Debug.Assert(variable is not null); EnsureEnvironmentCached(); lock (s_environment!) { variable = TrimStringOnFirstZero(variable); - value = value == null ? null : TrimStringOnFirstZero(value); + value = value is null ? null : TrimStringOnFirstZero(value); if (string.IsNullOrEmpty(value)) { s_environment.Remove(variable); @@ -87,7 +87,7 @@ private static string TrimStringOnFirstZero(string value) private static void EnsureEnvironmentCached() { - if (s_environment == null) + if (s_environment is null) { Interlocked.CompareExchange(ref s_environment, GetSystemEnvironmentVariables(), null); } @@ -99,7 +99,7 @@ private static Dictionary GetSystemEnvironmentVariables() foreach (string name in GetEnvironmentVariableNames()) { - if (name != null) + if (name is not null) { results.Add(name, InternalGetEnvironmentVariable(name)); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Environment.iOS.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Environment.iOS.cs index 1a95bdc408f1c2..8a4680d9b3dac1 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Environment.iOS.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Environment.iOS.cs @@ -15,7 +15,7 @@ public static partial class Environment private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) { - if (s_specialFolders == null) + if (s_specialFolders is null) { Interlocked.CompareExchange(ref s_specialFolders, new Dictionary(), null); } @@ -96,7 +96,7 @@ private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOptio static string CombineSearchPath(NSSearchPathDirectory searchPath, string subdirectory) { string? path = Interop.Sys.SearchPath(searchPath); - return path != null ? + return path is not null ? Path.Combine(path, subdirectory) : string.Empty; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs index dbe3dcb0c6c4ac..dd52795b41180a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs @@ -60,9 +60,9 @@ public MethodBase? TargetSite string? stackTraceString = _stackTraceString; string? remoteStackTraceString = _remoteStackTraceString; - if (stackTraceString != null) + if (stackTraceString is not null) return remoteStackTraceString + stackTraceString; - if (_traceIPs == null) + if (_traceIPs is null) return remoteStackTraceString; return remoteStackTraceString + new StackTrace(this, needFileInfo).ToString(Diagnostics.StackTrace.TraceFormat.Normal); @@ -72,12 +72,12 @@ internal DispatchState CaptureDispatchState() { MonoStackFrame[]? stackFrames; - if (_traceIPs != null) + if (_traceIPs is not null) { stackFrames = Diagnostics.StackTrace.get_trace(this, 0, true); stackFrames[stackFrames.Length - 1].isLastFrameFromForeignException = true; - if (foreignExceptionsFrames != null) + if (foreignExceptionsFrames is not null) { var combinedStackFrames = new MonoStackFrame[stackFrames.Length + foreignExceptionsFrames.Length]; Array.Copy(foreignExceptionsFrames, 0, combinedStackFrames, 0, foreignExceptionsFrames.Length); @@ -105,7 +105,7 @@ internal void RestoreDispatchState(in DispatchState state) internal void SetCurrentStackTrace() { // Check to see if the exception already has a stack set in it. - if (_traceIPs != null || _stackTraceString != null || _remoteStackTraceString != null) + if (_traceIPs is not null || _stackTraceString is not null || _remoteStackTraceString is not null) { ThrowHelper.ThrowInvalidOperationException(); } @@ -130,10 +130,10 @@ internal void SetCurrentStackTrace() Module? module = method?.Module; RuntimeModule? rtModule = module as RuntimeModule; - if (rtModule == null) + if (rtModule is null) { var moduleBuilder = module as System.Reflection.Emit.ModuleBuilder; - if (moduleBuilder != null) + if (moduleBuilder is not null) throw new NotImplementedException(); // TODO: rtModule = moduleBuilder.InternalModule; else throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs index f121f038dec600..23e63a217efdb9 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs @@ -111,7 +111,7 @@ public static void KeepAlive(object? obj) public static int GetGeneration(WeakReference wo) { object? obj = wo.Target; - if (obj == null) + if (obj is null) throw new ArgumentException(null, nameof(wo)); return GetGeneration(obj); } @@ -132,7 +132,7 @@ public static int MaxGeneration public static void SuppressFinalize(object obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); _SuppressFinalize(obj); } @@ -142,7 +142,7 @@ public static void SuppressFinalize(object obj) public static void ReRegisterForFinalize(object obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); _ReRegisterForFinalize(obj); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs b/src/mono/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs index a29e584f4d4ce1..385bdd542166f7 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs @@ -51,7 +51,7 @@ public RuntimeTypeHandle ResolveTypeHandle(int typeToken) private static IntPtr[]? ptrs_from_handles(RuntimeTypeHandle[]? handles) { - if (handles == null) + if (handles is null) return null; var res = new IntPtr[handles.Length]; @@ -114,7 +114,7 @@ public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((ModuleHandle)obj).Value; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs b/src/mono/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs index 5582c760b6c2aa..c92e9a824fddd6 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs @@ -29,7 +29,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont protected sealed override object? DynamicInvokeImpl(object?[]? args) { - if (delegates == null) + if (delegates is null) { return base.DynamicInvokeImpl(args); } @@ -56,7 +56,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont // Do not remove this API internal bool HasSingleTarget { - get { return delegates == null; } + get { return delegates is null; } } // @@ -71,11 +71,11 @@ public sealed override bool Equals(object? obj) if (!(obj is MulticastDelegate d)) return false; - if (delegates == null && d.delegates == null) + if (delegates is null && d.delegates is null) { return true; } - else if (delegates == null ^ d.delegates == null) + else if (delegates is null ^ d.delegates is null) { return false; } @@ -104,7 +104,7 @@ public sealed override int GetHashCode() protected override MethodInfo GetMethodImpl() { - if (delegates != null) + if (delegates is not null) return delegates[delegates.Length - 1].Method; return base.GetMethodImpl(); @@ -116,7 +116,7 @@ protected override MethodInfo GetMethodImpl() // public sealed override Delegate[] GetInvocationList() { - if (delegates != null) + if (delegates is not null) return (Delegate[])delegates.Clone(); else return new Delegate[1] { this }; @@ -130,25 +130,25 @@ public sealed override Delegate[] GetInvocationList() // protected sealed override Delegate CombineImpl(Delegate? follow) { - if (follow == null) + if (follow is null) return this; MulticastDelegate other = (MulticastDelegate)follow; MulticastDelegate ret = AllocDelegateLike_internal(this); - if (delegates == null && other.delegates == null) + if (delegates is null && other.delegates is null) { ret.delegates = new Delegate[2] { this, other }; } - else if (delegates == null) + else if (delegates is null) { ret.delegates = new Delegate[1 + other.delegates!.Length]; ret.delegates[0] = this; Array.Copy(other.delegates, 0, ret.delegates, 1, other.delegates.Length); } - else if (other.delegates == null) + else if (other.delegates is null) { ret.delegates = new Delegate[delegates.Length + 1]; @@ -197,18 +197,18 @@ private static int LastIndexOf(Delegate[] haystack, Delegate[] needle) protected sealed override Delegate? RemoveImpl(Delegate value) { - if (value == null) + if (value is null) return this; MulticastDelegate other = (MulticastDelegate)value; - if (delegates == null && other.delegates == null) + if (delegates is null && other.delegates is null) { /* if they are not equal and the current one is not * a multicastdelegate then we cannot delete it */ return this.Equals(other) ? null : this; } - else if (delegates == null) + else if (delegates is null) { foreach (Delegate? d in other.delegates!) { @@ -217,7 +217,7 @@ private static int LastIndexOf(Delegate[] haystack, Delegate[] needle) } return this; } - else if (other.delegates == null) + else if (other.delegates is null) { int idx = Array.LastIndexOf(delegates, other); if (idx == -1) @@ -268,16 +268,16 @@ private static int LastIndexOf(Delegate[] haystack, Delegate[] needle) public static bool operator ==(MulticastDelegate? d1, MulticastDelegate? d2) { - if (d1 == null) - return d2 == null; + if (d1 is null) + return d2 is null; return d1.Equals(d2); } public static bool operator !=(MulticastDelegate? d1, MulticastDelegate? d2) { - if (d1 == null) - return d2 != null; + if (d1 is null) + return d2 is not null; return !d1.Equals(d2); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs index 23f7668e73549b..8326a67b34e22a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs @@ -22,14 +22,14 @@ public partial struct Nullable private static T? Unbox(object o) { - if (o == null) + if (o is null) return null; return (T)o; } private static T? UnboxExact(object o) { - if (o == null) + if (o is null) return null; if (o.GetType() != typeof(T)) throw new InvalidCastException(); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs index a6cd32e850f3ad..14fe9b49e0d2fd 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs @@ -17,7 +17,7 @@ public partial class Assembly [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly? LoadWithPartialName(string partialName) { - if (partialName == null) + if (partialName is null) throw new ArgumentNullException(nameof(partialName)); if (partialName.Length == 0 || partialName[0] == '\0') @@ -58,7 +58,7 @@ public static Assembly GetExecutingAssembly() [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(string assemblyString) { - if (assemblyString == null) + if (assemblyString is null) throw new ArgumentNullException(nameof(assemblyString)); var name = new AssemblyName(assemblyString); @@ -71,7 +71,7 @@ public static Assembly Load(string assemblyString) [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(AssemblyName assemblyRef) { - if (assemblyRef == null) + if (assemblyRef is null) throw new ArgumentNullException(nameof(assemblyRef)); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -81,8 +81,8 @@ public static Assembly Load(AssemblyName assemblyRef) internal static Assembly Load(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext? assemblyLoadContext) { // TODO: pass AssemblyName - Assembly? assembly = InternalLoad(assemblyRef.FullName, ref stackMark, assemblyLoadContext != null ? assemblyLoadContext.NativeALC : IntPtr.Zero); - if (assembly == null) + Assembly? assembly = InternalLoad(assemblyRef.FullName, ref stackMark, assemblyLoadContext is not null ? assemblyLoadContext.NativeALC : IntPtr.Zero); + if (assembly is null) throw new FileNotFoundException(null, assemblyRef.Name); return assembly; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs index 88ad8e1c5a5967..514d943b7649b4 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs @@ -15,7 +15,7 @@ public partial class AssemblyName { public AssemblyName(string assemblyName) { - if (assemblyName == null) + if (assemblyName is null) throw new ArgumentNullException(nameof(assemblyName)); if (assemblyName.Length == 0 || assemblyName[0] == '\0') throw new ArgumentException(SR.Format_StringZeroLength); @@ -42,7 +42,7 @@ public AssemblyName(string assemblyName) private unsafe byte[]? ComputePublicKeyToken() { - if (_publicKey == null) + if (_publicKey is null) return null; if (_publicKey.Length == 0) return Array.Empty(); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs index 0f12e9cea4773f..ad6fac98a3390e 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs @@ -48,7 +48,7 @@ private static bool IsUserCattrProvider(object obj) return false; if ((obj is Type)) return true; - if (corlib == null) + if (corlib is null) corlib = typeof(int).Assembly; return obj.GetType().Assembly != corlib; } @@ -69,7 +69,7 @@ private static bool IsUserCattrProvider(object obj) else if (obj is Type t) pseudoAttrs = GetPseudoCustomAttributes(t); - if ((attributeType != null) && (pseudoAttrs != null)) + if ((attributeType is not null) && (pseudoAttrs is not null)) { for (int i = 0; i < pseudoAttrs.Length; ++i) if (attributeType.IsAssignableFrom(pseudoAttrs[i].GetType())) @@ -124,7 +124,7 @@ internal static object[] GetCustomAttributesBase(ICustomAttributeProvider obj, T if (!inheritedOnly) { object[]? pseudoAttrs = GetPseudoCustomAttributes(obj, attributeType!); - if (pseudoAttrs != null) + if (pseudoAttrs is not null) { object[] res = new Attribute[attrs.Length + pseudoAttrs.Length]; Array.Copy(attrs, res, attrs.Length); @@ -138,9 +138,9 @@ internal static object[] GetCustomAttributesBase(ICustomAttributeProvider obj, T internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type attributeType, bool inherit) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && !attributeType.IsInterface && attributeType != typeof(Attribute) && attributeType != typeof(CustomAttribute) && attributeType != typeof(object)) @@ -159,10 +159,10 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type // shortcut if (!inherit && res.Length == 1) { - if (res[0] == null) + if (res[0] is null) throw new CustomAttributeFormatException("Invalid custom attribute format"); - if (attributeType != null) + if (attributeType is not null) { if (attributeType.IsAssignableFrom(res[0].GetType())) { @@ -182,12 +182,12 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type return r; } - if (inherit && GetBase(obj) == null) + if (inherit && GetBase(obj) is null) inherit = false; // if AttributeType is sealed, and Inherited is set to false, then // there's no use in scanning base types - if ((attributeType != null && attributeType.IsSealed) && inherit) + if ((attributeType is not null && attributeType.IsSealed) && inherit) { AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage( attributeType); @@ -203,11 +203,11 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type /* Non-inherit case */ if (!inherit) { - if (attributeType == null) + if (attributeType is null) { foreach (object attr in res) { - if (attr == null) + if (attr is null) throw new CustomAttributeFormatException("Invalid custom attribute format"); } var result = new Attribute[res.Length]; @@ -218,16 +218,16 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type a = new List(initialSize); foreach (object attr in res) { - if (attr == null) + if (attr is null) throw new CustomAttributeFormatException("Invalid custom attribute format"); Type attrType = attr.GetType(); - if (attributeType != null && !attributeType.IsAssignableFrom(attrType)) + if (attributeType is not null && !attributeType.IsAssignableFrom(attrType)) continue; a.Add(attr); } - if (attributeType == null || attributeType.IsValueType) + if (attributeType is null || attributeType.IsValueType) array = new Attribute[a.Count]; else array = (Array.CreateInstance(attributeType, a.Count) as object[])!; @@ -245,11 +245,11 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type foreach (object attr in res) { AttributeUsageAttribute usage; - if (attr == null) + if (attr is null) throw new CustomAttributeFormatException("Invalid custom attribute format"); Type attrType = attr.GetType(); - if (attributeType != null) + if (attributeType is not null) { if (!attributeType.IsAssignableFrom(attrType)) continue; @@ -271,22 +271,23 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type // - the attribute is on same inheritance level than the first // attribute that was discovered for this attribute type )) if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple || - (firstAttribute == null || (firstAttribute != null + (firstAttribute is null || (firstAttribute is not null && firstAttribute.InheritanceLevel == inheritanceLevel)))) a.Add(attr); - if (firstAttribute == null) + if (firstAttribute is null) attributeInfos.Add(attrType, new AttributeInfo(usage, inheritanceLevel)); } - if ((btype = GetBase(btype)) != null) + btype = GetBase(btype); + if (btype is not null) { inheritanceLevel++; res = GetCustomAttributesBase(btype, attributeType, true); } - } while (inherit && btype != null); + } while (inherit && btype is not null); - if (attributeType == null || attributeType.IsValueType) + if (attributeType is null || attributeType.IsValueType) array = new Attribute[a.Count]; else array = (Array.CreateInstance(attributeType, a.Count) as object[])!; @@ -299,7 +300,7 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, bool inherit) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); if (!inherit) @@ -316,7 +317,7 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, bool internal static IList GetCustomAttributesData(ICustomAttributeProvider obj, bool inherit = false) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); if (!inherit) @@ -327,9 +328,9 @@ internal static IList GetCustomAttributesData(ICustomAttrib internal static IList GetCustomAttributesData(ICustomAttributeProvider obj, Type? attributeType, bool inherit) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); if (attributeType == typeof(CustomAttribute)) @@ -341,9 +342,9 @@ internal static IList GetCustomAttributesData(ICustomAttrib // shortcut if (!inherit && res.Count == 1) { - if (res[0] == null) + if (res[0] is null) throw new CustomAttributeFormatException(Message); - if (attributeType != null) + if (attributeType is not null) { if (attributeType.IsAssignableFrom(res[0].AttributeType)) r = new CustomAttributeData[] { res[0] }; @@ -358,12 +359,12 @@ internal static IList GetCustomAttributesData(ICustomAttrib return r; } - if (inherit && GetBase(obj) == null) + if (inherit && GetBase(obj) is null) inherit = false; // if AttributeType is sealed, and Inherited is set to false, then // there's no use in scanning base types - if ((attributeType != null && attributeType.IsSealed) && inherit) + if ((attributeType is not null && attributeType.IsSealed) && inherit) { AttributeUsageAttribute? usageAttribute = RetrieveAttributeUsage(attributeType); if (!usageAttribute.Inherited) @@ -377,11 +378,11 @@ internal static IList GetCustomAttributesData(ICustomAttrib /* Non-inherit case */ if (!inherit) { - if (attributeType == null) + if (attributeType is null) { foreach (CustomAttributeData attrData in res) { - if (attrData == null) + if (attrData is null) throw new CustomAttributeFormatException(Message); } @@ -394,7 +395,7 @@ internal static IList GetCustomAttributesData(ICustomAttrib a = new List(initialSize); foreach (CustomAttributeData attrData in res) { - if (attrData == null) + if (attrData is null) throw new CustomAttributeFormatException(Message); if (!attributeType.IsAssignableFrom(attrData.AttributeType)) continue; @@ -415,11 +416,11 @@ internal static IList GetCustomAttributesData(ICustomAttrib foreach (CustomAttributeData attrData in res) { AttributeUsageAttribute usage; - if (attrData == null) + if (attrData is null) throw new CustomAttributeFormatException(Message); Type attrType = attrData.AttributeType; - if (attributeType != null) + if (attributeType is not null) { if (!attributeType.IsAssignableFrom(attrType)) continue; @@ -443,20 +444,21 @@ internal static IList GetCustomAttributesData(ICustomAttrib // - the attribute is on same inheritance level than the first // attribute that was discovered for this attribute type )) if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple || - (firstAttribute == null || (firstAttribute != null + (firstAttribute is null || (firstAttribute is not null && firstAttribute.InheritanceLevel == inheritanceLevel)))) a.Add(attrData); - if (firstAttribute == null) + if (firstAttribute is null) attributeInfos.Add(attrType, new AttributeInfo(usage, inheritanceLevel)); } - if ((btype = GetBase(btype)) != null) + btype = GetBase(btype); + if (btype is not null) { inheritanceLevel++; res = GetCustomAttributesDataBase(btype, attributeType, true); } - } while (inherit && btype != null); + } while (inherit && btype is not null); return a.ToArray(); } @@ -480,7 +482,7 @@ internal static IList GetCustomAttributesDataBase(ICustomAt if (!inheritedOnly) { CustomAttributeData[]? pseudoAttrsData = GetPseudoCustomAttributesData(obj, attributeType); - if (pseudoAttrsData != null) + if (pseudoAttrsData is not null) { if (attrsData.Length == 0) return Array.AsReadOnly(pseudoAttrsData); @@ -508,7 +510,7 @@ internal static IList GetCustomAttributesDataBase(ICustomAt else if (obj is Type t) pseudoAttrsData = GetPseudoCustomAttributesData(t); - if ((attributeType != null) && (pseudoAttrsData != null)) + if ((attributeType is not null) && (pseudoAttrsData is not null)) { for (int i = 0; i < pseudoAttrsData.Length; ++i) { @@ -553,7 +555,7 @@ internal static IList GetCustomAttributesDataBase(ICustomAt internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && !attributeType.IsInterface && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); @@ -568,14 +570,14 @@ internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, return true; object[]? pseudoAttrs = GetPseudoCustomAttributes(obj, attributeType); - if (pseudoAttrs != null) + if (pseudoAttrs is not null) { for (int i = 0; i < pseudoAttrs.Length; ++i) if (attributeType.IsAssignableFrom(pseudoAttrs[i].GetType())) return true; } - if (usage == null) + if (usage is null) { if (!inherit) return false; @@ -586,7 +588,7 @@ internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, } obj = GetBase(obj)!; - } while (obj != null); + } while (obj is not null); return false; } @@ -599,16 +601,16 @@ internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, private static PropertyInfo? GetBasePropertyDefinition(RuntimePropertyInfo property) { MethodInfo? method = property.GetGetMethod(true); - if (method == null || !method.IsVirtual) + if (method is null || !method.IsVirtual) method = property.GetSetMethod(true); - if (method == null || !method.IsVirtual) + if (method is null || !method.IsVirtual) return null; MethodInfo baseMethod = ((RuntimeMethodInfo)method).GetBaseMethod(); - if (baseMethod != null && baseMethod != method) + if (baseMethod is not null && baseMethod != method) { ParameterInfo[] parameters = property.GetIndexParameters(); - if (parameters != null && parameters.Length > 0) + if (parameters is not null && parameters.Length > 0) { Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < paramTypes.Length; i++) @@ -630,15 +632,15 @@ internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, private static EventInfo? GetBaseEventDefinition(RuntimeEventInfo evt) { MethodInfo? method = evt.GetAddMethod(true); - if (method == null || !method.IsVirtual) + if (method is null || !method.IsVirtual) method = evt.GetRaiseMethod(true); - if (method == null || !method.IsVirtual) + if (method is null || !method.IsVirtual) method = evt.GetRemoveMethod(true); - if (method == null || !method.IsVirtual) + if (method is null || !method.IsVirtual) return null; MethodInfo baseMethod = ((RuntimeMethodInfo)method).GetBaseMethod(); - if (baseMethod != null && baseMethod != method) + if (baseMethod is not null && baseMethod != method) { BindingFlags flags = method.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic; flags |= method.IsStatic ? BindingFlags.Static : BindingFlags.Instance; @@ -653,7 +655,7 @@ internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, // but for those we return null here. private static ICustomAttributeProvider? GetBase(ICustomAttributeProvider obj) { - if (obj == null) + if (obj is null) return null; if (obj is Type) @@ -687,7 +689,7 @@ internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, * RuntimeEventInfo -> null * RuntimeFieldInfo -> null */ - if (method == null || !method.IsVirtual) + if (method is null || !method.IsVirtual) return null; MethodInfo baseMethod = ((RuntimeMethodInfo)method).GetBaseMethod(); @@ -709,12 +711,12 @@ private static AttributeUsageAttribute RetrieveAttributeUsageNoCache(Type attrib { // if no AttributeUsage was defined on the attribute level, then // try to retrieve if from its base type - if (attributeType.BaseType != null) + if (attributeType.BaseType is not null) { usageAttribute = RetrieveAttributeUsage(attributeType.BaseType); } - if (usageAttribute != null) + if (usageAttribute is not null) { // return AttributeUsage of base class return usageAttribute; @@ -740,7 +742,7 @@ private static AttributeUsageAttribute RetrieveAttributeUsage(Type attributeType { AttributeUsageAttribute? usageAttribute = null; /* Usage a thread-local cache to speed this up, since it is called a lot from GetCustomAttributes () */ - if (usage_cache == null) + if (usage_cache is null) usage_cache = new Dictionary(); if (usage_cache.TryGetValue(attributeType, out usageAttribute)) return usageAttribute; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs index ec376ae88b6872..8cdbe882d6f658 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs @@ -80,15 +80,15 @@ internal CustomAttributeData(ConstructorInfo ctorInfo, IList - (ctor_args != null ? UnboxValues(ctor_args) : Array.Empty()); + (ctor_args is not null ? UnboxValues(ctor_args) : Array.Empty()); this.namedArgs = Array.AsReadOnly - (named_args != null ? UnboxValues(named_args) : Array.Empty()); + (named_args is not null ? UnboxValues(named_args) : Array.Empty()); lazyData = null; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs index 34eaf34c90ceae..234d937d45bf79 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs @@ -62,7 +62,7 @@ internal GenericInstanceKey(Type gtd, Type[] args) private static bool IsBoundedVector(Type type) { ArrayType? at = type as ArrayType; - if (at != null) + if (at is not null) return at.GetEffectiveRank() == 1; return type.ToString().EndsWith("[*]", StringComparison.Ordinal); /*Super uggly hack, SR doesn't allow one to query for it */ } @@ -144,7 +144,7 @@ depend on proper UT canonicalization. public override bool Equals(object? obj) { GenericInstanceKey? other = obj as GenericInstanceKey; - if (other == null) + if (other is null) return false; if (gtd != other.gtd) return false; @@ -238,13 +238,13 @@ private AssemblyBuilder(AssemblyName n, string? directory, AssemblyBuilderAccess dir = directory; /* Set defaults from n */ - if (n.CultureInfo != null) + if (n.CultureInfo is not null) { culture = n.CultureInfo.Name; versioninfo_culture = n.CultureInfo.Name; } Version? v = n.Version; - if (v != null) + if (v is not null) { version = v.ToString(); } @@ -284,7 +284,7 @@ public override bool ReflectionOnly public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return new AssemblyBuilder(name, null, access, false); @@ -293,7 +293,7 @@ public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyB public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable? assemblyAttributes) { AssemblyBuilder ab = DefineDynamicAssembly(name, access); - if (assemblyAttributes != null) + if (assemblyAttributes is not null) { foreach (CustomAttributeBuilder attr in assemblyAttributes) ab.SetCustomAttribute(attr); @@ -309,7 +309,7 @@ public ModuleBuilder DefineDynamicModule(string name) public ModuleBuilder DefineDynamicModule(string name, bool emitSymbolInfo) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("Empty name is not legal.", nameof(name)); @@ -324,12 +324,12 @@ public ModuleBuilder DefineDynamicModule(string name, bool emitSymbolInfo) public ModuleBuilder? GetDynamicModule(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("Empty name is not legal.", nameof(name)); - if (modules != null) + if (modules is not null) for (int i = 0; i < modules.Length; ++i) if (modules[i].name == name) return modules[i]; @@ -389,10 +389,10 @@ internal string? AssemblyDir public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -411,9 +411,9 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) [ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); @@ -434,7 +434,7 @@ internal static Type MakeGenericType(Type gtd, Type[] typeArguments) [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string name, bool throwOnError, bool ignoreCase) { - if (name == null) + if (name is null) throw new ArgumentNullException(name); if (name.Length == 0) throw new ArgumentException("Name cannot be empty", nameof(name)); @@ -451,12 +451,12 @@ internal static Type MakeGenericType(Type gtd, Type[] typeArguments) public override Module? GetModule(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("Name can't be empty"); - if (modules == null) + if (modules is null) return null; foreach (Module module in modules) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs index b3127b95c6d420..49c92985ebf4e8 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs @@ -67,10 +67,10 @@ internal ConstructorBuilder(TypeBuilder tb, MethodAttributes attributes, Calling { attrs = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; call_conv = callingConvention; - if (parameterTypes != null) + if (parameterTypes is not null) { for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes[i] == null) + if (parameterTypes[i] is null) throw new ArgumentException("Elements of the parameterTypes array cannot be null", nameof(parameterTypes)); this.parameters = new Type[parameterTypes.Length]; @@ -128,7 +128,7 @@ public override ParameterInfo[] GetParameters() internal override ParameterInfo[] GetParametersInternal() { - if (parameters == null) + if (parameters is null) return Array.Empty(); ParameterInfo[] retval = new ParameterInfo[parameters.Length]; @@ -140,7 +140,7 @@ internal override ParameterInfo[] GetParametersInternal() internal override int GetParametersCount() { - if (parameters == null) + if (parameters is null) return 0; return parameters.Length; @@ -258,7 +258,7 @@ public ILGenerator GetILGenerator(int streamSize) { if (finished) throw new InvalidOperationException(); - if (ilgen != null) + if (ilgen is not null) return ilgen; if (!(((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0))) throw new InvalidOperationException(); @@ -268,7 +268,7 @@ public ILGenerator GetILGenerator(int streamSize) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; @@ -281,7 +281,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) SetImplementationFlags((MethodImplAttributes)impla); return; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -298,9 +298,9 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) [ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); @@ -336,26 +336,26 @@ internal void fixup() { if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) { - if ((ilgen == null) || (ilgen.ILOffset == 0)) + if ((ilgen is null) || (ilgen.ILOffset == 0)) throw new InvalidOperationException("Method '" + Name + "' does not have a method body."); } if (IsStatic && ((call_conv & CallingConventions.VarArgs) != 0 || (call_conv & CallingConventions.HasThis) != 0)) throw new TypeLoadException(); - if (ilgen != null) + if (ilgen is not null) ilgen.label_fixup(this); } internal void ResolveUserTypes() { TypeBuilder.ResolveUserTypes(parameters); - if (paramModReq != null) + if (paramModReq is not null) { foreach (Type[] types in paramModReq) TypeBuilder.ResolveUserTypes(types); } - if (paramModOpt != null) + if (paramModOpt is not null) { foreach (Type[] types in paramModOpt) TypeBuilder.ResolveUserTypes(types); @@ -364,7 +364,7 @@ internal void ResolveUserTypes() /* internal void GenerateDebugInfo (ISymbolWriter symbolWriter) { - if (ilgen != null && ilgen.HasDebugInfo) { + if (ilgen is not null && ilgen.HasDebugInfo) { SymbolToken token = new SymbolToken (GetToken().Token); symbolWriter.OpenMethod (token); symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name)); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs index 7f26920c5e52d8..e857b2b4d4ff53 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs @@ -79,9 +79,9 @@ internal object Invoke() internal CustomAttributeBuilder(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); ctor = con; data = (byte[])binaryAttribute.Clone(); @@ -147,13 +147,13 @@ private static bool IsValidParam(object o, Type paramType) private static bool IsValidValue(Type type, object? value) { - if (type.IsValueType && value == null) + if (type.IsValueType && value is null) return false; if (type.IsArray && type.GetElementType()!.IsValueType) { foreach (object? v in (Array)value!) { - if (v == null) + if (v is null) return false; } } @@ -171,17 +171,17 @@ private void Initialize(ConstructorInfo con, object?[] constructorArgs, this.namedFields = namedFields; this.fieldValues = fieldValues; - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (constructorArgs == null) + if (constructorArgs is null) throw new ArgumentNullException(nameof(constructorArgs)); - if (namedProperties == null) + if (namedProperties is null) throw new ArgumentNullException(nameof(namedProperties)); - if (propertyValues == null) + if (propertyValues is null) throw new ArgumentNullException(nameof(propertyValues)); - if (namedFields == null) + if (namedFields is null) throw new ArgumentNullException(nameof(namedFields)); - if (fieldValues == null) + if (fieldValues is null) throw new ArgumentNullException(nameof(fieldValues)); if (con.GetParametersCount() != constructorArgs.Length) throw new ArgumentException(SR.Argument_BadParameterCountsForConstructor); @@ -210,7 +210,7 @@ private void Initialize(ConstructorInfo con, object?[] constructorArgs, if (!IsValidValue(fi.FieldType, fieldValues[i])) throw new ArgumentException("Field " + fi.Name + " is not a valid value."); // FIXME: Check enums and TypeBuilders as well - if (fieldValues[i] != null) + if (fieldValues[i] is not null) // IsEnum does not seem to work on TypeBuilders if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType(fieldValues[i])) { @@ -236,7 +236,7 @@ private void Initialize(ConstructorInfo con, object?[] constructorArgs, throw new ArgumentException("Property '" + pi.Name + "' does not have a valid type."); if (!IsValidValue(pi.PropertyType, propertyValues[i])) throw new ArgumentException("Property " + pi.Name + " is not a valid value."); - if (propertyValues[i] != null) + if (propertyValues[i] is not null) { if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType(propertyValues[i])) if (!pi.PropertyType.IsArray) @@ -248,7 +248,7 @@ private void Initialize(ConstructorInfo con, object?[] constructorArgs, i = 0; foreach (ParameterInfo pi in GetParameters(con)) { - if (pi != null) + if (pi is not null) { Type paramType = pi.ParameterType; if (!IsValidType(paramType)) @@ -256,7 +256,7 @@ private void Initialize(ConstructorInfo con, object?[] constructorArgs, if (!IsValidValue(paramType, constructorArgs[i])) throw new ArgumentException("Parameter " + i + " is not a valid value."); - if (constructorArgs[i] != null) + if (constructorArgs[i] is not null) { if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType(constructorArgs[i])) if (!paramType.IsArray) @@ -401,7 +401,7 @@ internal static UnmanagedMarshal get_umarshal(CustomAttributeBuilder customBuild break; case "MarshalTypeRef": marshalTypeName = decode_string(data, pos, out pos); - if (marshalTypeName != null) + if (marshalTypeName is not null) marshalTypeRef = Type.GetType(marshalTypeName); break; case "MarshalCookie": @@ -551,11 +551,11 @@ internal static CustomAttributeInfo decode_cattr(CustomAttributeBuilder customBu { /* Field */ FieldInfo? fi = ctor.DeclaringType!.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - if (fi == null) + if (fi is null) throw new Exception("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'"); object? val = decode_cattr_value(fi.FieldType, data, pos, out pos); - if (enum_type_name != null) + if (enum_type_name is not null) { Type enumType = Type.GetType(enum_type_name)!; val = Enum.ToObject(enumType, val!); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs index 707cf5274ead69..fb8b0336a5e1bd 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs @@ -101,7 +101,7 @@ public override string? AssemblyQualifiedName get { string? fullName = FormatName(m_baseType.FullName); - if (fullName == null) + if (fullName is null) return null; return fullName + ", " + m_baseType.Assembly.FullName; } @@ -342,7 +342,7 @@ public override Type GetElementType() protected override bool HasElementTypeImpl() { - return m_baseType != null; + return m_baseType is not null; } public override object[] GetCustomAttributes(bool inherit) @@ -416,7 +416,7 @@ public override int GetArrayRank() [return: NotNullIfNotNull("elementName")] internal override string? FormatName(string? elementName) { - if (elementName == null) + if (elementName is null) return null; StringBuilder sb = new StringBuilder(elementName); sb.Append('['); @@ -449,7 +449,7 @@ protected override bool IsByRefImpl() [return: NotNullIfNotNull("elementName")] internal override string? FormatName(string? elementName) { - if (elementName == null) + if (elementName is null) return null; return elementName + "&"; } @@ -495,7 +495,7 @@ protected override bool IsPointerImpl() [return: NotNullIfNotNull("elementName")] internal override string? FormatName(string? elementName) { - if (elementName == null) + if (elementName is null) return null; return elementName + "*"; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs index e01a0583235907..53f9455e22e6ef 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs @@ -113,7 +113,7 @@ public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { if (codeSize < 0) throw new ArgumentOutOfRangeException(nameof(codeSize), SR.ArgumentOutOfRange_GenericPositive); - if (codeSize > 0 && code == null) + if (codeSize > 0 && code is null) throw new ArgumentNullException(nameof(code)); method.GetILGenerator().SetCode(code, codeSize, maxStackSize); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs index 4c84b6c4f985b5..38bc58982beb9f 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -109,26 +109,26 @@ public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, bool [DynamicDependency(nameof(owner))] // Automatically keeps all previous fields too due to StructLayout private DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type? owner, Module? m, bool skipVisibility, bool anonHosted, bool typeOwner) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); - if (returnType == null) + if (returnType is null) returnType = typeof(void); - if (owner == null && typeOwner) + if (owner is null && typeOwner) throw new ArgumentNullException(nameof(owner)); - if ((m == null) && !anonHosted) + if ((m is null) && !anonHosted) throw new ArgumentNullException(nameof(m)); - if (parameterTypes != null) + if (parameterTypes is not null) { for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes[i] == null) + if (parameterTypes[i] is null) throw new ArgumentException($"Parameter {i} is null"); } - if (owner != null && (owner.IsArray || owner.IsInterface)) + if (owner is not null && (owner.IsArray || owner.IsInterface)) { throw new ArgumentException("Owner can't be an array or an interface."); } - if (m == null) + if (m is null) m = AnonHostModuleHolder.AnonHostModule; this.name = name; @@ -151,7 +151,7 @@ private void CreateDynMethod() { if (mhandle.Value == IntPtr.Zero) { - if (ilgen == null || ilgen.ILOffset == 0) + if (ilgen is null || ilgen.ILOffset == 0) throw new InvalidOperationException("Method '" + name + "' does not have a method body."); ilgen.label_fixup(this); @@ -161,7 +161,7 @@ private void CreateDynMethod() { // Used to avoid cycles creating = true; - if (refs != null) + if (refs is not null) { for (int i = 0; i < refs.Length; ++i) { @@ -187,9 +187,9 @@ private void CreateDynMethod() public sealed override Delegate CreateDelegate(Type delegateType) { - if (delegateType == null) + if (delegateType is null) throw new ArgumentNullException(nameof(delegateType)); - if (deleg != null) + if (deleg is not null) return deleg; CreateDynMethod(); @@ -202,7 +202,7 @@ override Delegate CreateDelegate(Type delegateType) public sealed override Delegate CreateDelegate(Type delegateType, object? target) { - if (delegateType == null) + if (delegateType is null) throw new ArgumentNullException(nameof(delegateType)); CreateDynMethod(); @@ -241,7 +241,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) @@ -252,7 +252,7 @@ public override object[] GetCustomAttributes(Type attributeType, public DynamicILInfo GetDynamicILInfo() { - if (il_info == null) + if (il_info is null) il_info = new DynamicILInfo(this); return il_info; } @@ -269,7 +269,7 @@ public ILGenerator GetILGenerator(int streamSize) ((GetMethodImplementationFlags() & MethodImplAttributes.ManagedMask) != MethodImplAttributes.Managed)) throw new InvalidOperationException("Method body should not exist."); - if (ilgen != null) + if (ilgen is not null) return ilgen; ilgen = new ILGenerator(Module, new DynamicMethodTokenGenerator(this), streamSize); return ilgen; @@ -287,7 +287,7 @@ public override ParameterInfo[] GetParameters() internal override ParameterInfo[] GetParametersInternal() { - if (parameters == null) + if (parameters is null) return Array.Empty(); ParameterInfo[] retval = new ParameterInfo[parameters.Length]; @@ -300,7 +300,7 @@ internal override ParameterInfo[] GetParametersInternal() internal override int GetParametersCount() { - return parameters == null ? 0 : parameters.Length; + return parameters is null ? 0 : parameters.Length; } internal override Type GetParameterType(int pos) @@ -311,7 +311,7 @@ internal override Type GetParameterType(int pos) /* public override object Invoke (object obj, object[] parameters) { CreateDynMethod (); - if (method == null) + if (method is null) method = new RuntimeMethodInfo (mhandle); return method.Invoke (obj, parameters); } @@ -336,7 +336,7 @@ public override object Invoke (object obj, object[] parameters) { public override bool IsDefined(Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) throw new ArgumentNullException(nameof(attributeType)); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) @@ -429,7 +429,7 @@ public override ParameterInfo ReturnParameter { get { - if (deleg == null) + if (deleg is null) { return new RuntimeParameterInfo((ParameterBuilder?)null, returnType, this, -1); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs index 38f9a9e7a0ddd4..32026d41a4f200 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs @@ -247,7 +247,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - if (attributeType == null) + if (attributeType is null) return _tb.GetCustomAttributes(inherit); else return _tb.GetCustomAttributes(attributeType, inherit); @@ -322,7 +322,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { - if (types == null) + if (types is null) { return _tb.GetMethod(name, bindingAttr); } @@ -471,7 +471,7 @@ public override bool IsConstructedGenericType public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { - if (typeInfo == null) return false; + if (typeInfo is null) return false; return IsAssignableFrom(typeInfo.AsType()); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs index 5865a42bd77f56..a15979c03bef29 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs @@ -72,10 +72,10 @@ internal int get_next_table_index(object obj, int table, int count) public void AddOtherMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); RejectIfCreated(); - if (other_methods != null) + if (other_methods is not null) { MethodBuilder[] newv = new MethodBuilder[other_methods.Length + 1]; other_methods.CopyTo(newv, 0); @@ -90,21 +90,21 @@ public void AddOtherMethod(MethodBuilder mdBuilder) public void SetAddOnMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); RejectIfCreated(); add_method = mdBuilder; } public void SetRaiseMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); RejectIfCreated(); raise_method = mdBuilder; } public void SetRemoveOnMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); RejectIfCreated(); remove_method = mdBuilder; @@ -112,7 +112,7 @@ public void SetRemoveOnMethod(MethodBuilder mdBuilder) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); RejectIfCreated(); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; @@ -121,7 +121,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) attrs |= EventAttributes.SpecialName; return; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -138,9 +138,9 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) [ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs index 65737484355acf..05429cda655f71 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs @@ -60,37 +60,37 @@ internal EventOnTypeBuilderInst(TypeBuilderInstantiation instantiation, EventInf public override EventAttributes Attributes { - get { return event_builder != null ? event_builder.attrs : event_info!.Attributes; } + get { return event_builder is not null ? event_builder.attrs : event_info!.Attributes; } } public override MethodInfo? GetAddMethod(bool nonPublic) { - MethodInfo? add = event_builder != null ? event_builder.add_method : event_info!.GetAddMethod(nonPublic); - if (add == null || (!nonPublic && !add.IsPublic)) + MethodInfo? add = event_builder is not null ? event_builder.add_method : event_info!.GetAddMethod(nonPublic); + if (add is null || (!nonPublic && !add.IsPublic)) return null; return TypeBuilder.GetMethod(instantiation, add); } public override MethodInfo? GetRaiseMethod(bool nonPublic) { - MethodInfo? raise = event_builder != null ? event_builder.raise_method : event_info!.GetRaiseMethod(nonPublic); - if (raise == null || (!nonPublic && !raise.IsPublic)) + MethodInfo? raise = event_builder is not null ? event_builder.raise_method : event_info!.GetRaiseMethod(nonPublic); + if (raise is null || (!nonPublic && !raise.IsPublic)) return null; return TypeBuilder.GetMethod(instantiation, raise); } public override MethodInfo? GetRemoveMethod(bool nonPublic) { - MethodInfo? remove = event_builder != null ? event_builder.remove_method : event_info!.GetRemoveMethod(nonPublic); - if (remove == null || (!nonPublic && !remove.IsPublic)) + MethodInfo? remove = event_builder is not null ? event_builder.remove_method : event_info!.GetRemoveMethod(nonPublic); + if (remove is null || (!nonPublic && !remove.IsPublic)) return null; return TypeBuilder.GetMethod(instantiation, remove); } public override MethodInfo[] GetOtherMethods(bool nonPublic) { - MethodInfo[]? other = event_builder != null ? event_builder.other_methods : event_info!.GetOtherMethods(nonPublic); - if (other == null) + MethodInfo[]? other = event_builder is not null ? event_builder.other_methods : event_info!.GetOtherMethods(nonPublic); + if (other is null) return Array.Empty(); List res = new List(); @@ -109,7 +109,7 @@ public override Type DeclaringType public override string Name { - get { return event_builder != null ? event_builder.name : event_info!.Name; } + get { return event_builder is not null ? event_builder.name : event_info!.Name; } } public override Type ReflectedType diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs index 4d63c64bdb1233..c04c7445f008f5 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs @@ -61,7 +61,7 @@ public sealed partial class FieldBuilder : FieldInfo [DynamicDependency(nameof(modOpt))] // Automatically keeps all previous fields too due to StructLayout internal FieldBuilder(TypeBuilder tb, string fieldName, Type type, FieldAttributes attributes, Type[]? modReq, Type[]? modOpt) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); attrs = attributes & ~FieldAttributes.ReservedMask; @@ -165,7 +165,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { RejectIfCreated(); - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; @@ -195,7 +195,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) /* FIXME: check for errors */ return; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -245,7 +245,7 @@ internal void ResolveUserTypes() type = TypeBuilder.ResolveUserType(type); TypeBuilder.ResolveUserTypes(modReq); TypeBuilder.ResolveUserTypes(modOpt); - if (marshal_info != null) + if (marshal_info is not null) marshal_info.marshaltyperef = TypeBuilder.ResolveUserType(marshal_info.marshaltyperef); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs index 875e6fdabdd9ce..c08c5cdfc10878 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -79,14 +79,14 @@ public void SetGenericParameterAttributes(GenericParameterAttributes genericPara internal override Type InternalResolve() { - if (mbuilder != null) + if (mbuilder is not null) return MethodBase.GetMethodFromHandle(mbuilder.MethodHandleInternal, mbuilder.TypeBuilder.InternalResolve().TypeHandle)!.GetGenericArguments()[index]; return tbuilder.InternalResolve().GetGenericArguments()[index]; } internal override Type RuntimeResolve() { - if (mbuilder != null) + if (mbuilder is not null) return MethodBase.GetMethodFromHandle(mbuilder.MethodHandleInternal, mbuilder.TypeBuilder.RuntimeResolve().TypeHandle)!.GetGenericArguments()[index]; return tbuilder.RuntimeResolve().GetGenericArguments()[index]; } @@ -225,7 +225,7 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { - if (typeInfo == null) + if (typeInfo is null) return false; return IsAssignableFrom(typeInfo.AsType()); @@ -263,7 +263,7 @@ protected override bool IsPrimitiveImpl() protected override bool IsValueTypeImpl() { - return base_type != null ? base_type.IsValueType : false; + return base_type is not null ? base_type.IsValueType : false; } public override bool IsSZArray @@ -359,7 +359,7 @@ public override Module Module public override Type? DeclaringType { - get { return mbuilder != null ? mbuilder.DeclaringType : tbuilder; } + get { return mbuilder is not null ? mbuilder.DeclaringType : tbuilder; } } public override Type? ReflectedType @@ -427,10 +427,10 @@ public override MethodBase? DeclaringMethod public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs index 3a68f0e9064f5e..0b5a14ffd20397 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs @@ -119,7 +119,7 @@ internal void AddFilter(int offset) internal void End(int offset) { - if (handlers == null) + if (handlers is null) return; int i = handlers.Length - 1; if (i >= 0) @@ -128,7 +128,7 @@ internal void End(int offset) internal int LastClauseType() { - if (handlers != null) + if (handlers is not null) return handlers[handlers.Length - 1].type; else return ILExceptionBlock.CATCH; @@ -136,7 +136,7 @@ internal int LastClauseType() internal void PatchFilterClause(int start) { - if (handlers != null && handlers.Length > 0) + if (handlers is not null && handlers.Length > 0) { handlers[handlers.Length - 1].start = start; handlers[handlers.Length - 1].type = ILExceptionBlock.FILTER; @@ -145,7 +145,7 @@ internal void PatchFilterClause(int start) private void add_block(int offset) { - if (handlers != null) + if (handlers is not null) { int i = handlers.Length; ILExceptionBlock[] new_b = new ILExceptionBlock[i + 1]; @@ -350,11 +350,11 @@ public virtual void BeginCatchBlock(Type exceptionType) if (open_blocks.Count <= 0) throw new NotSupportedException("Not in an exception block"); - if (exceptionType != null && exceptionType.IsUserType) + if (exceptionType is not null && exceptionType.IsUserType) throw new NotSupportedException("User defined subclasses of System.Type are not yet supported."); if (ex_handlers![cur_block].LastClauseType() == ILExceptionBlock.FILTER_START) { - if (exceptionType != null) + if (exceptionType is not null) throw new ArgumentException("Do not supply an exception type for filter clause"); Emit(OpCodes.Endfilter); ex_handlers[cur_block].PatchFilterClause(code_len); @@ -374,7 +374,7 @@ public virtual void BeginCatchBlock(Type exceptionType) public virtual void BeginExceptFilterBlock() { - if (open_blocks == null) + if (open_blocks is null) open_blocks = new Stack(defaultExceptionStackSize); if (open_blocks.Count <= 0) @@ -387,10 +387,10 @@ public virtual void BeginExceptFilterBlock() public virtual Label BeginExceptionBlock() { //System.Console.WriteLine ("Begin Block"); - if (open_blocks == null) + if (open_blocks is null) open_blocks = new Stack(defaultExceptionStackSize); - if (ex_handlers != null) + if (ex_handlers is not null) { cur_block = ex_handlers.Length; ILExceptionInfo[] new_ex = new ILExceptionInfo[cur_block + 1]; @@ -409,7 +409,7 @@ public virtual Label BeginExceptionBlock() public virtual void BeginFaultBlock() { - if (open_blocks == null) + if (open_blocks is null) open_blocks = new Stack(defaultExceptionStackSize); if (open_blocks.Count <= 0) @@ -428,7 +428,7 @@ public virtual void BeginFaultBlock() public virtual void BeginFinallyBlock() { - if (open_blocks == null) + if (open_blocks is null) open_blocks = new Stack(defaultExceptionStackSize); if (open_blocks.Count <= 0) @@ -457,14 +457,14 @@ public virtual LocalBuilder DeclareLocal(Type localType) public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { - if (localType == null) + if (localType is null) throw new ArgumentNullException(nameof(localType)); if (localType.IsUserType) throw new NotSupportedException("User defined subclasses of System.Type are not yet supported."); LocalBuilder res = new LocalBuilder(localType, this); res.is_pinned = pinned; - if (locals != null) + if (locals is not null) { LocalBuilder[] new_l = new LocalBuilder[locals.Length + 1]; Array.Copy(locals, new_l, locals.Length); @@ -482,7 +482,7 @@ public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) public virtual Label DefineLabel() { - if (labels == null) + if (labels is null) labels = new LabelData[defaultLabelsSize]; else if (num_labels >= labels.Length) { @@ -589,7 +589,7 @@ public virtual void Emit(OpCode opcode, Label label) if (cur_stack > labels![label.m_label].maxStack) labels[label.m_label].maxStack = cur_stack; - if (fixups == null) + if (fixups is null) fixups = new LabelFixup[defaultFixupSize]; else if (num_fixups >= fixups.Length) { @@ -607,7 +607,7 @@ public virtual void Emit(OpCode opcode, Label label) public virtual void Emit(OpCode opcode, Label[] labels) { - if (labels == null) + if (labels is null) throw new ArgumentNullException(nameof(labels)); /* opcode needs to be switch. */ @@ -620,7 +620,7 @@ public virtual void Emit(OpCode opcode, Label[] labels) this.labels[labels[i].m_label].maxStack = cur_stack; emit_int(count); - if (fixups == null) + if (fixups is null) fixups = new LabelFixup[defaultFixupSize + count]; else if (num_fixups + count >= fixups.Length) { @@ -655,7 +655,7 @@ public virtual void Emit(OpCode opcode, Label[] labels) public virtual void Emit(OpCode opcode, LocalBuilder local) { - if (local == null) + if (local is null) throw new ArgumentNullException(nameof(local)); if (local.ilgen != this) throw new ArgumentException(SR.Argument_UnmatchedMethodForLocal, nameof(local)); @@ -747,7 +747,7 @@ public virtual void Emit(OpCode opcode, LocalBuilder local) public virtual void Emit(OpCode opcode, MethodInfo meth) { - if (meth == null) + if (meth is null) throw new ArgumentNullException(nameof(meth)); // For compatibility with MS @@ -823,7 +823,7 @@ public virtual void Emit(OpCode opcode, string str) public virtual void Emit(OpCode opcode, Type cls) { - if (cls != null && cls.IsByRef) + if (cls is not null && cls.IsByRef) throw new ArgumentException("Cannot get TypeToken for a ByRef type."); make_room(6); @@ -835,14 +835,14 @@ public virtual void Emit(OpCode opcode, Type cls) // FIXME: vararg methods are not supported public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes) { - if (methodInfo == null) + if (methodInfo is null) throw new ArgumentNullException(nameof(methodInfo)); short value = opcode.Value; if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value)) throw new NotSupportedException("Only Call and CallVirt are allowed"); if ((methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) optionalParameterTypes = null; - if (optionalParameterTypes != null) + if (optionalParameterTypes is not null) { if ((methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) { @@ -866,7 +866,7 @@ public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[]? parameterTypes, Type[]? optionalParameterTypes) { - if (optionalParameterTypes != null) + if (optionalParameterTypes is not null) throw new NotImplementedException(); SignatureHelper helper = SignatureHelper.GetMethodSigHelper(module as ModuleBuilder, callingConvention, 0, returnType, parameterTypes); @@ -877,7 +877,7 @@ public virtual void EmitCalli(OpCode opcode, CallingConventions callingConventio public virtual void EmitWriteLine(FieldInfo fld) { - if (fld == null) + if (fld is null) throw new ArgumentNullException(nameof(fld)); // The MS implementation does not check for valuetypes here but it @@ -896,7 +896,7 @@ public virtual void EmitWriteLine(FieldInfo fld) public virtual void EmitWriteLine(LocalBuilder localBuilder) { - if (localBuilder == null) + if (localBuilder is null) throw new ArgumentNullException(nameof(localBuilder)); if (localBuilder.LocalType is TypeBuilder) throw new ArgumentException("Output streams do not support TypeBuilders."); @@ -916,7 +916,7 @@ public virtual void EmitWriteLine(string value) public virtual void EndExceptionBlock() { - if (open_blocks == null) + if (open_blocks is null) open_blocks = new Stack(defaultExceptionStackSize); if (open_blocks.Count <= 0) @@ -950,9 +950,9 @@ public virtual void MarkLabel(Label loc) public virtual void MarkSequencePoint(ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn) { - if (currentSequence == null || currentSequence.Document != document) + if (currentSequence is null || currentSequence.Document != document) { - if (sequencePointLists == null) + if (sequencePointLists is null) sequencePointLists = new List(); currentSequence = new SequencePointList(document); sequencePointLists.Add(currentSequence); @@ -964,7 +964,7 @@ public virtual void MarkSequencePoint(ISymbolDocumentWriter document, int startL /* internal void GenerateDebugInfo (ISymbolWriter symbolWriter) { - if (sequencePointLists != null) { + if (sequencePointLists is not null) { SequencePointList first = (SequencePointList) sequencePointLists [0]; SequencePointList last = (SequencePointList) sequencePointLists [sequencePointLists.Count - 1]; symbolWriter.SetMethodSourceRange (first.Document, first.StartLine, first.StartColumn, last.Document, last.EndLine, last.EndColumn); @@ -972,9 +972,9 @@ internal void GenerateDebugInfo (ISymbolWriter symbolWriter) foreach (SequencePointList list in sequencePointLists) symbolWriter.DefineSequencePoints (list.Document, list.GetOffsets(), list.GetLines(), list.GetColumns(), list.GetEndLines(), list.GetEndColumns()); - if (locals != null) { + if (locals is not null) { foreach (LocalBuilder local in locals) { - if (local.Name != null && local.Name.Length > 0) { + if (local.Name is not null && local.Name.Length > 0) { SignatureHelper sighelper = SignatureHelper.GetLocalVarSigHelper (module as ModuleBuilder); sighelper.AddArgument (local.LocalType); byte[] signature = sighelper.GetSignature (); @@ -989,18 +989,18 @@ internal void GenerateDebugInfo (ISymbolWriter symbolWriter) internal bool HasDebugInfo { - get { return sequencePointLists != null; } + get { return sequencePointLists is not null; } } public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type excType) { - if (excType == null) + if (excType is null) throw new ArgumentNullException(nameof(excType)); if (!((excType == typeof(Exception)) || excType.IsSubclassOf(typeof(Exception)))) throw new ArgumentException("Type should be an exception type", nameof(excType)); ConstructorInfo? ctor = excType.GetConstructor(Type.EmptyTypes); - if (ctor == null) + if (ctor is null) throw new ArgumentException("Type should have a default constructor", nameof(excType)); Emit(OpCodes.Newobj, ctor); Emit(OpCodes.Throw); @@ -1038,7 +1038,7 @@ internal void label_fixup(MethodBase mb) internal void SetCode(byte[]? code, int max_stack) { // Make a copy to avoid possible security problems - this.code = code != null ? (byte[])code.Clone() : Array.Empty(); + this.code = code is not null ? (byte[])code.Clone() : Array.Empty(); this.code_len = this.code.Length; this.max_stack = max_stack; this.cur_stack = 0; @@ -1142,7 +1142,7 @@ public void AddSequencePoint(int offset, int line, int col, int endLine, int end s.EndLine = endLine; s.EndCol = endCol; - if (points == null) + if (points is null) { points = new SequencePoint[arrayGrow]; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs index a2989b77bace5e..0baec3da07299d 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs @@ -90,10 +90,10 @@ internal MethodBuilder(TypeBuilder tb, string name, MethodAttributes attributes, // appends a HasThis flag if the method is not static if ((attributes & MethodAttributes.Static) == 0) this.call_conv |= CallingConventions.HasThis; - if (parameterTypes != null) + if (parameterTypes is not null) { for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes[i] == null) + if (parameterTypes[i] is null) throw new ArgumentException("Elements of the parameterTypes array cannot be null", nameof(parameterTypes)); this.parameters = new Type[parameterTypes.Length]; @@ -250,7 +250,7 @@ public override ParameterInfo[] GetParameters() internal override ParameterInfo[] GetParametersInternal() { - if (parameters == null) + if (parameters is null) return Array.Empty(); ParameterInfo[] retval = new ParameterInfo[parameters.Length]; @@ -263,7 +263,7 @@ internal override ParameterInfo[] GetParametersInternal() internal override int GetParametersCount() { - if (parameters == null) + if (parameters is null) return 0; return parameters.Length; @@ -327,7 +327,7 @@ public ILGenerator GetILGenerator(int size) ((iattrs & MethodImplAttributes.ManagedMask) != MethodImplAttributes.Managed)) throw new InvalidOperationException("Method body should not exist."); - if (ilgen != null) + if (ilgen is not null) return ilgen; ilgen = new ILGenerator(type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator(), size); return ilgen; @@ -340,11 +340,11 @@ public ParameterBuilder DefineParameter(int position, ParameterAttributes attrib // // Extension: Mono allows position == 0 for the return attribute // - if ((position < 0) || parameters == null || (position > parameters.Length)) + if ((position < 0) || parameters is null || (position > parameters.Length)) throw new ArgumentOutOfRangeException(nameof(position)); ParameterBuilder pb = new ParameterBuilder(this, position, attributes, strParamName); - if (pinfo == null) + if (pinfo is null) pinfo = new ParameterBuilder[parameters.Length + 1]; pinfo[position] = pb; return pb; @@ -352,7 +352,7 @@ public ParameterBuilder DefineParameter(int position, ParameterAttributes attrib internal void check_override() { - if (override_methods != null) + if (override_methods is not null) { foreach (MethodInfo m in override_methods) { @@ -367,12 +367,12 @@ internal void fixup() if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) { // do not allow zero length method body on MS.NET 2.0 (and higher) - if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0)) + if (((ilgen is null) || (ilgen.ILOffset == 0)) && (code is null || code.Length == 0)) throw new InvalidOperationException( string.Format("Method '{0}.{1}' does not have a method body.", DeclaringType!.FullName, Name)); } - if (ilgen != null) + if (ilgen is not null) ilgen.label_fixup(this); } @@ -382,12 +382,12 @@ internal void ResolveUserTypes() TypeBuilder.ResolveUserTypes(parameters); TypeBuilder.ResolveUserTypes(returnModReq); TypeBuilder.ResolveUserTypes(returnModOpt); - if (paramModReq != null) + if (paramModReq is not null) { foreach (Type[] types in paramModReq) TypeBuilder.ResolveUserTypes(types); } - if (paramModOpt != null) + if (paramModOpt is not null) { foreach (Type[] types in paramModOpt) TypeBuilder.ResolveUserTypes(types); @@ -396,7 +396,7 @@ internal void ResolveUserTypes() /* internal void GenerateDebugInfo (ISymbolWriter symbolWriter) { - if (ilgen != null && ilgen.HasDebugInfo) { + if (ilgen is not null && ilgen.HasDebugInfo) { SymbolToken token = new SymbolToken (GetToken().Token); symbolWriter.OpenMethod (token); symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name)); @@ -407,7 +407,7 @@ internal void GenerateDebugInfo (ISymbolWriter symbolWriter) */ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); switch (customBuilder.Ctor.ReflectedType!.FullName) @@ -436,7 +436,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) */ pi_dll = (string?)attr.ctorArgs[0]; - if (pi_dll == null || pi_dll.Length == 0) + if (pi_dll is null || pi_dll.Length == 0) throw new ArgumentException("DllName cannot be empty"); native_cc = Runtime.InteropServices.CallingConvention.Winapi; @@ -480,7 +480,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) break; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -497,9 +497,9 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) [ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); } @@ -533,7 +533,7 @@ internal override int get_next_table_index(object obj, int table, int count) private static void ExtendArray([NotNull] ref T[]? array, T elem) { - if (array == null) + if (array is null) { array = new T[1]; } @@ -566,13 +566,13 @@ public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { if (!IsGenericMethodDefinition) throw new InvalidOperationException("Method is not a generic method definition"); - if (typeArguments == null) + if (typeArguments is null) throw new ArgumentNullException(nameof(typeArguments)); if (generic_params!.Length != typeArguments.Length) throw new ArgumentException("Incorrect length", nameof(typeArguments)); foreach (Type type in typeArguments) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(typeArguments)); } @@ -583,7 +583,7 @@ public override bool IsGenericMethodDefinition { get { - return generic_params != null; + return generic_params is not null; } } @@ -591,7 +591,7 @@ public override bool IsGenericMethod { get { - return generic_params != null; + return generic_params is not null; } } @@ -605,7 +605,7 @@ public override MethodInfo GetGenericMethodDefinition() public override Type[] GetGenericArguments() { - if (generic_params == null) + if (generic_params is null) return Type.EmptyTypes; Type[] result = new Type[generic_params.Length]; @@ -617,7 +617,7 @@ public override Type[] GetGenericArguments() public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { - if (names == null) + if (names is null) throw new ArgumentNullException(nameof(names)); if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); @@ -626,7 +626,7 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam for (int i = 0; i < names.Length; i++) { string item = names[i]; - if (item == null) + if (item is null) throw new ArgumentNullException(nameof(names)); generic_params[i] = new GenericTypeParameterBuilder(type, this, item, i); } @@ -641,10 +641,10 @@ public void SetReturnType(Type? returnType) public void SetParameters(params Type[]? parameterTypes) { - if (parameterTypes != null) + if (parameterTypes is not null) { for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes[i] == null) + if (parameterTypes[i] is null) throw new ArgumentNullException(nameof(parameterTypes), "Elements of the parameterTypes array cannot be null"); this.parameters = new Type[parameterTypes.Length]; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs index 50c9711ec306cf..2c08e6c8fe085a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs @@ -104,7 +104,7 @@ internal MethodInfo RuntimeResolve() { Type type = instantiation.InternalResolve(); MethodInfo m = type.GetMethod(base_method); - if (method_arguments != null) + if (method_arguments is not null) { var args = new Type[method_arguments.Length]; for (int i = 0; i < method_arguments.Length; ++i) @@ -246,10 +246,10 @@ public override CallingConventions CallingConvention public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { - if (!base_method.IsGenericMethodDefinition || (method_arguments != null)) + if (!base_method.IsGenericMethodDefinition || (method_arguments is not null)) throw new InvalidOperationException("Method is not a generic method definition"); - if (methodInstantiation == null) + if (methodInstantiation is null) throw new ArgumentNullException(nameof(methodInstantiation)); if (base_method.GetGenericArguments().Length != methodInstantiation.Length) @@ -257,7 +257,7 @@ public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) foreach (Type type in methodInstantiation) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(methodInstantiation)); } @@ -287,7 +287,7 @@ public override bool ContainsGenericParameters return true; if (!base_method.IsGenericMethodDefinition) throw new NotSupportedException(); - if (method_arguments == null) + if (method_arguments is null) return true; foreach (Type t in method_arguments) { @@ -302,7 +302,7 @@ public override bool IsGenericMethodDefinition { get { - return base_method.IsGenericMethodDefinition && method_arguments == null; + return base_method.IsGenericMethodDefinition && method_arguments is null; } } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs index 88f65880396504..2861fd0685706c 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs @@ -111,9 +111,9 @@ public override string FullyQualifiedName get { string fullyQualifiedName = fqname; - if (fullyQualifiedName == null) + if (fullyQualifiedName is null) return null!; // FIXME: this should not return null - if (assemblyb.AssemblyDir != null) + if (assemblyb.AssemblyDir is not null) { fullyQualifiedName = Path.Combine(assemblyb.AssemblyDir, fullyQualifiedName); fullyQualifiedName = Path.GetFullPath(fullyQualifiedName); @@ -130,15 +130,15 @@ public bool IsTransient() public void CreateGlobalFunctions() { - if (global_type_created != null) + if (global_type_created is not null) throw new InvalidOperationException("global methods already created"); - if (global_type != null) + if (global_type is not null) global_type_created = global_type.CreateType()!; } public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); FieldAttributes maskedAttributes = attributes & ~FieldAttributes.ReservedMask; @@ -157,11 +157,11 @@ public FieldBuilder DefineUninitializedData(string name, int size, FieldAttribut Justification = "Reflection.Emit is not subject to trimming")] private FieldBuilder DefineDataImpl(string name, int size, FieldAttributes attributes) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("name cannot be empty", nameof(name)); - if (global_type_created != null) + if (global_type_created is not null) throw new InvalidOperationException("global fields already created"); if ((size <= 0) || (size >= 0x3f0000)) throw new ArgumentException("Data size must be > 0 and < 0x3f0000", null as string); @@ -170,7 +170,7 @@ private FieldBuilder DefineDataImpl(string name, int size, FieldAttributes attri string typeName = "$ArrayType$" + size; Type? datablobtype = GetType(typeName, false, false); - if (datablobtype == null) + if (datablobtype is null) { TypeBuilder tb = DefineType(typeName, TypeAttributes.Public | TypeAttributes.ExplicitLayout | TypeAttributes.Sealed, @@ -180,7 +180,7 @@ private FieldBuilder DefineDataImpl(string name, int size, FieldAttributes attri } FieldBuilder fb = global_type!.DefineField(name, datablobtype, attributes | FieldAttributes.Static); - if (global_fields != null) + if (global_fields is not null) { FieldBuilder[] new_fields = new FieldBuilder[global_fields.Length + 1]; Array.Copy(global_fields, new_fields, global_fields.Length); @@ -196,7 +196,7 @@ private FieldBuilder DefineDataImpl(string name, int size, FieldAttributes attri private void addGlobalMethod(MethodBuilder mb) { - if (global_methods != null) + if (global_methods is not null) { MethodBuilder[] new_methods = new MethodBuilder[global_methods.Length + 1]; Array.Copy(global_methods, new_methods, global_methods.Length); @@ -221,11 +221,11 @@ public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException("global methods must be static"); - if (global_type_created != null) + if (global_type_created is not null) throw new InvalidOperationException("global methods already created"); CreateGlobalType(); MethodBuilder mb = global_type!.DefineMethod(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); @@ -241,11 +241,11 @@ public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttr public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException("global methods must be static"); - if (global_type_created != null) + if (global_type_created is not null) throw new InvalidOperationException("global methods already created"); CreateGlobalType(); MethodBuilder mb = global_type!.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); @@ -273,7 +273,7 @@ public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent) private void AddType(TypeBuilder tb) { - if (types != null) + if (types is not null) { if (types.Length == num_types) { @@ -294,7 +294,7 @@ private void AddType(TypeBuilder tb) Justification = "Reflection.Emit is not subject to trimming")] private TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, Type[]? interfaces, PackingSize packingSize, int typesize) { - if (name == null) + if (name is null) throw new ArgumentNullException("fullname"); ITypeIdentifier ident = TypeIdentifiers.FromInternal(name); if (name_cache.ContainsKey(ident)) @@ -402,10 +402,10 @@ public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type under foreach (ITypeName pname in nested) { - if (result.subtypes == null) + if (result.subtypes is null) return null; result = search_nested_in_array(result.subtypes, result.subtypes.Length, pname); - if (result == null) + if (result is null) return null; } return result; @@ -415,14 +415,14 @@ public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type under [ComVisible(true)] public override Type? GetType(string className, bool throwOnError, bool ignoreCase) { - if (className == null) + if (className is null) throw new ArgumentNullException(nameof(className)); if (className.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(className)); TypeBuilder? result = null; - if (types == null && throwOnError) + if (types is null && throwOnError) throw new TypeLoadException(className); TypeSpec ts = TypeSpec.Parse(className); @@ -434,16 +434,16 @@ public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type under } else { - if (types != null) + if (types is not null) result = search_in_array(types, num_types, ts.Name!); - if (!ts.IsNested && result != null) + if (!ts.IsNested && result is not null) { result = GetMaybeNested(result, ts.Nested); } } - if ((result == null) && throwOnError) + if ((result is null) && throwOnError) throw new TypeLoadException(className); - if (result != null && (ts.HasModifiers || ts.IsByRef)) + if (result is not null && (ts.HasModifiers || ts.IsByRef)) { Type mt = result; if (result is TypeBuilder) @@ -470,10 +470,10 @@ public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type under if (ts.IsByRef) mt = mt.MakeByRefType(); result = mt as TypeBuilder; - if (result == null) + if (result is null) return mt; } - if (result != null && result.is_created) + if (result is not null && result.is_created) return result.CreateType(); else return result; @@ -481,7 +481,7 @@ public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type under internal int get_next_table_index(object obj, int table, int count) { - if (table_indexes == null) + if (table_indexes is null) { table_indexes = new int[64]; for (int i = 0; i < 64; ++i) @@ -497,9 +497,9 @@ internal int get_next_table_index(object obj, int table, int count) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -521,7 +521,7 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) /* internal ISymbolDocumentWriter? DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) { - if (symbolWriter != null) + if (symbolWriter is not null) return symbolWriter.DefineDocument (url, language, languageVendor, documentType); else return null; @@ -530,7 +530,7 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetTypes() { - if (types == null) + if (types is null) return Type.EmptyTypes; int n = num_types; @@ -547,7 +547,7 @@ public override Type[] GetTypes() internal int GetMethodToken(MethodInfo method) { - if (method == null) + if (method is null) throw new ArgumentNullException(nameof(method)); return method.MetadataToken; @@ -561,7 +561,7 @@ internal int GetArrayMethodToken(Type arrayClass, string methodName, CallingConv [ComVisible(true)] internal int GetConstructorToken(ConstructorInfo con) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); return con.MetadataToken; @@ -569,7 +569,7 @@ internal int GetConstructorToken(ConstructorInfo con) internal int GetFieldToken(FieldInfo field) { - if (field == null) + if (field is null) throw new ArgumentNullException(nameof(field)); return field.MetadataToken; @@ -583,21 +583,21 @@ internal int GetSignatureToken(byte[] sigBytes, int sigLength) internal int GetSignatureToken(SignatureHelper sigHelper) { - if (sigHelper == null) + if (sigHelper is null) throw new ArgumentNullException(nameof(sigHelper)); return GetToken(sigHelper); } internal int GetStringConstant(string str) { - if (str == null) + if (str is null) throw new ArgumentNullException(nameof(str)); return GetToken(str); } internal int GetTypeToken(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); if (type.IsByRef) throw new ArgumentException("type can't be a byref type", nameof(type)); @@ -653,7 +653,7 @@ private int GetPseudoToken(MemberInfo member, bool create_open_instance) { int token; Dictionary? dict = create_open_instance ? inst_tokens_open : inst_tokens; - if (dict == null) + if (dict is null) { dict = new Dictionary(ReferenceEqualityComparer.Instance); if (create_open_instance) @@ -740,7 +740,7 @@ internal int GetToken(MethodBase method, IEnumerable opt_param_types) if (method is ConstructorBuilder || method is MethodBuilder) return GetPseudoToken(method, false); - if (opt_param_types == null) + if (opt_param_types is null) return getToken(this, method, true); var optParamTypes = new List(opt_param_types); @@ -774,7 +774,7 @@ internal int GetToken(SignatureHelper helper) internal ITokenGenerator GetTokenGenerator() { - if (token_gen == null) + if (token_gen is null) token_gen = new ModuleBuilderTokenGenerator(this); return token_gen; } @@ -819,7 +819,7 @@ internal bool IsMain internal void CreateGlobalType() { - if (global_type == null) + if (global_type is null) global_type = new TypeBuilder(this, 0, 1); } @@ -858,9 +858,9 @@ public override bool IsResource() [RequiresUnreferencedCode("Methods might be removed")] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { - if (global_type_created == null) + if (global_type_created is null) return null; - if (types == null) + if (types is null) return global_type_created.GetMethod(name); return global_type_created.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } @@ -881,11 +881,11 @@ internal MemberInfo ResolveOrGetRegisteredToken(int metadataToken, Type[] generi { ResolveTokenError error; MemberInfo? m = RuntimeModule.ResolveMemberToken(_impl, metadataToken, RuntimeModule.ptrs_from_types(genericTypeArguments), RuntimeModule.ptrs_from_types(genericMethodArguments), out error); - if (m != null) + if (m is not null) return m; m = GetRegisteredToken(metadataToken) as MemberInfo; - if (m == null) + if (m is null) throw RuntimeModule.resolve_token_exception(Name, metadataToken, error, "MemberInfo"); else return m; @@ -937,7 +937,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - if (cattrs == null || cattrs.Length == 0) + if (cattrs is null || cattrs.Length == 0) return Array.Empty(); if (attributeType is TypeBuilder) @@ -951,7 +951,7 @@ public override object[] GetCustomAttributes(Type attributeType, bool inherit) if (t is TypeBuilder) throw new InvalidOperationException("Can't construct custom attribute for TypeBuilder type"); - if (attributeType == null || attributeType.IsAssignableFrom(t)) + if (attributeType is null || attributeType.IsAssignableFrom(t)) results.Add(cattrs[i].Invoke()); } @@ -966,7 +966,7 @@ public override IList GetCustomAttributesData() [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { - if (global_type_created == null) + if (global_type_created is null) throw new InvalidOperationException("Module-level fields cannot be retrieved until after the CreateGlobalFunctions method has been called for the module."); return global_type_created.GetField(name, bindingAttr); } @@ -974,7 +974,7 @@ public override IList GetCustomAttributesData() [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo[] GetFields(BindingFlags bindingFlags) { - if (global_type_created == null) + if (global_type_created is null) throw new InvalidOperationException("Module-level fields cannot be retrieved until after the CreateGlobalFunctions method has been called for the module."); return global_type_created.GetFields(bindingFlags); } @@ -982,7 +982,7 @@ public override FieldInfo[] GetFields(BindingFlags bindingFlags) [RequiresUnreferencedCode("Methods might be removed")] public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { - if (global_type_created == null) + if (global_type_created is null) throw new InvalidOperationException("Module-level methods cannot be retrieved until after the CreateGlobalFunctions method has been called for the module."); return global_type_created.GetMethods(bindingFlags); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs index 0d51eeeb8cd261..38a238c6a5365e 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs @@ -170,7 +170,7 @@ public override string ToString() parms = parms + ", "; parms = parms + p[i].ParameterType.Name; } - if (ReturnType != null) + if (ReturnType is not null) return ReturnType.Name + " " + Name + "(" + parms + ")"; else return "void " + Name + "(" + parms + ")"; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs index 337fd78991bda9..174c8787657a8e 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs @@ -138,7 +138,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) return; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs index d24191a1719c0b..7221fb350bc46b 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs @@ -71,7 +71,7 @@ internal PropertyBuilder(TypeBuilder tb, string name, PropertyAttributes attribu this.returnModOpt = returnModOpt; this.paramModReq = paramModReq; this.paramModOpt = paramModOpt; - if (parameterTypes != null) + if (parameterTypes is not null) { this.parameters = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, this.parameters, this.parameters.Length); @@ -86,11 +86,11 @@ public override PropertyAttributes Attributes } public override bool CanRead { - get { return get_method != null; } + get { return get_method is not null; } } public override bool CanWrite { - get { return set_method != null; } + get { return set_method is not null; } } public override Type DeclaringType { @@ -111,7 +111,7 @@ public override Type ReflectedType public void AddOtherMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); typeb.check_not_created(); } @@ -162,7 +162,7 @@ public void SetConstant(object? defaultValue) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); typeb.check_not_created(); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; @@ -172,7 +172,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) return; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -195,14 +195,14 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) public void SetGetMethod(MethodBuilder mdBuilder) { typeb.check_not_created(); - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); get_method = mdBuilder; } public void SetSetMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) + if (mdBuilder is null) throw new ArgumentNullException(nameof(mdBuilder)); set_method = mdBuilder; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs index a3ad727d434725..4a0b395d96fc6b 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs @@ -92,17 +92,17 @@ public override MethodInfo[] GetAccessors(bool nonPublic) MethodInfo? setter = GetSetMethod(nonPublic); int methods = 0; - if (getter != null) + if (getter is not null) ++methods; - if (setter != null) + if (setter is not null) ++methods; MethodInfo[] res = new MethodInfo[methods]; methods = 0; - if (getter != null) + if (getter is not null) res[methods++] = getter; - if (setter != null) + if (setter is not null) res[methods] = setter; return res; @@ -112,7 +112,7 @@ public override MethodInfo[] GetAccessors(bool nonPublic) public override MethodInfo? GetGetMethod(bool nonPublic) { MethodInfo? mi = prop.GetGetMethod(nonPublic); - if (mi != null && prop.DeclaringType == instantiation.generic_type) + if (mi is not null && prop.DeclaringType == instantiation.generic_type) { mi = TypeBuilder.GetMethod(instantiation, mi); } @@ -122,7 +122,7 @@ public override MethodInfo[] GetAccessors(bool nonPublic) public override ParameterInfo[] GetIndexParameters() { MethodInfo? method = GetGetMethod(true); - if (method != null) + if (method is not null) return method.GetParameters(); return Array.Empty(); @@ -131,7 +131,7 @@ public override ParameterInfo[] GetIndexParameters() public override MethodInfo? GetSetMethod(bool nonPublic) { MethodInfo? mi = prop.GetSetMethod(nonPublic); - if (mi != null && prop.DeclaringType == instantiation.generic_type) + if (mi is not null && prop.DeclaringType == instantiation.generic_type) { mi = TypeBuilder.GetMethod(instantiation, mi); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index 0cdb3884729f93..b57db0b60a922c 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -71,7 +71,7 @@ internal SignatureHelper(ModuleBuilder? module, SignatureHelperType type) public static SignatureHelper GetFieldSigHelper(Module? mod) { - if (mod != null && !(mod is ModuleBuilder)) + if (mod is not null && !(mod is ModuleBuilder)) throw new ArgumentException("ModuleBuilder is expected"); return new SignatureHelper((ModuleBuilder?)mod, SignatureHelperType.HELPER_FIELD); @@ -79,7 +79,7 @@ public static SignatureHelper GetFieldSigHelper(Module? mod) public static SignatureHelper GetLocalVarSigHelper(Module? mod) { - if (mod != null && !(mod is ModuleBuilder)) + if (mod is not null && !(mod is ModuleBuilder)) throw new ArgumentException("ModuleBuilder is expected"); return new SignatureHelper((ModuleBuilder?)mod, SignatureHelperType.HELPER_LOCAL); @@ -151,7 +151,7 @@ public static SignatureHelper GetPropertySigHelper(Module? mod, // private static int AppendArray([NotNull] ref Type[]? array, Type t) { - if (array != null) + if (array is not null) { Type[] new_a = new Type[array.Length + 1]; Array.Copy(array, new_a, array.Length); @@ -178,9 +178,9 @@ private static int AppendArray([NotNull] ref Type[]? array, Type t) // private static void AppendArrayAt([NotNull] ref Type[][]? array, Type[] t, int pos) { - int top = Math.Max(pos, array == null ? 0 : array.Length); + int top = Math.Max(pos, array is null ? 0 : array.Length); Type[][] new_a = new Type[top + 1][]; - if (array != null) + if (array is not null) Array.Copy(array, new_a, top); new_a[pos] = t; array = new_a; @@ -190,7 +190,7 @@ private static void ValidateParameterModifiers(string name, Type[] parameter_mod { foreach (Type modifier in parameter_modifiers) { - if (modifier == null) + if (modifier is null) throw new ArgumentNullException(name); if (modifier.IsArray) throw new ArgumentException("Array type not permitted", name); @@ -201,7 +201,7 @@ private static void ValidateParameterModifiers(string name, Type[] parameter_mod private static void ValidateCustomModifier(int n, Type[][]? custom_modifiers, string name) { - if (custom_modifiers == null) + if (custom_modifiers is null) return; if (custom_modifiers.Length != n) @@ -209,7 +209,7 @@ private static void ValidateCustomModifier(int n, Type[][]? custom_modifiers, st foreach (Type[] parameter_modifiers in custom_modifiers) { - if (parameter_modifiers == null) + if (parameter_modifiers is null) continue; ValidateParameterModifiers(name, parameter_modifiers); @@ -224,11 +224,11 @@ private static Exception MissingFeature() // FIXME: "Currently we ignore requiredCustomModifiers and optionalCustomModifiers" public void AddArguments(Type[]? arguments, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { - if (arguments == null) + if (arguments is null) throw new ArgumentNullException(nameof(arguments)); // For now - if (requiredCustomModifiers != null || optionalCustomModifiers != null) + if (requiredCustomModifiers is not null || optionalCustomModifiers is not null) { throw MissingFeature(); } @@ -250,24 +250,24 @@ public void AddArgument(Type argument, bool pinned) public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) { - if (argument == null) + if (argument is null) throw new ArgumentNullException(nameof(argument)); - if (requiredCustomModifiers != null) + if (requiredCustomModifiers is not null) ValidateParameterModifiers("requiredCustomModifiers", requiredCustomModifiers); - if (optionalCustomModifiers != null) + if (optionalCustomModifiers is not null) ValidateParameterModifiers("optionalCustomModifiers", optionalCustomModifiers); int p = AppendArray(ref arguments, argument); - if (requiredCustomModifiers != null) + if (requiredCustomModifiers is not null) AppendArrayAt(ref modreqs, requiredCustomModifiers, p); - if (optionalCustomModifiers != null) + if (optionalCustomModifiers is not null) AppendArrayAt(ref modopts, optionalCustomModifiers, p); } public void AddArgument(Type clsArgument) { - if (clsArgument == null) + if (clsArgument is null) throw new ArgumentNullException(nameof(clsArgument)); AppendArray(ref arguments, clsArgument); @@ -281,13 +281,13 @@ public void AddSentinel() private static bool CompareOK(Type[][]? one, Type[][]? two) { - if (one == null) + if (one is null) { - if (two == null) + if (two is null) return true; return false; } - else if (two == null) + else if (two is null) return false; if (one.Length != two.Length) @@ -298,12 +298,12 @@ private static bool CompareOK(Type[][]? one, Type[][]? two) Type[] tone = one[i]; Type[] ttwo = two[i]; - if (tone == null) + if (tone is null) { - if (ttwo == null) + if (ttwo is null) continue; } - else if (ttwo == null) + else if (ttwo is null) return false; if (tone!.Length != ttwo.Length) @@ -314,13 +314,13 @@ private static bool CompareOK(Type[][]? one, Type[][]? two) Type uone = tone[j]; Type utwo = ttwo[j]; - if (uone == null) + if (uone is null) { - if (utwo == null) + if (utwo is null) continue; return false; } - else if (utwo == null) + else if (utwo is null) return false; if (!uone.Equals(utwo)) @@ -333,7 +333,7 @@ private static bool CompareOK(Type[][]? one, Type[][]? two) public override bool Equals(object? obj) { SignatureHelper? other = obj as SignatureHelper; - if (other == null) + if (other is null) return false; if (other.module != module || @@ -342,9 +342,9 @@ public override bool Equals(object? obj) other.unmanagedCallConv != unmanagedCallConv) return false; - if (arguments != null) + if (arguments is not null) { - if (other.arguments == null) + if (other.arguments is null) return false; if (arguments.Length != other.arguments.Length) return false; @@ -353,7 +353,7 @@ public override bool Equals(object? obj) if (!other.arguments[i].Equals(arguments[i])) return false; } - else if (other.arguments != null) + else if (other.arguments is not null) return false; return CompareOK(other.modreqs, modreqs) && CompareOK(other.modopts, modopts); @@ -392,15 +392,15 @@ public override string ToString() internal static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventions callingConvention, CallingConvention unmanagedCallingConvention, Type? returnType, Type[]? parameters) { - if (mod != null && !(mod is ModuleBuilder)) + if (mod is not null && !(mod is ModuleBuilder)) throw new ArgumentException("ModuleBuilder is expected"); - if (returnType == null) + if (returnType is null) returnType = typeof(void); if (returnType.IsUserType) throw new NotSupportedException("User defined subclasses of System.Type are not yet supported."); - if (parameters != null) + if (parameters is not null) { for (int i = 0; i < parameters.Length; ++i) if (parameters[i].IsUserType) @@ -413,7 +413,7 @@ internal static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventio helper.callConv = callingConvention; helper.unmanagedCallConv = unmanagedCallingConvention; - if (parameters != null) + if (parameters is not null) { helper.arguments = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; ++i) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs index b1d1c061930850..bf353e6212607a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs @@ -120,7 +120,7 @@ internal TypeBuilder(ModuleBuilder mb, string fullname, TypeAttributes attr, [Dy check_name(nameof(fullname), fullname); - if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0) + if (parent is null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0) throw new InvalidOperationException(SR.InvalidOperation_BadInterfaceNotAbstract); sep_index = fullname.LastIndexOf('.'); @@ -134,14 +134,14 @@ internal TypeBuilder(ModuleBuilder mb, string fullname, TypeAttributes attr, [Dy this.tname = fullname; this.nspace = string.Empty; } - if (interfaces != null) + if (interfaces is not null) { this.interfaces = new Type[interfaces.Length]; Array.Copy(interfaces, this.interfaces, interfaces.Length); } pmodule = mb; - if (((attr & TypeAttributes.Interface) == 0) && (parent == null)) + if (((attr & TypeAttributes.Interface) == 0) && (parent is null)) this.parent = typeof(object); // skip . ? @@ -179,12 +179,12 @@ public override Type? DeclaringType public override bool IsSubclassOf(Type c) { Type? t; - if (c == null) + if (c is null) return false; if (c == this) return false; t = parent; - while (t != null) + while (t is not null) { if (c == t) return true; @@ -202,7 +202,7 @@ public override Type UnderlyingSystemType if (IsEnum) { - if (underlying_type != null) + if (underlying_type is not null) return underlying_type; throw new InvalidOperationException( "Enumeration type is not defined."); @@ -215,9 +215,9 @@ public override Type UnderlyingSystemType private ITypeName GetFullName() { ITypeIdentifier ident = TypeIdentifiers.FromInternal(tname); - if (nesting_type != null) + if (nesting_type is not null) return TypeNames.FromDisplay(nesting_type.FullName!).NestedName(ident); - if ((nspace != null) && (nspace.Length > 0)) + if ((nspace is not null) && (nspace.Length > 0)) return TypeIdentifiers.FromInternal(nspace, ident); return ident; } @@ -272,13 +272,13 @@ public override Type? ReflectedType [ComVisible(true)] public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType) { - if (interfaceType == null) + if (interfaceType is null) throw new ArgumentNullException(nameof(interfaceType)); if (interfaceType.IsByRef) throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef); check_not_created(); - if (interfaces != null) + if (interfaces is not null) { // Check for duplicates foreach (Type t in interfaces) @@ -312,7 +312,7 @@ public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAc * newly built one. */ - if (ctors == null) + if (ctors is null) return null; ConstructorBuilder? found = null; @@ -328,7 +328,7 @@ public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAc if (count == 0) return null; - if (types == null) + if (types is null) { if (count > 1) throw new AmbiguousMatchException(); @@ -405,11 +405,11 @@ private TypeBuilder DefineNestedType(string name, TypeAttributes attr, [Dynamica ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic)) throw new ArgumentException (nameof(attr), "Bad type flags for nested type."); */ - if (interfaces != null) + if (interfaces is not null) { foreach (Type iface in interfaces) { - if (iface == null) + if (iface is null) throw new ArgumentNullException(nameof(interfaces)); if (iface.IsByRef) throw new ArgumentException(nameof(interfaces)); @@ -419,7 +419,7 @@ private TypeBuilder DefineNestedType(string name, TypeAttributes attr, [Dynamica TypeBuilder res = new TypeBuilder(pmodule, name, attr, parent, interfaces, packSize, typeSize, this); res.fullname = res.GetFullName(); pmodule.RegisterTypeName(res, res.fullname); - if (subtypes != null) + if (subtypes is not null) { TypeBuilder[] new_types = new TypeBuilder[subtypes.Length + 1]; Array.Copy(subtypes, new_types, subtypes.Length); @@ -471,7 +471,7 @@ public ConstructorBuilder DefineConstructor(MethodAttributes attributes, Calling ConstructorBuilder cb = new ConstructorBuilder(this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); - if (ctors != null) + if (ctors is not null) { ConstructorBuilder[] new_ctors = new ConstructorBuilder[ctors.Length + 1]; Array.Copy(ctors, new_ctors, ctors.Length); @@ -498,7 +498,7 @@ public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) if ((attributes & (MethodAttributes.Static | MethodAttributes.Virtual)) > 0) throw new ArgumentException(SR.Arg_NoStaticVirtual); - if (parent != null) + if (parent is not null) parent_type = parent; else parent_type = typeof(object); @@ -513,7 +513,7 @@ public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) parent_type.GetConstructor( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, EmptyTypes, null); - if (parent_constructor == null) + if (parent_constructor is null) { throw new NotSupportedException("Parent does" + " not have a default constructor." @@ -533,7 +533,7 @@ public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) private void append_method(MethodBuilder mb) { - if (methods != null) + if (methods is not null) { if (methods.Length == num_methods) { @@ -572,7 +572,7 @@ public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Call !(((attributes & MethodAttributes.Static) != 0))) throw new ArgumentException("Interface method must be abstract and virtual."); - if (returnType == null) + if (returnType is null) returnType = typeof(void); MethodBuilder res = new MethodBuilder(this, name, attributes, callingConvention, returnType, @@ -652,9 +652,9 @@ public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Call public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) { - if (methodInfoBody == null) + if (methodInfoBody is null) throw new ArgumentNullException(nameof(methodInfoBody)); - if (methodInfoDeclaration == null) + if (methodInfoDeclaration is null) throw new ArgumentNullException(nameof(methodInfoDeclaration)); check_not_created(); if (methodInfoBody.DeclaringType != this) @@ -679,7 +679,7 @@ public FieldBuilder DefineField(string fieldName, Type type, Type[]? requiredCus check_not_created(); FieldBuilder res = new FieldBuilder(this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers); - if (fields != null) + if (fields is not null) { if (fields.Length == num_fields) { @@ -699,7 +699,7 @@ public FieldBuilder DefineField(string fieldName, Type type, Type[]? requiredCus if (IsEnum) { - if (underlying_type == null && (attributes & FieldAttributes.Static) == 0) + if (underlying_type is null && (attributes & FieldAttributes.Static) == 0) underlying_type = type; } @@ -724,15 +724,15 @@ public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { check_name(nameof(name), name); - if (parameterTypes != null) + if (parameterTypes is not null) foreach (Type param in parameterTypes) - if (param == null) + if (param is null) throw new ArgumentNullException(nameof(parameterTypes)); check_not_created(); PropertyBuilder res = new PropertyBuilder(this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); - if (properties != null) + if (properties is not null) { Array.Resize(ref properties, properties.Length + 1); properties[properties.Length - 1] = res; @@ -759,7 +759,7 @@ public ConstructorBuilder DefineTypeInitializer() private bool is_nested_in(Type? t) { - while (t != null) + while (t is not null) { if (t == this) return true; @@ -805,18 +805,18 @@ private bool has_ctor_method() if (createTypeCalled) return created; - if (!IsInterface && (parent == null) && (this != typeof(object)) && (FullName != "")) + if (!IsInterface && (parent is null) && (this != typeof(object)) && (FullName != "")) { SetParent(typeof(object)); } // Fire TypeResolve events for fields whose type is an unfinished // value type. - if (fields != null) + if (fields is not null) { foreach (FieldBuilder fb in fields) { - if (fb == null) + if (fb is null) continue; Type ft = fb.FieldType; if (!fb.IsStatic && (ft is TypeBuilder builder) && ft.IsValueType && (ft != this) && is_nested_in(ft)) @@ -830,7 +830,7 @@ private bool has_ctor_method() } } - if (parent != null) + if (parent is not null) { if (parent.IsByRef) throw new ArgumentException(); @@ -841,13 +841,13 @@ private bool has_ctor_method() // // On classes, define a default constructor if not provided // - if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "") && + if (!(IsInterface || IsValueType) && (ctors is null) && (tname != "") && (GetAttributeFlagsImpl() & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method()) DefineDefaultConstructor(MethodAttributes.Public); createTypeCalled = true; - if (parent != null) + if (parent is not null) { if (parent.IsSealed) throw new TypeLoadException("Could not load type '" + fullname.DisplayName + "' from assembly '" + Assembly + "' because the parent type is sealed."); @@ -855,9 +855,9 @@ private bool has_ctor_method() throw new BadImageFormatException(); } - if (parent == typeof(Enum) && methods != null) + if (parent == typeof(Enum) && methods is not null) throw new TypeLoadException("Could not load type '" + fullname.DisplayName + "' from assembly '" + Assembly + "' because it is an enum with methods."); - if (interfaces != null) + if (interfaces is not null) { foreach (Type iface in interfaces) { @@ -872,18 +872,18 @@ private bool has_ctor_method() } } - if (fields != null) + if (fields is not null) { foreach (FieldBuilder fb in fields) { - if (fb == null) + if (fb is null) continue; if (fb.FieldType.IsByRef) throw new COMException(); } } - if (methods != null) + if (methods is not null) { bool is_concrete = !IsAbstract; for (int i = 0; i < num_methods; ++i) @@ -896,7 +896,7 @@ private bool has_ctor_method() } } - if (ctors != null) + if (ctors is not null) { foreach (ConstructorBuilder ctor in ctors) ctor.fixup(); @@ -905,7 +905,7 @@ private bool has_ctor_method() ResolveUserTypes(); created = create_runtime_class(); - if (created != null) + if (created is not null) return created; return this; } @@ -914,27 +914,27 @@ private void ResolveUserTypes() { parent = ResolveUserType(parent); ResolveUserTypes(interfaces); - if (fields != null) + if (fields is not null) { foreach (FieldBuilder fb in fields) { - if (fb != null) + if (fb is not null) fb.ResolveUserTypes(); } } - if (methods != null) + if (methods is not null) { foreach (MethodBuilder mb in methods) { - if (mb != null) + if (mb is not null) mb.ResolveUserTypes(); } } - if (ctors != null) + if (ctors is not null) { foreach (ConstructorBuilder cb in ctors) { - if (cb != null) + if (cb is not null) cb.ResolveUserTypes(); } } @@ -942,7 +942,7 @@ private void ResolveUserTypes() internal static void ResolveUserTypes(Type?[]? types) { - if (types != null) + if (types is not null) for (int i = 0; i < types.Length; ++i) types[i] = ResolveUserType(types[i]); } @@ -950,10 +950,10 @@ internal static void ResolveUserTypes(Type?[]? types) [return: NotNullIfNotNull("t")] internal static Type? ResolveUserType(Type? t) { - if (t != null && ((t.GetType().Assembly != typeof(int).Assembly) || (t is TypeDelegator))) + if (t is not null && ((t.GetType().Assembly != typeof(int).Assembly) || (t is TypeDelegator))) { t = t.UnderlyingSystemType; - if (t != null && ((t.GetType().Assembly != typeof(int).Assembly) || (t is TypeDelegator))) + if (t is not null && ((t.GetType().Assembly != typeof(int).Assembly) || (t is TypeDelegator))) throw new NotSupportedException("User defined subclasses of System.Type are not yet supported."); return t; } @@ -967,21 +967,21 @@ internal void GenerateDebugInfo (ISymbolWriter symbolWriter) { symbolWriter.OpenNamespace (this.Namespace); - if (methods != null) { + if (methods is not null) { for (int i = 0; i < num_methods; ++i) { MethodBuilder metb = (MethodBuilder) methods[i]; metb.GenerateDebugInfo (symbolWriter); } } - if (ctors != null) { + if (ctors is not null) { foreach (ConstructorBuilder ctor in ctors) ctor.GenerateDebugInfo (symbolWriter); } symbolWriter.CloseNamespace (); - if (subtypes != null) { + if (subtypes is not null) { for (int i = 0; i < subtypes.Length; ++i) subtypes [i].GenerateDebugInfo (symbolWriter); } @@ -999,7 +999,7 @@ public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) internal ConstructorInfo[] GetConstructorsInternal(BindingFlags bindingAttr) { - if (ctors == null) + if (ctors is null) return Array.Empty(); List result = new List(); bool match; @@ -1094,7 +1094,7 @@ public override Type[] GetInterfaces() if (is_created) return created!.GetInterfaces(); - if (interfaces != null) + if (interfaces is not null) { Type[] ret = new Type[interfaces.Length]; interfaces.CopyTo(ret, 0); @@ -1127,7 +1127,7 @@ private MethodInfo[] GetMethodsByName(string? name, BindingFlags bindingAttr, bo bool match; MethodAttributes mattrs; - if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) + if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent is not null)) { MethodInfo[] parent_methods = parent.GetMethods(bindingAttr); List parent_candidates = new List(parent_methods.Length); @@ -1155,7 +1155,7 @@ private MethodInfo[] GetMethodsByName(string? name, BindingFlags bindingAttr, bo parent_candidates.Add(m); } - if (methods == null) + if (methods is null) { candidates = new MethodInfo[parent_candidates.Count]; parent_candidates.CopyTo(candidates); @@ -1170,16 +1170,16 @@ private MethodInfo[] GetMethodsByName(string? name, BindingFlags bindingAttr, bo else candidates = methods; - if (candidates == null) + if (candidates is null) return Array.Empty(); List result = new List(); foreach (MethodInfo c in candidates) { - if (c == null) + if (c is null) continue; - if (name != null) + if (name is not null) { if (string.Compare(c.Name, name, ignoreCase) != 0) continue; @@ -1232,7 +1232,7 @@ public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { check_created(); - if (types == null) + if (types is null) return created!.GetMethod(name, bindingAttr); return created!.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); @@ -1243,7 +1243,7 @@ public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { check_created(); - if (subtypes == null) + if (subtypes is null) return null; foreach (TypeBuilder t in subtypes) @@ -1276,7 +1276,7 @@ public override Type[] GetNestedTypes(BindingFlags bindingAttr) bool match; List result = new List(); - if (subtypes == null) + if (subtypes is null) return EmptyTypes; foreach (TypeBuilder t in subtypes) { @@ -1357,7 +1357,7 @@ protected override bool IsPrimitiveImpl() protected override bool IsValueTypeImpl() { Type? parent_type = parent; - while (parent_type != null) + while (parent_type is not null) { if (parent_type == typeof(ValueType)) return true; @@ -1397,7 +1397,7 @@ public override Type MakeGenericType(params Type[] typeArguments) if (!IsGenericTypeDefinition) throw new InvalidOperationException("not a generic type definition"); - if (typeArguments == null) + if (typeArguments is null) throw new ArgumentNullException(nameof(typeArguments)); if (generic_params!.Length != typeArguments.Length) @@ -1405,7 +1405,7 @@ public override Type MakeGenericType(params Type[] typeArguments) foreach (Type t in typeArguments) { - if (t == null) + if (t is null) throw new ArgumentNullException(nameof(typeArguments)); } @@ -1430,7 +1430,7 @@ public override RuntimeTypeHandle TypeHandle public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; @@ -1534,7 +1534,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) attrs |= TypeAttributes.HasSecurity; } - if (cattrs != null) + if (cattrs is not null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); @@ -1557,13 +1557,13 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) public EventBuilder DefineEvent(string name, EventAttributes attributes, Type eventtype) { check_name(nameof(name), name); - if (eventtype == null) + if (eventtype is null) throw new ArgumentNullException(nameof(eventtype)); check_not_created(); if (eventtype.IsByRef) throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef); EventBuilder res = new EventBuilder(this, name, attributes, eventtype); - if (events != null) + if (events is not null) { EventBuilder[] new_events = new EventBuilder[events.Length + 1]; Array.Copy(events, new_events, events.Length); @@ -1580,7 +1580,7 @@ public EventBuilder DefineEvent(string name, EventAttributes attributes, Type ev public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); FieldBuilder res = DefineUninitializedData(name, data.Length, attributes); @@ -1590,7 +1590,7 @@ public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttribu public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("Empty name is not legal", nameof(name)); @@ -1601,7 +1601,7 @@ public FieldBuilder DefineUninitializedData(string name, int size, FieldAttribut string typeName = "$ArrayType$" + size; ITypeIdentifier ident = TypeIdentifiers.WithoutEscape(typeName); Type? datablobtype = pmodule.GetRegisteredType(fullname.NestedName(ident)); - if (datablobtype == null) + if (datablobtype is null) { TypeBuilder tb = DefineNestedType(typeName, TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Sealed, @@ -1620,7 +1620,7 @@ public void SetParent([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes { check_not_created(); - if (parent == null) + if (parent is null) { if ((attrs & TypeAttributes.Interface) != 0) { @@ -1650,7 +1650,7 @@ internal int get_next_table_index(object obj, int table, int count) [ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { - if (created == null) + if (created is null) throw new NotSupportedException("This method is not implemented for incomplete types."); return created.GetInterfaceMap(interfaceType); @@ -1695,7 +1695,7 @@ private void check_created() private static void check_name(string argName, string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(argName); if (name.Length == 0 || name[0] == ((char)0)) throw new ArgumentException(SR.Argument_EmptyName, argName); @@ -1720,13 +1720,13 @@ internal bool IsAssignableToInternal([NotNullWhen(true)] Type? c) if (c!.IsInterface) { - if (parent != null && is_created) + if (parent is not null && is_created) { if (c.IsAssignableFrom(parent)) return true; } - if (interfaces == null) + if (interfaces is null) return false; foreach (Type t in interfaces) if (c.IsAssignableFrom(t)) @@ -1735,7 +1735,7 @@ internal bool IsAssignableToInternal([NotNullWhen(true)] Type? c) return false; } - if (parent == null) + if (parent is null) return c == typeof(object); else return c.IsAssignableFrom(parent); @@ -1748,7 +1748,7 @@ public bool IsCreated() public override Type[] GetGenericArguments() { - if (generic_params == null) + if (generic_params is null) return Type.EmptyTypes; Type[] args = new Type[generic_params.Length]; generic_params.CopyTo(args, 0); @@ -1757,7 +1757,7 @@ public override Type[] GetGenericArguments() public override Type GetGenericTypeDefinition() { - if (generic_params == null) + if (generic_params is null) throw new InvalidOperationException("Type is not generic"); return this; } @@ -1766,7 +1766,7 @@ public override bool ContainsGenericParameters { get { - return generic_params != null; + return generic_params is not null; } } @@ -1787,7 +1787,7 @@ public override bool IsGenericTypeDefinition { get { - return generic_params != null; + return generic_params is not null; } } @@ -1815,7 +1815,7 @@ public override MethodBase? DeclaringMethod public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { - if (names == null) + if (names is null) throw new ArgumentNullException(nameof(names)); if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); @@ -1824,7 +1824,7 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam for (int i = 0; i < names.Length; i++) { string item = names[i]; - if (item == null) + if (item is null) throw new ArgumentNullException(nameof(names)); generic_params[i] = new GenericTypeParameterBuilder(this, null, item, i); } @@ -1837,7 +1837,7 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor) { /*FIXME I would expect the same checks of GetMethod here*/ - if (type == null) + if (type is null) throw new ArgumentException("Type is not generic", nameof(type)); if (!type.IsGenericType) @@ -1846,7 +1846,7 @@ public static ConstructorInfo GetConstructor(Type type, ConstructorInfo construc if (type.IsGenericTypeDefinition) throw new ArgumentException("Type cannot be a generic type definition", nameof(type)); - if (constructor == null) + if (constructor is null) throw new NullReferenceException(); //MS raises this instead of an ArgumentNullException if (!constructor.DeclaringType!.IsGenericTypeDefinition) @@ -1855,7 +1855,7 @@ public static ConstructorInfo GetConstructor(Type type, ConstructorInfo construc throw new ArgumentException("constructor declaring type is not the generic type definition of type", nameof(constructor)); ConstructorInfo res = type.GetConstructor(constructor); - if (res == null) + if (res is null) throw new ArgumentException("constructor not found"); return res; @@ -1872,7 +1872,7 @@ private static bool IsValidGetMethodType(Type type) return false; Type[] inst = type.GetGenericArguments(); - if (inst == null) + if (inst is null) return false; for (int i = 0; i < inst.Length; ++i) { @@ -1899,11 +1899,11 @@ public static MethodInfo GetMethod(Type type, MethodInfo method) throw new ArgumentException("method declaring type is not a generic type definition", nameof(method)); if (method.DeclaringType != type.GetGenericTypeDefinition()) throw new ArgumentException("method declaring type is not the generic type definition of type", nameof(method)); - if (method == null) + if (method is null) throw new NullReferenceException(); //MS raises this instead of an ArgumentNullException MethodInfo res = type.GetMethod(method); - if (res == null) + if (res is null) throw new ArgumentException(string.Format("method {0} not found in type {1}", method.Name, type)); return res; @@ -1924,7 +1924,7 @@ public static FieldInfo GetField(Type type, FieldInfo field) throw new ArgumentException("field declaring type is not the generic type definition of type", nameof(field)); FieldInfo res = type.GetField(field); - if (res == null) + if (res is null) throw new System.Exception("field not found"); else return res; @@ -1962,7 +1962,7 @@ internal static bool SetConstantValue(Type destType, object? value, ref object? // This is a helper function that is used by ParameterBuilder, PropertyBuilder, // and FieldBuilder to validate a default value and save it in the meta-data. - if (value != null) + if (value is not null) { Type type = value.GetType(); @@ -2006,7 +2006,7 @@ internal static bool SetConstantValue(Type destType, object? value, ref object? // The constant value supplied should match either the baked enum type or its underlying type // typeBldr.m_enumUnderlyingType is null if the user hasn't created a "value__" field on the enum - if (underlyingType == null || (type != typeBldr.UnderlyingSystemType && type != underlyingType)) + if (underlyingType is null || (type != typeBldr.UnderlyingSystemType && type != underlyingType)) throw_argument_ConstantDoesntMatch(); } else diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index a6a48c031a21a3..7c602e71c44be7 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -127,15 +127,15 @@ internal bool IsCreated Justification = "Reflection emitted types have all of their members")] internal static Type? InflateType(Type? type, Type[]? type_args, Type[]? method_args) { - if (type == null) + if (type is null) return null; if (!type.IsGenericParameter && !type.ContainsGenericParameters) return type; if (type.IsGenericParameter) { - if (type.DeclaringMethod == null) - return type_args == null ? type : type_args[type.GenericParameterPosition]; - return method_args == null ? type : method_args[type.GenericParameterPosition]; + if (type.DeclaringMethod is null) + return type_args is null ? type : type_args[type.GenericParameterPosition]; + return method_args is null ? type : method_args[type.GenericParameterPosition]; } if (type.IsPointer) return InflateType(type.GetElementType(), type_args, method_args)!.MakePointerType(); @@ -176,7 +176,7 @@ protected override bool IsValueTypeImpl() internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated) { - if (methods == null) + if (methods is null) methods = new Dictionary(); if (!methods.ContainsKey(fromNoninstanciated)) methods[fromNoninstanciated] = new MethodOnTypeBuilderInst(this, fromNoninstanciated); @@ -185,7 +185,7 @@ internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated) internal override ConstructorInfo GetConstructor(ConstructorInfo fromNoninstanciated) { - if (ctors == null) + if (ctors is null) ctors = new Dictionary(); if (!ctors.ContainsKey(fromNoninstanciated)) ctors[fromNoninstanciated] = new ConstructorOnTypeBuilderInst(this, fromNoninstanciated); @@ -194,7 +194,7 @@ internal override ConstructorInfo GetConstructor(ConstructorInfo fromNoninstanci internal override FieldInfo GetField(FieldInfo fromNoninstanciated) { - if (fields == null) + if (fields is null) fields = new Dictionary(); if (!fields.ContainsKey(fromNoninstanciated)) fields[fromNoninstanciated] = new FieldOnTypeBuilderInst(this, fromNoninstanciated); @@ -297,14 +297,14 @@ public override Guid GUID { string? assemblyName = type_arguments[i].Assembly.FullName; name = type_arguments[i].FullName; - if (name != null && assemblyName != null) + if (name is not null && assemblyName is not null) name = name + ", " + assemblyName; } else { name = type_arguments[i].ToString(); } - if (name == null) + if (name is null) { return null; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs index ea843ea40893ac..49ea0500fe4000 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs @@ -23,7 +23,7 @@ public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTyp if (handle.IsNullHandle()) throw new ArgumentException(SR.Argument_InvalidHandle); FieldInfo fi = internal_from_handle_type(handle.Value, declaringType.Value); - if (fi == null) + if (fi is null) throw new ArgumentException("The field handle and the type handle are incompatible."); return fi; } @@ -47,7 +47,7 @@ internal virtual int GetFieldOffset() count++; MarshalAsAttribute marshalAs = get_marshal_info(); - if (marshalAs != null) + if (marshalAs is not null) count++; if (count == 0) @@ -59,7 +59,7 @@ internal virtual int GetFieldOffset() attrs[count++] = new NonSerializedAttribute(); if (DeclaringType.IsExplicitLayout) attrs[count++] = new FieldOffsetAttribute(GetFieldOffset()); - if (marshalAs != null) + if (marshalAs is not null) attrs[count++] = marshalAs; return attrs; @@ -76,7 +76,7 @@ internal virtual int GetFieldOffset() count++; MarshalAsAttribute marshalAs = get_marshal_info(); - if (marshalAs != null) + if (marshalAs is not null) count++; if (count == 0) @@ -95,7 +95,7 @@ internal virtual int GetFieldOffset() Array.Empty()); } - if (marshalAs != null) + if (marshalAs is not null) { var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(typeof(UnmanagedType), marshalAs.Value) }; attrsData[count++] = new CustomAttributeData( diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs index f6882f4984721a..35222bd979f805 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs @@ -7,7 +7,7 @@ public abstract partial class MemberInfo { internal bool HasSameMetadataDefinitionAsCore(MemberInfo other) where TOther : MemberInfo { - if (other == null) + if (other is null) throw new ArgumentNullException(nameof(other)); // Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it! diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs index 0ae9be023b864b..31e920be208961 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs @@ -13,11 +13,11 @@ public partial class MethodBase throw new ArgumentException(SR.Argument_InvalidHandle); MethodBase? m = RuntimeMethodInfo.GetMethodFromHandleInternalType(handle.Value, IntPtr.Zero); - if (m == null) + if (m is null) throw new ArgumentException(SR.Argument_InvalidHandle); Type? declaringType = m.DeclaringType; - if (declaringType != null && declaringType.IsGenericType) + if (declaringType is not null && declaringType.IsGenericType) throw new ArgumentException(string.Format(SR.Argument_MethodDeclaringTypeGeneric, m, declaringType.GetGenericTypeDefinition())); @@ -29,7 +29,7 @@ public partial class MethodBase if (handle.IsNullHandle()) throw new ArgumentException(SR.Argument_InvalidHandle); MethodBase m = RuntimeMethodInfo.GetMethodFromHandleInternalType(handle.Value, declaringType.Value); - if (m == null) + if (m is null) throw new ArgumentException(SR.Argument_InvalidHandle); return m; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index f9434d7d7e4ed9..0e432aad8c60e4 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -128,7 +128,7 @@ public override string Location internal static AssemblyName? CreateAssemblyName(string assemblyString, out RuntimeAssembly? assemblyFromResolveEvent) { - if (assemblyString == null) + if (assemblyString is null) throw new ArgumentNullException(nameof(assemblyString)); if ((assemblyString.Length == 0) || @@ -143,7 +143,7 @@ public override string Location catch (Exception) { assemblyFromResolveEvent = (RuntimeAssembly?)AssemblyLoadContext.DoAssemblyResolve(assemblyString); - if (assemblyFromResolveEvent == null) + if (assemblyFromResolveEvent is null) throw new FileLoadException(assemblyString); return null; } @@ -203,7 +203,7 @@ private static void AddPublicNestedTypes(Type type, List types, List types, List types, List types, List GetCustomAttributesData() private void CheckGeneric() { Type? declaringType = DeclaringType; - if (declaringType != null && declaringType.ContainsGenericParameters) + if (declaringType is not null && declaringType.ContainsGenericParameters) throw new InvalidOperationException("Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true."); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs index 47de4bd37684b6..9c46ce7455e69b 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs @@ -193,7 +193,7 @@ public override Delegate CreateDelegate(Type delegateType, object? target) // copied from CoreCLR's RuntimeMethodInfo public override string ToString() { - if (toString == null) + if (toString is null) { var sbName = new ValueStringBuilder(MethodNameBufferSize); @@ -350,14 +350,14 @@ internal override int GetParametersCount() { if (!DeclaringType.IsInstanceOfType(obj)) { - if (obj == null) + if (obj is null) throw new TargetException("Non-static method requires a target."); else throw new TargetException("Object does not match target type."); } } - if (binder == null) + if (binder is null) binder = Type.DefaultBinder; /*Avoid allocating an array every time*/ @@ -401,14 +401,14 @@ internal override int GetParametersCount() } } - if (exc != null) + if (exc is not null) throw exc; return o; } internal static void ConvertValues(Binder binder, object?[]? args, ParameterInfo[] pinfo, CultureInfo? culture, BindingFlags invokeAttr) { - if (args == null) + if (args is null) { if (pinfo.Length == 0) return; @@ -479,7 +479,7 @@ public override string Name { get { - if (name != null) + if (name is not null) return name; return get_name(this); } @@ -672,7 +672,7 @@ private Attribute GetDllImportAttribute() public override MethodInfo MakeGenericMethod(Type[] methodInstantiation) { - if (methodInstantiation == null) + if (methodInstantiation is null) throw new ArgumentNullException(nameof(methodInstantiation)); if (!IsGenericMethodDefinition) @@ -685,7 +685,7 @@ public override MethodInfo MakeGenericMethod(Type[] methodInstantiation) bool hasUserType = false; foreach (Type type in methodInstantiation) { - if (type == null) + if (type is null) throw new ArgumentNullException(); if (!(type is RuntimeType)) hasUserType = true; @@ -700,7 +700,7 @@ public override MethodInfo MakeGenericMethod(Type[] methodInstantiation) } MethodInfo ret = MakeGenericMethod_impl(methodInstantiation); - if (ret == null) + if (ret is null) throw new ArgumentException(string.Format("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments().Length, methodInstantiation.Length)); return ret; } @@ -717,7 +717,7 @@ public override MethodInfo MakeGenericMethod(Type[] methodInstantiation) public override MethodInfo GetGenericMethodDefinition() { MethodInfo res = GetGenericMethodDefinition_impl(); - if (res == null) + if (res is null) throw new InvalidOperationException(); return res; @@ -812,7 +812,7 @@ internal override ParameterInfo[] GetParametersInternal() internal override int GetParametersCount() { ParameterInfo[] pi = MonoMethodInfo.GetParametersInfo(mhandle, this); - return pi == null ? 0 : pi.Length; + return pi is null ? 0 : pi.Length; } /* @@ -826,7 +826,7 @@ internal override int GetParametersCount() [DebuggerStepThrough] public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { - if (obj == null) + if (obj is null) { if (!IsStatic) throw new TargetException("Instance constructor requires a target"); @@ -841,14 +841,14 @@ internal override int GetParametersCount() private object DoInvoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { - if (binder == null) + if (binder is null) binder = Type.DefaultBinder; ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo(mhandle, this); RuntimeMethodInfo.ConvertValues(binder, parameters, pinfo, culture, invokeAttr); - if (obj == null && DeclaringType.ContainsGenericParameters) + if (obj is null && DeclaringType.ContainsGenericParameters) throw new MemberAccessException("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true."); if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) @@ -888,10 +888,10 @@ private object DoInvoke(object? obj, BindingFlags invokeAttr, Binder? binder, ob o = InternalInvoke(obj, parameters, out exc); } - if (exc != null) + if (exc is not null) throw exc; - return obj == null ? o : null; + return obj is null ? o : null; } [DebuggerHidden] @@ -951,7 +951,7 @@ public override string Name { get { - if (name != null) + if (name is not null) return name; return RuntimeMethodInfo.get_name(this); } @@ -980,7 +980,7 @@ public override MethodBody GetMethodBody() // copied from CoreCLR's RuntimeConstructorInfo public override string ToString() { - if (toString == null) + if (toString is null) { var sbName = new ValueStringBuilder(MethodNameBufferSize); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs index ef8f6554be7079..5b6ebeb26e01fe 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs @@ -116,7 +116,7 @@ Type[] FindTypes(TypeFilter? filter, object? filterCriteria) { var filtered = new List(); foreach (Type t in GetTypes()) - if (filter != null && filter(t, filterCriteria)) + if (filter is not null && filter(t, filterCriteria)) filtered.Add(t); return filtered.ToArray(); } @@ -137,7 +137,7 @@ object[] GetCustomAttributes(Type attributeType, bool inherit) public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (IsResource()) @@ -155,7 +155,7 @@ FieldInfo[] GetFields(BindingFlags bindingFlags) return Array.Empty(); Type globalType = GetGlobalType(_impl); - return (globalType != null) ? globalType.GetFields(bindingFlags) : Array.Empty(); + return (globalType is not null) ? globalType.GetFields(bindingFlags) : Array.Empty(); } public override @@ -176,9 +176,9 @@ int MetadataToken return null; Type globalType = GetGlobalType(_impl); - if (globalType == null) + if (globalType is null) return null; - if (types == null) + if (types is null) return globalType.GetMethod(name); return globalType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } @@ -192,7 +192,7 @@ MethodInfo[] GetMethods(BindingFlags bindingFlags) return Array.Empty(); Type globalType = GetGlobalType(_impl); - return (globalType != null) ? globalType.GetMethods(bindingFlags) : Array.Empty(); + return (globalType is not null) ? globalType.GetMethods(bindingFlags) : Array.Empty(); } public override @@ -205,7 +205,7 @@ void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) public override Type GetType(string className, bool throwOnError, bool ignoreCase) { - if (className == null) + if (className is null) throw new ArgumentNullException(nameof(className)); if (className.Length == 0) throw new ArgumentException("Type name can't be empty"); @@ -250,7 +250,7 @@ internal static MemberInfo ResolveMember(Module module, IntPtr monoModule, int m ResolveTokenError error; MemberInfo m = ResolveMemberToken(monoModule, metadataToken, ptrs_from_types(genericTypeArguments), ptrs_from_types(genericMethodArguments), out error); - if (m == null) + if (m is null) throw resolve_token_exception(module.Name, metadataToken, error, "MemberInfo"); else return m; @@ -288,7 +288,7 @@ internal static string ResolveString(Module module, IntPtr monoModule, int metad ResolveTokenError error; string s = ResolveStringToken(monoModule, metadataToken, out error); - if (s == null) + if (s is null) throw resolve_token_exception(module.Name, metadataToken, error, "string"); else return s; @@ -326,7 +326,7 @@ internal static byte[] ResolveSignature(Module module, IntPtr monoModule, int me ResolveTokenError error; byte[] res = ResolveSignature(monoModule, metadataToken, out error); - if (res == null) + if (res is null) throw resolve_token_exception(module.Name, metadataToken, error, "signature"); else return res; @@ -374,14 +374,14 @@ internal static Exception resolve_token_exception(string name, int metadataToken internal static IntPtr[]? ptrs_from_types(Type[]? types) { - if (types == null) + if (types is null) return null; else { IntPtr[] res = new IntPtr[types.Length]; for (int i = 0; i < types.Length; ++i) { - if (types[i] == null) + if (types[i] is null) throw new ArgumentException(); res[i] = types[i].TypeHandle.Value; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs index b725f72ec60a23..ef11d85a5fb054 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs @@ -62,7 +62,7 @@ internal RuntimeParameterInfo(ParameterBuilder? pb, Type? type, MemberInfo membe { this.ClassImpl = type; this.MemberImpl = member; - if (pb != null) + if (pb is not null) { this.NameImpl = pb.Name; this.PositionImpl = pb.Position - 1; // ParameterInfo.Position is zero-based @@ -86,7 +86,7 @@ internal RuntimeParameterInfo(ParameterInfo? pinfo, Type? type, MemberInfo membe { this.ClassImpl = type; this.MemberImpl = member; - if (pinfo != null) + if (pinfo is not null) { this.NameImpl = pinfo.Name; this.PositionImpl = pinfo.Position - 1; // ParameterInfo.Position is zero-based @@ -149,7 +149,7 @@ public override { get { - if (DefaultValue != null && DefaultValue.GetType().IsEnum) + if (DefaultValue is not null && DefaultValue.GetType().IsEnum) return ((Enum)DefaultValue).GetValue(); /*FIXME right now DefaultValue doesn't throw for reflection-only assemblies. Change this once the former is fixed.*/ return DefaultValue; @@ -224,7 +224,7 @@ public override IList GetCustomAttributesData() count++; if (IsOptional) count++; - if (marshalAs != null) + if (marshalAs is not null) count++; if (count == 0) @@ -239,7 +239,7 @@ public override IList GetCustomAttributesData() if (IsOptional) attrs[count++] = new OptionalAttribute(); - if (marshalAs != null) + if (marshalAs is not null) { attrs[count++] = (MarshalAsAttribute)marshalAs.CloneInternal(); } @@ -257,7 +257,7 @@ public override IList GetCustomAttributesData() count++; if (IsOptional) count++; - if (marshalAs != null) + if (marshalAs is not null) count++; if (count == 0) @@ -271,7 +271,7 @@ public override IList GetCustomAttributesData() attrsData[count++] = new CustomAttributeData((typeof(OutAttribute)).GetConstructor(Type.EmptyTypes)!); if (IsOptional) attrsData[count++] = new CustomAttributeData((typeof(OptionalAttribute)).GetConstructor(Type.EmptyTypes)!); - if (marshalAs != null) + if (marshalAs is not null) { var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(typeof(UnmanagedType), marshalAs.Value) }; attrsData[count++] = new CustomAttributeData( @@ -290,7 +290,7 @@ public override bool HasDefaultValue get { object? defaultValue = DefaultValue; - if (defaultValue == null) + if (defaultValue is null) return true; if (defaultValue.GetType() == typeof(DBNull) || defaultValue.GetType() == typeof(Missing)) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs index 0967b1e4978809..5308c3638f6655 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs @@ -192,7 +192,7 @@ public override bool CanRead get { CachePropertyInfo(PInfo.GetMethod); - return (info.get_method != null); + return (info.get_method is not null); } } @@ -201,7 +201,7 @@ public override bool CanWrite get { CachePropertyInfo(PInfo.SetMethod); - return (info.set_method != null); + return (info.set_method is not null); } } @@ -211,7 +211,7 @@ public override Type PropertyType { CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod); - if (info.get_method != null) + if (info.get_method is not null) { return info.get_method.ReturnType; } @@ -260,9 +260,9 @@ public override MethodInfo[] GetAccessors(bool nonPublic) CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod); - if (info.set_method != null && (nonPublic || info.set_method.IsPublic)) + if (info.set_method is not null && (nonPublic || info.set_method.IsPublic)) nset = 1; - if (info.get_method != null && (nonPublic || info.get_method.IsPublic)) + if (info.get_method is not null && (nonPublic || info.get_method.IsPublic)) nget = 1; MethodInfo[] res = new MethodInfo[nget + nset]; @@ -277,7 +277,7 @@ public override MethodInfo[] GetAccessors(bool nonPublic) public override MethodInfo? GetGetMethod(bool nonPublic) { CachePropertyInfo(PInfo.GetMethod); - if (info.get_method != null && (nonPublic || info.get_method.IsPublic)) + if (info.get_method is not null && (nonPublic || info.get_method.IsPublic)) return info.get_method; else return null; @@ -288,12 +288,12 @@ public override ParameterInfo[] GetIndexParameters() CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod); ParameterInfo[] src; int length; - if (info.get_method != null) + if (info.get_method is not null) { src = info.get_method.GetParametersInternal(); length = src.Length; } - else if (info.set_method != null) + else if (info.set_method is not null) { src = info.set_method.GetParametersInternal(); length = src.Length - 1; @@ -312,7 +312,7 @@ public override ParameterInfo[] GetIndexParameters() public override MethodInfo? GetSetMethod(bool nonPublic) { CachePropertyInfo(PInfo.SetMethod); - if (info.set_method != null && (nonPublic || info.set_method.IsPublic)) + if (info.set_method is not null && (nonPublic || info.set_method.IsPublic)) return info.set_method; else return null; @@ -405,13 +405,13 @@ private static GetterAdapter CreateGetterDelegate(MethodInfo method) public override object? GetValue(object? obj, object?[]? index) { - if ((index == null || index.Length == 0) && RuntimeFeature.IsDynamicCodeSupported) + if ((index is null || index.Length == 0) && RuntimeFeature.IsDynamicCodeSupported) { /*FIXME we should check if the number of arguments matches the expected one, otherwise the error message will be pretty criptic.*/ - if (cached_getter == null) + if (cached_getter is null) { MethodInfo? method = GetGetMethod(true); - if (method == null) + if (method is null) throw new ArgumentException($"Get Method not found for '{Name}'"); if (!DeclaringType.IsValueType && !PropertyType.IsByRef && !method.ContainsGenericParameters) { @@ -449,10 +449,10 @@ private static GetterAdapter CreateGetterDelegate(MethodInfo method) object? ret = null; MethodInfo? method = GetGetMethod(true); - if (method == null) + if (method is null) throw new ArgumentException($"Get Method not found for '{Name}'"); - if (index == null || index.Length == 0) + if (index is null || index.Length == 0) ret = method.Invoke(obj, invokeAttr, binder, null, culture); else ret = method.Invoke(obj, invokeAttr, binder, index, culture); @@ -463,11 +463,11 @@ private static GetterAdapter CreateGetterDelegate(MethodInfo method) public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) { MethodInfo? method = GetSetMethod(true); - if (method == null) + if (method is null) throw new ArgumentException("Set Method not found for '" + Name + "'"); object?[] parms; - if (index == null || index.Length == 0) + if (index is null || index.Length == 0) parms = new object?[] { value }; else { @@ -512,7 +512,7 @@ internal static PropertyInfo GetPropertyFromHandle(RuntimePropertyHandle handle, if (handle.Value == IntPtr.Zero) throw new ArgumentException("The handle is invalid."); PropertyInfo pi = internal_from_handle_type(handle.Value, reflectedType.Value); - if (pi == null) + if (pi is null) throw new ArgumentException("The property handle and the type handle are incompatible."); return pi; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs index 1b976a5906afad..4c0b17635297ed 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs @@ -24,7 +24,7 @@ public DependentHandle(object? primary, object? secondary) GC.register_ephemeron_array(data); } - public bool IsAllocated => data != null; + public bool IsAllocated => data is not null; // Getting the secondary object is more expensive than getting the first so // we provide a separate primary-only accessor for those times we only want the diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs index bb366f9b30f8bd..c051fe52f2d351 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs @@ -7,7 +7,7 @@ public partial class RuntimeHelpers { public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (fldHandle.Value == IntPtr.Zero) throw new ArgumentNullException(nameof(fldHandle)); @@ -34,7 +34,7 @@ public static int GetHashCode(object? o) if (o1 == o2) return true; - if (o1 == null || o2 == null) + if (o1 is null || o2 is null) return false; if (o1 is ValueType) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs index 7d50fa0d28f655..c5830945607211 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs @@ -28,7 +28,7 @@ public partial class Marshal internal static bool IsPinnable(object? obj) { - if (obj == null || obj is string) + if (obj is null || obj is string) return true; return IsPinnableType(obj.GetType()); //Type type = obj.GetType (); @@ -284,7 +284,7 @@ private static void PrelinkCore(MethodInfo m) private static void PtrToStructureHelper(IntPtr ptr, object? structure, bool allowValueClasses) { - if (structure == null) + if (structure is null) throw new ArgumentNullException(nameof(structure)); PtrToStructureInternal(ptr, structure, allowValueClasses); } @@ -361,7 +361,7 @@ public int GetHashCode((Type, string) key) throw new ApplicationException($"Custom marshaler '{type.FullName}' implements multiple static GetInstance methods that take a single string parameter."); } - if ((getInstanceMethod == null) || + if ((getInstanceMethod is null) || (getInstanceMethod.ReturnType != typeof(ICustomMarshaler))) { throw new ApplicationException($"Custom marshaler '{type.FullName}' does not implement a static GetInstance method that takes a single string parameter and returns an ICustomMarshaler."); @@ -380,13 +380,13 @@ public int GetHashCode((Type, string) key) result = null; } - if (exc != null) + if (exc is not null) { var edi = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exc); edi.Throw(); } - if (result == null) + if (result is null) throw new ApplicationException($"A call to GetInstance() for custom marshaler '{type.FullName}' returned null, which is not allowed."); lock (MarshalerInstanceCache) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs index a2dbfc9da734f9..ed803d142678b7 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs @@ -66,7 +66,7 @@ internal static Assembly[] GetLoadedAssemblies() // Returns the load context in which the specified assembly has been loaded public static AssemblyLoadContext? GetLoadContext(Assembly assembly) { - if (assembly == null) + if (assembly is null) throw new ArgumentNullException(nameof(assembly)); AssemblyLoadContext? loadContextForAssembly = null; @@ -74,7 +74,7 @@ internal static Assembly[] GetLoadedAssemblies() RuntimeAssembly? rtAsm = assembly as RuntimeAssembly; // We only support looking up load context for runtime assemblies. - if (rtAsm != null) + if (rtAsm is not null) { RuntimeAssembly runtimeAssembly = rtAsm; IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly(runtimeAssembly); @@ -169,7 +169,7 @@ private static void MonoResolveUnmanagedDllUsingEvent(string unmanagedDllName, A private static RuntimeAssembly? GetRuntimeAssembly(Assembly? asm) { return - asm == null ? null : + asm is null ? null : asm is RuntimeAssembly rtAssembly ? rtAssembly : asm is System.Reflection.Emit.AssemblyBuilder ab ? Unsafe.As(ab) : // Mono AssemblyBuilder is also a RuntimeAssembly, see AssemblyBuilder.Mono.cs null; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs index 46724b64c5d708..edab40080d9587 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs @@ -42,7 +42,7 @@ internal bool IsNullHandle() public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((RuntimeFieldHandle)obj).Value; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs index 73d66fd9bcfcf6..9db98e7c01ca34 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs @@ -40,7 +40,7 @@ public IntPtr GetFunctionPointer() public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((RuntimeMethodHandle)obj).Value; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs index f3f18653d97e2c..b6c0c1b0697fb5 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs @@ -79,7 +79,7 @@ public T this[int index] get { Debug.Assert(index < Count); - return (_items != null) ? _items[index] : _item; + return (_items is not null) ? _items[index] : _item; } } @@ -156,7 +156,7 @@ public void Add(T item) internal static RuntimeType? GetType(string typeName, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark) { - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); return RuntimeTypeHandle.GetTypeByName( @@ -172,12 +172,12 @@ private static void ThrowIfTypeNeverValidGenericArgument(RuntimeType type) internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParamters) { - if (genericArguments == null) + if (genericArguments is null) throw new ArgumentNullException(); for (int i = 0; i < genericArguments.Length; i++) { - if (genericArguments[i] == null) + if (genericArguments[i] is null) throw new ArgumentNullException(); ThrowIfTypeNeverValidGenericArgument(genericArguments[i]); @@ -193,7 +193,7 @@ private static void SplitName(string? fullname, out string? name, out string? ns name = null; ns = null; - if (fullname == null) + if (fullname is null) return; // Get namespace @@ -258,7 +258,7 @@ private static void FilterHelper( prefixLookup = false; ignoreCase = false; - if (name != null) + if (name is not null) { if ((bindingFlags & BindingFlags.IgnoreCase) != 0) { @@ -298,7 +298,7 @@ private static void FilterHelper(BindingFlags bindingFlags, ref string? name, ou // Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not. private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string? name, bool ignoreCase) { - Debug.Assert(name != null); + Debug.Assert(name is not null); if (ignoreCase) { @@ -321,8 +321,8 @@ private static bool FilterApplyBase( string? name, bool prefixLookup) { #region Preconditions - Debug.Assert(memberInfo != null); - Debug.Assert(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLowerInvariant().Equals(name))); + Debug.Assert(memberInfo is not null); + Debug.Assert(name is null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLowerInvariant().Equals(name))); #endregion #region Filter by Public & Private @@ -387,7 +387,7 @@ private static bool FilterApplyBase( { MethodInfo? methodInfo = memberInfo as MethodInfo; - if (methodInfo == null) + if (methodInfo is null) return false; if (!methodInfo.IsVirtual && !methodInfo.IsAbstract) @@ -411,7 +411,7 @@ private static bool FilterApplyType( if (!FilterApplyBase(type, bindingFlags, isPublic, type.IsNestedAssembly, isStatic, name, prefixLookup)) return false; - if (ns != null && ns != type.Namespace) + if (ns is not null && ns != type.Namespace) return false; return true; @@ -437,7 +437,7 @@ private static bool FilterApplyConstructorInfo( private static bool FilterApplyMethodBase( MethodBase methodBase, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes) { - Debug.Assert(methodBase != null); + Debug.Assert(methodBase is not null); bindingFlags ^= BindingFlags.DeclaredOnly; #region Check CallingConvention @@ -454,7 +454,7 @@ private static bool FilterApplyMethodBase( #endregion #region If argumentTypes supplied - if (argumentTypes != null) + if (argumentTypes is not null) { ParameterInfo[] parameterInfos = methodBase.GetParametersNoCopy(); @@ -655,7 +655,7 @@ private ListBuilder GetPropertyCandidates( RuntimePropertyInfo propertyInfo = cache[i]; if ((bindingAttr & propertyInfo.BindingFlags) == propertyInfo.BindingFlags && (!prefixLookup || FilterApplyPrefixLookup(propertyInfo, name, ignoreCase)) && - (types == null || (propertyInfo.GetIndexParameters().Length == types.Length))) + (types is null || (propertyInfo.GetIndexParameters().Length == types.Length))) { candidates.Add(propertyInfo); } @@ -820,7 +820,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) if (candidates.Count == 0) return null; - if (types == null || types.Length == 0) + if (types is null || types.Length == 0) { MethodInfo firstCandidate = candidates[0]; @@ -828,7 +828,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return firstCandidate; } - else if (types == null) + else if (types is null) { for (int j = 1; j < candidates.Count; j++) { @@ -842,7 +842,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) } } - if (binder == null) + if (binder is null) binder = DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo; @@ -863,7 +863,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) ConstructorInfo firstCandidate = candidates[0]; ParameterInfo[] parameters = firstCandidate.GetParametersNoCopy(); - if (parameters == null || parameters.Length == 0) + if (parameters is null || parameters.Length == 0) { return firstCandidate; } @@ -872,7 +872,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo; - if (binder == null) + if (binder is null) binder = DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo; @@ -882,14 +882,14 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) protected override PropertyInfo? GetPropertyImpl( string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { - if (name == null) throw new ArgumentNullException(nameof(name)); + if (name is null) throw new ArgumentNullException(nameof(name)); ListBuilder candidates = GetPropertyCandidates(name, bindingAttr, types, false); if (candidates.Count == 0) return null; - if (types == null || types.Length == 0) + if (types is null || types.Length == 0) { // no arguments if (candidates.Count == 1) @@ -912,7 +912,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers); - if (binder == null) + if (binder is null) binder = DefaultBinder; return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers); @@ -921,7 +921,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(nameof(name)); + if (name is null) throw new ArgumentNullException(nameof(name)); bool ignoreCase; MemberListType listType; @@ -937,7 +937,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) RuntimeEventInfo eventInfo = cache[i]; if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags) { - if (match != null) + if (match is not null) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); match = eventInfo; @@ -950,7 +950,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + if (name is null) throw new ArgumentNullException(); bool ignoreCase; MemberListType listType; @@ -966,7 +966,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { RuntimeFieldInfo fieldInfo = cache[i]; { - if (match != null) + if (match is not null) { if (ReferenceEquals(fieldInfo.DeclaringType, match.DeclaringType)) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); @@ -975,7 +975,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) multipleStaticFieldMatches = true; } - if (match == null || fieldInfo.DeclaringType!.IsSubclassOf(match.DeclaringType!) || match.DeclaringType!.IsInterface) + if (match is null || fieldInfo.DeclaringType!.IsSubclassOf(match.DeclaringType!) || match.DeclaringType!.IsInterface) match = fieldInfo; } } @@ -988,7 +988,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) public override Type? GetInterface(string fullname, bool ignoreCase) { - if (fullname == null) throw new ArgumentNullException(nameof(fullname)); + if (fullname is null) throw new ArgumentNullException(nameof(fullname)); BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; @@ -1012,13 +1012,13 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) continue; } - if (list == null) + if (list is null) list = new List(2); list.Add(t); } - if (list == null) + if (list is null) return null; RuntimeType[]? cache = list.ToArray(); @@ -1029,7 +1029,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) RuntimeType iface = cache[i]; if (FilterApplyType(iface, bindingAttr, name, false, ns)) { - if (match != null) + if (match is not null) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); match = iface; @@ -1042,7 +1042,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type? GetNestedType(string fullname, BindingFlags bindingAttr) { - if (fullname == null) throw new ArgumentNullException(nameof(fullname)); + if (fullname is null) throw new ArgumentNullException(nameof(fullname)); bool ignoreCase; bindingAttr &= ~BindingFlags.Static; @@ -1058,7 +1058,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) RuntimeType nestedType = cache[i]; if (FilterApplyType(nestedType, bindingAttr, name, false, ns)) { - if (match != null) + if (match is not null) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); match = nestedType; @@ -1071,7 +1071,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(nameof(name)); + if (name is null) throw new ArgumentNullException(nameof(name)); ListBuilder methods = default; ListBuilder constructors = default; @@ -1205,7 +1205,7 @@ public override Type[] GetGenericArguments() { Type[] types = GetGenericArgumentsInternal(false); - if (types == null) + if (types is null) types = Array.Empty(); return types; @@ -1213,7 +1213,7 @@ public override Type[] GetGenericArguments() public override Type MakeGenericType(Type[] instantiation) { - if (instantiation == null) + if (instantiation is null) throw new ArgumentNullException(nameof(instantiation)); RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length]; @@ -1228,12 +1228,12 @@ public override Type MakeGenericType(Type[] instantiation) for (int i = 0; i < instantiation.Length; i++) { Type instantiationElem = instantiation[i]; - if (instantiationElem == null) + if (instantiationElem is null) throw new ArgumentNullException(); RuntimeType? rtInstantiationElem = instantiationElem as RuntimeType; - if (rtInstantiationElem == null) + if (rtInstantiationElem is null) { if (instantiationElem.IsSignatureType) return MakeGenericSignatureType(this, instantiation); @@ -1253,7 +1253,7 @@ public override Type MakeGenericType(Type[] instantiation) SanityCheckGenericArguments(instantiationRuntimeType, genericParameters); Type? ret = MakeGenericType(this, instantiationRuntimeType); - if (ret == null) + if (ret is null) throw new TypeLoadException(); return ret; } @@ -1303,9 +1303,9 @@ public override int GenericParameterPosition } // There must not be more named parameters than provided arguments - if (namedParams != null) + if (namedParams is not null) { - if (providedArgs != null) + if (providedArgs is not null) { if (namedParams.Length > providedArgs.Length) // "Named parameter array can not be bigger than argument array." @@ -1321,15 +1321,15 @@ public override int GenericParameterPosition #endregion #region Check that any named paramters are not null - if (namedParams != null && Array.IndexOf(namedParams, null) != -1) + if (namedParams is not null && Array.IndexOf(namedParams, null) != -1) // "Named parameter value must not be null." throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamNull"), nameof(namedParams)); #endregion - int argCnt = (providedArgs != null) ? providedArgs.Length : 0; + int argCnt = (providedArgs is not null) ? providedArgs.Length : 0; #region Get a Binder - if (binder == null) + if (binder is null) binder = DefaultBinder; #endregion @@ -1350,7 +1350,7 @@ public override int GenericParameterPosition bindingFlags |= BindingFlags.SetProperty; #region Name - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0 || name.Equals(@"[DISPID=0]")) @@ -1380,7 +1380,7 @@ public override int GenericParameterPosition { Debug.Assert(IsSetField); - if (providedArgs == null) + if (providedArgs is null) throw new ArgumentNullException(nameof(providedArgs)); if ((bindingFlags & BindingFlags.GetProperty) != 0) @@ -1397,7 +1397,7 @@ public override int GenericParameterPosition FieldInfo? selFld = null; FieldInfo[]? flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[]; - Debug.Assert(flds != null); + Debug.Assert(flds is not null); if (flds.Length == 1) { @@ -1409,7 +1409,7 @@ public override int GenericParameterPosition } #endregion - if (selFld != null) + if (selFld is not null) { #region Invocation on a field if (selFld.FieldType.IsArray || ReferenceEquals(selFld.FieldType, typeof(System.Array))) @@ -1497,14 +1497,14 @@ public override int GenericParameterPosition // else with the same (insufficient) number of actual arguments to get a // cache hit because then they would bypass the default argument processing // and the invocation would fail. - if (bDefaultBinder && namedParams == null && argCnt < 6) + if (bDefaultBinder && namedParams is null && argCnt < 6) useCache = true; if (useCache) { MethodBase invokeMethod = GetMethodFromCache (name, bindingFlags, argCnt, providedArgs); - if (invokeMethod != null) + if (invokeMethod is not null) return ((MethodInfo) invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); } */ @@ -1551,12 +1551,12 @@ public override int GenericParameterPosition for (int i = 0; i < semiFinalists.Length; i++) { MethodInfo semiFinalist = semiFinalists[i]; - Debug.Assert(semiFinalist != null); + Debug.Assert(semiFinalist is not null); if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt])) continue; - if (finalist == null) + if (finalist is null) { finalist = semiFinalist; } @@ -1567,7 +1567,7 @@ public override int GenericParameterPosition } } - if (results != null) + if (results is not null) { Debug.Assert(results.Count > 1); finalists = new MethodInfo[results.Count]; @@ -1577,10 +1577,10 @@ public override int GenericParameterPosition } #endregion - Debug.Assert(finalists == null || finalist != null); + Debug.Assert(finalists is null || finalist is not null); #region BindingFlags.GetProperty or BindingFlags.SetProperty - if (finalist == null && isGetProperty || isSetProperty) + if (finalist is null && isGetProperty || isSetProperty) { #region Lookup Property PropertyInfo[] semiFinalists = (GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[])!; @@ -1599,13 +1599,13 @@ public override int GenericParameterPosition semiFinalist = semiFinalists[i].GetGetMethod(true); } - if (semiFinalist == null) + if (semiFinalist is null) continue; if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt])) continue; - if (finalist == null) + if (finalist is null) { finalist = semiFinalist; } @@ -1616,7 +1616,7 @@ public override int GenericParameterPosition } } - if (results != null) + if (results is not null) { Debug.Assert(results.Count > 1); finalists = new MethodInfo[results.Count]; @@ -1626,10 +1626,10 @@ public override int GenericParameterPosition } #endregion - if (finalist != null) + if (finalist is not null) { #region Invoke - if (finalists == null && + if (finalists is null && argCnt == 0 && finalist.GetParametersNoCopy().Length == 0 && (bindingFlags & BindingFlags.OptionalParamBinding) == 0) @@ -1651,7 +1651,7 @@ public override int GenericParameterPosition try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); } catch (MissingMethodException) { } - if (invokeMethod == null) + if (invokeMethod is null) throw new MissingMethodException(FullName, name); //if (useCache && argCnt == invokeMethod.GetParameters().Length) @@ -1659,7 +1659,7 @@ public override int GenericParameterPosition object? result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); - if (state != null) + if (state is not null) binder.ReorderArgumentArray(ref providedArgs, state); return result; @@ -1716,7 +1716,7 @@ private void CreateInstanceCheckThis() int argCnt = args.Length; // Without a binder we need to do use the default binder... - if (binder == null) + if (binder is null) binder = DefaultBinder; // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors @@ -1737,7 +1737,7 @@ private void CreateInstanceCheckThis() Type[] argsType = new Type[argCnt]; for (int i = 0; i < argCnt; i++) { - if (args[i] != null) + if (args[i] is not null) { argsType[i] = args[i]!.GetType(); } @@ -1751,10 +1751,10 @@ private void CreateInstanceCheckThis() MethodBase[]? cons = new MethodBase[matches.Count]; matches.CopyTo(cons); - if (cons != null && cons.Length == 0) + if (cons is not null && cons.Length == 0) cons = null; - if (cons == null) + if (cons is null) { throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); } @@ -1768,7 +1768,7 @@ private void CreateInstanceCheckThis() } catch (MissingMethodException) { invokeMethod = null; } - if (invokeMethod == null) + if (invokeMethod is null) { throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); } @@ -1790,7 +1790,7 @@ private void CreateInstanceCheckThis() else { server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture); - if (state != null) + if (state is not null) binder.ReorderArgumentArray(ref args, state); } } @@ -1828,7 +1828,7 @@ internal TypeCache Cache { get { - if (cache == null) + if (cache is null) LazyInitializer.EnsureInitialized(ref cache, () => new TypeCache()); return cache; @@ -1883,14 +1883,14 @@ internal RuntimeType(object obj) internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated) { - if (fromNoninstanciated == null) + if (fromNoninstanciated is null) throw new ArgumentNullException(nameof(fromNoninstanciated)); return GetCorrespondingInflatedMethod(fromNoninstanciated); } internal override ConstructorInfo GetConstructor(ConstructorInfo fromNoninstanciated) { - if (fromNoninstanciated == null) + if (fromNoninstanciated is null) throw new ArgumentNullException(nameof(fromNoninstanciated)); return GetCorrespondingInflatedConstructor(fromNoninstanciated); } @@ -1914,7 +1914,7 @@ internal override FieldInfo GetField(FieldInfo fromNoninstanciated) private RuntimeConstructorInfo? m_serializationCtor; internal RuntimeConstructorInfo? GetSerializationCtor() { - if (m_serializationCtor == null) + if (m_serializationCtor is null) { var s_SICtorParamTypes = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; @@ -1947,12 +1947,12 @@ internal override FieldInfo GetField(FieldInfo fromNoninstanciated) private object? CreateInstanceMono(bool nonPublic, bool wrapExceptions) { RuntimeConstructorInfo? ctor = GetDefaultConstructor(); - if (!nonPublic && ctor != null && !ctor.IsPublic) + if (!nonPublic && ctor is not null && !ctor.IsPublic) { throw new MissingMethodException(SR.Format(SR.Arg_NoDefCTor, FullName)); } - if (ctor == null) + if (ctor is null) { Type elementType = this.GetRootElementType(); if (ReferenceEquals(elementType, typeof(TypedReference)) || ReferenceEquals(elementType, typeof(RuntimeArgumentHandle))) @@ -1983,7 +1983,7 @@ internal override FieldInfo GetField(FieldInfo fromNoninstanciated) if ((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding) throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value!.GetType(), this)); - if (binder != null && binder != DefaultBinder) + if (binder is not null && binder != DefaultBinder) return binder.ChangeType(value!, this, culture); throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value!.GetType(), this)); @@ -1999,13 +1999,13 @@ internal override FieldInfo GetField(FieldInfo fromNoninstanciated) if (IsByRef) { Type? elementType = GetElementType(); - if (value == null || elementType.IsInstanceOfType(value)) + if (value is null || elementType.IsInstanceOfType(value)) { return value; } } - if (value == null) + if (value is null) return value; if (IsEnum) @@ -2014,13 +2014,13 @@ internal override FieldInfo GetField(FieldInfo fromNoninstanciated) if (type == value.GetType()) return value; object? res = IsConvertibleToPrimitiveType(value, type); - if (res != null) + if (res is not null) return res; } else if (IsPrimitive) { object? res = IsConvertibleToPrimitiveType(value, this); - if (res != null) + if (res is not null) return res; } else if (IsPointer) @@ -2353,7 +2353,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) RuntimeType? ifaceRtType = ifaceType as RuntimeType; - if (ifaceRtType == null) + if (ifaceRtType is null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(ifaceType)); InterfaceMapping res; @@ -2364,7 +2364,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) res.TargetType = this; res.InterfaceType = ifaceType; GetInterfaceMapData(this, ifaceType, out res.TargetMethods, out res.InterfaceMethods); - if (res.TargetMethods == null) + if (res.TargetMethods is null) throw new ArgumentException("Interface not found", nameof(ifaceType)); return res; @@ -2464,7 +2464,7 @@ private RuntimeEventInfo[] GetEvents_internal(string? name, MemberListType listT private RuntimeType[] GetNestedTypes_internal(string? displayName, BindingFlags bindingAttr, MemberListType listType) { string? internalName = null; - if (displayName != null) + if (displayName is not null) internalName = displayName; using (var namePtr = new Mono.SafeStringMarshal(internalName)) using (var h = new Mono.SafeGPtrArrayHandle(GetNestedTypes_native(namePtr.Value, bindingAttr, listType))) @@ -2517,7 +2517,7 @@ public override string? FullName string? fullName; TypeCache? cache = Cache; - if ((fullName = cache.full_name) == null) + if ((fullName = cache.full_name) is null) fullName = cache.full_name = getFullName(true, false); return fullName; @@ -2548,7 +2548,7 @@ public override bool IsSubclassOf(Type type) throw new ArgumentNullException(nameof(type)); RuntimeType? rtType = type as RuntimeType; - if (rtType == null) + if (rtType is null) return false; return RuntimeTypeHandle.IsSubclassOf(this, rtType); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs index dc1eaef95e6f97..cc10ea6acd2a19 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs @@ -74,7 +74,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) public override bool Equals(object? obj) { - if (obj == null || GetType() != obj.GetType()) + if (obj is null || GetType() != obj.GetType()) return false; return value == ((RuntimeTypeHandle)obj).Value; @@ -92,22 +92,22 @@ public override int GetHashCode() public static bool operator ==(RuntimeTypeHandle left, object right) { - return (right != null) && (right is RuntimeTypeHandle) && left.Equals((RuntimeTypeHandle)right); + return (right is not null) && (right is RuntimeTypeHandle) && left.Equals((RuntimeTypeHandle)right); } public static bool operator !=(RuntimeTypeHandle left, object right) { - return (right == null) || !(right is RuntimeTypeHandle) || !left.Equals((RuntimeTypeHandle)right); + return (right is null) || !(right is RuntimeTypeHandle) || !left.Equals((RuntimeTypeHandle)right); } public static bool operator ==(object left, RuntimeTypeHandle right) { - return (left != null) && (left is RuntimeTypeHandle) && ((RuntimeTypeHandle)left).Equals(right); + return (left is not null) && (left is RuntimeTypeHandle) && ((RuntimeTypeHandle)left).Equals(right); } public static bool operator !=(object left, RuntimeTypeHandle right) { - return (left == null) || !(left is RuntimeTypeHandle) || !((RuntimeTypeHandle)left).Equals(right); + return (left is null) || !(left is RuntimeTypeHandle) || !((RuntimeTypeHandle)left).Equals(right); } [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -290,7 +290,7 @@ internal static bool IsTypeDefinition(RuntimeType type) internal static RuntimeType? GetTypeByName(string typeName, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName) { - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); if (typeName.Length == 0) @@ -320,14 +320,14 @@ internal static bool IsTypeDefinition(RuntimeType type) } RuntimeType? t = internal_from_name(typeName, ref stackMark, null, throwOnError, ignoreCase, false); - if (throwOnError && t == null) + if (throwOnError && t is null) throw new TypeLoadException("Error loading '" + typeName + "'"); return t; } internal static IntPtr[]? CopyRuntimeTypeHandles(RuntimeTypeHandle[]? inHandles, out int length) { - if (inHandles == null || inHandles.Length == 0) + if (inHandles is null || inHandles.Length == 0) { length = 0; return null; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/String.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/String.Mono.cs index fccc1c96340b88..38d2b986be236d 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/String.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/String.Mono.cs @@ -27,7 +27,7 @@ public char this[int index] public static string Intern(string str) { - if (str == null) + if (str is null) throw new ArgumentNullException(nameof(str)); return InternalIntern(str); @@ -35,7 +35,7 @@ public static string Intern(string str) public static string IsInterned(string str) { - if (str == null) + if (str is null) throw new ArgumentNullException(nameof(str)); return InternalIsInterned(str); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs index 854a6b4eae7086..477784aa4e3a88 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs @@ -40,7 +40,7 @@ public bool Reset() private unsafe void CreateEventCore(bool initialState, EventResetMode mode, string? name, out bool createdNew) { - if (name != null) + if (name is not null) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); SafeWaitHandle handle = new SafeWaitHandle(CreateEventInternal(mode == EventResetMode.ManualReset, initialState, null, 0, out int errorCode), ownsHandle: true); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.Mono.cs index 1bed27d4f2e929..b623d2704a9e8a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.Mono.cs @@ -92,7 +92,7 @@ public static T CompareExchange(ref T location1, T value, T comparand) where { unsafe { - if (Unsafe.AsPointer(ref location1) == null) + if (Unsafe.AsPointer(ref location1) is null) throw new NullReferenceException(); } // Besides avoiding coop handles for efficiency, @@ -130,7 +130,7 @@ public static T Exchange([NotNullIfNotNull("value")] ref T location1, T value { unsafe { - if (Unsafe.AsPointer(ref location1) == null) + if (Unsafe.AsPointer(ref location1) is null) throw new NullReferenceException(); } // See CompareExchange(T) for comments. diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs index 7e88e31ea16117..e3afdb384b2834 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs @@ -56,7 +56,7 @@ public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTa public static bool IsEntered(object obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); return IsEnteredNative(obj); } @@ -64,21 +64,21 @@ public static bool IsEntered(object obj) [UnsupportedOSPlatform("browser")] public static bool Wait(object obj, int millisecondsTimeout) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); return ObjWait(millisecondsTimeout, obj); } public static void Pulse(object obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); ObjPulse(obj); } public static void PulseAll(object obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); ObjPulseAll(obj); } @@ -126,7 +126,7 @@ private static bool ObjWait(int millisecondsTimeout, object obj) private static void ReliableEnterTimeout(object obj, int timeout, ref bool lockTaken) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); if (timeout < 0 && timeout != (int)Timeout.Infinite) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs index fc25c741a937dd..cc88acf8b58829 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs @@ -28,7 +28,7 @@ private static unsafe IntPtr CreateMutex_internal(bool initiallyOwned, string? n private static OpenExistingResult OpenExistingWorker(string name, out Mutex? result) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); result = null; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs index 8c4bb289df259f..fec22299d3d058 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -27,7 +27,7 @@ internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, Execut private static void IOCompletionCallback_Context(object? state) { _IOCompletionCallback helper = (_IOCompletionCallback)state!; - Debug.Assert(helper != null, "_IOCompletionCallback cannot be null"); + Debug.Assert(helper is not null, "_IOCompletionCallback cannot be null"); helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pNativeOverlapped); } @@ -56,7 +56,7 @@ internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint num //Quickly check the VM again, to see if a packet has arrived. //OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); pNativeOverlapped = null; - } while (pNativeOverlapped != null); + } while (pNativeOverlapped is not null); } } @@ -78,21 +78,21 @@ internal sealed unsafe class OverlappedData internal ref IAsyncResult? AsyncResult => ref _asyncResult; - internal ref int OffsetLow => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetLow : ref _offsetLow; - internal ref int OffsetHigh => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetHigh : ref _offsetHigh; - internal ref IntPtr EventHandle => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->EventHandle : ref _eventHandle; + internal ref int OffsetLow => ref (_pNativeOverlapped is not null) ? ref _pNativeOverlapped->OffsetLow : ref _offsetLow; + internal ref int OffsetHigh => ref (_pNativeOverlapped is not null) ? ref _pNativeOverlapped->OffsetHigh : ref _offsetHigh; + internal ref IntPtr EventHandle => ref (_pNativeOverlapped is not null) ? ref _pNativeOverlapped->EventHandle : ref _eventHandle; internal unsafe NativeOverlapped* Pack(IOCompletionCallback? iocb, object? userData) { - if (_pNativeOverlapped != null) + if (_pNativeOverlapped is not null) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } - if (iocb != null) + if (iocb is not null) { ExecutionContext? ec = ExecutionContext.Capture(); - _callback = (ec != null && !ec.IsDefault) ? new _IOCompletionCallback(iocb, ec) : (object)iocb; + _callback = (ec is not null && !ec.IsDefault) ? new _IOCompletionCallback(iocb, ec) : (object)iocb; } else { @@ -104,7 +104,7 @@ internal sealed unsafe class OverlappedData internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback? iocb, object? userData) { - if (_pNativeOverlapped != null) + if (_pNativeOverlapped is not null) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } @@ -115,12 +115,12 @@ internal sealed unsafe class OverlappedData private unsafe NativeOverlapped* AllocateNativeOverlapped() { - Debug.Assert(_pinnedData == null); + Debug.Assert(_pinnedData is null); bool success = false; try { - if (_userObject != null) + if (_userObject is not null) { if (_userObject.GetType() == typeof(object[])) { @@ -171,7 +171,7 @@ internal static unsafe void FreeNativeOverlapped(NativeOverlapped* nativeOverlap private void FreeNativeOverlapped() { - if (_pinnedData != null) + if (_pinnedData is not null) { for (int i = 0; i < _pinnedData.Length; i++) { @@ -183,7 +183,7 @@ private void FreeNativeOverlapped() _pinnedData = null; } - if (_pNativeOverlapped != null) + if (_pNativeOverlapped is not null) { GCHandle handle = *(GCHandle*)(_pNativeOverlapped + 1); if (handle.IsAllocated) @@ -298,7 +298,7 @@ public IntPtr EventHandleIntPtr [CLSCompliant(false)] public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { - if (nativeOverlappedPtr == null) + if (nativeOverlappedPtr is null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped!; @@ -307,7 +307,7 @@ public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) [CLSCompliant(false)] public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr) { - if (nativeOverlappedPtr == null) + if (nativeOverlappedPtr is null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped!._overlappedData = null!; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs index ac51ec48210cca..0f9980706e7eb7 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs @@ -23,7 +23,7 @@ private int ReleaseCore(int releaseCount) private static OpenExistingResult OpenExistingWorker(string name, out Semaphore? result) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs index 05fda86297391e..737701709cc796 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs @@ -209,7 +209,7 @@ public bool Join(int millisecondsTimeout) internal void ResetThreadPoolThread() { - if (_name != null) + if (_name is not null) Name = null; if ((state & ThreadState.Background) == 0) @@ -271,9 +271,9 @@ public void Start(object parameter) // Called from the runtime internal void StartCallback() { - if (culture != null) + if (culture is not null) CurrentCulture = culture; - if (ui_culture != null) + if (ui_culture is not null) CurrentUICulture = ui_culture; if (m_start is ThreadStart del) { diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs index e71edb9c10f8a6..9fc940c7f0a24e 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs @@ -98,10 +98,10 @@ private static RegisteredWaitHandle RegisterWaitForSingleObject( bool executeOnlyOnce, bool flowExecutionContext) { - if (waitObject == null) + if (waitObject is null) throw new ArgumentNullException(nameof(waitObject)); - if (callBack == null) + if (callBack is null) throw new ArgumentNullException(nameof(callBack)); throw new PlatformNotSupportedException(); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs index 475f0c8af1eddb..94a880ac0961dc 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs @@ -60,7 +60,7 @@ private bool SetTimer(uint actualDuration) private static int PumpTimerQueue() // NOTE: this method is called via reflection by test code { - if (s_scheduledTimersToFire == null) + if (s_scheduledTimersToFire is null) { return int.MaxValue; } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs b/src/mono/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs index a2560dd06cfb18..2b18a288c52878 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs @@ -77,7 +77,7 @@ internal abstract class ATypeName : ITypeName public bool Equals(ITypeName? other) { - return other != null && DisplayName == other.DisplayName; + return other is not null && DisplayName == other.DisplayName; } public override int GetHashCode() diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs index a531a773e515bc..b8493d8641399f 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs @@ -15,10 +15,10 @@ internal TypeLoadException(string className, string assemblyName) private void SetMessageField() { - if (_message != null) + if (_message is not null) return; - if (_className == null) + if (_className is null) { _message = SR.Arg_TypeLoadException; return; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs b/src/mono/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs index 852bf81ce9ba00..6509bb8340fe6f 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs @@ -23,11 +23,11 @@ internal static class TypeNameParser bool ignoreCase, ref StackCrawlMark stackMark) { - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); ParsedName? pname = ParseName(typeName, false, 0, out int end_pos); - if (pname == null) + if (pname is null) { if (throwOnError) throw new ArgumentException(); @@ -48,34 +48,34 @@ internal static class TypeNameParser { // Resolve assembly Assembly? assembly = null; - if (pname.AssemblyName != null) + if (pname.AssemblyName is not null) { assembly = ResolveAssembly(pname.AssemblyName, assemblyResolver, throwOnError, ref stackMark); - if (assembly == null) + if (assembly is null) // If throwOnError is true, an exception was already thrown return null; } // Resolve base type Type? type = ResolveType(assembly!, pname.Names!, typeResolver, throwOnError, ignoreCase, ref stackMark); - if (type == null) + if (type is null) return null; // Resolve type arguments - if (pname.TypeArguments != null) + if (pname.TypeArguments is not null) { var args = new Type?[pname.TypeArguments.Count]; for (int i = 0; i < pname.TypeArguments.Count; ++i) { args[i] = ConstructType(pname.TypeArguments[i], assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); - if (args[i] == null) + if (args[i] is null) return null; } type = type.MakeGenericType(args!); } // Resolve modifiers - if (pname.Modifiers != null) + if (pname.Modifiers is not null) { bool bounded = false; foreach (int mod in pname.Modifiers) @@ -112,7 +112,7 @@ internal static class TypeNameParser { var aname = new AssemblyName(name); - if (assemblyResolver == null) + if (assemblyResolver is null) { if (throwOnError) { @@ -133,7 +133,7 @@ internal static class TypeNameParser else { Assembly? assembly = assemblyResolver(aname); - if (assembly == null && throwOnError) + if (assembly is null && throwOnError) throw new FileNotFoundException(SR.FileNotFound_ResolveAssembly, name); return assembly; } @@ -146,12 +146,12 @@ internal static class TypeNameParser string name = EscapeTypeName(names[0]); // Resolve the top level type. - if (typeResolver != null) + if (typeResolver is not null) { type = typeResolver(assembly, name, ignoreCase); - if (type == null && throwOnError) + if (type is null && throwOnError) { - if (assembly == null) + if (assembly is null) throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveType, name)); else throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveTypeFromAssembly, name, assembly.FullName)); @@ -159,13 +159,13 @@ internal static class TypeNameParser } else { - if (assembly == null) + if (assembly is null) type = RuntimeType.GetType(name, throwOnError, ignoreCase, false, ref stackMark); else type = assembly.GetType(name, throwOnError, ignoreCase); } - if (type == null) + if (type is null) return null; // Resolve nested types. @@ -176,7 +176,7 @@ internal static class TypeNameParser for (int i = 1; i < names.Count; ++i) { type = type.GetNestedType(names[i], bindingFlags); - if (type == null) + if (type is null) { if (throwOnError) throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveNestedType, names[i], names[i - 1])); @@ -230,20 +230,20 @@ private class ParsedName public override string ToString () { var sb = new StringBuilder (); sb.Append (Names [0]); - if (TypeArguments != null) { + if (TypeArguments is not null) { sb.Append ("["); for (int i = 0; i < TypeArguments.Count; ++i) { - if (TypeArguments [i].AssemblyName != null) + if (TypeArguments [i].AssemblyName is not null) sb.Append ('['); sb.Append (TypeArguments [i].ToString ()); - if (TypeArguments [i].AssemblyName != null) + if (TypeArguments [i].AssemblyName is not null) sb.Append (']'); if (i < TypeArguments.Count - 1) sb.Append (", "); } sb.Append ("]"); } - if (AssemblyName != null) + if (AssemblyName is not null) sb.Append ($", {AssemblyName}"); return sb.ToString (); } @@ -309,7 +309,7 @@ public override string ToString () { pos++; isbyref = true; isptr = false; - if (res.Modifiers == null) + if (res.Modifiers is null) res.Modifiers = new List(); res.Modifiers.Add(0); break; @@ -317,7 +317,7 @@ public override string ToString () { if (isbyref) return null; pos++; - if (res.Modifiers == null) + if (res.Modifiers is null) res.Modifiers = new List(); res.Modifiers.Add(-1); isptr = true; @@ -357,7 +357,7 @@ public override string ToString () { if (bounded && rank > 1) return null; /* n.b. bounded needs both modifiers: -2 == bounded, 1 == rank 1 array */ - if (res.Modifiers == null) + if (res.Modifiers is null) res.Modifiers = new List(); if (bounded) res.Modifiers.Add(-2); @@ -382,7 +382,7 @@ public override string ToString () { } ParsedName? arg = ParseName(name, true, pos, out pos); - if (arg == null) + if (arg is null) return null; res.TypeArguments.Add(arg); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/TypeSpec.cs b/src/mono/netcore/System.Private.CoreLib/src/System/TypeSpec.cs index f78b4c208d656a..8a6e29312803c8 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/TypeSpec.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/TypeSpec.cs @@ -135,12 +135,12 @@ internal class TypeSpec internal bool HasModifiers { - get { return modifier_spec != null; } + get { return modifier_spec is not null; } } internal bool IsNested { - get { return nested != null && nested.Count > 0; } + get { return nested is not null && nested.Count > 0; } } internal bool IsByRef @@ -157,7 +157,7 @@ internal IEnumerable Nested { get { - if (nested != null) + if (nested is not null) return nested; else return Array.Empty(); @@ -168,7 +168,7 @@ internal IEnumerable Modifiers { get { - if (modifier_spec != null) + if (modifier_spec is not null) return modifier_spec; else return Array.Empty(); @@ -194,20 +194,20 @@ private string GetDisplayFullName(DisplayNameFormat flags) bool wantAssembly = (flags & DisplayNameFormat.WANT_ASSEMBLY) != 0; bool wantModifiers = (flags & DisplayNameFormat.NO_MODIFIERS) == 0; var sb = new Text.StringBuilder(name!.DisplayName); - if (nested != null) + if (nested is not null) { foreach (ITypeIdentifier? n in nested) sb.Append('+').Append(n.DisplayName); } - if (generic_params != null) + if (generic_params is not null) { sb.Append('['); for (int i = 0; i < generic_params.Count; ++i) { if (i > 0) sb.Append(", "); - if (generic_params[i].assembly_name != null) + if (generic_params[i].assembly_name is not null) sb.Append('[').Append(generic_params[i].DisplayFullName).Append(']'); else sb.Append(generic_params[i].DisplayFullName); @@ -218,7 +218,7 @@ private string GetDisplayFullName(DisplayNameFormat flags) if (wantModifiers) GetModifierString(sb); - if (assembly_name != null && wantAssembly) + if (assembly_name is not null && wantAssembly) sb.Append(", ").Append(assembly_name); return sb.ToString(); @@ -231,7 +231,7 @@ internal string ModifierString() private Text.StringBuilder GetModifierString(Text.StringBuilder sb) { - if (modifier_spec != null) + if (modifier_spec is not null) { foreach (IModifierSpec? md in modifier_spec) md.Append(sb); @@ -247,7 +247,7 @@ internal string DisplayFullName { get { - if (display_fullname == null) + if (display_fullname is null) display_fullname = GetDisplayFullName(DisplayNameFormat.Default); return display_fullname; } @@ -256,7 +256,7 @@ internal string DisplayFullName internal static TypeSpec Parse(string typeName) { int pos = 0; - if (typeName == null) + if (typeName is null) throw new ArgumentNullException(nameof(typeName)); TypeSpec res = Parse(typeName, ref pos, false, true); @@ -329,17 +329,17 @@ internal static bool NeedsEscaping(string internalName) internal Type? Resolve(Func assemblyResolver, Func typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { Assembly? asm = null; - if (assemblyResolver == null && typeResolver == null) + if (assemblyResolver is null && typeResolver is null) return RuntimeType.GetType(DisplayFullName, throwOnError, ignoreCase, false, ref stackMark); - if (assembly_name != null) + if (assembly_name is not null) { - if (assemblyResolver != null) + if (assemblyResolver is not null) asm = assemblyResolver(new AssemblyName(assembly_name)); else asm = Assembly.Load(assembly_name); - if (asm == null) + if (asm is null) { if (throwOnError) throw new FileNotFoundException("Could not resolve assembly '" + assembly_name + "'"); @@ -348,23 +348,23 @@ internal static bool NeedsEscaping(string internalName) } Type? type = null; - if (typeResolver != null) + if (typeResolver is not null) type = typeResolver(asm!, name!.DisplayName, ignoreCase); else type = asm!.GetType(name!.DisplayName, false, ignoreCase); - if (type == null) + if (type is null) { if (throwOnError) throw new TypeLoadException("Could not resolve type '" + name + "'"); return null; } - if (nested != null) + if (nested is not null) { foreach (ITypeIdentifier? n in nested) { Type? tmp = type.GetNestedType(n.DisplayName, BindingFlags.Public | BindingFlags.NonPublic); - if (tmp == null) + if (tmp is null) { if (throwOnError) throw new TypeLoadException("Could not resolve type '" + n + "'"); @@ -374,13 +374,13 @@ internal static bool NeedsEscaping(string internalName) } } - if (generic_params != null) + if (generic_params is not null) { Type[] args = new Type[generic_params.Count]; for (int i = 0; i < args.Length; ++i) { Type? tmp = generic_params[i].Resolve(assemblyResolver!, typeResolver!, throwOnError, ignoreCase, ref stackMark); - if (tmp == null) + if (tmp is null) { if (throwOnError) throw new TypeLoadException("Could not resolve type '" + generic_params[i].name + "'"); @@ -391,7 +391,7 @@ internal static bool NeedsEscaping(string internalName) type = type.MakeGenericType(args); } - if (modifier_spec != null) + if (modifier_spec is not null) { foreach (IModifierSpec? md in modifier_spec) type = md.Resolve(type); @@ -405,13 +405,13 @@ internal static bool NeedsEscaping(string internalName) private void AddName(string type_name) { - if (name == null) + if (name is null) { name = ParsedTypeIdentifier(type_name); } else { - if (nested == null) + if (nested is null) nested = new List(); nested.Add(ParsedTypeIdentifier(type_name)); } @@ -419,7 +419,7 @@ private void AddName(string type_name) private void AddModifier(IModifierSpec md) { - if (modifier_spec == null) + if (modifier_spec is null) modifier_spec = new List(); modifier_spec.Add(md); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/TypedReference.cs b/src/mono/netcore/System.Private.CoreLib/src/System/TypedReference.cs index 7cbf47592fc1da..f2b17d0b9c913a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/TypedReference.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/TypedReference.cs @@ -19,9 +19,9 @@ public ref struct TypedReference public static TypedReference MakeTypedReference(object target, FieldInfo[] flds) { - if (target == null) + if (target is null) throw new ArgumentNullException(nameof(target)); - if (flds == null) + if (flds is null) throw new ArgumentNullException(nameof(flds)); if (flds.Length == 0) throw new ArgumentException(SR.Arg_ArrayZeroError, nameof(flds)); @@ -31,7 +31,7 @@ public static TypedReference MakeTypedReference(object target, FieldInfo[] flds) for (int i = 0; i < flds.Length; i++) { var field = flds[i] as RuntimeFieldInfo; - if (field == null) + if (field is null) throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo); if (field.IsStatic) throw new ArgumentException(SR.Argument_TypedReferenceInvalidField); diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/ValueType.cs b/src/mono/netcore/System.Private.CoreLib/src/System/ValueType.cs index 52eb3106a02cae..f0c265bd8d1c8c 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/ValueType.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/ValueType.cs @@ -20,16 +20,16 @@ internal static bool DefaultEquals(object o1, object o2) object[] fields; bool res = InternalEquals(o1, o2, out fields); - if (fields == null) + if (fields is null) return res; for (int i = 0; i < fields.Length; i += 2) { object meVal = fields[i]; object youVal = fields[i + 1]; - if (meVal == null) + if (meVal is null) { - if (youVal == null) + if (youVal is null) continue; return false; @@ -44,7 +44,7 @@ internal static bool DefaultEquals(object o1, object o2) public override bool Equals(object? obj) { - if (obj == null) + if (obj is null) return false; return DefaultEquals(this, obj); @@ -54,9 +54,9 @@ public override int GetHashCode() { int result = InternalGetHashCode(this, out object[]? fields); - if (fields != null) + if (fields is not null) for (int i = 0; i < fields.Length; ++i) - if (fields[i] != null) + if (fields[i] is not null) result ^= fields[i].GetHashCode(); return result; diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs index 4446f6d4d3072e..152d9792b1a0c4 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs @@ -10,7 +10,7 @@ public partial class WeakReference private bool trackResurrection; private GCHandle handle; - public virtual bool IsAlive => Target != null; + public virtual bool IsAlive => Target is not null; public virtual object? Target {